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 ICmpInst &I) { 3621 ICmpInst::Predicate predicate = I.getPredicate(); 3622 SDValue Op1 = getValue(I.getOperand(0)); 3623 SDValue Op2 = getValue(I.getOperand(1)); 3624 ISD::CondCode Opcode = getICmpCondCode(predicate); 3625 3626 auto &TLI = DAG.getTargetLoweringInfo(); 3627 EVT MemVT = 3628 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3629 3630 // If a pointer's DAG type is larger than its memory type then the DAG values 3631 // are zero-extended. This breaks signed comparisons so truncate back to the 3632 // underlying type before doing the compare. 3633 if (Op1.getValueType() != MemVT) { 3634 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3635 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3636 } 3637 3638 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3639 I.getType()); 3640 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3641 } 3642 3643 void SelectionDAGBuilder::visitFCmp(const FCmpInst &I) { 3644 FCmpInst::Predicate predicate = I.getPredicate(); 3645 SDValue Op1 = getValue(I.getOperand(0)); 3646 SDValue Op2 = getValue(I.getOperand(1)); 3647 3648 ISD::CondCode Condition = getFCmpCondCode(predicate); 3649 auto *FPMO = cast<FPMathOperator>(&I); 3650 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3651 Condition = getFCmpCodeWithoutNaN(Condition); 3652 3653 SDNodeFlags Flags; 3654 Flags.copyFMF(*FPMO); 3655 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3656 3657 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3658 I.getType()); 3659 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3660 } 3661 3662 // Check if the condition of the select has one use or two users that are both 3663 // selects with the same condition. 3664 static bool hasOnlySelectUsers(const Value *Cond) { 3665 return llvm::all_of(Cond->users(), [](const Value *V) { 3666 return isa<SelectInst>(V); 3667 }); 3668 } 3669 3670 void SelectionDAGBuilder::visitSelect(const User &I) { 3671 SmallVector<EVT, 4> ValueVTs; 3672 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3673 ValueVTs); 3674 unsigned NumValues = ValueVTs.size(); 3675 if (NumValues == 0) return; 3676 3677 SmallVector<SDValue, 4> Values(NumValues); 3678 SDValue Cond = getValue(I.getOperand(0)); 3679 SDValue LHSVal = getValue(I.getOperand(1)); 3680 SDValue RHSVal = getValue(I.getOperand(2)); 3681 SmallVector<SDValue, 1> BaseOps(1, Cond); 3682 ISD::NodeType OpCode = 3683 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3684 3685 bool IsUnaryAbs = false; 3686 bool Negate = false; 3687 3688 SDNodeFlags Flags; 3689 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3690 Flags.copyFMF(*FPOp); 3691 3692 Flags.setUnpredictable( 3693 cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable)); 3694 3695 // Min/max matching is only viable if all output VTs are the same. 3696 if (all_equal(ValueVTs)) { 3697 EVT VT = ValueVTs[0]; 3698 LLVMContext &Ctx = *DAG.getContext(); 3699 auto &TLI = DAG.getTargetLoweringInfo(); 3700 3701 // We care about the legality of the operation after it has been type 3702 // legalized. 3703 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3704 VT = TLI.getTypeToTransformTo(Ctx, VT); 3705 3706 // If the vselect is legal, assume we want to leave this as a vector setcc + 3707 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3708 // min/max is legal on the scalar type. 3709 bool UseScalarMinMax = VT.isVector() && 3710 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3711 3712 // ValueTracking's select pattern matching does not account for -0.0, 3713 // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that 3714 // -0.0 is less than +0.0. 3715 Value *LHS, *RHS; 3716 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3717 ISD::NodeType Opc = ISD::DELETED_NODE; 3718 switch (SPR.Flavor) { 3719 case SPF_UMAX: Opc = ISD::UMAX; break; 3720 case SPF_UMIN: Opc = ISD::UMIN; break; 3721 case SPF_SMAX: Opc = ISD::SMAX; break; 3722 case SPF_SMIN: Opc = ISD::SMIN; break; 3723 case SPF_FMINNUM: 3724 switch (SPR.NaNBehavior) { 3725 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3726 case SPNB_RETURNS_NAN: break; 3727 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3728 case SPNB_RETURNS_ANY: 3729 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) || 3730 (UseScalarMinMax && 3731 TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()))) 3732 Opc = ISD::FMINNUM; 3733 break; 3734 } 3735 break; 3736 case SPF_FMAXNUM: 3737 switch (SPR.NaNBehavior) { 3738 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3739 case SPNB_RETURNS_NAN: break; 3740 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3741 case SPNB_RETURNS_ANY: 3742 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) || 3743 (UseScalarMinMax && 3744 TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()))) 3745 Opc = ISD::FMAXNUM; 3746 break; 3747 } 3748 break; 3749 case SPF_NABS: 3750 Negate = true; 3751 [[fallthrough]]; 3752 case SPF_ABS: 3753 IsUnaryAbs = true; 3754 Opc = ISD::ABS; 3755 break; 3756 default: break; 3757 } 3758 3759 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3760 (TLI.isOperationLegalOrCustomOrPromote(Opc, VT) || 3761 (UseScalarMinMax && 3762 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3763 // If the underlying comparison instruction is used by any other 3764 // instruction, the consumed instructions won't be destroyed, so it is 3765 // not profitable to convert to a min/max. 3766 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3767 OpCode = Opc; 3768 LHSVal = getValue(LHS); 3769 RHSVal = getValue(RHS); 3770 BaseOps.clear(); 3771 } 3772 3773 if (IsUnaryAbs) { 3774 OpCode = Opc; 3775 LHSVal = getValue(LHS); 3776 BaseOps.clear(); 3777 } 3778 } 3779 3780 if (IsUnaryAbs) { 3781 for (unsigned i = 0; i != NumValues; ++i) { 3782 SDLoc dl = getCurSDLoc(); 3783 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3784 Values[i] = 3785 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3786 if (Negate) 3787 Values[i] = DAG.getNegative(Values[i], dl, VT); 3788 } 3789 } else { 3790 for (unsigned i = 0; i != NumValues; ++i) { 3791 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3792 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3793 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3794 Values[i] = DAG.getNode( 3795 OpCode, getCurSDLoc(), 3796 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3797 } 3798 } 3799 3800 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3801 DAG.getVTList(ValueVTs), Values)); 3802 } 3803 3804 void SelectionDAGBuilder::visitTrunc(const User &I) { 3805 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3806 SDValue N = getValue(I.getOperand(0)); 3807 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3808 I.getType()); 3809 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3810 } 3811 3812 void SelectionDAGBuilder::visitZExt(const User &I) { 3813 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3814 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3815 SDValue N = getValue(I.getOperand(0)); 3816 auto &TLI = DAG.getTargetLoweringInfo(); 3817 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3818 3819 SDNodeFlags Flags; 3820 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I)) 3821 Flags.setNonNeg(PNI->hasNonNeg()); 3822 3823 // Eagerly use nonneg information to canonicalize towards sign_extend if 3824 // that is the target's preference. 3825 // TODO: Let the target do this later. 3826 if (Flags.hasNonNeg() && 3827 TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) { 3828 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3829 return; 3830 } 3831 3832 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags)); 3833 } 3834 3835 void SelectionDAGBuilder::visitSExt(const User &I) { 3836 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3837 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3838 SDValue N = getValue(I.getOperand(0)); 3839 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3840 I.getType()); 3841 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3842 } 3843 3844 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3845 // FPTrunc is never a no-op cast, no need to check 3846 SDValue N = getValue(I.getOperand(0)); 3847 SDLoc dl = getCurSDLoc(); 3848 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3849 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3850 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3851 DAG.getTargetConstant( 3852 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3853 } 3854 3855 void SelectionDAGBuilder::visitFPExt(const User &I) { 3856 // FPExt is never a no-op cast, no need to check 3857 SDValue N = getValue(I.getOperand(0)); 3858 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3859 I.getType()); 3860 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3861 } 3862 3863 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3864 // FPToUI 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_TO_UINT, getCurSDLoc(), DestVT, N)); 3869 } 3870 3871 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3872 // FPToSI 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_SINT, getCurSDLoc(), DestVT, N)); 3877 } 3878 3879 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3880 // UIToFP 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 SDNodeFlags Flags; 3885 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I)) 3886 Flags.setNonNeg(PNI->hasNonNeg()); 3887 3888 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N, Flags)); 3889 } 3890 3891 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3892 // SIToFP is never a no-op cast, no need to check 3893 SDValue N = getValue(I.getOperand(0)); 3894 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3895 I.getType()); 3896 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3897 } 3898 3899 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3900 // What to do depends on the size of the integer and the size of the pointer. 3901 // We can either truncate, zero extend, or no-op, accordingly. 3902 SDValue N = getValue(I.getOperand(0)); 3903 auto &TLI = DAG.getTargetLoweringInfo(); 3904 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3905 I.getType()); 3906 EVT PtrMemVT = 3907 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3908 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3909 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3910 setValue(&I, N); 3911 } 3912 3913 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3914 // What to do depends on the size of the integer and the size of the pointer. 3915 // We can either truncate, zero extend, or no-op, accordingly. 3916 SDValue N = getValue(I.getOperand(0)); 3917 auto &TLI = DAG.getTargetLoweringInfo(); 3918 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3919 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3920 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3921 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3922 setValue(&I, N); 3923 } 3924 3925 void SelectionDAGBuilder::visitBitCast(const User &I) { 3926 SDValue N = getValue(I.getOperand(0)); 3927 SDLoc dl = getCurSDLoc(); 3928 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3929 I.getType()); 3930 3931 // BitCast assures us that source and destination are the same size so this is 3932 // either a BITCAST or a no-op. 3933 if (DestVT != N.getValueType()) 3934 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3935 DestVT, N)); // convert types. 3936 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3937 // might fold any kind of constant expression to an integer constant and that 3938 // is not what we are looking for. Only recognize a bitcast of a genuine 3939 // constant integer as an opaque constant. 3940 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3941 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3942 /*isOpaque*/true)); 3943 else 3944 setValue(&I, N); // noop cast. 3945 } 3946 3947 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3948 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3949 const Value *SV = I.getOperand(0); 3950 SDValue N = getValue(SV); 3951 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3952 3953 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3954 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3955 3956 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3957 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3958 3959 setValue(&I, N); 3960 } 3961 3962 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3963 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3964 SDValue InVec = getValue(I.getOperand(0)); 3965 SDValue InVal = getValue(I.getOperand(1)); 3966 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3967 TLI.getVectorIdxTy(DAG.getDataLayout())); 3968 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3969 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3970 InVec, InVal, InIdx)); 3971 } 3972 3973 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3974 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3975 SDValue InVec = getValue(I.getOperand(0)); 3976 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3977 TLI.getVectorIdxTy(DAG.getDataLayout())); 3978 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3979 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3980 InVec, InIdx)); 3981 } 3982 3983 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3984 SDValue Src1 = getValue(I.getOperand(0)); 3985 SDValue Src2 = getValue(I.getOperand(1)); 3986 ArrayRef<int> Mask; 3987 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3988 Mask = SVI->getShuffleMask(); 3989 else 3990 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3991 SDLoc DL = getCurSDLoc(); 3992 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3993 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3994 EVT SrcVT = Src1.getValueType(); 3995 3996 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3997 VT.isScalableVector()) { 3998 // Canonical splat form of first element of first input vector. 3999 SDValue FirstElt = 4000 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 4001 DAG.getVectorIdxConstant(0, DL)); 4002 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 4003 return; 4004 } 4005 4006 // For now, we only handle splats for scalable vectors. 4007 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 4008 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 4009 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 4010 4011 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 4012 unsigned MaskNumElts = Mask.size(); 4013 4014 if (SrcNumElts == MaskNumElts) { 4015 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 4016 return; 4017 } 4018 4019 // Normalize the shuffle vector since mask and vector length don't match. 4020 if (SrcNumElts < MaskNumElts) { 4021 // Mask is longer than the source vectors. We can use concatenate vector to 4022 // make the mask and vectors lengths match. 4023 4024 if (MaskNumElts % SrcNumElts == 0) { 4025 // Mask length is a multiple of the source vector length. 4026 // Check if the shuffle is some kind of concatenation of the input 4027 // vectors. 4028 unsigned NumConcat = MaskNumElts / SrcNumElts; 4029 bool IsConcat = true; 4030 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 4031 for (unsigned i = 0; i != MaskNumElts; ++i) { 4032 int Idx = Mask[i]; 4033 if (Idx < 0) 4034 continue; 4035 // Ensure the indices in each SrcVT sized piece are sequential and that 4036 // the same source is used for the whole piece. 4037 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 4038 (ConcatSrcs[i / SrcNumElts] >= 0 && 4039 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 4040 IsConcat = false; 4041 break; 4042 } 4043 // Remember which source this index came from. 4044 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 4045 } 4046 4047 // The shuffle is concatenating multiple vectors together. Just emit 4048 // a CONCAT_VECTORS operation. 4049 if (IsConcat) { 4050 SmallVector<SDValue, 8> ConcatOps; 4051 for (auto Src : ConcatSrcs) { 4052 if (Src < 0) 4053 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 4054 else if (Src == 0) 4055 ConcatOps.push_back(Src1); 4056 else 4057 ConcatOps.push_back(Src2); 4058 } 4059 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 4060 return; 4061 } 4062 } 4063 4064 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 4065 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 4066 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 4067 PaddedMaskNumElts); 4068 4069 // Pad both vectors with undefs to make them the same length as the mask. 4070 SDValue UndefVal = DAG.getUNDEF(SrcVT); 4071 4072 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 4073 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 4074 MOps1[0] = Src1; 4075 MOps2[0] = Src2; 4076 4077 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 4078 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 4079 4080 // Readjust mask for new input vector length. 4081 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 4082 for (unsigned i = 0; i != MaskNumElts; ++i) { 4083 int Idx = Mask[i]; 4084 if (Idx >= (int)SrcNumElts) 4085 Idx -= SrcNumElts - PaddedMaskNumElts; 4086 MappedOps[i] = Idx; 4087 } 4088 4089 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 4090 4091 // If the concatenated vector was padded, extract a subvector with the 4092 // correct number of elements. 4093 if (MaskNumElts != PaddedMaskNumElts) 4094 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 4095 DAG.getVectorIdxConstant(0, DL)); 4096 4097 setValue(&I, Result); 4098 return; 4099 } 4100 4101 if (SrcNumElts > MaskNumElts) { 4102 // Analyze the access pattern of the vector to see if we can extract 4103 // two subvectors and do the shuffle. 4104 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 4105 bool CanExtract = true; 4106 for (int Idx : Mask) { 4107 unsigned Input = 0; 4108 if (Idx < 0) 4109 continue; 4110 4111 if (Idx >= (int)SrcNumElts) { 4112 Input = 1; 4113 Idx -= SrcNumElts; 4114 } 4115 4116 // If all the indices come from the same MaskNumElts sized portion of 4117 // the sources we can use extract. Also make sure the extract wouldn't 4118 // extract past the end of the source. 4119 int NewStartIdx = alignDown(Idx, MaskNumElts); 4120 if (NewStartIdx + MaskNumElts > SrcNumElts || 4121 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 4122 CanExtract = false; 4123 // Make sure we always update StartIdx as we use it to track if all 4124 // elements are undef. 4125 StartIdx[Input] = NewStartIdx; 4126 } 4127 4128 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 4129 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 4130 return; 4131 } 4132 if (CanExtract) { 4133 // Extract appropriate subvector and generate a vector shuffle 4134 for (unsigned Input = 0; Input < 2; ++Input) { 4135 SDValue &Src = Input == 0 ? Src1 : Src2; 4136 if (StartIdx[Input] < 0) 4137 Src = DAG.getUNDEF(VT); 4138 else { 4139 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 4140 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 4141 } 4142 } 4143 4144 // Calculate new mask. 4145 SmallVector<int, 8> MappedOps(Mask); 4146 for (int &Idx : MappedOps) { 4147 if (Idx >= (int)SrcNumElts) 4148 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 4149 else if (Idx >= 0) 4150 Idx -= StartIdx[0]; 4151 } 4152 4153 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 4154 return; 4155 } 4156 } 4157 4158 // We can't use either concat vectors or extract subvectors so fall back to 4159 // replacing the shuffle with extract and build vector. 4160 // to insert and build vector. 4161 EVT EltVT = VT.getVectorElementType(); 4162 SmallVector<SDValue,8> Ops; 4163 for (int Idx : Mask) { 4164 SDValue Res; 4165 4166 if (Idx < 0) { 4167 Res = DAG.getUNDEF(EltVT); 4168 } else { 4169 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 4170 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 4171 4172 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 4173 DAG.getVectorIdxConstant(Idx, DL)); 4174 } 4175 4176 Ops.push_back(Res); 4177 } 4178 4179 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 4180 } 4181 4182 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) { 4183 ArrayRef<unsigned> Indices = I.getIndices(); 4184 const Value *Op0 = I.getOperand(0); 4185 const Value *Op1 = I.getOperand(1); 4186 Type *AggTy = I.getType(); 4187 Type *ValTy = Op1->getType(); 4188 bool IntoUndef = isa<UndefValue>(Op0); 4189 bool FromUndef = isa<UndefValue>(Op1); 4190 4191 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 4192 4193 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4194 SmallVector<EVT, 4> AggValueVTs; 4195 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 4196 SmallVector<EVT, 4> ValValueVTs; 4197 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 4198 4199 unsigned NumAggValues = AggValueVTs.size(); 4200 unsigned NumValValues = ValValueVTs.size(); 4201 SmallVector<SDValue, 4> Values(NumAggValues); 4202 4203 // Ignore an insertvalue that produces an empty object 4204 if (!NumAggValues) { 4205 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 4206 return; 4207 } 4208 4209 SDValue Agg = getValue(Op0); 4210 unsigned i = 0; 4211 // Copy the beginning value(s) from the original aggregate. 4212 for (; i != LinearIndex; ++i) 4213 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 4214 SDValue(Agg.getNode(), Agg.getResNo() + i); 4215 // Copy values from the inserted value(s). 4216 if (NumValValues) { 4217 SDValue Val = getValue(Op1); 4218 for (; i != LinearIndex + NumValValues; ++i) 4219 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 4220 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 4221 } 4222 // Copy remaining value(s) from the original aggregate. 4223 for (; i != NumAggValues; ++i) 4224 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 4225 SDValue(Agg.getNode(), Agg.getResNo() + i); 4226 4227 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 4228 DAG.getVTList(AggValueVTs), Values)); 4229 } 4230 4231 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) { 4232 ArrayRef<unsigned> Indices = I.getIndices(); 4233 const Value *Op0 = I.getOperand(0); 4234 Type *AggTy = Op0->getType(); 4235 Type *ValTy = I.getType(); 4236 bool OutOfUndef = isa<UndefValue>(Op0); 4237 4238 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 4239 4240 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4241 SmallVector<EVT, 4> ValValueVTs; 4242 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 4243 4244 unsigned NumValValues = ValValueVTs.size(); 4245 4246 // Ignore a extractvalue that produces an empty object 4247 if (!NumValValues) { 4248 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 4249 return; 4250 } 4251 4252 SmallVector<SDValue, 4> Values(NumValValues); 4253 4254 SDValue Agg = getValue(Op0); 4255 // Copy out the selected value(s). 4256 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 4257 Values[i - LinearIndex] = 4258 OutOfUndef ? 4259 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 4260 SDValue(Agg.getNode(), Agg.getResNo() + i); 4261 4262 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 4263 DAG.getVTList(ValValueVTs), Values)); 4264 } 4265 4266 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 4267 Value *Op0 = I.getOperand(0); 4268 // Note that the pointer operand may be a vector of pointers. Take the scalar 4269 // element which holds a pointer. 4270 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 4271 SDValue N = getValue(Op0); 4272 SDLoc dl = getCurSDLoc(); 4273 auto &TLI = DAG.getTargetLoweringInfo(); 4274 4275 // Normalize Vector GEP - all scalar operands should be converted to the 4276 // splat vector. 4277 bool IsVectorGEP = I.getType()->isVectorTy(); 4278 ElementCount VectorElementCount = 4279 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 4280 : ElementCount::getFixed(0); 4281 4282 if (IsVectorGEP && !N.getValueType().isVector()) { 4283 LLVMContext &Context = *DAG.getContext(); 4284 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 4285 N = DAG.getSplat(VT, dl, N); 4286 } 4287 4288 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 4289 GTI != E; ++GTI) { 4290 const Value *Idx = GTI.getOperand(); 4291 if (StructType *StTy = GTI.getStructTypeOrNull()) { 4292 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 4293 if (Field) { 4294 // N = N + Offset 4295 uint64_t Offset = 4296 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field); 4297 4298 // In an inbounds GEP with an offset that is nonnegative even when 4299 // interpreted as signed, assume there is no unsigned overflow. 4300 SDNodeFlags Flags; 4301 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 4302 Flags.setNoUnsignedWrap(true); 4303 4304 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 4305 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 4306 } 4307 } else { 4308 // IdxSize is the width of the arithmetic according to IR semantics. 4309 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 4310 // (and fix up the result later). 4311 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 4312 MVT IdxTy = MVT::getIntegerVT(IdxSize); 4313 TypeSize ElementSize = 4314 GTI.getSequentialElementStride(DAG.getDataLayout()); 4315 // We intentionally mask away the high bits here; ElementSize may not 4316 // fit in IdxTy. 4317 APInt ElementMul(IdxSize, ElementSize.getKnownMinValue()); 4318 bool ElementScalable = ElementSize.isScalable(); 4319 4320 // If this is a scalar constant or a splat vector of constants, 4321 // handle it quickly. 4322 const auto *C = dyn_cast<Constant>(Idx); 4323 if (C && isa<VectorType>(C->getType())) 4324 C = C->getSplatValue(); 4325 4326 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 4327 if (CI && CI->isZero()) 4328 continue; 4329 if (CI && !ElementScalable) { 4330 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 4331 LLVMContext &Context = *DAG.getContext(); 4332 SDValue OffsVal; 4333 if (IsVectorGEP) 4334 OffsVal = DAG.getConstant( 4335 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 4336 else 4337 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 4338 4339 // In an inbounds GEP with an offset that is nonnegative even when 4340 // interpreted as signed, assume there is no unsigned overflow. 4341 SDNodeFlags Flags; 4342 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 4343 Flags.setNoUnsignedWrap(true); 4344 4345 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 4346 4347 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 4348 continue; 4349 } 4350 4351 // N = N + Idx * ElementMul; 4352 SDValue IdxN = getValue(Idx); 4353 4354 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 4355 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 4356 VectorElementCount); 4357 IdxN = DAG.getSplat(VT, dl, IdxN); 4358 } 4359 4360 // If the index is smaller or larger than intptr_t, truncate or extend 4361 // it. 4362 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 4363 4364 if (ElementScalable) { 4365 EVT VScaleTy = N.getValueType().getScalarType(); 4366 SDValue VScale = DAG.getNode( 4367 ISD::VSCALE, dl, VScaleTy, 4368 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 4369 if (IsVectorGEP) 4370 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 4371 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 4372 } else { 4373 // If this is a multiply by a power of two, turn it into a shl 4374 // immediately. This is a very common case. 4375 if (ElementMul != 1) { 4376 if (ElementMul.isPowerOf2()) { 4377 unsigned Amt = ElementMul.logBase2(); 4378 IdxN = DAG.getNode(ISD::SHL, dl, 4379 N.getValueType(), IdxN, 4380 DAG.getConstant(Amt, dl, IdxN.getValueType())); 4381 } else { 4382 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 4383 IdxN.getValueType()); 4384 IdxN = DAG.getNode(ISD::MUL, dl, 4385 N.getValueType(), IdxN, Scale); 4386 } 4387 } 4388 } 4389 4390 N = DAG.getNode(ISD::ADD, dl, 4391 N.getValueType(), N, IdxN); 4392 } 4393 } 4394 4395 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 4396 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 4397 if (IsVectorGEP) { 4398 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 4399 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 4400 } 4401 4402 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 4403 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 4404 4405 setValue(&I, N); 4406 } 4407 4408 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 4409 // If this is a fixed sized alloca in the entry block of the function, 4410 // allocate it statically on the stack. 4411 if (FuncInfo.StaticAllocaMap.count(&I)) 4412 return; // getValue will auto-populate this. 4413 4414 SDLoc dl = getCurSDLoc(); 4415 Type *Ty = I.getAllocatedType(); 4416 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4417 auto &DL = DAG.getDataLayout(); 4418 TypeSize TySize = DL.getTypeAllocSize(Ty); 4419 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 4420 4421 SDValue AllocSize = getValue(I.getArraySize()); 4422 4423 EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace()); 4424 if (AllocSize.getValueType() != IntPtr) 4425 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 4426 4427 if (TySize.isScalable()) 4428 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4429 DAG.getVScale(dl, IntPtr, 4430 APInt(IntPtr.getScalarSizeInBits(), 4431 TySize.getKnownMinValue()))); 4432 else { 4433 SDValue TySizeValue = 4434 DAG.getConstant(TySize.getFixedValue(), dl, MVT::getIntegerVT(64)); 4435 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4436 DAG.getZExtOrTrunc(TySizeValue, dl, IntPtr)); 4437 } 4438 4439 // Handle alignment. If the requested alignment is less than or equal to 4440 // the stack alignment, ignore it. If the size is greater than or equal to 4441 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4442 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 4443 if (*Alignment <= StackAlign) 4444 Alignment = std::nullopt; 4445 4446 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4447 // Round the size of the allocation up to the stack alignment size 4448 // by add SA-1 to the size. This doesn't overflow because we're computing 4449 // an address inside an alloca. 4450 SDNodeFlags Flags; 4451 Flags.setNoUnsignedWrap(true); 4452 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4453 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4454 4455 // Mask out the low bits for alignment purposes. 4456 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4457 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 4458 4459 SDValue Ops[] = { 4460 getRoot(), AllocSize, 4461 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4462 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4463 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4464 setValue(&I, DSA); 4465 DAG.setRoot(DSA.getValue(1)); 4466 4467 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4468 } 4469 4470 static const MDNode *getRangeMetadata(const Instruction &I) { 4471 // If !noundef is not present, then !range violation results in a poison 4472 // value rather than immediate undefined behavior. In theory, transferring 4473 // these annotations to SDAG is fine, but in practice there are key SDAG 4474 // transforms that are known not to be poison-safe, such as folding logical 4475 // and/or to bitwise and/or. For now, only transfer !range if !noundef is 4476 // also present. 4477 if (!I.hasMetadata(LLVMContext::MD_noundef)) 4478 return nullptr; 4479 return I.getMetadata(LLVMContext::MD_range); 4480 } 4481 4482 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4483 if (I.isAtomic()) 4484 return visitAtomicLoad(I); 4485 4486 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4487 const Value *SV = I.getOperand(0); 4488 if (TLI.supportSwiftError()) { 4489 // Swifterror values can come from either a function parameter with 4490 // swifterror attribute or an alloca with swifterror attribute. 4491 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4492 if (Arg->hasSwiftErrorAttr()) 4493 return visitLoadFromSwiftError(I); 4494 } 4495 4496 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4497 if (Alloca->isSwiftError()) 4498 return visitLoadFromSwiftError(I); 4499 } 4500 } 4501 4502 SDValue Ptr = getValue(SV); 4503 4504 Type *Ty = I.getType(); 4505 SmallVector<EVT, 4> ValueVTs, MemVTs; 4506 SmallVector<TypeSize, 4> Offsets; 4507 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4508 unsigned NumValues = ValueVTs.size(); 4509 if (NumValues == 0) 4510 return; 4511 4512 Align Alignment = I.getAlign(); 4513 AAMDNodes AAInfo = I.getAAMetadata(); 4514 const MDNode *Ranges = getRangeMetadata(I); 4515 bool isVolatile = I.isVolatile(); 4516 MachineMemOperand::Flags MMOFlags = 4517 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 4518 4519 SDValue Root; 4520 bool ConstantMemory = false; 4521 if (isVolatile) 4522 // Serialize volatile loads with other side effects. 4523 Root = getRoot(); 4524 else if (NumValues > MaxParallelChains) 4525 Root = getMemoryRoot(); 4526 else if (AA && 4527 AA->pointsToConstantMemory(MemoryLocation( 4528 SV, 4529 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4530 AAInfo))) { 4531 // Do not serialize (non-volatile) loads of constant memory with anything. 4532 Root = DAG.getEntryNode(); 4533 ConstantMemory = true; 4534 MMOFlags |= MachineMemOperand::MOInvariant; 4535 } else { 4536 // Do not serialize non-volatile loads against each other. 4537 Root = DAG.getRoot(); 4538 } 4539 4540 SDLoc dl = getCurSDLoc(); 4541 4542 if (isVolatile) 4543 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4544 4545 SmallVector<SDValue, 4> Values(NumValues); 4546 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4547 4548 unsigned ChainI = 0; 4549 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4550 // Serializing loads here may result in excessive register pressure, and 4551 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4552 // could recover a bit by hoisting nodes upward in the chain by recognizing 4553 // they are side-effect free or do not alias. The optimizer should really 4554 // avoid this case by converting large object/array copies to llvm.memcpy 4555 // (MaxParallelChains should always remain as failsafe). 4556 if (ChainI == MaxParallelChains) { 4557 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4558 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4559 ArrayRef(Chains.data(), ChainI)); 4560 Root = Chain; 4561 ChainI = 0; 4562 } 4563 4564 // TODO: MachinePointerInfo only supports a fixed length offset. 4565 MachinePointerInfo PtrInfo = 4566 !Offsets[i].isScalable() || Offsets[i].isZero() 4567 ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue()) 4568 : MachinePointerInfo(); 4569 4570 SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]); 4571 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment, 4572 MMOFlags, AAInfo, Ranges); 4573 Chains[ChainI] = L.getValue(1); 4574 4575 if (MemVTs[i] != ValueVTs[i]) 4576 L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]); 4577 4578 Values[i] = L; 4579 } 4580 4581 if (!ConstantMemory) { 4582 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4583 ArrayRef(Chains.data(), ChainI)); 4584 if (isVolatile) 4585 DAG.setRoot(Chain); 4586 else 4587 PendingLoads.push_back(Chain); 4588 } 4589 4590 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4591 DAG.getVTList(ValueVTs), Values)); 4592 } 4593 4594 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4595 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4596 "call visitStoreToSwiftError when backend supports swifterror"); 4597 4598 SmallVector<EVT, 4> ValueVTs; 4599 SmallVector<uint64_t, 4> Offsets; 4600 const Value *SrcV = I.getOperand(0); 4601 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4602 SrcV->getType(), ValueVTs, &Offsets, 0); 4603 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4604 "expect a single EVT for swifterror"); 4605 4606 SDValue Src = getValue(SrcV); 4607 // Create a virtual register, then update the virtual register. 4608 Register VReg = 4609 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4610 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4611 // Chain can be getRoot or getControlRoot. 4612 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4613 SDValue(Src.getNode(), Src.getResNo())); 4614 DAG.setRoot(CopyNode); 4615 } 4616 4617 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4618 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4619 "call visitLoadFromSwiftError when backend supports swifterror"); 4620 4621 assert(!I.isVolatile() && 4622 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4623 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4624 "Support volatile, non temporal, invariant for load_from_swift_error"); 4625 4626 const Value *SV = I.getOperand(0); 4627 Type *Ty = I.getType(); 4628 assert( 4629 (!AA || 4630 !AA->pointsToConstantMemory(MemoryLocation( 4631 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4632 I.getAAMetadata()))) && 4633 "load_from_swift_error should not be constant memory"); 4634 4635 SmallVector<EVT, 4> ValueVTs; 4636 SmallVector<uint64_t, 4> Offsets; 4637 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4638 ValueVTs, &Offsets, 0); 4639 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4640 "expect a single EVT for swifterror"); 4641 4642 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4643 SDValue L = DAG.getCopyFromReg( 4644 getRoot(), getCurSDLoc(), 4645 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4646 4647 setValue(&I, L); 4648 } 4649 4650 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4651 if (I.isAtomic()) 4652 return visitAtomicStore(I); 4653 4654 const Value *SrcV = I.getOperand(0); 4655 const Value *PtrV = I.getOperand(1); 4656 4657 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4658 if (TLI.supportSwiftError()) { 4659 // Swifterror values can come from either a function parameter with 4660 // swifterror attribute or an alloca with swifterror attribute. 4661 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4662 if (Arg->hasSwiftErrorAttr()) 4663 return visitStoreToSwiftError(I); 4664 } 4665 4666 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4667 if (Alloca->isSwiftError()) 4668 return visitStoreToSwiftError(I); 4669 } 4670 } 4671 4672 SmallVector<EVT, 4> ValueVTs, MemVTs; 4673 SmallVector<TypeSize, 4> Offsets; 4674 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4675 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4676 unsigned NumValues = ValueVTs.size(); 4677 if (NumValues == 0) 4678 return; 4679 4680 // Get the lowered operands. Note that we do this after 4681 // checking if NumResults is zero, because with zero results 4682 // the operands won't have values in the map. 4683 SDValue Src = getValue(SrcV); 4684 SDValue Ptr = getValue(PtrV); 4685 4686 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4687 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4688 SDLoc dl = getCurSDLoc(); 4689 Align Alignment = I.getAlign(); 4690 AAMDNodes AAInfo = I.getAAMetadata(); 4691 4692 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4693 4694 unsigned ChainI = 0; 4695 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4696 // See visitLoad comments. 4697 if (ChainI == MaxParallelChains) { 4698 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4699 ArrayRef(Chains.data(), ChainI)); 4700 Root = Chain; 4701 ChainI = 0; 4702 } 4703 4704 // TODO: MachinePointerInfo only supports a fixed length offset. 4705 MachinePointerInfo PtrInfo = 4706 !Offsets[i].isScalable() || Offsets[i].isZero() 4707 ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue()) 4708 : MachinePointerInfo(); 4709 4710 SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]); 4711 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4712 if (MemVTs[i] != ValueVTs[i]) 4713 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4714 SDValue St = 4715 DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags, AAInfo); 4716 Chains[ChainI] = St; 4717 } 4718 4719 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4720 ArrayRef(Chains.data(), ChainI)); 4721 setValue(&I, StoreNode); 4722 DAG.setRoot(StoreNode); 4723 } 4724 4725 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4726 bool IsCompressing) { 4727 SDLoc sdl = getCurSDLoc(); 4728 4729 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4730 Align &Alignment) { 4731 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4732 Src0 = I.getArgOperand(0); 4733 Ptr = I.getArgOperand(1); 4734 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getAlignValue(); 4735 Mask = I.getArgOperand(3); 4736 }; 4737 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4738 Align &Alignment) { 4739 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4740 Src0 = I.getArgOperand(0); 4741 Ptr = I.getArgOperand(1); 4742 Mask = I.getArgOperand(2); 4743 Alignment = I.getParamAlign(1).valueOrOne(); 4744 }; 4745 4746 Value *PtrOperand, *MaskOperand, *Src0Operand; 4747 Align Alignment; 4748 if (IsCompressing) 4749 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4750 else 4751 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4752 4753 SDValue Ptr = getValue(PtrOperand); 4754 SDValue Src0 = getValue(Src0Operand); 4755 SDValue Mask = getValue(MaskOperand); 4756 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4757 4758 EVT VT = Src0.getValueType(); 4759 4760 auto MMOFlags = MachineMemOperand::MOStore; 4761 if (I.hasMetadata(LLVMContext::MD_nontemporal)) 4762 MMOFlags |= MachineMemOperand::MONonTemporal; 4763 4764 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4765 MachinePointerInfo(PtrOperand), MMOFlags, 4766 LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata()); 4767 SDValue StoreNode = 4768 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4769 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4770 DAG.setRoot(StoreNode); 4771 setValue(&I, StoreNode); 4772 } 4773 4774 // Get a uniform base for the Gather/Scatter intrinsic. 4775 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4776 // We try to represent it as a base pointer + vector of indices. 4777 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4778 // The first operand of the GEP may be a single pointer or a vector of pointers 4779 // Example: 4780 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4781 // or 4782 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4783 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4784 // 4785 // When the first GEP operand is a single pointer - it is the uniform base we 4786 // are looking for. If first operand of the GEP is a splat vector - we 4787 // extract the splat value and use it as a uniform base. 4788 // In all other cases the function returns 'false'. 4789 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4790 ISD::MemIndexType &IndexType, SDValue &Scale, 4791 SelectionDAGBuilder *SDB, const BasicBlock *CurBB, 4792 uint64_t ElemSize) { 4793 SelectionDAG& DAG = SDB->DAG; 4794 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4795 const DataLayout &DL = DAG.getDataLayout(); 4796 4797 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type"); 4798 4799 // Handle splat constant pointer. 4800 if (auto *C = dyn_cast<Constant>(Ptr)) { 4801 C = C->getSplatValue(); 4802 if (!C) 4803 return false; 4804 4805 Base = SDB->getValue(C); 4806 4807 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); 4808 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4809 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4810 IndexType = ISD::SIGNED_SCALED; 4811 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4812 return true; 4813 } 4814 4815 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4816 if (!GEP || GEP->getParent() != CurBB) 4817 return false; 4818 4819 if (GEP->getNumOperands() != 2) 4820 return false; 4821 4822 const Value *BasePtr = GEP->getPointerOperand(); 4823 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4824 4825 // Make sure the base is scalar and the index is a vector. 4826 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4827 return false; 4828 4829 TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType()); 4830 if (ScaleVal.isScalable()) 4831 return false; 4832 4833 // Target may not support the required addressing mode. 4834 if (ScaleVal != 1 && 4835 !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize)) 4836 return false; 4837 4838 Base = SDB->getValue(BasePtr); 4839 Index = SDB->getValue(IndexVal); 4840 IndexType = ISD::SIGNED_SCALED; 4841 4842 Scale = 4843 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4844 return true; 4845 } 4846 4847 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4848 SDLoc sdl = getCurSDLoc(); 4849 4850 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4851 const Value *Ptr = I.getArgOperand(1); 4852 SDValue Src0 = getValue(I.getArgOperand(0)); 4853 SDValue Mask = getValue(I.getArgOperand(3)); 4854 EVT VT = Src0.getValueType(); 4855 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4856 ->getMaybeAlignValue() 4857 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4858 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4859 4860 SDValue Base; 4861 SDValue Index; 4862 ISD::MemIndexType IndexType; 4863 SDValue Scale; 4864 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4865 I.getParent(), VT.getScalarStoreSize()); 4866 4867 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4868 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4869 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4870 LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata()); 4871 if (!UniformBase) { 4872 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4873 Index = getValue(Ptr); 4874 IndexType = ISD::SIGNED_SCALED; 4875 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4876 } 4877 4878 EVT IdxVT = Index.getValueType(); 4879 EVT EltTy = IdxVT.getVectorElementType(); 4880 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4881 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4882 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4883 } 4884 4885 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4886 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4887 Ops, MMO, IndexType, false); 4888 DAG.setRoot(Scatter); 4889 setValue(&I, Scatter); 4890 } 4891 4892 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4893 SDLoc sdl = getCurSDLoc(); 4894 4895 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4896 Align &Alignment) { 4897 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4898 Ptr = I.getArgOperand(0); 4899 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getAlignValue(); 4900 Mask = I.getArgOperand(2); 4901 Src0 = I.getArgOperand(3); 4902 }; 4903 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4904 Align &Alignment) { 4905 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4906 Ptr = I.getArgOperand(0); 4907 Alignment = I.getParamAlign(0).valueOrOne(); 4908 Mask = I.getArgOperand(1); 4909 Src0 = I.getArgOperand(2); 4910 }; 4911 4912 Value *PtrOperand, *MaskOperand, *Src0Operand; 4913 Align Alignment; 4914 if (IsExpanding) 4915 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4916 else 4917 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4918 4919 SDValue Ptr = getValue(PtrOperand); 4920 SDValue Src0 = getValue(Src0Operand); 4921 SDValue Mask = getValue(MaskOperand); 4922 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4923 4924 EVT VT = Src0.getValueType(); 4925 AAMDNodes AAInfo = I.getAAMetadata(); 4926 const MDNode *Ranges = getRangeMetadata(I); 4927 4928 // Do not serialize masked loads of constant memory with anything. 4929 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 4930 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4931 4932 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4933 4934 auto MMOFlags = MachineMemOperand::MOLoad; 4935 if (I.hasMetadata(LLVMContext::MD_nontemporal)) 4936 MMOFlags |= MachineMemOperand::MONonTemporal; 4937 4938 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4939 MachinePointerInfo(PtrOperand), MMOFlags, 4940 LocationSize::beforeOrAfterPointer(), Alignment, AAInfo, Ranges); 4941 4942 SDValue Load = 4943 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4944 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4945 if (AddToChain) 4946 PendingLoads.push_back(Load.getValue(1)); 4947 setValue(&I, Load); 4948 } 4949 4950 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4951 SDLoc sdl = getCurSDLoc(); 4952 4953 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4954 const Value *Ptr = I.getArgOperand(0); 4955 SDValue Src0 = getValue(I.getArgOperand(3)); 4956 SDValue Mask = getValue(I.getArgOperand(2)); 4957 4958 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4959 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4960 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4961 ->getMaybeAlignValue() 4962 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4963 4964 const MDNode *Ranges = getRangeMetadata(I); 4965 4966 SDValue Root = DAG.getRoot(); 4967 SDValue Base; 4968 SDValue Index; 4969 ISD::MemIndexType IndexType; 4970 SDValue Scale; 4971 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4972 I.getParent(), VT.getScalarStoreSize()); 4973 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4974 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4975 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4976 LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata(), 4977 Ranges); 4978 4979 if (!UniformBase) { 4980 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4981 Index = getValue(Ptr); 4982 IndexType = ISD::SIGNED_SCALED; 4983 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4984 } 4985 4986 EVT IdxVT = Index.getValueType(); 4987 EVT EltTy = IdxVT.getVectorElementType(); 4988 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4989 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4990 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4991 } 4992 4993 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4994 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4995 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4996 4997 PendingLoads.push_back(Gather.getValue(1)); 4998 setValue(&I, Gather); 4999 } 5000 5001 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 5002 SDLoc dl = getCurSDLoc(); 5003 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 5004 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 5005 SyncScope::ID SSID = I.getSyncScopeID(); 5006 5007 SDValue InChain = getRoot(); 5008 5009 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 5010 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 5011 5012 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5013 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 5014 5015 MachineFunction &MF = DAG.getMachineFunction(); 5016 MachineMemOperand *MMO = MF.getMachineMemOperand( 5017 MachinePointerInfo(I.getPointerOperand()), Flags, 5018 LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT), 5019 AAMDNodes(), nullptr, SSID, SuccessOrdering, FailureOrdering); 5020 5021 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 5022 dl, MemVT, VTs, InChain, 5023 getValue(I.getPointerOperand()), 5024 getValue(I.getCompareOperand()), 5025 getValue(I.getNewValOperand()), MMO); 5026 5027 SDValue OutChain = L.getValue(2); 5028 5029 setValue(&I, L); 5030 DAG.setRoot(OutChain); 5031 } 5032 5033 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 5034 SDLoc dl = getCurSDLoc(); 5035 ISD::NodeType NT; 5036 switch (I.getOperation()) { 5037 default: llvm_unreachable("Unknown atomicrmw operation"); 5038 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 5039 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 5040 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 5041 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 5042 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 5043 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 5044 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 5045 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 5046 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 5047 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 5048 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 5049 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 5050 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 5051 case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break; 5052 case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break; 5053 case AtomicRMWInst::UIncWrap: 5054 NT = ISD::ATOMIC_LOAD_UINC_WRAP; 5055 break; 5056 case AtomicRMWInst::UDecWrap: 5057 NT = ISD::ATOMIC_LOAD_UDEC_WRAP; 5058 break; 5059 } 5060 AtomicOrdering Ordering = I.getOrdering(); 5061 SyncScope::ID SSID = I.getSyncScopeID(); 5062 5063 SDValue InChain = getRoot(); 5064 5065 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 5066 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5067 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 5068 5069 MachineFunction &MF = DAG.getMachineFunction(); 5070 MachineMemOperand *MMO = MF.getMachineMemOperand( 5071 MachinePointerInfo(I.getPointerOperand()), Flags, 5072 LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT), 5073 AAMDNodes(), nullptr, SSID, Ordering); 5074 5075 SDValue L = 5076 DAG.getAtomic(NT, dl, MemVT, InChain, 5077 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 5078 MMO); 5079 5080 SDValue OutChain = L.getValue(1); 5081 5082 setValue(&I, L); 5083 DAG.setRoot(OutChain); 5084 } 5085 5086 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 5087 SDLoc dl = getCurSDLoc(); 5088 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5089 SDValue Ops[3]; 5090 Ops[0] = getRoot(); 5091 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 5092 TLI.getFenceOperandTy(DAG.getDataLayout())); 5093 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 5094 TLI.getFenceOperandTy(DAG.getDataLayout())); 5095 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops); 5096 setValue(&I, N); 5097 DAG.setRoot(N); 5098 } 5099 5100 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 5101 SDLoc dl = getCurSDLoc(); 5102 AtomicOrdering Order = I.getOrdering(); 5103 SyncScope::ID SSID = I.getSyncScopeID(); 5104 5105 SDValue InChain = getRoot(); 5106 5107 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5108 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5109 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 5110 5111 if (!TLI.supportsUnalignedAtomics() && 5112 I.getAlign().value() < MemVT.getSizeInBits() / 8) 5113 report_fatal_error("Cannot generate unaligned atomic load"); 5114 5115 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 5116 5117 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 5118 MachinePointerInfo(I.getPointerOperand()), Flags, 5119 LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(), 5120 nullptr, SSID, Order); 5121 5122 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 5123 5124 SDValue Ptr = getValue(I.getPointerOperand()); 5125 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 5126 Ptr, MMO); 5127 5128 SDValue OutChain = L.getValue(1); 5129 if (MemVT != VT) 5130 L = DAG.getPtrExtOrTrunc(L, dl, VT); 5131 5132 setValue(&I, L); 5133 DAG.setRoot(OutChain); 5134 } 5135 5136 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 5137 SDLoc dl = getCurSDLoc(); 5138 5139 AtomicOrdering Ordering = I.getOrdering(); 5140 SyncScope::ID SSID = I.getSyncScopeID(); 5141 5142 SDValue InChain = getRoot(); 5143 5144 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5145 EVT MemVT = 5146 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 5147 5148 if (!TLI.supportsUnalignedAtomics() && 5149 I.getAlign().value() < MemVT.getSizeInBits() / 8) 5150 report_fatal_error("Cannot generate unaligned atomic store"); 5151 5152 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 5153 5154 MachineFunction &MF = DAG.getMachineFunction(); 5155 MachineMemOperand *MMO = MF.getMachineMemOperand( 5156 MachinePointerInfo(I.getPointerOperand()), Flags, 5157 LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(), 5158 nullptr, SSID, Ordering); 5159 5160 SDValue Val = getValue(I.getValueOperand()); 5161 if (Val.getValueType() != MemVT) 5162 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 5163 SDValue Ptr = getValue(I.getPointerOperand()); 5164 5165 SDValue OutChain = 5166 DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO); 5167 5168 setValue(&I, OutChain); 5169 DAG.setRoot(OutChain); 5170 } 5171 5172 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 5173 /// node. 5174 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 5175 unsigned Intrinsic) { 5176 // Ignore the callsite's attributes. A specific call site may be marked with 5177 // readnone, but the lowering code will expect the chain based on the 5178 // definition. 5179 const Function *F = I.getCalledFunction(); 5180 bool HasChain = !F->doesNotAccessMemory(); 5181 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 5182 5183 // Build the operand list. 5184 SmallVector<SDValue, 8> Ops; 5185 if (HasChain) { // If this intrinsic has side-effects, chainify it. 5186 if (OnlyLoad) { 5187 // We don't need to serialize loads against other loads. 5188 Ops.push_back(DAG.getRoot()); 5189 } else { 5190 Ops.push_back(getRoot()); 5191 } 5192 } 5193 5194 // Info is set by getTgtMemIntrinsic 5195 TargetLowering::IntrinsicInfo Info; 5196 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5197 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 5198 DAG.getMachineFunction(), 5199 Intrinsic); 5200 5201 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 5202 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 5203 Info.opc == ISD::INTRINSIC_W_CHAIN) 5204 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 5205 TLI.getPointerTy(DAG.getDataLayout()))); 5206 5207 // Add all operands of the call to the operand list. 5208 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) { 5209 const Value *Arg = I.getArgOperand(i); 5210 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 5211 Ops.push_back(getValue(Arg)); 5212 continue; 5213 } 5214 5215 // Use TargetConstant instead of a regular constant for immarg. 5216 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true); 5217 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 5218 assert(CI->getBitWidth() <= 64 && 5219 "large intrinsic immediates not handled"); 5220 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 5221 } else { 5222 Ops.push_back( 5223 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 5224 } 5225 } 5226 5227 SmallVector<EVT, 4> ValueVTs; 5228 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 5229 5230 if (HasChain) 5231 ValueVTs.push_back(MVT::Other); 5232 5233 SDVTList VTs = DAG.getVTList(ValueVTs); 5234 5235 // Propagate fast-math-flags from IR to node(s). 5236 SDNodeFlags Flags; 5237 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 5238 Flags.copyFMF(*FPMO); 5239 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 5240 5241 // Create the node. 5242 SDValue Result; 5243 5244 if (auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl)) { 5245 auto *Token = Bundle->Inputs[0].get(); 5246 SDValue ConvControlToken = getValue(Token); 5247 assert(Ops.back().getValueType() != MVT::Glue && 5248 "Did not expected another glue node here."); 5249 ConvControlToken = 5250 DAG.getNode(ISD::CONVERGENCECTRL_GLUE, {}, MVT::Glue, ConvControlToken); 5251 Ops.push_back(ConvControlToken); 5252 } 5253 5254 // In some cases, custom collection of operands from CallInst I may be needed. 5255 TLI.CollectTargetIntrinsicOperands(I, Ops, DAG); 5256 if (IsTgtIntrinsic) { 5257 // This is target intrinsic that touches memory 5258 // 5259 // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic 5260 // didn't yield anything useful. 5261 MachinePointerInfo MPI; 5262 if (Info.ptrVal) 5263 MPI = MachinePointerInfo(Info.ptrVal, Info.offset); 5264 else if (Info.fallbackAddressSpace) 5265 MPI = MachinePointerInfo(*Info.fallbackAddressSpace); 5266 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, 5267 Info.memVT, MPI, Info.align, Info.flags, 5268 Info.size, I.getAAMetadata()); 5269 } else if (!HasChain) { 5270 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 5271 } else if (!I.getType()->isVoidTy()) { 5272 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 5273 } else { 5274 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 5275 } 5276 5277 if (HasChain) { 5278 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 5279 if (OnlyLoad) 5280 PendingLoads.push_back(Chain); 5281 else 5282 DAG.setRoot(Chain); 5283 } 5284 5285 if (!I.getType()->isVoidTy()) { 5286 if (!isa<VectorType>(I.getType())) 5287 Result = lowerRangeToAssertZExt(DAG, I, Result); 5288 5289 MaybeAlign Alignment = I.getRetAlign(); 5290 5291 // Insert `assertalign` node if there's an alignment. 5292 if (InsertAssertAlign && Alignment) { 5293 Result = 5294 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 5295 } 5296 } 5297 5298 setValue(&I, Result); 5299 } 5300 5301 /// GetSignificand - Get the significand and build it into a floating-point 5302 /// number with exponent of 1: 5303 /// 5304 /// Op = (Op & 0x007fffff) | 0x3f800000; 5305 /// 5306 /// where Op is the hexadecimal representation of floating point value. 5307 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 5308 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 5309 DAG.getConstant(0x007fffff, dl, MVT::i32)); 5310 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 5311 DAG.getConstant(0x3f800000, dl, MVT::i32)); 5312 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 5313 } 5314 5315 /// GetExponent - Get the exponent: 5316 /// 5317 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 5318 /// 5319 /// where Op is the hexadecimal representation of floating point value. 5320 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 5321 const TargetLowering &TLI, const SDLoc &dl) { 5322 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 5323 DAG.getConstant(0x7f800000, dl, MVT::i32)); 5324 SDValue t1 = DAG.getNode( 5325 ISD::SRL, dl, MVT::i32, t0, 5326 DAG.getConstant(23, dl, 5327 TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout()))); 5328 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 5329 DAG.getConstant(127, dl, MVT::i32)); 5330 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 5331 } 5332 5333 /// getF32Constant - Get 32-bit floating point constant. 5334 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 5335 const SDLoc &dl) { 5336 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 5337 MVT::f32); 5338 } 5339 5340 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 5341 SelectionDAG &DAG) { 5342 // TODO: What fast-math-flags should be set on the floating-point nodes? 5343 5344 // IntegerPartOfX = ((int32_t)(t0); 5345 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 5346 5347 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 5348 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 5349 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 5350 5351 // IntegerPartOfX <<= 23; 5352 IntegerPartOfX = 5353 DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 5354 DAG.getConstant(23, dl, 5355 DAG.getTargetLoweringInfo().getShiftAmountTy( 5356 MVT::i32, DAG.getDataLayout()))); 5357 5358 SDValue TwoToFractionalPartOfX; 5359 if (LimitFloatPrecision <= 6) { 5360 // For floating-point precision of 6: 5361 // 5362 // TwoToFractionalPartOfX = 5363 // 0.997535578f + 5364 // (0.735607626f + 0.252464424f * x) * x; 5365 // 5366 // error 0.0144103317, which is 6 bits 5367 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5368 getF32Constant(DAG, 0x3e814304, dl)); 5369 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5370 getF32Constant(DAG, 0x3f3c50c8, dl)); 5371 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5372 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5373 getF32Constant(DAG, 0x3f7f5e7e, dl)); 5374 } else if (LimitFloatPrecision <= 12) { 5375 // For floating-point precision of 12: 5376 // 5377 // TwoToFractionalPartOfX = 5378 // 0.999892986f + 5379 // (0.696457318f + 5380 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 5381 // 5382 // error 0.000107046256, which is 13 to 14 bits 5383 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5384 getF32Constant(DAG, 0x3da235e3, dl)); 5385 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5386 getF32Constant(DAG, 0x3e65b8f3, dl)); 5387 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5388 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5389 getF32Constant(DAG, 0x3f324b07, dl)); 5390 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5391 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5392 getF32Constant(DAG, 0x3f7ff8fd, dl)); 5393 } else { // LimitFloatPrecision <= 18 5394 // For floating-point precision of 18: 5395 // 5396 // TwoToFractionalPartOfX = 5397 // 0.999999982f + 5398 // (0.693148872f + 5399 // (0.240227044f + 5400 // (0.554906021e-1f + 5401 // (0.961591928e-2f + 5402 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 5403 // error 2.47208000*10^(-7), which is better than 18 bits 5404 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5405 getF32Constant(DAG, 0x3924b03e, dl)); 5406 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5407 getF32Constant(DAG, 0x3ab24b87, dl)); 5408 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5409 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5410 getF32Constant(DAG, 0x3c1d8c17, dl)); 5411 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5412 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5413 getF32Constant(DAG, 0x3d634a1d, dl)); 5414 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5415 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5416 getF32Constant(DAG, 0x3e75fe14, dl)); 5417 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5418 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 5419 getF32Constant(DAG, 0x3f317234, dl)); 5420 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 5421 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 5422 getF32Constant(DAG, 0x3f800000, dl)); 5423 } 5424 5425 // Add the exponent into the result in integer domain. 5426 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 5427 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5428 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 5429 } 5430 5431 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5432 /// limited-precision mode. 5433 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5434 const TargetLowering &TLI, SDNodeFlags Flags) { 5435 if (Op.getValueType() == MVT::f32 && 5436 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5437 5438 // Put the exponent in the right bit position for later addition to the 5439 // final result: 5440 // 5441 // t0 = Op * log2(e) 5442 5443 // TODO: What fast-math-flags should be set here? 5444 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5445 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5446 return getLimitedPrecisionExp2(t0, dl, DAG); 5447 } 5448 5449 // No special expansion. 5450 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5451 } 5452 5453 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5454 /// limited-precision mode. 5455 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5456 const TargetLowering &TLI, SDNodeFlags Flags) { 5457 // TODO: What fast-math-flags should be set on the floating-point nodes? 5458 5459 if (Op.getValueType() == MVT::f32 && 5460 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5461 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5462 5463 // Scale the exponent by log(2). 5464 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5465 SDValue LogOfExponent = 5466 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5467 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5468 5469 // Get the significand and build it into a floating-point number with 5470 // exponent of 1. 5471 SDValue X = GetSignificand(DAG, Op1, dl); 5472 5473 SDValue LogOfMantissa; 5474 if (LimitFloatPrecision <= 6) { 5475 // For floating-point precision of 6: 5476 // 5477 // LogofMantissa = 5478 // -1.1609546f + 5479 // (1.4034025f - 0.23903021f * x) * x; 5480 // 5481 // error 0.0034276066, which is better than 8 bits 5482 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5483 getF32Constant(DAG, 0xbe74c456, dl)); 5484 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5485 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5486 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5487 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5488 getF32Constant(DAG, 0x3f949a29, dl)); 5489 } else if (LimitFloatPrecision <= 12) { 5490 // For floating-point precision of 12: 5491 // 5492 // LogOfMantissa = 5493 // -1.7417939f + 5494 // (2.8212026f + 5495 // (-1.4699568f + 5496 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5497 // 5498 // error 0.000061011436, which is 14 bits 5499 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5500 getF32Constant(DAG, 0xbd67b6d6, dl)); 5501 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5502 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5503 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5504 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5505 getF32Constant(DAG, 0x3fbc278b, dl)); 5506 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5507 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5508 getF32Constant(DAG, 0x40348e95, dl)); 5509 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5510 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5511 getF32Constant(DAG, 0x3fdef31a, dl)); 5512 } else { // LimitFloatPrecision <= 18 5513 // For floating-point precision of 18: 5514 // 5515 // LogOfMantissa = 5516 // -2.1072184f + 5517 // (4.2372794f + 5518 // (-3.7029485f + 5519 // (2.2781945f + 5520 // (-0.87823314f + 5521 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5522 // 5523 // error 0.0000023660568, which is better than 18 bits 5524 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5525 getF32Constant(DAG, 0xbc91e5ac, dl)); 5526 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5527 getF32Constant(DAG, 0x3e4350aa, dl)); 5528 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5529 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5530 getF32Constant(DAG, 0x3f60d3e3, dl)); 5531 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5532 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5533 getF32Constant(DAG, 0x4011cdf0, dl)); 5534 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5535 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5536 getF32Constant(DAG, 0x406cfd1c, dl)); 5537 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5538 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5539 getF32Constant(DAG, 0x408797cb, dl)); 5540 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5541 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5542 getF32Constant(DAG, 0x4006dcab, dl)); 5543 } 5544 5545 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5546 } 5547 5548 // No special expansion. 5549 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5550 } 5551 5552 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5553 /// limited-precision mode. 5554 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5555 const TargetLowering &TLI, SDNodeFlags Flags) { 5556 // TODO: What fast-math-flags should be set on the floating-point nodes? 5557 5558 if (Op.getValueType() == MVT::f32 && 5559 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5560 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5561 5562 // Get the exponent. 5563 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5564 5565 // Get the significand and build it into a floating-point number with 5566 // exponent of 1. 5567 SDValue X = GetSignificand(DAG, Op1, dl); 5568 5569 // Different possible minimax approximations of significand in 5570 // floating-point for various degrees of accuracy over [1,2]. 5571 SDValue Log2ofMantissa; 5572 if (LimitFloatPrecision <= 6) { 5573 // For floating-point precision of 6: 5574 // 5575 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5576 // 5577 // error 0.0049451742, which is more than 7 bits 5578 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5579 getF32Constant(DAG, 0xbeb08fe0, dl)); 5580 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5581 getF32Constant(DAG, 0x40019463, dl)); 5582 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5583 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5584 getF32Constant(DAG, 0x3fd6633d, dl)); 5585 } else if (LimitFloatPrecision <= 12) { 5586 // For floating-point precision of 12: 5587 // 5588 // Log2ofMantissa = 5589 // -2.51285454f + 5590 // (4.07009056f + 5591 // (-2.12067489f + 5592 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5593 // 5594 // error 0.0000876136000, which is better than 13 bits 5595 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5596 getF32Constant(DAG, 0xbda7262e, dl)); 5597 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5598 getF32Constant(DAG, 0x3f25280b, dl)); 5599 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5600 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5601 getF32Constant(DAG, 0x4007b923, dl)); 5602 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5603 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5604 getF32Constant(DAG, 0x40823e2f, dl)); 5605 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5606 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5607 getF32Constant(DAG, 0x4020d29c, dl)); 5608 } else { // LimitFloatPrecision <= 18 5609 // For floating-point precision of 18: 5610 // 5611 // Log2ofMantissa = 5612 // -3.0400495f + 5613 // (6.1129976f + 5614 // (-5.3420409f + 5615 // (3.2865683f + 5616 // (-1.2669343f + 5617 // (0.27515199f - 5618 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5619 // 5620 // error 0.0000018516, which is better than 18 bits 5621 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5622 getF32Constant(DAG, 0xbcd2769e, dl)); 5623 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5624 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5625 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5626 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5627 getF32Constant(DAG, 0x3fa22ae7, dl)); 5628 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5629 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5630 getF32Constant(DAG, 0x40525723, dl)); 5631 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5632 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5633 getF32Constant(DAG, 0x40aaf200, dl)); 5634 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5635 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5636 getF32Constant(DAG, 0x40c39dad, dl)); 5637 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5638 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5639 getF32Constant(DAG, 0x4042902c, dl)); 5640 } 5641 5642 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5643 } 5644 5645 // No special expansion. 5646 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5647 } 5648 5649 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5650 /// limited-precision mode. 5651 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5652 const TargetLowering &TLI, SDNodeFlags Flags) { 5653 // TODO: What fast-math-flags should be set on the floating-point nodes? 5654 5655 if (Op.getValueType() == MVT::f32 && 5656 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5657 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5658 5659 // Scale the exponent by log10(2) [0.30102999f]. 5660 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5661 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5662 getF32Constant(DAG, 0x3e9a209a, dl)); 5663 5664 // Get the significand and build it into a floating-point number with 5665 // exponent of 1. 5666 SDValue X = GetSignificand(DAG, Op1, dl); 5667 5668 SDValue Log10ofMantissa; 5669 if (LimitFloatPrecision <= 6) { 5670 // For floating-point precision of 6: 5671 // 5672 // Log10ofMantissa = 5673 // -0.50419619f + 5674 // (0.60948995f - 0.10380950f * x) * x; 5675 // 5676 // error 0.0014886165, which is 6 bits 5677 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5678 getF32Constant(DAG, 0xbdd49a13, dl)); 5679 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5680 getF32Constant(DAG, 0x3f1c0789, dl)); 5681 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5682 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5683 getF32Constant(DAG, 0x3f011300, dl)); 5684 } else if (LimitFloatPrecision <= 12) { 5685 // For floating-point precision of 12: 5686 // 5687 // Log10ofMantissa = 5688 // -0.64831180f + 5689 // (0.91751397f + 5690 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5691 // 5692 // error 0.00019228036, which is better than 12 bits 5693 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5694 getF32Constant(DAG, 0x3d431f31, dl)); 5695 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5696 getF32Constant(DAG, 0x3ea21fb2, dl)); 5697 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5698 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5699 getF32Constant(DAG, 0x3f6ae232, dl)); 5700 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5701 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5702 getF32Constant(DAG, 0x3f25f7c3, dl)); 5703 } else { // LimitFloatPrecision <= 18 5704 // For floating-point precision of 18: 5705 // 5706 // Log10ofMantissa = 5707 // -0.84299375f + 5708 // (1.5327582f + 5709 // (-1.0688956f + 5710 // (0.49102474f + 5711 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5712 // 5713 // error 0.0000037995730, which is better than 18 bits 5714 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5715 getF32Constant(DAG, 0x3c5d51ce, dl)); 5716 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5717 getF32Constant(DAG, 0x3e00685a, dl)); 5718 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5719 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5720 getF32Constant(DAG, 0x3efb6798, dl)); 5721 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5722 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5723 getF32Constant(DAG, 0x3f88d192, dl)); 5724 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5725 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5726 getF32Constant(DAG, 0x3fc4316c, dl)); 5727 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5728 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5729 getF32Constant(DAG, 0x3f57ce70, dl)); 5730 } 5731 5732 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5733 } 5734 5735 // No special expansion. 5736 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5737 } 5738 5739 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5740 /// limited-precision mode. 5741 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5742 const TargetLowering &TLI, SDNodeFlags Flags) { 5743 if (Op.getValueType() == MVT::f32 && 5744 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5745 return getLimitedPrecisionExp2(Op, dl, DAG); 5746 5747 // No special expansion. 5748 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5749 } 5750 5751 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5752 /// limited-precision mode with x == 10.0f. 5753 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5754 SelectionDAG &DAG, const TargetLowering &TLI, 5755 SDNodeFlags Flags) { 5756 bool IsExp10 = false; 5757 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5758 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5759 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5760 APFloat Ten(10.0f); 5761 IsExp10 = LHSC->isExactlyValue(Ten); 5762 } 5763 } 5764 5765 // TODO: What fast-math-flags should be set on the FMUL node? 5766 if (IsExp10) { 5767 // Put the exponent in the right bit position for later addition to the 5768 // final result: 5769 // 5770 // #define LOG2OF10 3.3219281f 5771 // t0 = Op * LOG2OF10; 5772 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5773 getF32Constant(DAG, 0x40549a78, dl)); 5774 return getLimitedPrecisionExp2(t0, dl, DAG); 5775 } 5776 5777 // No special expansion. 5778 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5779 } 5780 5781 /// ExpandPowI - Expand a llvm.powi intrinsic. 5782 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5783 SelectionDAG &DAG) { 5784 // If RHS is a constant, we can expand this out to a multiplication tree if 5785 // it's beneficial on the target, otherwise we end up lowering to a call to 5786 // __powidf2 (for example). 5787 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5788 unsigned Val = RHSC->getSExtValue(); 5789 5790 // powi(x, 0) -> 1.0 5791 if (Val == 0) 5792 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5793 5794 if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI( 5795 Val, DAG.shouldOptForSize())) { 5796 // Get the exponent as a positive value. 5797 if ((int)Val < 0) 5798 Val = -Val; 5799 // We use the simple binary decomposition method to generate the multiply 5800 // sequence. There are more optimal ways to do this (for example, 5801 // powi(x,15) generates one more multiply than it should), but this has 5802 // the benefit of being both really simple and much better than a libcall. 5803 SDValue Res; // Logically starts equal to 1.0 5804 SDValue CurSquare = LHS; 5805 // TODO: Intrinsics should have fast-math-flags that propagate to these 5806 // nodes. 5807 while (Val) { 5808 if (Val & 1) { 5809 if (Res.getNode()) 5810 Res = 5811 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare); 5812 else 5813 Res = CurSquare; // 1.0*CurSquare. 5814 } 5815 5816 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5817 CurSquare, CurSquare); 5818 Val >>= 1; 5819 } 5820 5821 // If the original was negative, invert the result, producing 1/(x*x*x). 5822 if (RHSC->getSExtValue() < 0) 5823 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5824 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5825 return Res; 5826 } 5827 } 5828 5829 // Otherwise, expand to a libcall. 5830 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5831 } 5832 5833 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5834 SDValue LHS, SDValue RHS, SDValue Scale, 5835 SelectionDAG &DAG, const TargetLowering &TLI) { 5836 EVT VT = LHS.getValueType(); 5837 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5838 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5839 LLVMContext &Ctx = *DAG.getContext(); 5840 5841 // If the type is legal but the operation isn't, this node might survive all 5842 // the way to operation legalization. If we end up there and we do not have 5843 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5844 // node. 5845 5846 // Coax the legalizer into expanding the node during type legalization instead 5847 // by bumping the size by one bit. This will force it to Promote, enabling the 5848 // early expansion and avoiding the need to expand later. 5849 5850 // We don't have to do this if Scale is 0; that can always be expanded, unless 5851 // it's a saturating signed operation. Those can experience true integer 5852 // division overflow, a case which we must avoid. 5853 5854 // FIXME: We wouldn't have to do this (or any of the early 5855 // expansion/promotion) if it was possible to expand a libcall of an 5856 // illegal type during operation legalization. But it's not, so things 5857 // get a bit hacky. 5858 unsigned ScaleInt = Scale->getAsZExtVal(); 5859 if ((ScaleInt > 0 || (Saturating && Signed)) && 5860 (TLI.isTypeLegal(VT) || 5861 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5862 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5863 Opcode, VT, ScaleInt); 5864 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5865 EVT PromVT; 5866 if (VT.isScalarInteger()) 5867 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5868 else if (VT.isVector()) { 5869 PromVT = VT.getVectorElementType(); 5870 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5871 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5872 } else 5873 llvm_unreachable("Wrong VT for DIVFIX?"); 5874 LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT); 5875 RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT); 5876 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5877 // For saturating operations, we need to shift up the LHS to get the 5878 // proper saturation width, and then shift down again afterwards. 5879 if (Saturating) 5880 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5881 DAG.getConstant(1, DL, ShiftTy)); 5882 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5883 if (Saturating) 5884 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5885 DAG.getConstant(1, DL, ShiftTy)); 5886 return DAG.getZExtOrTrunc(Res, DL, VT); 5887 } 5888 } 5889 5890 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5891 } 5892 5893 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5894 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5895 static void 5896 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5897 const SDValue &N) { 5898 switch (N.getOpcode()) { 5899 case ISD::CopyFromReg: { 5900 SDValue Op = N.getOperand(1); 5901 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5902 Op.getValueType().getSizeInBits()); 5903 return; 5904 } 5905 case ISD::BITCAST: 5906 case ISD::AssertZext: 5907 case ISD::AssertSext: 5908 case ISD::TRUNCATE: 5909 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5910 return; 5911 case ISD::BUILD_PAIR: 5912 case ISD::BUILD_VECTOR: 5913 case ISD::CONCAT_VECTORS: 5914 for (SDValue Op : N->op_values()) 5915 getUnderlyingArgRegs(Regs, Op); 5916 return; 5917 default: 5918 return; 5919 } 5920 } 5921 5922 /// If the DbgValueInst is a dbg_value of a function argument, create the 5923 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5924 /// instruction selection, they will be inserted to the entry BB. 5925 /// We don't currently support this for variadic dbg_values, as they shouldn't 5926 /// appear for function arguments or in the prologue. 5927 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5928 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5929 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) { 5930 const Argument *Arg = dyn_cast<Argument>(V); 5931 if (!Arg) 5932 return false; 5933 5934 MachineFunction &MF = DAG.getMachineFunction(); 5935 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5936 5937 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind 5938 // we've been asked to pursue. 5939 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr, 5940 bool Indirect) { 5941 if (Reg.isVirtual() && MF.useDebugInstrRef()) { 5942 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF 5943 // pointing at the VReg, which will be patched up later. 5944 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF); 5945 SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg( 5946 /* Reg */ Reg, /* isDef */ false, /* isImp */ false, 5947 /* isKill */ false, /* isDead */ false, 5948 /* isUndef */ false, /* isEarlyClobber */ false, 5949 /* SubReg */ 0, /* isDebug */ true)}); 5950 5951 auto *NewDIExpr = FragExpr; 5952 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into 5953 // the DIExpression. 5954 if (Indirect) 5955 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore); 5956 SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0}); 5957 NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops); 5958 return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr); 5959 } else { 5960 // Create a completely standard DBG_VALUE. 5961 auto &Inst = TII->get(TargetOpcode::DBG_VALUE); 5962 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr); 5963 } 5964 }; 5965 5966 if (Kind == FuncArgumentDbgValueKind::Value) { 5967 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5968 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5969 // the entry block. 5970 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5971 if (!IsInEntryBlock) 5972 return false; 5973 5974 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5975 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5976 // variable that also is a param. 5977 // 5978 // Although, if we are at the top of the entry block already, we can still 5979 // emit using ArgDbgValue. This might catch some situations when the 5980 // dbg.value refers to an argument that isn't used in the entry block, so 5981 // any CopyToReg node would be optimized out and the only way to express 5982 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5983 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5984 // we should only emit as ArgDbgValue if the Variable is an argument to the 5985 // current function, and the dbg.value intrinsic is found in the entry 5986 // block. 5987 bool VariableIsFunctionInputArg = Variable->isParameter() && 5988 !DL->getInlinedAt(); 5989 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5990 if (!IsInPrologue && !VariableIsFunctionInputArg) 5991 return false; 5992 5993 // Here we assume that a function argument on IR level only can be used to 5994 // describe one input parameter on source level. If we for example have 5995 // source code like this 5996 // 5997 // struct A { long x, y; }; 5998 // void foo(struct A a, long b) { 5999 // ... 6000 // b = a.x; 6001 // ... 6002 // } 6003 // 6004 // and IR like this 6005 // 6006 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 6007 // entry: 6008 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 6009 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 6010 // call void @llvm.dbg.value(metadata i32 %b, "b", 6011 // ... 6012 // call void @llvm.dbg.value(metadata i32 %a1, "b" 6013 // ... 6014 // 6015 // then the last dbg.value is describing a parameter "b" using a value that 6016 // is an argument. But since we already has used %a1 to describe a parameter 6017 // we should not handle that last dbg.value here (that would result in an 6018 // incorrect hoisting of the DBG_VALUE to the function entry). 6019 // Notice that we allow one dbg.value per IR level argument, to accommodate 6020 // for the situation with fragments above. 6021 // If there is no node for the value being handled, we return true to skip 6022 // the normal generation of debug info, as it would kill existing debug 6023 // info for the parameter in case of duplicates. 6024 if (VariableIsFunctionInputArg) { 6025 unsigned ArgNo = Arg->getArgNo(); 6026 if (ArgNo >= FuncInfo.DescribedArgs.size()) 6027 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 6028 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 6029 return !NodeMap[V].getNode(); 6030 FuncInfo.DescribedArgs.set(ArgNo); 6031 } 6032 } 6033 6034 bool IsIndirect = false; 6035 std::optional<MachineOperand> Op; 6036 // Some arguments' frame index is recorded during argument lowering. 6037 int FI = FuncInfo.getArgumentFrameIndex(Arg); 6038 if (FI != std::numeric_limits<int>::max()) 6039 Op = MachineOperand::CreateFI(FI); 6040 6041 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 6042 if (!Op && N.getNode()) { 6043 getUnderlyingArgRegs(ArgRegsAndSizes, N); 6044 Register Reg; 6045 if (ArgRegsAndSizes.size() == 1) 6046 Reg = ArgRegsAndSizes.front().first; 6047 6048 if (Reg && Reg.isVirtual()) { 6049 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 6050 Register PR = RegInfo.getLiveInPhysReg(Reg); 6051 if (PR) 6052 Reg = PR; 6053 } 6054 if (Reg) { 6055 Op = MachineOperand::CreateReg(Reg, false); 6056 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 6057 } 6058 } 6059 6060 if (!Op && N.getNode()) { 6061 // Check if frame index is available. 6062 SDValue LCandidate = peekThroughBitcasts(N); 6063 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 6064 if (FrameIndexSDNode *FINode = 6065 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 6066 Op = MachineOperand::CreateFI(FINode->getIndex()); 6067 } 6068 6069 if (!Op) { 6070 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 6071 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 6072 SplitRegs) { 6073 unsigned Offset = 0; 6074 for (const auto &RegAndSize : SplitRegs) { 6075 // If the expression is already a fragment, the current register 6076 // offset+size might extend beyond the fragment. In this case, only 6077 // the register bits that are inside the fragment are relevant. 6078 int RegFragmentSizeInBits = RegAndSize.second; 6079 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 6080 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 6081 // The register is entirely outside the expression fragment, 6082 // so is irrelevant for debug info. 6083 if (Offset >= ExprFragmentSizeInBits) 6084 break; 6085 // The register is partially outside the expression fragment, only 6086 // the low bits within the fragment are relevant for debug info. 6087 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 6088 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 6089 } 6090 } 6091 6092 auto FragmentExpr = DIExpression::createFragmentExpression( 6093 Expr, Offset, RegFragmentSizeInBits); 6094 Offset += RegAndSize.second; 6095 // If a valid fragment expression cannot be created, the variable's 6096 // correct value cannot be determined and so it is set as Undef. 6097 if (!FragmentExpr) { 6098 SDDbgValue *SDV = DAG.getConstantDbgValue( 6099 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 6100 DAG.AddDbgValue(SDV, false); 6101 continue; 6102 } 6103 MachineInstr *NewMI = 6104 MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, 6105 Kind != FuncArgumentDbgValueKind::Value); 6106 FuncInfo.ArgDbgValues.push_back(NewMI); 6107 } 6108 }; 6109 6110 // Check if ValueMap has reg number. 6111 DenseMap<const Value *, Register>::const_iterator 6112 VMI = FuncInfo.ValueMap.find(V); 6113 if (VMI != FuncInfo.ValueMap.end()) { 6114 const auto &TLI = DAG.getTargetLoweringInfo(); 6115 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 6116 V->getType(), std::nullopt); 6117 if (RFV.occupiesMultipleRegs()) { 6118 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 6119 return true; 6120 } 6121 6122 Op = MachineOperand::CreateReg(VMI->second, false); 6123 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 6124 } else if (ArgRegsAndSizes.size() > 1) { 6125 // This was split due to the calling convention, and no virtual register 6126 // mapping exists for the value. 6127 splitMultiRegDbgValue(ArgRegsAndSizes); 6128 return true; 6129 } 6130 } 6131 6132 if (!Op) 6133 return false; 6134 6135 assert(Variable->isValidLocationForIntrinsic(DL) && 6136 "Expected inlined-at fields to agree"); 6137 MachineInstr *NewMI = nullptr; 6138 6139 if (Op->isReg()) 6140 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect); 6141 else 6142 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op, 6143 Variable, Expr); 6144 6145 // Otherwise, use ArgDbgValues. 6146 FuncInfo.ArgDbgValues.push_back(NewMI); 6147 return true; 6148 } 6149 6150 /// Return the appropriate SDDbgValue based on N. 6151 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 6152 DILocalVariable *Variable, 6153 DIExpression *Expr, 6154 const DebugLoc &dl, 6155 unsigned DbgSDNodeOrder) { 6156 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 6157 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 6158 // stack slot locations. 6159 // 6160 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 6161 // debug values here after optimization: 6162 // 6163 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 6164 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 6165 // 6166 // Both describe the direct values of their associated variables. 6167 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 6168 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 6169 } 6170 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 6171 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 6172 } 6173 6174 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 6175 switch (Intrinsic) { 6176 case Intrinsic::smul_fix: 6177 return ISD::SMULFIX; 6178 case Intrinsic::umul_fix: 6179 return ISD::UMULFIX; 6180 case Intrinsic::smul_fix_sat: 6181 return ISD::SMULFIXSAT; 6182 case Intrinsic::umul_fix_sat: 6183 return ISD::UMULFIXSAT; 6184 case Intrinsic::sdiv_fix: 6185 return ISD::SDIVFIX; 6186 case Intrinsic::udiv_fix: 6187 return ISD::UDIVFIX; 6188 case Intrinsic::sdiv_fix_sat: 6189 return ISD::SDIVFIXSAT; 6190 case Intrinsic::udiv_fix_sat: 6191 return ISD::UDIVFIXSAT; 6192 default: 6193 llvm_unreachable("Unhandled fixed point intrinsic"); 6194 } 6195 } 6196 6197 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 6198 const char *FunctionName) { 6199 assert(FunctionName && "FunctionName must not be nullptr"); 6200 SDValue Callee = DAG.getExternalSymbol( 6201 FunctionName, 6202 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 6203 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 6204 } 6205 6206 /// Given a @llvm.call.preallocated.setup, return the corresponding 6207 /// preallocated call. 6208 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 6209 assert(cast<CallBase>(PreallocatedSetup) 6210 ->getCalledFunction() 6211 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 6212 "expected call_preallocated_setup Value"); 6213 for (const auto *U : PreallocatedSetup->users()) { 6214 auto *UseCall = cast<CallBase>(U); 6215 const Function *Fn = UseCall->getCalledFunction(); 6216 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 6217 return UseCall; 6218 } 6219 } 6220 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 6221 } 6222 6223 /// If DI is a debug value with an EntryValue expression, lower it using the 6224 /// corresponding physical register of the associated Argument value 6225 /// (guaranteed to exist by the verifier). 6226 bool SelectionDAGBuilder::visitEntryValueDbgValue( 6227 ArrayRef<const Value *> Values, DILocalVariable *Variable, 6228 DIExpression *Expr, DebugLoc DbgLoc) { 6229 if (!Expr->isEntryValue() || !hasSingleElement(Values)) 6230 return false; 6231 6232 // These properties are guaranteed by the verifier. 6233 const Argument *Arg = cast<Argument>(Values[0]); 6234 assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync)); 6235 6236 auto ArgIt = FuncInfo.ValueMap.find(Arg); 6237 if (ArgIt == FuncInfo.ValueMap.end()) { 6238 LLVM_DEBUG( 6239 dbgs() << "Dropping dbg.value: expression is entry_value but " 6240 "couldn't find an associated register for the Argument\n"); 6241 return true; 6242 } 6243 Register ArgVReg = ArgIt->getSecond(); 6244 6245 for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins()) 6246 if (ArgVReg == VirtReg || ArgVReg == PhysReg) { 6247 SDDbgValue *SDV = DAG.getVRegDbgValue( 6248 Variable, Expr, PhysReg, false /*IsIndidrect*/, DbgLoc, SDNodeOrder); 6249 DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/); 6250 return true; 6251 } 6252 LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but " 6253 "couldn't find a physical register\n"); 6254 return true; 6255 } 6256 6257 /// Lower the call to the specified intrinsic function. 6258 void SelectionDAGBuilder::visitConvergenceControl(const CallInst &I, 6259 unsigned Intrinsic) { 6260 SDLoc sdl = getCurSDLoc(); 6261 switch (Intrinsic) { 6262 case Intrinsic::experimental_convergence_anchor: 6263 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ANCHOR, sdl, MVT::Untyped)); 6264 break; 6265 case Intrinsic::experimental_convergence_entry: 6266 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ENTRY, sdl, MVT::Untyped)); 6267 break; 6268 case Intrinsic::experimental_convergence_loop: { 6269 auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl); 6270 auto *Token = Bundle->Inputs[0].get(); 6271 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_LOOP, sdl, MVT::Untyped, 6272 getValue(Token))); 6273 break; 6274 } 6275 } 6276 } 6277 6278 void SelectionDAGBuilder::visitVectorHistogram(const CallInst &I, 6279 unsigned IntrinsicID) { 6280 // For now, we're only lowering an 'add' histogram. 6281 // We can add others later, e.g. saturating adds, min/max. 6282 assert(IntrinsicID == Intrinsic::experimental_vector_histogram_add && 6283 "Tried to lower unsupported histogram type"); 6284 SDLoc sdl = getCurSDLoc(); 6285 Value *Ptr = I.getOperand(0); 6286 SDValue Inc = getValue(I.getOperand(1)); 6287 SDValue Mask = getValue(I.getOperand(2)); 6288 6289 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6290 DataLayout TargetDL = DAG.getDataLayout(); 6291 EVT VT = Inc.getValueType(); 6292 Align Alignment = DAG.getEVTAlign(VT); 6293 6294 const MDNode *Ranges = getRangeMetadata(I); 6295 6296 SDValue Root = DAG.getRoot(); 6297 SDValue Base; 6298 SDValue Index; 6299 ISD::MemIndexType IndexType; 6300 SDValue Scale; 6301 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 6302 I.getParent(), VT.getScalarStoreSize()); 6303 6304 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 6305 6306 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 6307 MachinePointerInfo(AS), 6308 MachineMemOperand::MOLoad | MachineMemOperand::MOStore, 6309 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges); 6310 6311 if (!UniformBase) { 6312 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 6313 Index = getValue(Ptr); 6314 IndexType = ISD::SIGNED_SCALED; 6315 Scale = 6316 DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 6317 } 6318 6319 EVT IdxVT = Index.getValueType(); 6320 EVT EltTy = IdxVT.getVectorElementType(); 6321 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 6322 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 6323 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 6324 } 6325 6326 SDValue ID = DAG.getTargetConstant(IntrinsicID, sdl, MVT::i32); 6327 6328 SDValue Ops[] = {Root, Inc, Mask, Base, Index, Scale, ID}; 6329 SDValue Histogram = DAG.getMaskedHistogram(DAG.getVTList(MVT::Other), VT, sdl, 6330 Ops, MMO, IndexType); 6331 6332 setValue(&I, Histogram); 6333 DAG.setRoot(Histogram); 6334 } 6335 6336 /// Lower the call to the specified intrinsic function. 6337 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 6338 unsigned Intrinsic) { 6339 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6340 SDLoc sdl = getCurSDLoc(); 6341 DebugLoc dl = getCurDebugLoc(); 6342 SDValue Res; 6343 6344 SDNodeFlags Flags; 6345 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 6346 Flags.copyFMF(*FPOp); 6347 6348 switch (Intrinsic) { 6349 default: 6350 // By default, turn this into a target intrinsic node. 6351 visitTargetIntrinsic(I, Intrinsic); 6352 return; 6353 case Intrinsic::vscale: { 6354 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6355 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1))); 6356 return; 6357 } 6358 case Intrinsic::vastart: visitVAStart(I); return; 6359 case Intrinsic::vaend: visitVAEnd(I); return; 6360 case Intrinsic::vacopy: visitVACopy(I); return; 6361 case Intrinsic::returnaddress: 6362 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 6363 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6364 getValue(I.getArgOperand(0)))); 6365 return; 6366 case Intrinsic::addressofreturnaddress: 6367 setValue(&I, 6368 DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 6369 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 6370 return; 6371 case Intrinsic::sponentry: 6372 setValue(&I, 6373 DAG.getNode(ISD::SPONENTRY, sdl, 6374 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 6375 return; 6376 case Intrinsic::frameaddress: 6377 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 6378 TLI.getFrameIndexTy(DAG.getDataLayout()), 6379 getValue(I.getArgOperand(0)))); 6380 return; 6381 case Intrinsic::read_volatile_register: 6382 case Intrinsic::read_register: { 6383 Value *Reg = I.getArgOperand(0); 6384 SDValue Chain = getRoot(); 6385 SDValue RegName = 6386 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 6387 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6388 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 6389 DAG.getVTList(VT, MVT::Other), Chain, RegName); 6390 setValue(&I, Res); 6391 DAG.setRoot(Res.getValue(1)); 6392 return; 6393 } 6394 case Intrinsic::write_register: { 6395 Value *Reg = I.getArgOperand(0); 6396 Value *RegValue = I.getArgOperand(1); 6397 SDValue Chain = getRoot(); 6398 SDValue RegName = 6399 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 6400 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 6401 RegName, getValue(RegValue))); 6402 return; 6403 } 6404 case Intrinsic::memcpy: { 6405 const auto &MCI = cast<MemCpyInst>(I); 6406 SDValue Op1 = getValue(I.getArgOperand(0)); 6407 SDValue Op2 = getValue(I.getArgOperand(1)); 6408 SDValue Op3 = getValue(I.getArgOperand(2)); 6409 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 6410 Align DstAlign = MCI.getDestAlign().valueOrOne(); 6411 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 6412 Align Alignment = std::min(DstAlign, SrcAlign); 6413 bool isVol = MCI.isVolatile(); 6414 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6415 // FIXME: Support passing different dest/src alignments to the memcpy DAG 6416 // node. 6417 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6418 SDValue MC = DAG.getMemcpy( 6419 Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6420 /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)), 6421 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 6422 updateDAGForMaybeTailCall(MC); 6423 return; 6424 } 6425 case Intrinsic::memcpy_inline: { 6426 const auto &MCI = cast<MemCpyInlineInst>(I); 6427 SDValue Dst = getValue(I.getArgOperand(0)); 6428 SDValue Src = getValue(I.getArgOperand(1)); 6429 SDValue Size = getValue(I.getArgOperand(2)); 6430 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 6431 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 6432 Align DstAlign = MCI.getDestAlign().valueOrOne(); 6433 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 6434 Align Alignment = std::min(DstAlign, SrcAlign); 6435 bool isVol = MCI.isVolatile(); 6436 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6437 // FIXME: Support passing different dest/src alignments to the memcpy DAG 6438 // node. 6439 SDValue MC = DAG.getMemcpy( 6440 getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 6441 /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)), 6442 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 6443 updateDAGForMaybeTailCall(MC); 6444 return; 6445 } 6446 case Intrinsic::memset: { 6447 const auto &MSI = cast<MemSetInst>(I); 6448 SDValue Op1 = getValue(I.getArgOperand(0)); 6449 SDValue Op2 = getValue(I.getArgOperand(1)); 6450 SDValue Op3 = getValue(I.getArgOperand(2)); 6451 // @llvm.memset defines 0 and 1 to both mean no alignment. 6452 Align Alignment = MSI.getDestAlign().valueOrOne(); 6453 bool isVol = MSI.isVolatile(); 6454 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6455 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6456 SDValue MS = DAG.getMemset( 6457 Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false, 6458 isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata()); 6459 updateDAGForMaybeTailCall(MS); 6460 return; 6461 } 6462 case Intrinsic::memset_inline: { 6463 const auto &MSII = cast<MemSetInlineInst>(I); 6464 SDValue Dst = getValue(I.getArgOperand(0)); 6465 SDValue Value = getValue(I.getArgOperand(1)); 6466 SDValue Size = getValue(I.getArgOperand(2)); 6467 assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size"); 6468 // @llvm.memset defines 0 and 1 to both mean no alignment. 6469 Align DstAlign = MSII.getDestAlign().valueOrOne(); 6470 bool isVol = MSII.isVolatile(); 6471 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6472 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6473 SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol, 6474 /* AlwaysInline */ true, isTC, 6475 MachinePointerInfo(I.getArgOperand(0)), 6476 I.getAAMetadata()); 6477 updateDAGForMaybeTailCall(MC); 6478 return; 6479 } 6480 case Intrinsic::memmove: { 6481 const auto &MMI = cast<MemMoveInst>(I); 6482 SDValue Op1 = getValue(I.getArgOperand(0)); 6483 SDValue Op2 = getValue(I.getArgOperand(1)); 6484 SDValue Op3 = getValue(I.getArgOperand(2)); 6485 // @llvm.memmove defines 0 and 1 to both mean no alignment. 6486 Align DstAlign = MMI.getDestAlign().valueOrOne(); 6487 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 6488 Align Alignment = std::min(DstAlign, SrcAlign); 6489 bool isVol = MMI.isVolatile(); 6490 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6491 // FIXME: Support passing different dest/src alignments to the memmove DAG 6492 // node. 6493 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6494 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6495 isTC, MachinePointerInfo(I.getArgOperand(0)), 6496 MachinePointerInfo(I.getArgOperand(1)), 6497 I.getAAMetadata(), AA); 6498 updateDAGForMaybeTailCall(MM); 6499 return; 6500 } 6501 case Intrinsic::memcpy_element_unordered_atomic: { 6502 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 6503 SDValue Dst = getValue(MI.getRawDest()); 6504 SDValue Src = getValue(MI.getRawSource()); 6505 SDValue Length = getValue(MI.getLength()); 6506 6507 Type *LengthTy = MI.getLength()->getType(); 6508 unsigned ElemSz = MI.getElementSizeInBytes(); 6509 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6510 SDValue MC = 6511 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6512 isTC, MachinePointerInfo(MI.getRawDest()), 6513 MachinePointerInfo(MI.getRawSource())); 6514 updateDAGForMaybeTailCall(MC); 6515 return; 6516 } 6517 case Intrinsic::memmove_element_unordered_atomic: { 6518 auto &MI = cast<AtomicMemMoveInst>(I); 6519 SDValue Dst = getValue(MI.getRawDest()); 6520 SDValue Src = getValue(MI.getRawSource()); 6521 SDValue Length = getValue(MI.getLength()); 6522 6523 Type *LengthTy = MI.getLength()->getType(); 6524 unsigned ElemSz = MI.getElementSizeInBytes(); 6525 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6526 SDValue MC = 6527 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6528 isTC, MachinePointerInfo(MI.getRawDest()), 6529 MachinePointerInfo(MI.getRawSource())); 6530 updateDAGForMaybeTailCall(MC); 6531 return; 6532 } 6533 case Intrinsic::memset_element_unordered_atomic: { 6534 auto &MI = cast<AtomicMemSetInst>(I); 6535 SDValue Dst = getValue(MI.getRawDest()); 6536 SDValue Val = getValue(MI.getValue()); 6537 SDValue Length = getValue(MI.getLength()); 6538 6539 Type *LengthTy = MI.getLength()->getType(); 6540 unsigned ElemSz = MI.getElementSizeInBytes(); 6541 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6542 SDValue MC = 6543 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz, 6544 isTC, MachinePointerInfo(MI.getRawDest())); 6545 updateDAGForMaybeTailCall(MC); 6546 return; 6547 } 6548 case Intrinsic::call_preallocated_setup: { 6549 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 6550 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6551 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 6552 getRoot(), SrcValue); 6553 setValue(&I, Res); 6554 DAG.setRoot(Res); 6555 return; 6556 } 6557 case Intrinsic::call_preallocated_arg: { 6558 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 6559 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6560 SDValue Ops[3]; 6561 Ops[0] = getRoot(); 6562 Ops[1] = SrcValue; 6563 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 6564 MVT::i32); // arg index 6565 SDValue Res = DAG.getNode( 6566 ISD::PREALLOCATED_ARG, sdl, 6567 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 6568 setValue(&I, Res); 6569 DAG.setRoot(Res.getValue(1)); 6570 return; 6571 } 6572 case Intrinsic::dbg_declare: { 6573 const auto &DI = cast<DbgDeclareInst>(I); 6574 // Debug intrinsics are handled separately in assignment tracking mode. 6575 // Some intrinsics are handled right after Argument lowering. 6576 if (AssignmentTrackingEnabled || 6577 FuncInfo.PreprocessedDbgDeclares.count(&DI)) 6578 return; 6579 LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DI << "\n"); 6580 DILocalVariable *Variable = DI.getVariable(); 6581 DIExpression *Expression = DI.getExpression(); 6582 dropDanglingDebugInfo(Variable, Expression); 6583 // Assume dbg.declare can not currently use DIArgList, i.e. 6584 // it is non-variadic. 6585 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 6586 handleDebugDeclare(DI.getVariableLocationOp(0), Variable, Expression, 6587 DI.getDebugLoc()); 6588 return; 6589 } 6590 case Intrinsic::dbg_label: { 6591 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6592 DILabel *Label = DI.getLabel(); 6593 assert(Label && "Missing label"); 6594 6595 SDDbgLabel *SDV; 6596 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6597 DAG.AddDbgLabel(SDV); 6598 return; 6599 } 6600 case Intrinsic::dbg_assign: { 6601 // Debug intrinsics are handled seperately in assignment tracking mode. 6602 if (AssignmentTrackingEnabled) 6603 return; 6604 // If assignment tracking hasn't been enabled then fall through and treat 6605 // the dbg.assign as a dbg.value. 6606 [[fallthrough]]; 6607 } 6608 case Intrinsic::dbg_value: { 6609 // Debug intrinsics are handled seperately in assignment tracking mode. 6610 if (AssignmentTrackingEnabled) 6611 return; 6612 const DbgValueInst &DI = cast<DbgValueInst>(I); 6613 assert(DI.getVariable() && "Missing variable"); 6614 6615 DILocalVariable *Variable = DI.getVariable(); 6616 DIExpression *Expression = DI.getExpression(); 6617 dropDanglingDebugInfo(Variable, Expression); 6618 6619 if (DI.isKillLocation()) { 6620 handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder); 6621 return; 6622 } 6623 6624 SmallVector<Value *, 4> Values(DI.getValues()); 6625 if (Values.empty()) 6626 return; 6627 6628 bool IsVariadic = DI.hasArgList(); 6629 if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(), 6630 SDNodeOrder, IsVariadic)) 6631 addDanglingDebugInfo(Values, Variable, Expression, IsVariadic, 6632 DI.getDebugLoc(), SDNodeOrder); 6633 return; 6634 } 6635 6636 case Intrinsic::eh_typeid_for: { 6637 // Find the type id for the given typeinfo. 6638 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6639 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6640 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6641 setValue(&I, Res); 6642 return; 6643 } 6644 6645 case Intrinsic::eh_return_i32: 6646 case Intrinsic::eh_return_i64: 6647 DAG.getMachineFunction().setCallsEHReturn(true); 6648 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6649 MVT::Other, 6650 getControlRoot(), 6651 getValue(I.getArgOperand(0)), 6652 getValue(I.getArgOperand(1)))); 6653 return; 6654 case Intrinsic::eh_unwind_init: 6655 DAG.getMachineFunction().setCallsUnwindInit(true); 6656 return; 6657 case Intrinsic::eh_dwarf_cfa: 6658 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6659 TLI.getPointerTy(DAG.getDataLayout()), 6660 getValue(I.getArgOperand(0)))); 6661 return; 6662 case Intrinsic::eh_sjlj_callsite: { 6663 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6664 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0)); 6665 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6666 6667 MMI.setCurrentCallSite(CI->getZExtValue()); 6668 return; 6669 } 6670 case Intrinsic::eh_sjlj_functioncontext: { 6671 // Get and store the index of the function context. 6672 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6673 AllocaInst *FnCtx = 6674 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6675 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6676 MFI.setFunctionContextIndex(FI); 6677 return; 6678 } 6679 case Intrinsic::eh_sjlj_setjmp: { 6680 SDValue Ops[2]; 6681 Ops[0] = getRoot(); 6682 Ops[1] = getValue(I.getArgOperand(0)); 6683 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6684 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6685 setValue(&I, Op.getValue(0)); 6686 DAG.setRoot(Op.getValue(1)); 6687 return; 6688 } 6689 case Intrinsic::eh_sjlj_longjmp: 6690 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6691 getRoot(), getValue(I.getArgOperand(0)))); 6692 return; 6693 case Intrinsic::eh_sjlj_setup_dispatch: 6694 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6695 getRoot())); 6696 return; 6697 case Intrinsic::masked_gather: 6698 visitMaskedGather(I); 6699 return; 6700 case Intrinsic::masked_load: 6701 visitMaskedLoad(I); 6702 return; 6703 case Intrinsic::masked_scatter: 6704 visitMaskedScatter(I); 6705 return; 6706 case Intrinsic::masked_store: 6707 visitMaskedStore(I); 6708 return; 6709 case Intrinsic::masked_expandload: 6710 visitMaskedLoad(I, true /* IsExpanding */); 6711 return; 6712 case Intrinsic::masked_compressstore: 6713 visitMaskedStore(I, true /* IsCompressing */); 6714 return; 6715 case Intrinsic::powi: 6716 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6717 getValue(I.getArgOperand(1)), DAG)); 6718 return; 6719 case Intrinsic::log: 6720 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6721 return; 6722 case Intrinsic::log2: 6723 setValue(&I, 6724 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6725 return; 6726 case Intrinsic::log10: 6727 setValue(&I, 6728 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6729 return; 6730 case Intrinsic::exp: 6731 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6732 return; 6733 case Intrinsic::exp2: 6734 setValue(&I, 6735 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6736 return; 6737 case Intrinsic::pow: 6738 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6739 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6740 return; 6741 case Intrinsic::sqrt: 6742 case Intrinsic::fabs: 6743 case Intrinsic::sin: 6744 case Intrinsic::cos: 6745 case Intrinsic::exp10: 6746 case Intrinsic::floor: 6747 case Intrinsic::ceil: 6748 case Intrinsic::trunc: 6749 case Intrinsic::rint: 6750 case Intrinsic::nearbyint: 6751 case Intrinsic::round: 6752 case Intrinsic::roundeven: 6753 case Intrinsic::canonicalize: { 6754 unsigned Opcode; 6755 // clang-format off 6756 switch (Intrinsic) { 6757 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6758 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6759 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6760 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6761 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6762 case Intrinsic::exp10: Opcode = ISD::FEXP10; break; 6763 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6764 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6765 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6766 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6767 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6768 case Intrinsic::round: Opcode = ISD::FROUND; break; 6769 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6770 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6771 } 6772 // clang-format on 6773 6774 setValue(&I, DAG.getNode(Opcode, sdl, 6775 getValue(I.getArgOperand(0)).getValueType(), 6776 getValue(I.getArgOperand(0)), Flags)); 6777 return; 6778 } 6779 case Intrinsic::lround: 6780 case Intrinsic::llround: 6781 case Intrinsic::lrint: 6782 case Intrinsic::llrint: { 6783 unsigned Opcode; 6784 // clang-format off 6785 switch (Intrinsic) { 6786 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6787 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6788 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6789 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6790 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6791 } 6792 // clang-format on 6793 6794 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6795 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6796 getValue(I.getArgOperand(0)))); 6797 return; 6798 } 6799 case Intrinsic::minnum: 6800 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6801 getValue(I.getArgOperand(0)).getValueType(), 6802 getValue(I.getArgOperand(0)), 6803 getValue(I.getArgOperand(1)), Flags)); 6804 return; 6805 case Intrinsic::maxnum: 6806 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6807 getValue(I.getArgOperand(0)).getValueType(), 6808 getValue(I.getArgOperand(0)), 6809 getValue(I.getArgOperand(1)), Flags)); 6810 return; 6811 case Intrinsic::minimum: 6812 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6813 getValue(I.getArgOperand(0)).getValueType(), 6814 getValue(I.getArgOperand(0)), 6815 getValue(I.getArgOperand(1)), Flags)); 6816 return; 6817 case Intrinsic::maximum: 6818 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6819 getValue(I.getArgOperand(0)).getValueType(), 6820 getValue(I.getArgOperand(0)), 6821 getValue(I.getArgOperand(1)), Flags)); 6822 return; 6823 case Intrinsic::copysign: 6824 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6825 getValue(I.getArgOperand(0)).getValueType(), 6826 getValue(I.getArgOperand(0)), 6827 getValue(I.getArgOperand(1)), Flags)); 6828 return; 6829 case Intrinsic::ldexp: 6830 setValue(&I, DAG.getNode(ISD::FLDEXP, sdl, 6831 getValue(I.getArgOperand(0)).getValueType(), 6832 getValue(I.getArgOperand(0)), 6833 getValue(I.getArgOperand(1)), Flags)); 6834 return; 6835 case Intrinsic::frexp: { 6836 SmallVector<EVT, 2> ValueVTs; 6837 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 6838 SDVTList VTs = DAG.getVTList(ValueVTs); 6839 setValue(&I, 6840 DAG.getNode(ISD::FFREXP, sdl, VTs, getValue(I.getArgOperand(0)))); 6841 return; 6842 } 6843 case Intrinsic::arithmetic_fence: { 6844 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl, 6845 getValue(I.getArgOperand(0)).getValueType(), 6846 getValue(I.getArgOperand(0)), Flags)); 6847 return; 6848 } 6849 case Intrinsic::fma: 6850 setValue(&I, DAG.getNode( 6851 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6852 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6853 getValue(I.getArgOperand(2)), Flags)); 6854 return; 6855 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6856 case Intrinsic::INTRINSIC: 6857 #include "llvm/IR/ConstrainedOps.def" 6858 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6859 return; 6860 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6861 #include "llvm/IR/VPIntrinsics.def" 6862 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6863 return; 6864 case Intrinsic::fptrunc_round: { 6865 // Get the last argument, the metadata and convert it to an integer in the 6866 // call 6867 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata(); 6868 std::optional<RoundingMode> RoundMode = 6869 convertStrToRoundingMode(cast<MDString>(MD)->getString()); 6870 6871 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6872 6873 // Propagate fast-math-flags from IR to node(s). 6874 SDNodeFlags Flags; 6875 Flags.copyFMF(*cast<FPMathOperator>(&I)); 6876 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 6877 6878 SDValue Result; 6879 Result = DAG.getNode( 6880 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)), 6881 DAG.getTargetConstant((int)*RoundMode, sdl, 6882 TLI.getPointerTy(DAG.getDataLayout()))); 6883 setValue(&I, Result); 6884 6885 return; 6886 } 6887 case Intrinsic::fmuladd: { 6888 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6889 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6890 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6891 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6892 getValue(I.getArgOperand(0)).getValueType(), 6893 getValue(I.getArgOperand(0)), 6894 getValue(I.getArgOperand(1)), 6895 getValue(I.getArgOperand(2)), Flags)); 6896 } else { 6897 // TODO: Intrinsic calls should have fast-math-flags. 6898 SDValue Mul = DAG.getNode( 6899 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6900 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6901 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6902 getValue(I.getArgOperand(0)).getValueType(), 6903 Mul, getValue(I.getArgOperand(2)), Flags); 6904 setValue(&I, Add); 6905 } 6906 return; 6907 } 6908 case Intrinsic::convert_to_fp16: 6909 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6910 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6911 getValue(I.getArgOperand(0)), 6912 DAG.getTargetConstant(0, sdl, 6913 MVT::i32)))); 6914 return; 6915 case Intrinsic::convert_from_fp16: 6916 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6917 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6918 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6919 getValue(I.getArgOperand(0))))); 6920 return; 6921 case Intrinsic::fptosi_sat: { 6922 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6923 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 6924 getValue(I.getArgOperand(0)), 6925 DAG.getValueType(VT.getScalarType()))); 6926 return; 6927 } 6928 case Intrinsic::fptoui_sat: { 6929 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6930 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 6931 getValue(I.getArgOperand(0)), 6932 DAG.getValueType(VT.getScalarType()))); 6933 return; 6934 } 6935 case Intrinsic::set_rounding: 6936 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6937 {getRoot(), getValue(I.getArgOperand(0))}); 6938 setValue(&I, Res); 6939 DAG.setRoot(Res.getValue(0)); 6940 return; 6941 case Intrinsic::is_fpclass: { 6942 const DataLayout DLayout = DAG.getDataLayout(); 6943 EVT DestVT = TLI.getValueType(DLayout, I.getType()); 6944 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType()); 6945 FPClassTest Test = static_cast<FPClassTest>( 6946 cast<ConstantInt>(I.getArgOperand(1))->getZExtValue()); 6947 MachineFunction &MF = DAG.getMachineFunction(); 6948 const Function &F = MF.getFunction(); 6949 SDValue Op = getValue(I.getArgOperand(0)); 6950 SDNodeFlags Flags; 6951 Flags.setNoFPExcept( 6952 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP)); 6953 // If ISD::IS_FPCLASS should be expanded, do it right now, because the 6954 // expansion can use illegal types. Making expansion early allows 6955 // legalizing these types prior to selection. 6956 if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) { 6957 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG); 6958 setValue(&I, Result); 6959 return; 6960 } 6961 6962 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32); 6963 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags); 6964 setValue(&I, V); 6965 return; 6966 } 6967 case Intrinsic::get_fpenv: { 6968 const DataLayout DLayout = DAG.getDataLayout(); 6969 EVT EnvVT = TLI.getValueType(DLayout, I.getType()); 6970 Align TempAlign = DAG.getEVTAlign(EnvVT); 6971 SDValue Chain = getRoot(); 6972 // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node 6973 // and temporary storage in stack. 6974 if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) { 6975 Res = DAG.getNode( 6976 ISD::GET_FPENV, sdl, 6977 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()), 6978 MVT::Other), 6979 Chain); 6980 } else { 6981 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value()); 6982 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex(); 6983 auto MPI = 6984 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI); 6985 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 6986 MPI, MachineMemOperand::MOStore, LocationSize::beforeOrAfterPointer(), 6987 TempAlign); 6988 Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO); 6989 Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI); 6990 } 6991 setValue(&I, Res); 6992 DAG.setRoot(Res.getValue(1)); 6993 return; 6994 } 6995 case Intrinsic::set_fpenv: { 6996 const DataLayout DLayout = DAG.getDataLayout(); 6997 SDValue Env = getValue(I.getArgOperand(0)); 6998 EVT EnvVT = Env.getValueType(); 6999 Align TempAlign = DAG.getEVTAlign(EnvVT); 7000 SDValue Chain = getRoot(); 7001 // If SET_FPENV is custom or legal, use it. Otherwise use loading 7002 // environment from memory. 7003 if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) { 7004 Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env); 7005 } else { 7006 // Allocate space in stack, copy environment bits into it and use this 7007 // memory in SET_FPENV_MEM. 7008 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value()); 7009 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex(); 7010 auto MPI = 7011 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI); 7012 Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign, 7013 MachineMemOperand::MOStore); 7014 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7015 MPI, MachineMemOperand::MOLoad, LocationSize::beforeOrAfterPointer(), 7016 TempAlign); 7017 Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO); 7018 } 7019 DAG.setRoot(Chain); 7020 return; 7021 } 7022 case Intrinsic::reset_fpenv: 7023 DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot())); 7024 return; 7025 case Intrinsic::get_fpmode: 7026 Res = DAG.getNode( 7027 ISD::GET_FPMODE, sdl, 7028 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()), 7029 MVT::Other), 7030 DAG.getRoot()); 7031 setValue(&I, Res); 7032 DAG.setRoot(Res.getValue(1)); 7033 return; 7034 case Intrinsic::set_fpmode: 7035 Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()}, 7036 getValue(I.getArgOperand(0))); 7037 DAG.setRoot(Res); 7038 return; 7039 case Intrinsic::reset_fpmode: { 7040 Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot()); 7041 DAG.setRoot(Res); 7042 return; 7043 } 7044 case Intrinsic::pcmarker: { 7045 SDValue Tmp = getValue(I.getArgOperand(0)); 7046 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 7047 return; 7048 } 7049 case Intrinsic::readcyclecounter: { 7050 SDValue Op = getRoot(); 7051 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 7052 DAG.getVTList(MVT::i64, MVT::Other), Op); 7053 setValue(&I, Res); 7054 DAG.setRoot(Res.getValue(1)); 7055 return; 7056 } 7057 case Intrinsic::readsteadycounter: { 7058 SDValue Op = getRoot(); 7059 Res = DAG.getNode(ISD::READSTEADYCOUNTER, 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::bitreverse: 7066 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 7067 getValue(I.getArgOperand(0)).getValueType(), 7068 getValue(I.getArgOperand(0)))); 7069 return; 7070 case Intrinsic::bswap: 7071 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 7072 getValue(I.getArgOperand(0)).getValueType(), 7073 getValue(I.getArgOperand(0)))); 7074 return; 7075 case Intrinsic::cttz: { 7076 SDValue Arg = getValue(I.getArgOperand(0)); 7077 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 7078 EVT Ty = Arg.getValueType(); 7079 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 7080 sdl, Ty, Arg)); 7081 return; 7082 } 7083 case Intrinsic::ctlz: { 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::CTLZ : ISD::CTLZ_ZERO_UNDEF, 7088 sdl, Ty, Arg)); 7089 return; 7090 } 7091 case Intrinsic::ctpop: { 7092 SDValue Arg = getValue(I.getArgOperand(0)); 7093 EVT Ty = Arg.getValueType(); 7094 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 7095 return; 7096 } 7097 case Intrinsic::fshl: 7098 case Intrinsic::fshr: { 7099 bool IsFSHL = Intrinsic == Intrinsic::fshl; 7100 SDValue X = getValue(I.getArgOperand(0)); 7101 SDValue Y = getValue(I.getArgOperand(1)); 7102 SDValue Z = getValue(I.getArgOperand(2)); 7103 EVT VT = X.getValueType(); 7104 7105 if (X == Y) { 7106 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 7107 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 7108 } else { 7109 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 7110 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 7111 } 7112 return; 7113 } 7114 case Intrinsic::sadd_sat: { 7115 SDValue Op1 = getValue(I.getArgOperand(0)); 7116 SDValue Op2 = getValue(I.getArgOperand(1)); 7117 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 7118 return; 7119 } 7120 case Intrinsic::uadd_sat: { 7121 SDValue Op1 = getValue(I.getArgOperand(0)); 7122 SDValue Op2 = getValue(I.getArgOperand(1)); 7123 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 7124 return; 7125 } 7126 case Intrinsic::ssub_sat: { 7127 SDValue Op1 = getValue(I.getArgOperand(0)); 7128 SDValue Op2 = getValue(I.getArgOperand(1)); 7129 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 7130 return; 7131 } 7132 case Intrinsic::usub_sat: { 7133 SDValue Op1 = getValue(I.getArgOperand(0)); 7134 SDValue Op2 = getValue(I.getArgOperand(1)); 7135 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 7136 return; 7137 } 7138 case Intrinsic::sshl_sat: { 7139 SDValue Op1 = getValue(I.getArgOperand(0)); 7140 SDValue Op2 = getValue(I.getArgOperand(1)); 7141 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 7142 return; 7143 } 7144 case Intrinsic::ushl_sat: { 7145 SDValue Op1 = getValue(I.getArgOperand(0)); 7146 SDValue Op2 = getValue(I.getArgOperand(1)); 7147 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 7148 return; 7149 } 7150 case Intrinsic::smul_fix: 7151 case Intrinsic::umul_fix: 7152 case Intrinsic::smul_fix_sat: 7153 case Intrinsic::umul_fix_sat: { 7154 SDValue Op1 = getValue(I.getArgOperand(0)); 7155 SDValue Op2 = getValue(I.getArgOperand(1)); 7156 SDValue Op3 = getValue(I.getArgOperand(2)); 7157 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 7158 Op1.getValueType(), Op1, Op2, Op3)); 7159 return; 7160 } 7161 case Intrinsic::sdiv_fix: 7162 case Intrinsic::udiv_fix: 7163 case Intrinsic::sdiv_fix_sat: 7164 case Intrinsic::udiv_fix_sat: { 7165 SDValue Op1 = getValue(I.getArgOperand(0)); 7166 SDValue Op2 = getValue(I.getArgOperand(1)); 7167 SDValue Op3 = getValue(I.getArgOperand(2)); 7168 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 7169 Op1, Op2, Op3, DAG, TLI)); 7170 return; 7171 } 7172 case Intrinsic::smax: { 7173 SDValue Op1 = getValue(I.getArgOperand(0)); 7174 SDValue Op2 = getValue(I.getArgOperand(1)); 7175 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 7176 return; 7177 } 7178 case Intrinsic::smin: { 7179 SDValue Op1 = getValue(I.getArgOperand(0)); 7180 SDValue Op2 = getValue(I.getArgOperand(1)); 7181 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 7182 return; 7183 } 7184 case Intrinsic::umax: { 7185 SDValue Op1 = getValue(I.getArgOperand(0)); 7186 SDValue Op2 = getValue(I.getArgOperand(1)); 7187 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 7188 return; 7189 } 7190 case Intrinsic::umin: { 7191 SDValue Op1 = getValue(I.getArgOperand(0)); 7192 SDValue Op2 = getValue(I.getArgOperand(1)); 7193 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 7194 return; 7195 } 7196 case Intrinsic::abs: { 7197 // TODO: Preserve "int min is poison" arg in SDAG? 7198 SDValue Op1 = getValue(I.getArgOperand(0)); 7199 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 7200 return; 7201 } 7202 case Intrinsic::stacksave: { 7203 SDValue Op = getRoot(); 7204 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7205 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 7206 setValue(&I, Res); 7207 DAG.setRoot(Res.getValue(1)); 7208 return; 7209 } 7210 case Intrinsic::stackrestore: 7211 Res = getValue(I.getArgOperand(0)); 7212 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 7213 return; 7214 case Intrinsic::get_dynamic_area_offset: { 7215 SDValue Op = getRoot(); 7216 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 7217 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7218 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 7219 // target. 7220 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 7221 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 7222 " intrinsic!"); 7223 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 7224 Op); 7225 DAG.setRoot(Op); 7226 setValue(&I, Res); 7227 return; 7228 } 7229 case Intrinsic::stackguard: { 7230 MachineFunction &MF = DAG.getMachineFunction(); 7231 const Module &M = *MF.getFunction().getParent(); 7232 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7233 SDValue Chain = getRoot(); 7234 if (TLI.useLoadStackGuardNode()) { 7235 Res = getLoadStackGuard(DAG, sdl, Chain); 7236 Res = DAG.getPtrExtOrTrunc(Res, sdl, PtrTy); 7237 } else { 7238 const Value *Global = TLI.getSDagStackGuard(M); 7239 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType()); 7240 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 7241 MachinePointerInfo(Global, 0), Align, 7242 MachineMemOperand::MOVolatile); 7243 } 7244 if (TLI.useStackGuardXorFP()) 7245 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 7246 DAG.setRoot(Chain); 7247 setValue(&I, Res); 7248 return; 7249 } 7250 case Intrinsic::stackprotector: { 7251 // Emit code into the DAG to store the stack guard onto the stack. 7252 MachineFunction &MF = DAG.getMachineFunction(); 7253 MachineFrameInfo &MFI = MF.getFrameInfo(); 7254 SDValue Src, Chain = getRoot(); 7255 7256 if (TLI.useLoadStackGuardNode()) 7257 Src = getLoadStackGuard(DAG, sdl, Chain); 7258 else 7259 Src = getValue(I.getArgOperand(0)); // The guard's value. 7260 7261 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 7262 7263 int FI = FuncInfo.StaticAllocaMap[Slot]; 7264 MFI.setStackProtectorIndex(FI); 7265 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 7266 7267 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 7268 7269 // Store the stack protector onto the stack. 7270 Res = DAG.getStore( 7271 Chain, sdl, Src, FIN, 7272 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 7273 MaybeAlign(), MachineMemOperand::MOVolatile); 7274 setValue(&I, Res); 7275 DAG.setRoot(Res); 7276 return; 7277 } 7278 case Intrinsic::objectsize: 7279 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 7280 7281 case Intrinsic::is_constant: 7282 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 7283 7284 case Intrinsic::annotation: 7285 case Intrinsic::ptr_annotation: 7286 case Intrinsic::launder_invariant_group: 7287 case Intrinsic::strip_invariant_group: 7288 // Drop the intrinsic, but forward the value 7289 setValue(&I, getValue(I.getOperand(0))); 7290 return; 7291 7292 case Intrinsic::assume: 7293 case Intrinsic::experimental_noalias_scope_decl: 7294 case Intrinsic::var_annotation: 7295 case Intrinsic::sideeffect: 7296 // Discard annotate attributes, noalias scope declarations, assumptions, and 7297 // artificial side-effects. 7298 return; 7299 7300 case Intrinsic::codeview_annotation: { 7301 // Emit a label associated with this metadata. 7302 MachineFunction &MF = DAG.getMachineFunction(); 7303 MCSymbol *Label = 7304 MF.getMMI().getContext().createTempSymbol("annotation", true); 7305 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 7306 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 7307 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 7308 DAG.setRoot(Res); 7309 return; 7310 } 7311 7312 case Intrinsic::init_trampoline: { 7313 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 7314 7315 SDValue Ops[6]; 7316 Ops[0] = getRoot(); 7317 Ops[1] = getValue(I.getArgOperand(0)); 7318 Ops[2] = getValue(I.getArgOperand(1)); 7319 Ops[3] = getValue(I.getArgOperand(2)); 7320 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 7321 Ops[5] = DAG.getSrcValue(F); 7322 7323 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 7324 7325 DAG.setRoot(Res); 7326 return; 7327 } 7328 case Intrinsic::adjust_trampoline: 7329 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 7330 TLI.getPointerTy(DAG.getDataLayout()), 7331 getValue(I.getArgOperand(0)))); 7332 return; 7333 case Intrinsic::gcroot: { 7334 assert(DAG.getMachineFunction().getFunction().hasGC() && 7335 "only valid in functions with gc specified, enforced by Verifier"); 7336 assert(GFI && "implied by previous"); 7337 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 7338 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 7339 7340 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 7341 GFI->addStackRoot(FI->getIndex(), TypeMap); 7342 return; 7343 } 7344 case Intrinsic::gcread: 7345 case Intrinsic::gcwrite: 7346 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 7347 case Intrinsic::get_rounding: 7348 Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot()); 7349 setValue(&I, Res); 7350 DAG.setRoot(Res.getValue(1)); 7351 return; 7352 7353 case Intrinsic::expect: 7354 // Just replace __builtin_expect(exp, c) with EXP. 7355 setValue(&I, getValue(I.getArgOperand(0))); 7356 return; 7357 7358 case Intrinsic::ubsantrap: 7359 case Intrinsic::debugtrap: 7360 case Intrinsic::trap: { 7361 StringRef TrapFuncName = 7362 I.getAttributes().getFnAttr("trap-func-name").getValueAsString(); 7363 if (TrapFuncName.empty()) { 7364 switch (Intrinsic) { 7365 case Intrinsic::trap: 7366 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 7367 break; 7368 case Intrinsic::debugtrap: 7369 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 7370 break; 7371 case Intrinsic::ubsantrap: 7372 DAG.setRoot(DAG.getNode( 7373 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 7374 DAG.getTargetConstant( 7375 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 7376 MVT::i32))); 7377 break; 7378 default: llvm_unreachable("unknown trap intrinsic"); 7379 } 7380 return; 7381 } 7382 TargetLowering::ArgListTy Args; 7383 if (Intrinsic == Intrinsic::ubsantrap) { 7384 Args.push_back(TargetLoweringBase::ArgListEntry()); 7385 Args[0].Val = I.getArgOperand(0); 7386 Args[0].Node = getValue(Args[0].Val); 7387 Args[0].Ty = Args[0].Val->getType(); 7388 } 7389 7390 TargetLowering::CallLoweringInfo CLI(DAG); 7391 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 7392 CallingConv::C, I.getType(), 7393 DAG.getExternalSymbol(TrapFuncName.data(), 7394 TLI.getPointerTy(DAG.getDataLayout())), 7395 std::move(Args)); 7396 7397 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7398 DAG.setRoot(Result.second); 7399 return; 7400 } 7401 7402 case Intrinsic::allow_runtime_check: 7403 case Intrinsic::allow_ubsan_check: 7404 setValue(&I, getValue(ConstantInt::getTrue(I.getType()))); 7405 return; 7406 7407 case Intrinsic::uadd_with_overflow: 7408 case Intrinsic::sadd_with_overflow: 7409 case Intrinsic::usub_with_overflow: 7410 case Intrinsic::ssub_with_overflow: 7411 case Intrinsic::umul_with_overflow: 7412 case Intrinsic::smul_with_overflow: { 7413 ISD::NodeType Op; 7414 switch (Intrinsic) { 7415 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7416 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 7417 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 7418 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 7419 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 7420 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 7421 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 7422 } 7423 SDValue Op1 = getValue(I.getArgOperand(0)); 7424 SDValue Op2 = getValue(I.getArgOperand(1)); 7425 7426 EVT ResultVT = Op1.getValueType(); 7427 EVT OverflowVT = MVT::i1; 7428 if (ResultVT.isVector()) 7429 OverflowVT = EVT::getVectorVT( 7430 *Context, OverflowVT, ResultVT.getVectorElementCount()); 7431 7432 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 7433 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 7434 return; 7435 } 7436 case Intrinsic::prefetch: { 7437 SDValue Ops[5]; 7438 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 7439 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 7440 Ops[0] = DAG.getRoot(); 7441 Ops[1] = getValue(I.getArgOperand(0)); 7442 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 7443 MVT::i32); 7444 Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl, 7445 MVT::i32); 7446 Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl, 7447 MVT::i32); 7448 SDValue Result = DAG.getMemIntrinsicNode( 7449 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 7450 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 7451 /* align */ std::nullopt, Flags); 7452 7453 // Chain the prefetch in parallel with any pending loads, to stay out of 7454 // the way of later optimizations. 7455 PendingLoads.push_back(Result); 7456 Result = getRoot(); 7457 DAG.setRoot(Result); 7458 return; 7459 } 7460 case Intrinsic::lifetime_start: 7461 case Intrinsic::lifetime_end: { 7462 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 7463 // Stack coloring is not enabled in O0, discard region information. 7464 if (TM.getOptLevel() == CodeGenOptLevel::None) 7465 return; 7466 7467 const int64_t ObjectSize = 7468 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 7469 Value *const ObjectPtr = I.getArgOperand(1); 7470 SmallVector<const Value *, 4> Allocas; 7471 getUnderlyingObjects(ObjectPtr, Allocas); 7472 7473 for (const Value *Alloca : Allocas) { 7474 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 7475 7476 // Could not find an Alloca. 7477 if (!LifetimeObject) 7478 continue; 7479 7480 // First check that the Alloca is static, otherwise it won't have a 7481 // valid frame index. 7482 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 7483 if (SI == FuncInfo.StaticAllocaMap.end()) 7484 return; 7485 7486 const int FrameIndex = SI->second; 7487 int64_t Offset; 7488 if (GetPointerBaseWithConstantOffset( 7489 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 7490 Offset = -1; // Cannot determine offset from alloca to lifetime object. 7491 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 7492 Offset); 7493 DAG.setRoot(Res); 7494 } 7495 return; 7496 } 7497 case Intrinsic::pseudoprobe: { 7498 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 7499 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 7500 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 7501 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 7502 DAG.setRoot(Res); 7503 return; 7504 } 7505 case Intrinsic::invariant_start: 7506 // Discard region information. 7507 setValue(&I, 7508 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType()))); 7509 return; 7510 case Intrinsic::invariant_end: 7511 // Discard region information. 7512 return; 7513 case Intrinsic::clear_cache: { 7514 SDValue InputChain = DAG.getRoot(); 7515 SDValue StartVal = getValue(I.getArgOperand(0)); 7516 SDValue EndVal = getValue(I.getArgOperand(1)); 7517 Res = DAG.getNode(ISD::CLEAR_CACHE, sdl, DAG.getVTList(MVT::Other), 7518 {InputChain, StartVal, EndVal}); 7519 setValue(&I, Res); 7520 DAG.setRoot(Res); 7521 return; 7522 } 7523 case Intrinsic::donothing: 7524 case Intrinsic::seh_try_begin: 7525 case Intrinsic::seh_scope_begin: 7526 case Intrinsic::seh_try_end: 7527 case Intrinsic::seh_scope_end: 7528 // ignore 7529 return; 7530 case Intrinsic::experimental_stackmap: 7531 visitStackmap(I); 7532 return; 7533 case Intrinsic::experimental_patchpoint_void: 7534 case Intrinsic::experimental_patchpoint: 7535 visitPatchpoint(I); 7536 return; 7537 case Intrinsic::experimental_gc_statepoint: 7538 LowerStatepoint(cast<GCStatepointInst>(I)); 7539 return; 7540 case Intrinsic::experimental_gc_result: 7541 visitGCResult(cast<GCResultInst>(I)); 7542 return; 7543 case Intrinsic::experimental_gc_relocate: 7544 visitGCRelocate(cast<GCRelocateInst>(I)); 7545 return; 7546 case Intrinsic::instrprof_cover: 7547 llvm_unreachable("instrprof failed to lower a cover"); 7548 case Intrinsic::instrprof_increment: 7549 llvm_unreachable("instrprof failed to lower an increment"); 7550 case Intrinsic::instrprof_timestamp: 7551 llvm_unreachable("instrprof failed to lower a timestamp"); 7552 case Intrinsic::instrprof_value_profile: 7553 llvm_unreachable("instrprof failed to lower a value profiling call"); 7554 case Intrinsic::instrprof_mcdc_parameters: 7555 llvm_unreachable("instrprof failed to lower mcdc parameters"); 7556 case Intrinsic::instrprof_mcdc_tvbitmap_update: 7557 llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update"); 7558 case Intrinsic::instrprof_mcdc_condbitmap_update: 7559 llvm_unreachable("instrprof failed to lower an mcdc condbitmap update"); 7560 case Intrinsic::localescape: { 7561 MachineFunction &MF = DAG.getMachineFunction(); 7562 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 7563 7564 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 7565 // is the same on all targets. 7566 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) { 7567 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 7568 if (isa<ConstantPointerNull>(Arg)) 7569 continue; // Skip null pointers. They represent a hole in index space. 7570 AllocaInst *Slot = cast<AllocaInst>(Arg); 7571 assert(FuncInfo.StaticAllocaMap.count(Slot) && 7572 "can only escape static allocas"); 7573 int FI = FuncInfo.StaticAllocaMap[Slot]; 7574 MCSymbol *FrameAllocSym = 7575 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7576 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 7577 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 7578 TII->get(TargetOpcode::LOCAL_ESCAPE)) 7579 .addSym(FrameAllocSym) 7580 .addFrameIndex(FI); 7581 } 7582 7583 return; 7584 } 7585 7586 case Intrinsic::localrecover: { 7587 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 7588 MachineFunction &MF = DAG.getMachineFunction(); 7589 7590 // Get the symbol that defines the frame offset. 7591 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 7592 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 7593 unsigned IdxVal = 7594 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 7595 MCSymbol *FrameAllocSym = 7596 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7597 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 7598 7599 Value *FP = I.getArgOperand(1); 7600 SDValue FPVal = getValue(FP); 7601 EVT PtrVT = FPVal.getValueType(); 7602 7603 // Create a MCSymbol for the label to avoid any target lowering 7604 // that would make this PC relative. 7605 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 7606 SDValue OffsetVal = 7607 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 7608 7609 // Add the offset to the FP. 7610 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 7611 setValue(&I, Add); 7612 7613 return; 7614 } 7615 7616 case Intrinsic::eh_exceptionpointer: 7617 case Intrinsic::eh_exceptioncode: { 7618 // Get the exception pointer vreg, copy from it, and resize it to fit. 7619 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 7620 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 7621 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 7622 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 7623 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT); 7624 if (Intrinsic == Intrinsic::eh_exceptioncode) 7625 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32); 7626 setValue(&I, N); 7627 return; 7628 } 7629 case Intrinsic::xray_customevent: { 7630 // Here we want to make sure that the intrinsic behaves as if it has a 7631 // specific calling convention. 7632 const auto &Triple = DAG.getTarget().getTargetTriple(); 7633 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64) 7634 return; 7635 7636 SmallVector<SDValue, 8> Ops; 7637 7638 // We want to say that we always want the arguments in registers. 7639 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 7640 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 7641 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7642 SDValue Chain = getRoot(); 7643 Ops.push_back(LogEntryVal); 7644 Ops.push_back(StrSizeVal); 7645 Ops.push_back(Chain); 7646 7647 // We need to enforce the calling convention for the callsite, so that 7648 // argument ordering is enforced correctly, and that register allocation can 7649 // see that some registers may be assumed clobbered and have to preserve 7650 // them across calls to the intrinsic. 7651 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 7652 sdl, NodeTys, Ops); 7653 SDValue patchableNode = SDValue(MN, 0); 7654 DAG.setRoot(patchableNode); 7655 setValue(&I, patchableNode); 7656 return; 7657 } 7658 case Intrinsic::xray_typedevent: { 7659 // Here we want to make sure that the intrinsic behaves as if it has a 7660 // specific calling convention. 7661 const auto &Triple = DAG.getTarget().getTargetTriple(); 7662 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64) 7663 return; 7664 7665 SmallVector<SDValue, 8> Ops; 7666 7667 // We want to say that we always want the arguments in registers. 7668 // It's unclear to me how manipulating the selection DAG here forces callers 7669 // to provide arguments in registers instead of on the stack. 7670 SDValue LogTypeId = getValue(I.getArgOperand(0)); 7671 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 7672 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 7673 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7674 SDValue Chain = getRoot(); 7675 Ops.push_back(LogTypeId); 7676 Ops.push_back(LogEntryVal); 7677 Ops.push_back(StrSizeVal); 7678 Ops.push_back(Chain); 7679 7680 // We need to enforce the calling convention for the callsite, so that 7681 // argument ordering is enforced correctly, and that register allocation can 7682 // see that some registers may be assumed clobbered and have to preserve 7683 // them across calls to the intrinsic. 7684 MachineSDNode *MN = DAG.getMachineNode( 7685 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops); 7686 SDValue patchableNode = SDValue(MN, 0); 7687 DAG.setRoot(patchableNode); 7688 setValue(&I, patchableNode); 7689 return; 7690 } 7691 case Intrinsic::experimental_deoptimize: 7692 LowerDeoptimizeCall(&I); 7693 return; 7694 case Intrinsic::experimental_stepvector: 7695 visitStepVector(I); 7696 return; 7697 case Intrinsic::vector_reduce_fadd: 7698 case Intrinsic::vector_reduce_fmul: 7699 case Intrinsic::vector_reduce_add: 7700 case Intrinsic::vector_reduce_mul: 7701 case Intrinsic::vector_reduce_and: 7702 case Intrinsic::vector_reduce_or: 7703 case Intrinsic::vector_reduce_xor: 7704 case Intrinsic::vector_reduce_smax: 7705 case Intrinsic::vector_reduce_smin: 7706 case Intrinsic::vector_reduce_umax: 7707 case Intrinsic::vector_reduce_umin: 7708 case Intrinsic::vector_reduce_fmax: 7709 case Intrinsic::vector_reduce_fmin: 7710 case Intrinsic::vector_reduce_fmaximum: 7711 case Intrinsic::vector_reduce_fminimum: 7712 visitVectorReduce(I, Intrinsic); 7713 return; 7714 7715 case Intrinsic::icall_branch_funnel: { 7716 SmallVector<SDValue, 16> Ops; 7717 Ops.push_back(getValue(I.getArgOperand(0))); 7718 7719 int64_t Offset; 7720 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7721 I.getArgOperand(1), Offset, DAG.getDataLayout())); 7722 if (!Base) 7723 report_fatal_error( 7724 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7725 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0)); 7726 7727 struct BranchFunnelTarget { 7728 int64_t Offset; 7729 SDValue Target; 7730 }; 7731 SmallVector<BranchFunnelTarget, 8> Targets; 7732 7733 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) { 7734 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7735 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7736 if (ElemBase != Base) 7737 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7738 "to the same GlobalValue"); 7739 7740 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7741 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7742 if (!GA) 7743 report_fatal_error( 7744 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7745 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7746 GA->getGlobal(), sdl, Val.getValueType(), 7747 GA->getOffset())}); 7748 } 7749 llvm::sort(Targets, 7750 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7751 return T1.Offset < T2.Offset; 7752 }); 7753 7754 for (auto &T : Targets) { 7755 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32)); 7756 Ops.push_back(T.Target); 7757 } 7758 7759 Ops.push_back(DAG.getRoot()); // Chain 7760 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl, 7761 MVT::Other, Ops), 7762 0); 7763 DAG.setRoot(N); 7764 setValue(&I, N); 7765 HasTailCall = true; 7766 return; 7767 } 7768 7769 case Intrinsic::wasm_landingpad_index: 7770 // Information this intrinsic contained has been transferred to 7771 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7772 // delete it now. 7773 return; 7774 7775 case Intrinsic::aarch64_settag: 7776 case Intrinsic::aarch64_settag_zero: { 7777 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7778 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7779 SDValue Val = TSI.EmitTargetCodeForSetTag( 7780 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)), 7781 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7782 ZeroMemory); 7783 DAG.setRoot(Val); 7784 setValue(&I, Val); 7785 return; 7786 } 7787 case Intrinsic::amdgcn_cs_chain: { 7788 assert(I.arg_size() == 5 && "Additional args not supported yet"); 7789 assert(cast<ConstantInt>(I.getOperand(4))->isZero() && 7790 "Non-zero flags not supported yet"); 7791 7792 // At this point we don't care if it's amdgpu_cs_chain or 7793 // amdgpu_cs_chain_preserve. 7794 CallingConv::ID CC = CallingConv::AMDGPU_CS_Chain; 7795 7796 Type *RetTy = I.getType(); 7797 assert(RetTy->isVoidTy() && "Should not return"); 7798 7799 SDValue Callee = getValue(I.getOperand(0)); 7800 7801 // We only have 2 actual args: one for the SGPRs and one for the VGPRs. 7802 // We'll also tack the value of the EXEC mask at the end. 7803 TargetLowering::ArgListTy Args; 7804 Args.reserve(3); 7805 7806 for (unsigned Idx : {2, 3, 1}) { 7807 TargetLowering::ArgListEntry Arg; 7808 Arg.Node = getValue(I.getOperand(Idx)); 7809 Arg.Ty = I.getOperand(Idx)->getType(); 7810 Arg.setAttributes(&I, Idx); 7811 Args.push_back(Arg); 7812 } 7813 7814 assert(Args[0].IsInReg && "SGPR args should be marked inreg"); 7815 assert(!Args[1].IsInReg && "VGPR args should not be marked inreg"); 7816 Args[2].IsInReg = true; // EXEC should be inreg 7817 7818 TargetLowering::CallLoweringInfo CLI(DAG); 7819 CLI.setDebugLoc(getCurSDLoc()) 7820 .setChain(getRoot()) 7821 .setCallee(CC, RetTy, Callee, std::move(Args)) 7822 .setNoReturn(true) 7823 .setTailCall(true) 7824 .setConvergent(I.isConvergent()); 7825 CLI.CB = &I; 7826 std::pair<SDValue, SDValue> Result = 7827 lowerInvokable(CLI, /*EHPadBB*/ nullptr); 7828 (void)Result; 7829 assert(!Result.first.getNode() && !Result.second.getNode() && 7830 "Should've lowered as tail call"); 7831 7832 HasTailCall = true; 7833 return; 7834 } 7835 case Intrinsic::ptrmask: { 7836 SDValue Ptr = getValue(I.getOperand(0)); 7837 SDValue Mask = getValue(I.getOperand(1)); 7838 7839 // On arm64_32, pointers are 32 bits when stored in memory, but 7840 // zero-extended to 64 bits when in registers. Thus the mask is 32 bits to 7841 // match the index type, but the pointer is 64 bits, so the the mask must be 7842 // zero-extended up to 64 bits to match the pointer. 7843 EVT PtrVT = 7844 TLI.getValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 7845 EVT MemVT = 7846 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 7847 assert(PtrVT == Ptr.getValueType()); 7848 assert(MemVT == Mask.getValueType()); 7849 if (MemVT != PtrVT) 7850 Mask = DAG.getPtrExtOrTrunc(Mask, sdl, PtrVT); 7851 7852 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask)); 7853 return; 7854 } 7855 case Intrinsic::threadlocal_address: { 7856 setValue(&I, getValue(I.getOperand(0))); 7857 return; 7858 } 7859 case Intrinsic::get_active_lane_mask: { 7860 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7861 SDValue Index = getValue(I.getOperand(0)); 7862 EVT ElementVT = Index.getValueType(); 7863 7864 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) { 7865 visitTargetIntrinsic(I, Intrinsic); 7866 return; 7867 } 7868 7869 SDValue TripCount = getValue(I.getOperand(1)); 7870 EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT, 7871 CCVT.getVectorElementCount()); 7872 7873 SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index); 7874 SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount); 7875 SDValue VectorStep = DAG.getStepVector(sdl, VecTy); 7876 SDValue VectorInduction = DAG.getNode( 7877 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep); 7878 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction, 7879 VectorTripCount, ISD::CondCode::SETULT); 7880 setValue(&I, SetCC); 7881 return; 7882 } 7883 case Intrinsic::experimental_get_vector_length: { 7884 assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 && 7885 "Expected positive VF"); 7886 unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue(); 7887 bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne(); 7888 7889 SDValue Count = getValue(I.getOperand(0)); 7890 EVT CountVT = Count.getValueType(); 7891 7892 if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) { 7893 visitTargetIntrinsic(I, Intrinsic); 7894 return; 7895 } 7896 7897 // Expand to a umin between the trip count and the maximum elements the type 7898 // can hold. 7899 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7900 7901 // Extend the trip count to at least the result VT. 7902 if (CountVT.bitsLT(VT)) { 7903 Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count); 7904 CountVT = VT; 7905 } 7906 7907 SDValue MaxEVL = DAG.getElementCount(sdl, CountVT, 7908 ElementCount::get(VF, IsScalable)); 7909 7910 SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL); 7911 // Clip to the result type if needed. 7912 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin); 7913 7914 setValue(&I, Trunc); 7915 return; 7916 } 7917 case Intrinsic::experimental_cttz_elts: { 7918 auto DL = getCurSDLoc(); 7919 SDValue Op = getValue(I.getOperand(0)); 7920 EVT OpVT = Op.getValueType(); 7921 7922 if (!TLI.shouldExpandCttzElements(OpVT)) { 7923 visitTargetIntrinsic(I, Intrinsic); 7924 return; 7925 } 7926 7927 if (OpVT.getScalarType() != MVT::i1) { 7928 // Compare the input vector elements to zero & use to count trailing zeros 7929 SDValue AllZero = DAG.getConstant(0, DL, OpVT); 7930 OpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, 7931 OpVT.getVectorElementCount()); 7932 Op = DAG.getSetCC(DL, OpVT, Op, AllZero, ISD::SETNE); 7933 } 7934 7935 // If the zero-is-poison flag is set, we can assume the upper limit 7936 // of the result is VF-1. 7937 bool ZeroIsPoison = 7938 !cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero(); 7939 ConstantRange VScaleRange(1, true); // Dummy value. 7940 if (isa<ScalableVectorType>(I.getOperand(0)->getType())) 7941 VScaleRange = getVScaleRange(I.getCaller(), 64); 7942 unsigned EltWidth = TLI.getBitWidthForCttzElements( 7943 I.getType(), OpVT.getVectorElementCount(), ZeroIsPoison, &VScaleRange); 7944 7945 MVT NewEltTy = MVT::getIntegerVT(EltWidth); 7946 7947 // Create the new vector type & get the vector length 7948 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), NewEltTy, 7949 OpVT.getVectorElementCount()); 7950 7951 SDValue VL = 7952 DAG.getElementCount(DL, NewEltTy, OpVT.getVectorElementCount()); 7953 7954 SDValue StepVec = DAG.getStepVector(DL, NewVT); 7955 SDValue SplatVL = DAG.getSplat(NewVT, DL, VL); 7956 SDValue StepVL = DAG.getNode(ISD::SUB, DL, NewVT, SplatVL, StepVec); 7957 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, Op); 7958 SDValue And = DAG.getNode(ISD::AND, DL, NewVT, StepVL, Ext); 7959 SDValue Max = DAG.getNode(ISD::VECREDUCE_UMAX, DL, NewEltTy, And); 7960 SDValue Sub = DAG.getNode(ISD::SUB, DL, NewEltTy, VL, Max); 7961 7962 EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7963 SDValue Ret = DAG.getZExtOrTrunc(Sub, DL, RetTy); 7964 7965 setValue(&I, Ret); 7966 return; 7967 } 7968 case Intrinsic::vector_insert: { 7969 SDValue Vec = getValue(I.getOperand(0)); 7970 SDValue SubVec = getValue(I.getOperand(1)); 7971 SDValue Index = getValue(I.getOperand(2)); 7972 7973 // The intrinsic's index type is i64, but the SDNode requires an index type 7974 // suitable for the target. Convert the index as required. 7975 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7976 if (Index.getValueType() != VectorIdxTy) 7977 Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl); 7978 7979 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7980 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec, 7981 Index)); 7982 return; 7983 } 7984 case Intrinsic::vector_extract: { 7985 SDValue Vec = getValue(I.getOperand(0)); 7986 SDValue Index = getValue(I.getOperand(1)); 7987 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7988 7989 // The intrinsic's index type is i64, but the SDNode requires an index type 7990 // suitable for the target. Convert the index as required. 7991 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7992 if (Index.getValueType() != VectorIdxTy) 7993 Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl); 7994 7995 setValue(&I, 7996 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index)); 7997 return; 7998 } 7999 case Intrinsic::vector_reverse: 8000 visitVectorReverse(I); 8001 return; 8002 case Intrinsic::vector_splice: 8003 visitVectorSplice(I); 8004 return; 8005 case Intrinsic::callbr_landingpad: 8006 visitCallBrLandingPad(I); 8007 return; 8008 case Intrinsic::vector_interleave2: 8009 visitVectorInterleave(I); 8010 return; 8011 case Intrinsic::vector_deinterleave2: 8012 visitVectorDeinterleave(I); 8013 return; 8014 case Intrinsic::experimental_convergence_anchor: 8015 case Intrinsic::experimental_convergence_entry: 8016 case Intrinsic::experimental_convergence_loop: 8017 visitConvergenceControl(I, Intrinsic); 8018 return; 8019 case Intrinsic::experimental_vector_histogram_add: { 8020 visitVectorHistogram(I, Intrinsic); 8021 return; 8022 } 8023 } 8024 } 8025 8026 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 8027 const ConstrainedFPIntrinsic &FPI) { 8028 SDLoc sdl = getCurSDLoc(); 8029 8030 // We do not need to serialize constrained FP intrinsics against 8031 // each other or against (nonvolatile) loads, so they can be 8032 // chained like loads. 8033 SDValue Chain = DAG.getRoot(); 8034 SmallVector<SDValue, 4> Opers; 8035 Opers.push_back(Chain); 8036 for (unsigned I = 0, E = FPI.getNonMetadataArgCount(); I != E; ++I) 8037 Opers.push_back(getValue(FPI.getArgOperand(I))); 8038 8039 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 8040 assert(Result.getNode()->getNumValues() == 2); 8041 8042 // Push node to the appropriate list so that future instructions can be 8043 // chained up correctly. 8044 SDValue OutChain = Result.getValue(1); 8045 switch (EB) { 8046 case fp::ExceptionBehavior::ebIgnore: 8047 // The only reason why ebIgnore nodes still need to be chained is that 8048 // they might depend on the current rounding mode, and therefore must 8049 // not be moved across instruction that may change that mode. 8050 [[fallthrough]]; 8051 case fp::ExceptionBehavior::ebMayTrap: 8052 // These must not be moved across calls or instructions that may change 8053 // floating-point exception masks. 8054 PendingConstrainedFP.push_back(OutChain); 8055 break; 8056 case fp::ExceptionBehavior::ebStrict: 8057 // These must not be moved across calls or instructions that may change 8058 // floating-point exception masks or read floating-point exception flags. 8059 // In addition, they cannot be optimized out even if unused. 8060 PendingConstrainedFPStrict.push_back(OutChain); 8061 break; 8062 } 8063 }; 8064 8065 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8066 EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType()); 8067 SDVTList VTs = DAG.getVTList(VT, MVT::Other); 8068 fp::ExceptionBehavior EB = *FPI.getExceptionBehavior(); 8069 8070 SDNodeFlags Flags; 8071 if (EB == fp::ExceptionBehavior::ebIgnore) 8072 Flags.setNoFPExcept(true); 8073 8074 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 8075 Flags.copyFMF(*FPOp); 8076 8077 unsigned Opcode; 8078 switch (FPI.getIntrinsicID()) { 8079 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 8080 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 8081 case Intrinsic::INTRINSIC: \ 8082 Opcode = ISD::STRICT_##DAGN; \ 8083 break; 8084 #include "llvm/IR/ConstrainedOps.def" 8085 case Intrinsic::experimental_constrained_fmuladd: { 8086 Opcode = ISD::STRICT_FMA; 8087 // Break fmuladd into fmul and fadd. 8088 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 8089 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 8090 Opers.pop_back(); 8091 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 8092 pushOutChain(Mul, EB); 8093 Opcode = ISD::STRICT_FADD; 8094 Opers.clear(); 8095 Opers.push_back(Mul.getValue(1)); 8096 Opers.push_back(Mul.getValue(0)); 8097 Opers.push_back(getValue(FPI.getArgOperand(2))); 8098 } 8099 break; 8100 } 8101 } 8102 8103 // A few strict DAG nodes carry additional operands that are not 8104 // set up by the default code above. 8105 switch (Opcode) { 8106 default: break; 8107 case ISD::STRICT_FP_ROUND: 8108 Opers.push_back( 8109 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 8110 break; 8111 case ISD::STRICT_FSETCC: 8112 case ISD::STRICT_FSETCCS: { 8113 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 8114 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 8115 if (TM.Options.NoNaNsFPMath) 8116 Condition = getFCmpCodeWithoutNaN(Condition); 8117 Opers.push_back(DAG.getCondCode(Condition)); 8118 break; 8119 } 8120 } 8121 8122 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 8123 pushOutChain(Result, EB); 8124 8125 SDValue FPResult = Result.getValue(0); 8126 setValue(&FPI, FPResult); 8127 } 8128 8129 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 8130 std::optional<unsigned> ResOPC; 8131 switch (VPIntrin.getIntrinsicID()) { 8132 case Intrinsic::vp_ctlz: { 8133 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 8134 ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ; 8135 break; 8136 } 8137 case Intrinsic::vp_cttz: { 8138 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 8139 ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ; 8140 break; 8141 } 8142 case Intrinsic::vp_cttz_elts: { 8143 bool IsZeroPoison = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 8144 ResOPC = IsZeroPoison ? ISD::VP_CTTZ_ELTS_ZERO_UNDEF : ISD::VP_CTTZ_ELTS; 8145 break; 8146 } 8147 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \ 8148 case Intrinsic::VPID: \ 8149 ResOPC = ISD::VPSD; \ 8150 break; 8151 #include "llvm/IR/VPIntrinsics.def" 8152 } 8153 8154 if (!ResOPC) 8155 llvm_unreachable( 8156 "Inconsistency: no SDNode available for this VPIntrinsic!"); 8157 8158 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD || 8159 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) { 8160 if (VPIntrin.getFastMathFlags().allowReassoc()) 8161 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD 8162 : ISD::VP_REDUCE_FMUL; 8163 } 8164 8165 return *ResOPC; 8166 } 8167 8168 void SelectionDAGBuilder::visitVPLoad( 8169 const VPIntrinsic &VPIntrin, EVT VT, 8170 const SmallVectorImpl<SDValue> &OpValues) { 8171 SDLoc DL = getCurSDLoc(); 8172 Value *PtrOperand = VPIntrin.getArgOperand(0); 8173 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8174 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8175 const MDNode *Ranges = getRangeMetadata(VPIntrin); 8176 SDValue LD; 8177 // Do not serialize variable-length loads of constant memory with 8178 // anything. 8179 if (!Alignment) 8180 Alignment = DAG.getEVTAlign(VT); 8181 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 8182 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 8183 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 8184 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8185 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 8186 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges); 8187 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2], 8188 MMO, false /*IsExpanding */); 8189 if (AddToChain) 8190 PendingLoads.push_back(LD.getValue(1)); 8191 setValue(&VPIntrin, LD); 8192 } 8193 8194 void SelectionDAGBuilder::visitVPGather( 8195 const VPIntrinsic &VPIntrin, EVT VT, 8196 const SmallVectorImpl<SDValue> &OpValues) { 8197 SDLoc DL = getCurSDLoc(); 8198 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8199 Value *PtrOperand = VPIntrin.getArgOperand(0); 8200 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8201 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8202 const MDNode *Ranges = getRangeMetadata(VPIntrin); 8203 SDValue LD; 8204 if (!Alignment) 8205 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8206 unsigned AS = 8207 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 8208 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8209 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 8210 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges); 8211 SDValue Base, Index, Scale; 8212 ISD::MemIndexType IndexType; 8213 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 8214 this, VPIntrin.getParent(), 8215 VT.getScalarStoreSize()); 8216 if (!UniformBase) { 8217 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 8218 Index = getValue(PtrOperand); 8219 IndexType = ISD::SIGNED_SCALED; 8220 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 8221 } 8222 EVT IdxVT = Index.getValueType(); 8223 EVT EltTy = IdxVT.getVectorElementType(); 8224 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 8225 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 8226 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 8227 } 8228 LD = DAG.getGatherVP( 8229 DAG.getVTList(VT, MVT::Other), VT, DL, 8230 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO, 8231 IndexType); 8232 PendingLoads.push_back(LD.getValue(1)); 8233 setValue(&VPIntrin, LD); 8234 } 8235 8236 void SelectionDAGBuilder::visitVPStore( 8237 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 8238 SDLoc DL = getCurSDLoc(); 8239 Value *PtrOperand = VPIntrin.getArgOperand(1); 8240 EVT VT = OpValues[0].getValueType(); 8241 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8242 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8243 SDValue ST; 8244 if (!Alignment) 8245 Alignment = DAG.getEVTAlign(VT); 8246 SDValue Ptr = OpValues[1]; 8247 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 8248 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8249 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 8250 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo); 8251 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset, 8252 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED, 8253 /* IsTruncating */ false, /*IsCompressing*/ false); 8254 DAG.setRoot(ST); 8255 setValue(&VPIntrin, ST); 8256 } 8257 8258 void SelectionDAGBuilder::visitVPScatter( 8259 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 8260 SDLoc DL = getCurSDLoc(); 8261 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8262 Value *PtrOperand = VPIntrin.getArgOperand(1); 8263 EVT VT = OpValues[0].getValueType(); 8264 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8265 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8266 SDValue ST; 8267 if (!Alignment) 8268 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8269 unsigned AS = 8270 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 8271 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8272 MachinePointerInfo(AS), MachineMemOperand::MOStore, 8273 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo); 8274 SDValue Base, Index, Scale; 8275 ISD::MemIndexType IndexType; 8276 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 8277 this, VPIntrin.getParent(), 8278 VT.getScalarStoreSize()); 8279 if (!UniformBase) { 8280 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 8281 Index = getValue(PtrOperand); 8282 IndexType = ISD::SIGNED_SCALED; 8283 Scale = 8284 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 8285 } 8286 EVT IdxVT = Index.getValueType(); 8287 EVT EltTy = IdxVT.getVectorElementType(); 8288 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 8289 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 8290 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 8291 } 8292 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL, 8293 {getMemoryRoot(), OpValues[0], Base, Index, Scale, 8294 OpValues[2], OpValues[3]}, 8295 MMO, IndexType); 8296 DAG.setRoot(ST); 8297 setValue(&VPIntrin, ST); 8298 } 8299 8300 void SelectionDAGBuilder::visitVPStridedLoad( 8301 const VPIntrinsic &VPIntrin, EVT VT, 8302 const SmallVectorImpl<SDValue> &OpValues) { 8303 SDLoc DL = getCurSDLoc(); 8304 Value *PtrOperand = VPIntrin.getArgOperand(0); 8305 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8306 if (!Alignment) 8307 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8308 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8309 const MDNode *Ranges = getRangeMetadata(VPIntrin); 8310 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 8311 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 8312 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 8313 unsigned AS = PtrOperand->getType()->getPointerAddressSpace(); 8314 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8315 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 8316 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges); 8317 8318 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], 8319 OpValues[2], OpValues[3], MMO, 8320 false /*IsExpanding*/); 8321 8322 if (AddToChain) 8323 PendingLoads.push_back(LD.getValue(1)); 8324 setValue(&VPIntrin, LD); 8325 } 8326 8327 void SelectionDAGBuilder::visitVPStridedStore( 8328 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 8329 SDLoc DL = getCurSDLoc(); 8330 Value *PtrOperand = VPIntrin.getArgOperand(1); 8331 EVT VT = OpValues[0].getValueType(); 8332 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8333 if (!Alignment) 8334 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8335 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8336 unsigned AS = PtrOperand->getType()->getPointerAddressSpace(); 8337 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8338 MachinePointerInfo(AS), MachineMemOperand::MOStore, 8339 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo); 8340 8341 SDValue ST = DAG.getStridedStoreVP( 8342 getMemoryRoot(), DL, OpValues[0], OpValues[1], 8343 DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3], 8344 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false, 8345 /*IsCompressing*/ false); 8346 8347 DAG.setRoot(ST); 8348 setValue(&VPIntrin, ST); 8349 } 8350 8351 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) { 8352 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8353 SDLoc DL = getCurSDLoc(); 8354 8355 ISD::CondCode Condition; 8356 CmpInst::Predicate CondCode = VPIntrin.getPredicate(); 8357 bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy(); 8358 if (IsFP) { 8359 // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan) 8360 // flags, but calls that don't return floating-point types can't be 8361 // FPMathOperators, like vp.fcmp. This affects constrained fcmp too. 8362 Condition = getFCmpCondCode(CondCode); 8363 if (TM.Options.NoNaNsFPMath) 8364 Condition = getFCmpCodeWithoutNaN(Condition); 8365 } else { 8366 Condition = getICmpCondCode(CondCode); 8367 } 8368 8369 SDValue Op1 = getValue(VPIntrin.getOperand(0)); 8370 SDValue Op2 = getValue(VPIntrin.getOperand(1)); 8371 // #2 is the condition code 8372 SDValue MaskOp = getValue(VPIntrin.getOperand(3)); 8373 SDValue EVL = getValue(VPIntrin.getOperand(4)); 8374 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 8375 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 8376 "Unexpected target EVL type"); 8377 EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL); 8378 8379 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8380 VPIntrin.getType()); 8381 setValue(&VPIntrin, 8382 DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL)); 8383 } 8384 8385 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 8386 const VPIntrinsic &VPIntrin) { 8387 SDLoc DL = getCurSDLoc(); 8388 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 8389 8390 auto IID = VPIntrin.getIntrinsicID(); 8391 8392 if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin)) 8393 return visitVPCmp(*CmpI); 8394 8395 SmallVector<EVT, 4> ValueVTs; 8396 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8397 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 8398 SDVTList VTs = DAG.getVTList(ValueVTs); 8399 8400 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID); 8401 8402 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 8403 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 8404 "Unexpected target EVL type"); 8405 8406 // Request operands. 8407 SmallVector<SDValue, 7> OpValues; 8408 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) { 8409 auto Op = getValue(VPIntrin.getArgOperand(I)); 8410 if (I == EVLParamPos) 8411 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op); 8412 OpValues.push_back(Op); 8413 } 8414 8415 switch (Opcode) { 8416 default: { 8417 SDNodeFlags SDFlags; 8418 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 8419 SDFlags.copyFMF(*FPMO); 8420 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags); 8421 setValue(&VPIntrin, Result); 8422 break; 8423 } 8424 case ISD::VP_LOAD: 8425 visitVPLoad(VPIntrin, ValueVTs[0], OpValues); 8426 break; 8427 case ISD::VP_GATHER: 8428 visitVPGather(VPIntrin, ValueVTs[0], OpValues); 8429 break; 8430 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: 8431 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues); 8432 break; 8433 case ISD::VP_STORE: 8434 visitVPStore(VPIntrin, OpValues); 8435 break; 8436 case ISD::VP_SCATTER: 8437 visitVPScatter(VPIntrin, OpValues); 8438 break; 8439 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: 8440 visitVPStridedStore(VPIntrin, OpValues); 8441 break; 8442 case ISD::VP_FMULADD: { 8443 assert(OpValues.size() == 5 && "Unexpected number of operands"); 8444 SDNodeFlags SDFlags; 8445 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 8446 SDFlags.copyFMF(*FPMO); 8447 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 8448 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) { 8449 setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags)); 8450 } else { 8451 SDValue Mul = DAG.getNode( 8452 ISD::VP_FMUL, DL, VTs, 8453 {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags); 8454 SDValue Add = 8455 DAG.getNode(ISD::VP_FADD, DL, VTs, 8456 {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags); 8457 setValue(&VPIntrin, Add); 8458 } 8459 break; 8460 } 8461 case ISD::VP_IS_FPCLASS: { 8462 const DataLayout DLayout = DAG.getDataLayout(); 8463 EVT DestVT = TLI.getValueType(DLayout, VPIntrin.getType()); 8464 auto Constant = OpValues[1]->getAsZExtVal(); 8465 SDValue Check = DAG.getTargetConstant(Constant, DL, MVT::i32); 8466 SDValue V = DAG.getNode(ISD::VP_IS_FPCLASS, DL, DestVT, 8467 {OpValues[0], Check, OpValues[2], OpValues[3]}); 8468 setValue(&VPIntrin, V); 8469 return; 8470 } 8471 case ISD::VP_INTTOPTR: { 8472 SDValue N = OpValues[0]; 8473 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType()); 8474 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType()); 8475 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 8476 OpValues[2]); 8477 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 8478 OpValues[2]); 8479 setValue(&VPIntrin, N); 8480 break; 8481 } 8482 case ISD::VP_PTRTOINT: { 8483 SDValue N = OpValues[0]; 8484 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8485 VPIntrin.getType()); 8486 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), 8487 VPIntrin.getOperand(0)->getType()); 8488 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 8489 OpValues[2]); 8490 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 8491 OpValues[2]); 8492 setValue(&VPIntrin, N); 8493 break; 8494 } 8495 case ISD::VP_ABS: 8496 case ISD::VP_CTLZ: 8497 case ISD::VP_CTLZ_ZERO_UNDEF: 8498 case ISD::VP_CTTZ: 8499 case ISD::VP_CTTZ_ZERO_UNDEF: 8500 case ISD::VP_CTTZ_ELTS_ZERO_UNDEF: 8501 case ISD::VP_CTTZ_ELTS: { 8502 SDValue Result = 8503 DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]}); 8504 setValue(&VPIntrin, Result); 8505 break; 8506 } 8507 } 8508 } 8509 8510 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 8511 const BasicBlock *EHPadBB, 8512 MCSymbol *&BeginLabel) { 8513 MachineFunction &MF = DAG.getMachineFunction(); 8514 MachineModuleInfo &MMI = MF.getMMI(); 8515 8516 // Insert a label before the invoke call to mark the try range. This can be 8517 // used to detect deletion of the invoke via the MachineModuleInfo. 8518 BeginLabel = MMI.getContext().createTempSymbol(); 8519 8520 // For SjLj, keep track of which landing pads go with which invokes 8521 // so as to maintain the ordering of pads in the LSDA. 8522 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 8523 if (CallSiteIndex) { 8524 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 8525 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 8526 8527 // Now that the call site is handled, stop tracking it. 8528 MMI.setCurrentCallSite(0); 8529 } 8530 8531 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 8532 } 8533 8534 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 8535 const BasicBlock *EHPadBB, 8536 MCSymbol *BeginLabel) { 8537 assert(BeginLabel && "BeginLabel should've been set"); 8538 8539 MachineFunction &MF = DAG.getMachineFunction(); 8540 MachineModuleInfo &MMI = MF.getMMI(); 8541 8542 // Insert a label at the end of the invoke call to mark the try range. This 8543 // can be used to detect deletion of the invoke via the MachineModuleInfo. 8544 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 8545 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 8546 8547 // Inform MachineModuleInfo of range. 8548 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 8549 // There is a platform (e.g. wasm) that uses funclet style IR but does not 8550 // actually use outlined funclets and their LSDA info style. 8551 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 8552 assert(II && "II should've been set"); 8553 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 8554 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 8555 } else if (!isScopedEHPersonality(Pers)) { 8556 assert(EHPadBB); 8557 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 8558 } 8559 8560 return Chain; 8561 } 8562 8563 std::pair<SDValue, SDValue> 8564 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 8565 const BasicBlock *EHPadBB) { 8566 MCSymbol *BeginLabel = nullptr; 8567 8568 if (EHPadBB) { 8569 // Both PendingLoads and PendingExports must be flushed here; 8570 // this call might not return. 8571 (void)getRoot(); 8572 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 8573 CLI.setChain(getRoot()); 8574 } 8575 8576 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8577 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 8578 8579 assert((CLI.IsTailCall || Result.second.getNode()) && 8580 "Non-null chain expected with non-tail call!"); 8581 assert((Result.second.getNode() || !Result.first.getNode()) && 8582 "Null value expected with tail call!"); 8583 8584 if (!Result.second.getNode()) { 8585 // As a special case, a null chain means that a tail call has been emitted 8586 // and the DAG root is already updated. 8587 HasTailCall = true; 8588 8589 // Since there's no actual continuation from this block, nothing can be 8590 // relying on us setting vregs for them. 8591 PendingExports.clear(); 8592 } else { 8593 DAG.setRoot(Result.second); 8594 } 8595 8596 if (EHPadBB) { 8597 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 8598 BeginLabel)); 8599 } 8600 8601 return Result; 8602 } 8603 8604 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 8605 bool isTailCall, bool isMustTailCall, 8606 const BasicBlock *EHPadBB, 8607 const TargetLowering::PtrAuthInfo *PAI) { 8608 auto &DL = DAG.getDataLayout(); 8609 FunctionType *FTy = CB.getFunctionType(); 8610 Type *RetTy = CB.getType(); 8611 8612 TargetLowering::ArgListTy Args; 8613 Args.reserve(CB.arg_size()); 8614 8615 const Value *SwiftErrorVal = nullptr; 8616 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8617 8618 if (isTailCall) { 8619 // Avoid emitting tail calls in functions with the disable-tail-calls 8620 // attribute. 8621 auto *Caller = CB.getParent()->getParent(); 8622 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 8623 "true" && !isMustTailCall) 8624 isTailCall = false; 8625 8626 // We can't tail call inside a function with a swifterror argument. Lowering 8627 // does not support this yet. It would have to move into the swifterror 8628 // register before the call. 8629 if (TLI.supportSwiftError() && 8630 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 8631 isTailCall = false; 8632 } 8633 8634 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 8635 TargetLowering::ArgListEntry Entry; 8636 const Value *V = *I; 8637 8638 // Skip empty types 8639 if (V->getType()->isEmptyTy()) 8640 continue; 8641 8642 SDValue ArgNode = getValue(V); 8643 Entry.Node = ArgNode; Entry.Ty = V->getType(); 8644 8645 Entry.setAttributes(&CB, I - CB.arg_begin()); 8646 8647 // Use swifterror virtual register as input to the call. 8648 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 8649 SwiftErrorVal = V; 8650 // We find the virtual register for the actual swifterror argument. 8651 // Instead of using the Value, we use the virtual register instead. 8652 Entry.Node = 8653 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 8654 EVT(TLI.getPointerTy(DL))); 8655 } 8656 8657 Args.push_back(Entry); 8658 8659 // If we have an explicit sret argument that is an Instruction, (i.e., it 8660 // might point to function-local memory), we can't meaningfully tail-call. 8661 if (Entry.IsSRet && isa<Instruction>(V)) 8662 isTailCall = false; 8663 } 8664 8665 // If call site has a cfguardtarget operand bundle, create and add an 8666 // additional ArgListEntry. 8667 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 8668 TargetLowering::ArgListEntry Entry; 8669 Value *V = Bundle->Inputs[0]; 8670 SDValue ArgNode = getValue(V); 8671 Entry.Node = ArgNode; 8672 Entry.Ty = V->getType(); 8673 Entry.IsCFGuardTarget = true; 8674 Args.push_back(Entry); 8675 } 8676 8677 // Check if target-independent constraints permit a tail call here. 8678 // Target-dependent constraints are checked within TLI->LowerCallTo. 8679 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 8680 isTailCall = false; 8681 8682 // Disable tail calls if there is an swifterror argument. Targets have not 8683 // been updated to support tail calls. 8684 if (TLI.supportSwiftError() && SwiftErrorVal) 8685 isTailCall = false; 8686 8687 ConstantInt *CFIType = nullptr; 8688 if (CB.isIndirectCall()) { 8689 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) { 8690 if (!TLI.supportKCFIBundles()) 8691 report_fatal_error( 8692 "Target doesn't support calls with kcfi operand bundles."); 8693 CFIType = cast<ConstantInt>(Bundle->Inputs[0]); 8694 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type"); 8695 } 8696 } 8697 8698 SDValue ConvControlToken; 8699 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_convergencectrl)) { 8700 auto *Token = Bundle->Inputs[0].get(); 8701 ConvControlToken = getValue(Token); 8702 } 8703 8704 TargetLowering::CallLoweringInfo CLI(DAG); 8705 CLI.setDebugLoc(getCurSDLoc()) 8706 .setChain(getRoot()) 8707 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 8708 .setTailCall(isTailCall) 8709 .setConvergent(CB.isConvergent()) 8710 .setIsPreallocated( 8711 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0) 8712 .setCFIType(CFIType) 8713 .setConvergenceControlToken(ConvControlToken); 8714 8715 // Set the pointer authentication info if we have it. 8716 if (PAI) { 8717 if (!TLI.supportPtrAuthBundles()) 8718 report_fatal_error( 8719 "This target doesn't support calls with ptrauth operand bundles."); 8720 CLI.setPtrAuth(*PAI); 8721 } 8722 8723 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8724 8725 if (Result.first.getNode()) { 8726 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 8727 setValue(&CB, Result.first); 8728 } 8729 8730 // The last element of CLI.InVals has the SDValue for swifterror return. 8731 // Here we copy it to a virtual register and update SwiftErrorMap for 8732 // book-keeping. 8733 if (SwiftErrorVal && TLI.supportSwiftError()) { 8734 // Get the last element of InVals. 8735 SDValue Src = CLI.InVals.back(); 8736 Register VReg = 8737 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 8738 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 8739 DAG.setRoot(CopyNode); 8740 } 8741 } 8742 8743 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 8744 SelectionDAGBuilder &Builder) { 8745 // Check to see if this load can be trivially constant folded, e.g. if the 8746 // input is from a string literal. 8747 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 8748 // Cast pointer to the type we really want to load. 8749 Type *LoadTy = 8750 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 8751 if (LoadVT.isVector()) 8752 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 8753 8754 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 8755 PointerType::getUnqual(LoadTy)); 8756 8757 if (const Constant *LoadCst = 8758 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput), 8759 LoadTy, Builder.DAG.getDataLayout())) 8760 return Builder.getValue(LoadCst); 8761 } 8762 8763 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 8764 // still constant memory, the input chain can be the entry node. 8765 SDValue Root; 8766 bool ConstantMemory = false; 8767 8768 // Do not serialize (non-volatile) loads of constant memory with anything. 8769 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 8770 Root = Builder.DAG.getEntryNode(); 8771 ConstantMemory = true; 8772 } else { 8773 // Do not serialize non-volatile loads against each other. 8774 Root = Builder.DAG.getRoot(); 8775 } 8776 8777 SDValue Ptr = Builder.getValue(PtrVal); 8778 SDValue LoadVal = 8779 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 8780 MachinePointerInfo(PtrVal), Align(1)); 8781 8782 if (!ConstantMemory) 8783 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 8784 return LoadVal; 8785 } 8786 8787 /// Record the value for an instruction that produces an integer result, 8788 /// converting the type where necessary. 8789 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 8790 SDValue Value, 8791 bool IsSigned) { 8792 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8793 I.getType(), true); 8794 Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT); 8795 setValue(&I, Value); 8796 } 8797 8798 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 8799 /// true and lower it. Otherwise return false, and it will be lowered like a 8800 /// normal call. 8801 /// The caller already checked that \p I calls the appropriate LibFunc with a 8802 /// correct prototype. 8803 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 8804 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 8805 const Value *Size = I.getArgOperand(2); 8806 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size)); 8807 if (CSize && CSize->getZExtValue() == 0) { 8808 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8809 I.getType(), true); 8810 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 8811 return true; 8812 } 8813 8814 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8815 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 8816 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 8817 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 8818 if (Res.first.getNode()) { 8819 processIntegerCallValue(I, Res.first, true); 8820 PendingLoads.push_back(Res.second); 8821 return true; 8822 } 8823 8824 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 8825 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 8826 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 8827 return false; 8828 8829 // If the target has a fast compare for the given size, it will return a 8830 // preferred load type for that size. Require that the load VT is legal and 8831 // that the target supports unaligned loads of that type. Otherwise, return 8832 // INVALID. 8833 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 8834 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8835 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 8836 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 8837 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 8838 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 8839 // TODO: Check alignment of src and dest ptrs. 8840 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 8841 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 8842 if (!TLI.isTypeLegal(LVT) || 8843 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 8844 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 8845 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 8846 } 8847 8848 return LVT; 8849 }; 8850 8851 // This turns into unaligned loads. We only do this if the target natively 8852 // supports the MVT we'll be loading or if it is small enough (<= 4) that 8853 // we'll only produce a small number of byte loads. 8854 MVT LoadVT; 8855 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 8856 switch (NumBitsToCompare) { 8857 default: 8858 return false; 8859 case 16: 8860 LoadVT = MVT::i16; 8861 break; 8862 case 32: 8863 LoadVT = MVT::i32; 8864 break; 8865 case 64: 8866 case 128: 8867 case 256: 8868 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 8869 break; 8870 } 8871 8872 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 8873 return false; 8874 8875 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 8876 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 8877 8878 // Bitcast to a wide integer type if the loads are vectors. 8879 if (LoadVT.isVector()) { 8880 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 8881 LoadL = DAG.getBitcast(CmpVT, LoadL); 8882 LoadR = DAG.getBitcast(CmpVT, LoadR); 8883 } 8884 8885 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 8886 processIntegerCallValue(I, Cmp, false); 8887 return true; 8888 } 8889 8890 /// See if we can lower a memchr call into an optimized form. If so, return 8891 /// true and lower it. Otherwise return false, and it will be lowered like a 8892 /// normal call. 8893 /// The caller already checked that \p I calls the appropriate LibFunc with a 8894 /// correct prototype. 8895 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 8896 const Value *Src = I.getArgOperand(0); 8897 const Value *Char = I.getArgOperand(1); 8898 const Value *Length = I.getArgOperand(2); 8899 8900 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8901 std::pair<SDValue, SDValue> Res = 8902 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 8903 getValue(Src), getValue(Char), getValue(Length), 8904 MachinePointerInfo(Src)); 8905 if (Res.first.getNode()) { 8906 setValue(&I, Res.first); 8907 PendingLoads.push_back(Res.second); 8908 return true; 8909 } 8910 8911 return false; 8912 } 8913 8914 /// See if we can lower a mempcpy call into an optimized form. If so, return 8915 /// true and lower it. Otherwise return false, and it will be lowered like a 8916 /// normal call. 8917 /// The caller already checked that \p I calls the appropriate LibFunc with a 8918 /// correct prototype. 8919 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 8920 SDValue Dst = getValue(I.getArgOperand(0)); 8921 SDValue Src = getValue(I.getArgOperand(1)); 8922 SDValue Size = getValue(I.getArgOperand(2)); 8923 8924 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 8925 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 8926 // DAG::getMemcpy needs Alignment to be defined. 8927 Align Alignment = std::min(DstAlign, SrcAlign); 8928 8929 SDLoc sdl = getCurSDLoc(); 8930 8931 // In the mempcpy context we need to pass in a false value for isTailCall 8932 // because the return pointer needs to be adjusted by the size of 8933 // the copied memory. 8934 SDValue Root = getMemoryRoot(); 8935 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, false, false, 8936 /*isTailCall=*/false, 8937 MachinePointerInfo(I.getArgOperand(0)), 8938 MachinePointerInfo(I.getArgOperand(1)), 8939 I.getAAMetadata()); 8940 assert(MC.getNode() != nullptr && 8941 "** memcpy should not be lowered as TailCall in mempcpy context **"); 8942 DAG.setRoot(MC); 8943 8944 // Check if Size needs to be truncated or extended. 8945 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 8946 8947 // Adjust return pointer to point just past the last dst byte. 8948 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 8949 Dst, Size); 8950 setValue(&I, DstPlusSize); 8951 return true; 8952 } 8953 8954 /// See if we can lower a strcpy call into an optimized form. If so, return 8955 /// true and lower it, otherwise return false and it will be lowered like a 8956 /// normal call. 8957 /// The caller already checked that \p I calls the appropriate LibFunc with a 8958 /// correct prototype. 8959 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 8960 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8961 8962 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8963 std::pair<SDValue, SDValue> Res = 8964 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 8965 getValue(Arg0), getValue(Arg1), 8966 MachinePointerInfo(Arg0), 8967 MachinePointerInfo(Arg1), isStpcpy); 8968 if (Res.first.getNode()) { 8969 setValue(&I, Res.first); 8970 DAG.setRoot(Res.second); 8971 return true; 8972 } 8973 8974 return false; 8975 } 8976 8977 /// See if we can lower a strcmp call into an optimized form. If so, return 8978 /// true and lower it, otherwise return false and it will be lowered like a 8979 /// normal call. 8980 /// The caller already checked that \p I calls the appropriate LibFunc with a 8981 /// correct prototype. 8982 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 8983 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8984 8985 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8986 std::pair<SDValue, SDValue> Res = 8987 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 8988 getValue(Arg0), getValue(Arg1), 8989 MachinePointerInfo(Arg0), 8990 MachinePointerInfo(Arg1)); 8991 if (Res.first.getNode()) { 8992 processIntegerCallValue(I, Res.first, true); 8993 PendingLoads.push_back(Res.second); 8994 return true; 8995 } 8996 8997 return false; 8998 } 8999 9000 /// See if we can lower a strlen call into an optimized form. If so, return 9001 /// true and lower it, otherwise return false and it will be lowered like a 9002 /// normal call. 9003 /// The caller already checked that \p I calls the appropriate LibFunc with a 9004 /// correct prototype. 9005 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 9006 const Value *Arg0 = I.getArgOperand(0); 9007 9008 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 9009 std::pair<SDValue, SDValue> Res = 9010 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 9011 getValue(Arg0), MachinePointerInfo(Arg0)); 9012 if (Res.first.getNode()) { 9013 processIntegerCallValue(I, Res.first, false); 9014 PendingLoads.push_back(Res.second); 9015 return true; 9016 } 9017 9018 return false; 9019 } 9020 9021 /// See if we can lower a strnlen call into an optimized form. If so, return 9022 /// true and lower it, otherwise return false and it will be lowered like a 9023 /// normal call. 9024 /// The caller already checked that \p I calls the appropriate LibFunc with a 9025 /// correct prototype. 9026 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 9027 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 9028 9029 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 9030 std::pair<SDValue, SDValue> Res = 9031 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 9032 getValue(Arg0), getValue(Arg1), 9033 MachinePointerInfo(Arg0)); 9034 if (Res.first.getNode()) { 9035 processIntegerCallValue(I, Res.first, false); 9036 PendingLoads.push_back(Res.second); 9037 return true; 9038 } 9039 9040 return false; 9041 } 9042 9043 /// See if we can lower a unary floating-point operation into an SDNode with 9044 /// the specified Opcode. If so, return true and lower it, otherwise return 9045 /// false and it will be lowered like a normal call. 9046 /// The caller already checked that \p I calls the appropriate LibFunc with a 9047 /// correct prototype. 9048 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 9049 unsigned Opcode) { 9050 // We already checked this call's prototype; verify it doesn't modify errno. 9051 if (!I.onlyReadsMemory()) 9052 return false; 9053 9054 SDNodeFlags Flags; 9055 Flags.copyFMF(cast<FPMathOperator>(I)); 9056 9057 SDValue Tmp = getValue(I.getArgOperand(0)); 9058 setValue(&I, 9059 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 9060 return true; 9061 } 9062 9063 /// See if we can lower a binary floating-point operation into an SDNode with 9064 /// the specified Opcode. If so, return true and lower it. Otherwise return 9065 /// false, and it will be lowered like a normal call. 9066 /// The caller already checked that \p I calls the appropriate LibFunc with a 9067 /// correct prototype. 9068 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 9069 unsigned Opcode) { 9070 // We already checked this call's prototype; verify it doesn't modify errno. 9071 if (!I.onlyReadsMemory()) 9072 return false; 9073 9074 SDNodeFlags Flags; 9075 Flags.copyFMF(cast<FPMathOperator>(I)); 9076 9077 SDValue Tmp0 = getValue(I.getArgOperand(0)); 9078 SDValue Tmp1 = getValue(I.getArgOperand(1)); 9079 EVT VT = Tmp0.getValueType(); 9080 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 9081 return true; 9082 } 9083 9084 void SelectionDAGBuilder::visitCall(const CallInst &I) { 9085 // Handle inline assembly differently. 9086 if (I.isInlineAsm()) { 9087 visitInlineAsm(I); 9088 return; 9089 } 9090 9091 diagnoseDontCall(I); 9092 9093 if (Function *F = I.getCalledFunction()) { 9094 if (F->isDeclaration()) { 9095 // Is this an LLVM intrinsic or a target-specific intrinsic? 9096 unsigned IID = F->getIntrinsicID(); 9097 if (!IID) 9098 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 9099 IID = II->getIntrinsicID(F); 9100 9101 if (IID) { 9102 visitIntrinsicCall(I, IID); 9103 return; 9104 } 9105 } 9106 9107 // Check for well-known libc/libm calls. If the function is internal, it 9108 // can't be a library call. Don't do the check if marked as nobuiltin for 9109 // some reason or the call site requires strict floating point semantics. 9110 LibFunc Func; 9111 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 9112 F->hasName() && LibInfo->getLibFunc(*F, Func) && 9113 LibInfo->hasOptimizedCodeGen(Func)) { 9114 switch (Func) { 9115 default: break; 9116 case LibFunc_bcmp: 9117 if (visitMemCmpBCmpCall(I)) 9118 return; 9119 break; 9120 case LibFunc_copysign: 9121 case LibFunc_copysignf: 9122 case LibFunc_copysignl: 9123 // We already checked this call's prototype; verify it doesn't modify 9124 // errno. 9125 if (I.onlyReadsMemory()) { 9126 SDValue LHS = getValue(I.getArgOperand(0)); 9127 SDValue RHS = getValue(I.getArgOperand(1)); 9128 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 9129 LHS.getValueType(), LHS, RHS)); 9130 return; 9131 } 9132 break; 9133 case LibFunc_fabs: 9134 case LibFunc_fabsf: 9135 case LibFunc_fabsl: 9136 if (visitUnaryFloatCall(I, ISD::FABS)) 9137 return; 9138 break; 9139 case LibFunc_fmin: 9140 case LibFunc_fminf: 9141 case LibFunc_fminl: 9142 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 9143 return; 9144 break; 9145 case LibFunc_fmax: 9146 case LibFunc_fmaxf: 9147 case LibFunc_fmaxl: 9148 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 9149 return; 9150 break; 9151 case LibFunc_sin: 9152 case LibFunc_sinf: 9153 case LibFunc_sinl: 9154 if (visitUnaryFloatCall(I, ISD::FSIN)) 9155 return; 9156 break; 9157 case LibFunc_cos: 9158 case LibFunc_cosf: 9159 case LibFunc_cosl: 9160 if (visitUnaryFloatCall(I, ISD::FCOS)) 9161 return; 9162 break; 9163 case LibFunc_sqrt: 9164 case LibFunc_sqrtf: 9165 case LibFunc_sqrtl: 9166 case LibFunc_sqrt_finite: 9167 case LibFunc_sqrtf_finite: 9168 case LibFunc_sqrtl_finite: 9169 if (visitUnaryFloatCall(I, ISD::FSQRT)) 9170 return; 9171 break; 9172 case LibFunc_floor: 9173 case LibFunc_floorf: 9174 case LibFunc_floorl: 9175 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 9176 return; 9177 break; 9178 case LibFunc_nearbyint: 9179 case LibFunc_nearbyintf: 9180 case LibFunc_nearbyintl: 9181 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 9182 return; 9183 break; 9184 case LibFunc_ceil: 9185 case LibFunc_ceilf: 9186 case LibFunc_ceill: 9187 if (visitUnaryFloatCall(I, ISD::FCEIL)) 9188 return; 9189 break; 9190 case LibFunc_rint: 9191 case LibFunc_rintf: 9192 case LibFunc_rintl: 9193 if (visitUnaryFloatCall(I, ISD::FRINT)) 9194 return; 9195 break; 9196 case LibFunc_round: 9197 case LibFunc_roundf: 9198 case LibFunc_roundl: 9199 if (visitUnaryFloatCall(I, ISD::FROUND)) 9200 return; 9201 break; 9202 case LibFunc_trunc: 9203 case LibFunc_truncf: 9204 case LibFunc_truncl: 9205 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 9206 return; 9207 break; 9208 case LibFunc_log2: 9209 case LibFunc_log2f: 9210 case LibFunc_log2l: 9211 if (visitUnaryFloatCall(I, ISD::FLOG2)) 9212 return; 9213 break; 9214 case LibFunc_exp2: 9215 case LibFunc_exp2f: 9216 case LibFunc_exp2l: 9217 if (visitUnaryFloatCall(I, ISD::FEXP2)) 9218 return; 9219 break; 9220 case LibFunc_exp10: 9221 case LibFunc_exp10f: 9222 case LibFunc_exp10l: 9223 if (visitUnaryFloatCall(I, ISD::FEXP10)) 9224 return; 9225 break; 9226 case LibFunc_ldexp: 9227 case LibFunc_ldexpf: 9228 case LibFunc_ldexpl: 9229 if (visitBinaryFloatCall(I, ISD::FLDEXP)) 9230 return; 9231 break; 9232 case LibFunc_memcmp: 9233 if (visitMemCmpBCmpCall(I)) 9234 return; 9235 break; 9236 case LibFunc_mempcpy: 9237 if (visitMemPCpyCall(I)) 9238 return; 9239 break; 9240 case LibFunc_memchr: 9241 if (visitMemChrCall(I)) 9242 return; 9243 break; 9244 case LibFunc_strcpy: 9245 if (visitStrCpyCall(I, false)) 9246 return; 9247 break; 9248 case LibFunc_stpcpy: 9249 if (visitStrCpyCall(I, true)) 9250 return; 9251 break; 9252 case LibFunc_strcmp: 9253 if (visitStrCmpCall(I)) 9254 return; 9255 break; 9256 case LibFunc_strlen: 9257 if (visitStrLenCall(I)) 9258 return; 9259 break; 9260 case LibFunc_strnlen: 9261 if (visitStrNLenCall(I)) 9262 return; 9263 break; 9264 } 9265 } 9266 } 9267 9268 if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) { 9269 LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), /*EHPadBB=*/nullptr); 9270 return; 9271 } 9272 9273 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 9274 // have to do anything here to lower funclet bundles. 9275 // CFGuardTarget bundles are lowered in LowerCallTo. 9276 assert(!I.hasOperandBundlesOtherThan( 9277 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 9278 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 9279 LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi, 9280 LLVMContext::OB_convergencectrl}) && 9281 "Cannot lower calls with arbitrary operand bundles!"); 9282 9283 SDValue Callee = getValue(I.getCalledOperand()); 9284 9285 if (I.hasDeoptState()) 9286 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 9287 else 9288 // Check if we can potentially perform a tail call. More detailed checking 9289 // is be done within LowerCallTo, after more information about the call is 9290 // known. 9291 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 9292 } 9293 9294 void SelectionDAGBuilder::LowerCallSiteWithPtrAuthBundle( 9295 const CallBase &CB, const BasicBlock *EHPadBB) { 9296 auto PAB = CB.getOperandBundle("ptrauth"); 9297 const Value *CalleeV = CB.getCalledOperand(); 9298 9299 // Gather the call ptrauth data from the operand bundle: 9300 // [ i32 <key>, i64 <discriminator> ] 9301 const auto *Key = cast<ConstantInt>(PAB->Inputs[0]); 9302 const Value *Discriminator = PAB->Inputs[1]; 9303 9304 assert(Key->getType()->isIntegerTy(32) && "Invalid ptrauth key"); 9305 assert(Discriminator->getType()->isIntegerTy(64) && 9306 "Invalid ptrauth discriminator"); 9307 9308 // Functions should never be ptrauth-called directly. 9309 assert(!isa<Function>(CalleeV) && "invalid direct ptrauth call"); 9310 9311 // Otherwise, do an authenticated indirect call. 9312 TargetLowering::PtrAuthInfo PAI = {Key->getZExtValue(), 9313 getValue(Discriminator)}; 9314 9315 LowerCallTo(CB, getValue(CalleeV), CB.isTailCall(), CB.isMustTailCall(), 9316 EHPadBB, &PAI); 9317 } 9318 9319 namespace { 9320 9321 /// AsmOperandInfo - This contains information for each constraint that we are 9322 /// lowering. 9323 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 9324 public: 9325 /// CallOperand - If this is the result output operand or a clobber 9326 /// this is null, otherwise it is the incoming operand to the CallInst. 9327 /// This gets modified as the asm is processed. 9328 SDValue CallOperand; 9329 9330 /// AssignedRegs - If this is a register or register class operand, this 9331 /// contains the set of register corresponding to the operand. 9332 RegsForValue AssignedRegs; 9333 9334 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 9335 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 9336 } 9337 9338 /// Whether or not this operand accesses memory 9339 bool hasMemory(const TargetLowering &TLI) const { 9340 // Indirect operand accesses access memory. 9341 if (isIndirect) 9342 return true; 9343 9344 for (const auto &Code : Codes) 9345 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 9346 return true; 9347 9348 return false; 9349 } 9350 }; 9351 9352 9353 } // end anonymous namespace 9354 9355 /// Make sure that the output operand \p OpInfo and its corresponding input 9356 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 9357 /// out). 9358 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 9359 SDISelAsmOperandInfo &MatchingOpInfo, 9360 SelectionDAG &DAG) { 9361 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 9362 return; 9363 9364 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 9365 const auto &TLI = DAG.getTargetLoweringInfo(); 9366 9367 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 9368 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 9369 OpInfo.ConstraintVT); 9370 std::pair<unsigned, const TargetRegisterClass *> InputRC = 9371 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 9372 MatchingOpInfo.ConstraintVT); 9373 if ((OpInfo.ConstraintVT.isInteger() != 9374 MatchingOpInfo.ConstraintVT.isInteger()) || 9375 (MatchRC.second != InputRC.second)) { 9376 // FIXME: error out in a more elegant fashion 9377 report_fatal_error("Unsupported asm: input constraint" 9378 " with a matching output constraint of" 9379 " incompatible type!"); 9380 } 9381 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 9382 } 9383 9384 /// Get a direct memory input to behave well as an indirect operand. 9385 /// This may introduce stores, hence the need for a \p Chain. 9386 /// \return The (possibly updated) chain. 9387 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 9388 SDISelAsmOperandInfo &OpInfo, 9389 SelectionDAG &DAG) { 9390 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9391 9392 // If we don't have an indirect input, put it in the constpool if we can, 9393 // otherwise spill it to a stack slot. 9394 // TODO: This isn't quite right. We need to handle these according to 9395 // the addressing mode that the constraint wants. Also, this may take 9396 // an additional register for the computation and we don't want that 9397 // either. 9398 9399 // If the operand is a float, integer, or vector constant, spill to a 9400 // constant pool entry to get its address. 9401 const Value *OpVal = OpInfo.CallOperandVal; 9402 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 9403 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 9404 OpInfo.CallOperand = DAG.getConstantPool( 9405 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 9406 return Chain; 9407 } 9408 9409 // Otherwise, create a stack slot and emit a store to it before the asm. 9410 Type *Ty = OpVal->getType(); 9411 auto &DL = DAG.getDataLayout(); 9412 uint64_t TySize = DL.getTypeAllocSize(Ty); 9413 MachineFunction &MF = DAG.getMachineFunction(); 9414 int SSFI = MF.getFrameInfo().CreateStackObject( 9415 TySize, DL.getPrefTypeAlign(Ty), false); 9416 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 9417 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 9418 MachinePointerInfo::getFixedStack(MF, SSFI), 9419 TLI.getMemValueType(DL, Ty)); 9420 OpInfo.CallOperand = StackSlot; 9421 9422 return Chain; 9423 } 9424 9425 /// GetRegistersForValue - Assign registers (virtual or physical) for the 9426 /// specified operand. We prefer to assign virtual registers, to allow the 9427 /// register allocator to handle the assignment process. However, if the asm 9428 /// uses features that we can't model on machineinstrs, we have SDISel do the 9429 /// allocation. This produces generally horrible, but correct, code. 9430 /// 9431 /// OpInfo describes the operand 9432 /// RefOpInfo describes the matching operand if any, the operand otherwise 9433 static std::optional<unsigned> 9434 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 9435 SDISelAsmOperandInfo &OpInfo, 9436 SDISelAsmOperandInfo &RefOpInfo) { 9437 LLVMContext &Context = *DAG.getContext(); 9438 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9439 9440 MachineFunction &MF = DAG.getMachineFunction(); 9441 SmallVector<unsigned, 4> Regs; 9442 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9443 9444 // No work to do for memory/address operands. 9445 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 9446 OpInfo.ConstraintType == TargetLowering::C_Address) 9447 return std::nullopt; 9448 9449 // If this is a constraint for a single physreg, or a constraint for a 9450 // register class, find it. 9451 unsigned AssignedReg; 9452 const TargetRegisterClass *RC; 9453 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 9454 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 9455 // RC is unset only on failure. Return immediately. 9456 if (!RC) 9457 return std::nullopt; 9458 9459 // Get the actual register value type. This is important, because the user 9460 // may have asked for (e.g.) the AX register in i32 type. We need to 9461 // remember that AX is actually i16 to get the right extension. 9462 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 9463 9464 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) { 9465 // If this is an FP operand in an integer register (or visa versa), or more 9466 // generally if the operand value disagrees with the register class we plan 9467 // to stick it in, fix the operand type. 9468 // 9469 // If this is an input value, the bitcast to the new type is done now. 9470 // Bitcast for output value is done at the end of visitInlineAsm(). 9471 if ((OpInfo.Type == InlineAsm::isOutput || 9472 OpInfo.Type == InlineAsm::isInput) && 9473 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 9474 // Try to convert to the first EVT that the reg class contains. If the 9475 // types are identical size, use a bitcast to convert (e.g. two differing 9476 // vector types). Note: output bitcast is done at the end of 9477 // visitInlineAsm(). 9478 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 9479 // Exclude indirect inputs while they are unsupported because the code 9480 // to perform the load is missing and thus OpInfo.CallOperand still 9481 // refers to the input address rather than the pointed-to value. 9482 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 9483 OpInfo.CallOperand = 9484 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 9485 OpInfo.ConstraintVT = RegVT; 9486 // If the operand is an FP value and we want it in integer registers, 9487 // use the corresponding integer type. This turns an f64 value into 9488 // i64, which can be passed with two i32 values on a 32-bit machine. 9489 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 9490 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 9491 if (OpInfo.Type == InlineAsm::isInput) 9492 OpInfo.CallOperand = 9493 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 9494 OpInfo.ConstraintVT = VT; 9495 } 9496 } 9497 } 9498 9499 // No need to allocate a matching input constraint since the constraint it's 9500 // matching to has already been allocated. 9501 if (OpInfo.isMatchingInputConstraint()) 9502 return std::nullopt; 9503 9504 EVT ValueVT = OpInfo.ConstraintVT; 9505 if (OpInfo.ConstraintVT == MVT::Other) 9506 ValueVT = RegVT; 9507 9508 // Initialize NumRegs. 9509 unsigned NumRegs = 1; 9510 if (OpInfo.ConstraintVT != MVT::Other) 9511 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT); 9512 9513 // If this is a constraint for a specific physical register, like {r17}, 9514 // assign it now. 9515 9516 // If this associated to a specific register, initialize iterator to correct 9517 // place. If virtual, make sure we have enough registers 9518 9519 // Initialize iterator if necessary 9520 TargetRegisterClass::iterator I = RC->begin(); 9521 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9522 9523 // Do not check for single registers. 9524 if (AssignedReg) { 9525 I = std::find(I, RC->end(), AssignedReg); 9526 if (I == RC->end()) { 9527 // RC does not contain the selected register, which indicates a 9528 // mismatch between the register and the required type/bitwidth. 9529 return {AssignedReg}; 9530 } 9531 } 9532 9533 for (; NumRegs; --NumRegs, ++I) { 9534 assert(I != RC->end() && "Ran out of registers to allocate!"); 9535 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 9536 Regs.push_back(R); 9537 } 9538 9539 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 9540 return std::nullopt; 9541 } 9542 9543 static unsigned 9544 findMatchingInlineAsmOperand(unsigned OperandNo, 9545 const std::vector<SDValue> &AsmNodeOperands) { 9546 // Scan until we find the definition we already emitted of this operand. 9547 unsigned CurOp = InlineAsm::Op_FirstOperand; 9548 for (; OperandNo; --OperandNo) { 9549 // Advance to the next operand. 9550 unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal(); 9551 const InlineAsm::Flag F(OpFlag); 9552 assert( 9553 (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) && 9554 "Skipped past definitions?"); 9555 CurOp += F.getNumOperandRegisters() + 1; 9556 } 9557 return CurOp; 9558 } 9559 9560 namespace { 9561 9562 class ExtraFlags { 9563 unsigned Flags = 0; 9564 9565 public: 9566 explicit ExtraFlags(const CallBase &Call) { 9567 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 9568 if (IA->hasSideEffects()) 9569 Flags |= InlineAsm::Extra_HasSideEffects; 9570 if (IA->isAlignStack()) 9571 Flags |= InlineAsm::Extra_IsAlignStack; 9572 if (Call.isConvergent()) 9573 Flags |= InlineAsm::Extra_IsConvergent; 9574 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 9575 } 9576 9577 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 9578 // Ideally, we would only check against memory constraints. However, the 9579 // meaning of an Other constraint can be target-specific and we can't easily 9580 // reason about it. Therefore, be conservative and set MayLoad/MayStore 9581 // for Other constraints as well. 9582 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 9583 OpInfo.ConstraintType == TargetLowering::C_Other) { 9584 if (OpInfo.Type == InlineAsm::isInput) 9585 Flags |= InlineAsm::Extra_MayLoad; 9586 else if (OpInfo.Type == InlineAsm::isOutput) 9587 Flags |= InlineAsm::Extra_MayStore; 9588 else if (OpInfo.Type == InlineAsm::isClobber) 9589 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 9590 } 9591 } 9592 9593 unsigned get() const { return Flags; } 9594 }; 9595 9596 } // end anonymous namespace 9597 9598 static bool isFunction(SDValue Op) { 9599 if (Op && Op.getOpcode() == ISD::GlobalAddress) { 9600 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 9601 auto Fn = dyn_cast_or_null<Function>(GA->getGlobal()); 9602 9603 // In normal "call dllimport func" instruction (non-inlineasm) it force 9604 // indirect access by specifing call opcode. And usually specially print 9605 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can 9606 // not do in this way now. (In fact, this is similar with "Data Access" 9607 // action). So here we ignore dllimport function. 9608 if (Fn && !Fn->hasDLLImportStorageClass()) 9609 return true; 9610 } 9611 } 9612 return false; 9613 } 9614 9615 /// visitInlineAsm - Handle a call to an InlineAsm object. 9616 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 9617 const BasicBlock *EHPadBB) { 9618 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 9619 9620 /// ConstraintOperands - Information about all of the constraints. 9621 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 9622 9623 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9624 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 9625 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 9626 9627 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 9628 // AsmDialect, MayLoad, MayStore). 9629 bool HasSideEffect = IA->hasSideEffects(); 9630 ExtraFlags ExtraInfo(Call); 9631 9632 for (auto &T : TargetConstraints) { 9633 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 9634 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 9635 9636 if (OpInfo.CallOperandVal) 9637 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 9638 9639 if (!HasSideEffect) 9640 HasSideEffect = OpInfo.hasMemory(TLI); 9641 9642 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 9643 // FIXME: Could we compute this on OpInfo rather than T? 9644 9645 // Compute the constraint code and ConstraintType to use. 9646 TLI.ComputeConstraintToUse(T, SDValue()); 9647 9648 if (T.ConstraintType == TargetLowering::C_Immediate && 9649 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 9650 // We've delayed emitting a diagnostic like the "n" constraint because 9651 // inlining could cause an integer showing up. 9652 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 9653 "' expects an integer constant " 9654 "expression"); 9655 9656 ExtraInfo.update(T); 9657 } 9658 9659 // We won't need to flush pending loads if this asm doesn't touch 9660 // memory and is nonvolatile. 9661 SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 9662 9663 bool EmitEHLabels = isa<InvokeInst>(Call); 9664 if (EmitEHLabels) { 9665 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 9666 } 9667 bool IsCallBr = isa<CallBrInst>(Call); 9668 9669 if (IsCallBr || EmitEHLabels) { 9670 // If this is a callbr or invoke we need to flush pending exports since 9671 // inlineasm_br and invoke are terminators. 9672 // We need to do this before nodes are glued to the inlineasm_br node. 9673 Chain = getControlRoot(); 9674 } 9675 9676 MCSymbol *BeginLabel = nullptr; 9677 if (EmitEHLabels) { 9678 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 9679 } 9680 9681 int OpNo = -1; 9682 SmallVector<StringRef> AsmStrs; 9683 IA->collectAsmStrs(AsmStrs); 9684 9685 // Second pass over the constraints: compute which constraint option to use. 9686 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9687 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput) 9688 OpNo++; 9689 9690 // If this is an output operand with a matching input operand, look up the 9691 // matching input. If their types mismatch, e.g. one is an integer, the 9692 // other is floating point, or their sizes are different, flag it as an 9693 // error. 9694 if (OpInfo.hasMatchingInput()) { 9695 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 9696 patchMatchingInput(OpInfo, Input, DAG); 9697 } 9698 9699 // Compute the constraint code and ConstraintType to use. 9700 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 9701 9702 if ((OpInfo.ConstraintType == TargetLowering::C_Memory && 9703 OpInfo.Type == InlineAsm::isClobber) || 9704 OpInfo.ConstraintType == TargetLowering::C_Address) 9705 continue; 9706 9707 // In Linux PIC model, there are 4 cases about value/label addressing: 9708 // 9709 // 1: Function call or Label jmp inside the module. 9710 // 2: Data access (such as global variable, static variable) inside module. 9711 // 3: Function call or Label jmp outside the module. 9712 // 4: Data access (such as global variable) outside the module. 9713 // 9714 // Due to current llvm inline asm architecture designed to not "recognize" 9715 // the asm code, there are quite troubles for us to treat mem addressing 9716 // differently for same value/adress used in different instuctions. 9717 // For example, in pic model, call a func may in plt way or direclty 9718 // pc-related, but lea/mov a function adress may use got. 9719 // 9720 // Here we try to "recognize" function call for the case 1 and case 3 in 9721 // inline asm. And try to adjust the constraint for them. 9722 // 9723 // TODO: Due to current inline asm didn't encourage to jmp to the outsider 9724 // label, so here we don't handle jmp function label now, but we need to 9725 // enhance it (especilly in PIC model) if we meet meaningful requirements. 9726 if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) && 9727 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) && 9728 TM.getCodeModel() != CodeModel::Large) { 9729 OpInfo.isIndirect = false; 9730 OpInfo.ConstraintType = TargetLowering::C_Address; 9731 } 9732 9733 // If this is a memory input, and if the operand is not indirect, do what we 9734 // need to provide an address for the memory input. 9735 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 9736 !OpInfo.isIndirect) { 9737 assert((OpInfo.isMultipleAlternative || 9738 (OpInfo.Type == InlineAsm::isInput)) && 9739 "Can only indirectify direct input operands!"); 9740 9741 // Memory operands really want the address of the value. 9742 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 9743 9744 // There is no longer a Value* corresponding to this operand. 9745 OpInfo.CallOperandVal = nullptr; 9746 9747 // It is now an indirect operand. 9748 OpInfo.isIndirect = true; 9749 } 9750 9751 } 9752 9753 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 9754 std::vector<SDValue> AsmNodeOperands; 9755 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 9756 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 9757 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 9758 9759 // If we have a !srcloc metadata node associated with it, we want to attach 9760 // this to the ultimately generated inline asm machineinstr. To do this, we 9761 // pass in the third operand as this (potentially null) inline asm MDNode. 9762 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 9763 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 9764 9765 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 9766 // bits as operand 3. 9767 AsmNodeOperands.push_back(DAG.getTargetConstant( 9768 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9769 9770 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 9771 // this, assign virtual and physical registers for inputs and otput. 9772 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9773 // Assign Registers. 9774 SDISelAsmOperandInfo &RefOpInfo = 9775 OpInfo.isMatchingInputConstraint() 9776 ? ConstraintOperands[OpInfo.getMatchedOperand()] 9777 : OpInfo; 9778 const auto RegError = 9779 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 9780 if (RegError) { 9781 const MachineFunction &MF = DAG.getMachineFunction(); 9782 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9783 const char *RegName = TRI.getName(*RegError); 9784 emitInlineAsmError(Call, "register '" + Twine(RegName) + 9785 "' allocated for constraint '" + 9786 Twine(OpInfo.ConstraintCode) + 9787 "' does not match required type"); 9788 return; 9789 } 9790 9791 auto DetectWriteToReservedRegister = [&]() { 9792 const MachineFunction &MF = DAG.getMachineFunction(); 9793 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9794 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 9795 if (Register::isPhysicalRegister(Reg) && 9796 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 9797 const char *RegName = TRI.getName(Reg); 9798 emitInlineAsmError(Call, "write to reserved register '" + 9799 Twine(RegName) + "'"); 9800 return true; 9801 } 9802 } 9803 return false; 9804 }; 9805 assert((OpInfo.ConstraintType != TargetLowering::C_Address || 9806 (OpInfo.Type == InlineAsm::isInput && 9807 !OpInfo.isMatchingInputConstraint())) && 9808 "Only address as input operand is allowed."); 9809 9810 switch (OpInfo.Type) { 9811 case InlineAsm::isOutput: 9812 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9813 const InlineAsm::ConstraintCode ConstraintID = 9814 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9815 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 9816 "Failed to convert memory constraint code to constraint id."); 9817 9818 // Add information to the INLINEASM node to know about this output. 9819 InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1); 9820 OpFlags.setMemConstraint(ConstraintID); 9821 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 9822 MVT::i32)); 9823 AsmNodeOperands.push_back(OpInfo.CallOperand); 9824 } else { 9825 // Otherwise, this outputs to a register (directly for C_Register / 9826 // C_RegisterClass, and a target-defined fashion for 9827 // C_Immediate/C_Other). Find a register that we can use. 9828 if (OpInfo.AssignedRegs.Regs.empty()) { 9829 emitInlineAsmError( 9830 Call, "couldn't allocate output register for constraint '" + 9831 Twine(OpInfo.ConstraintCode) + "'"); 9832 return; 9833 } 9834 9835 if (DetectWriteToReservedRegister()) 9836 return; 9837 9838 // Add information to the INLINEASM node to know that this register is 9839 // set. 9840 OpInfo.AssignedRegs.AddInlineAsmOperands( 9841 OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber 9842 : InlineAsm::Kind::RegDef, 9843 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 9844 } 9845 break; 9846 9847 case InlineAsm::isInput: 9848 case InlineAsm::isLabel: { 9849 SDValue InOperandVal = OpInfo.CallOperand; 9850 9851 if (OpInfo.isMatchingInputConstraint()) { 9852 // If this is required to match an output register we have already set, 9853 // just use its register. 9854 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 9855 AsmNodeOperands); 9856 InlineAsm::Flag Flag(AsmNodeOperands[CurOp]->getAsZExtVal()); 9857 if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) { 9858 if (OpInfo.isIndirect) { 9859 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 9860 emitInlineAsmError(Call, "inline asm not supported yet: " 9861 "don't know how to handle tied " 9862 "indirect register inputs"); 9863 return; 9864 } 9865 9866 SmallVector<unsigned, 4> Regs; 9867 MachineFunction &MF = DAG.getMachineFunction(); 9868 MachineRegisterInfo &MRI = MF.getRegInfo(); 9869 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9870 auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]); 9871 Register TiedReg = R->getReg(); 9872 MVT RegVT = R->getSimpleValueType(0); 9873 const TargetRegisterClass *RC = 9874 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg) 9875 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT) 9876 : TRI.getMinimalPhysRegClass(TiedReg); 9877 for (unsigned i = 0, e = Flag.getNumOperandRegisters(); i != e; ++i) 9878 Regs.push_back(MRI.createVirtualRegister(RC)); 9879 9880 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 9881 9882 SDLoc dl = getCurSDLoc(); 9883 // Use the produced MatchedRegs object to 9884 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call); 9885 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, true, 9886 OpInfo.getMatchedOperand(), dl, DAG, 9887 AsmNodeOperands); 9888 break; 9889 } 9890 9891 assert(Flag.isMemKind() && "Unknown matching constraint!"); 9892 assert(Flag.getNumOperandRegisters() == 1 && 9893 "Unexpected number of operands"); 9894 // Add information to the INLINEASM node to know about this input. 9895 // See InlineAsm.h isUseOperandTiedToDef. 9896 Flag.clearMemConstraint(); 9897 Flag.setMatchingOp(OpInfo.getMatchedOperand()); 9898 AsmNodeOperands.push_back(DAG.getTargetConstant( 9899 Flag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9900 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 9901 break; 9902 } 9903 9904 // Treat indirect 'X' constraint as memory. 9905 if (OpInfo.ConstraintType == TargetLowering::C_Other && 9906 OpInfo.isIndirect) 9907 OpInfo.ConstraintType = TargetLowering::C_Memory; 9908 9909 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 9910 OpInfo.ConstraintType == TargetLowering::C_Other) { 9911 std::vector<SDValue> Ops; 9912 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 9913 Ops, DAG); 9914 if (Ops.empty()) { 9915 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 9916 if (isa<ConstantSDNode>(InOperandVal)) { 9917 emitInlineAsmError(Call, "value out of range for constraint '" + 9918 Twine(OpInfo.ConstraintCode) + "'"); 9919 return; 9920 } 9921 9922 emitInlineAsmError(Call, 9923 "invalid operand for inline asm constraint '" + 9924 Twine(OpInfo.ConstraintCode) + "'"); 9925 return; 9926 } 9927 9928 // Add information to the INLINEASM node to know about this input. 9929 InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size()); 9930 AsmNodeOperands.push_back(DAG.getTargetConstant( 9931 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9932 llvm::append_range(AsmNodeOperands, Ops); 9933 break; 9934 } 9935 9936 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9937 assert((OpInfo.isIndirect || 9938 OpInfo.ConstraintType != TargetLowering::C_Memory) && 9939 "Operand must be indirect to be a mem!"); 9940 assert(InOperandVal.getValueType() == 9941 TLI.getPointerTy(DAG.getDataLayout()) && 9942 "Memory operands expect pointer values"); 9943 9944 const InlineAsm::ConstraintCode ConstraintID = 9945 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9946 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 9947 "Failed to convert memory constraint code to constraint id."); 9948 9949 // Add information to the INLINEASM node to know about this input. 9950 InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1); 9951 ResOpType.setMemConstraint(ConstraintID); 9952 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 9953 getCurSDLoc(), 9954 MVT::i32)); 9955 AsmNodeOperands.push_back(InOperandVal); 9956 break; 9957 } 9958 9959 if (OpInfo.ConstraintType == TargetLowering::C_Address) { 9960 const InlineAsm::ConstraintCode ConstraintID = 9961 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9962 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 9963 "Failed to convert memory constraint code to constraint id."); 9964 9965 InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1); 9966 9967 SDValue AsmOp = InOperandVal; 9968 if (isFunction(InOperandVal)) { 9969 auto *GA = cast<GlobalAddressSDNode>(InOperandVal); 9970 ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1); 9971 AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(), 9972 InOperandVal.getValueType(), 9973 GA->getOffset()); 9974 } 9975 9976 // Add information to the INLINEASM node to know about this input. 9977 ResOpType.setMemConstraint(ConstraintID); 9978 9979 AsmNodeOperands.push_back( 9980 DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32)); 9981 9982 AsmNodeOperands.push_back(AsmOp); 9983 break; 9984 } 9985 9986 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 9987 OpInfo.ConstraintType == TargetLowering::C_Register) && 9988 "Unknown constraint type!"); 9989 9990 // TODO: Support this. 9991 if (OpInfo.isIndirect) { 9992 emitInlineAsmError( 9993 Call, "Don't know how to handle indirect register inputs yet " 9994 "for constraint '" + 9995 Twine(OpInfo.ConstraintCode) + "'"); 9996 return; 9997 } 9998 9999 // Copy the input into the appropriate registers. 10000 if (OpInfo.AssignedRegs.Regs.empty()) { 10001 emitInlineAsmError(Call, 10002 "couldn't allocate input reg for constraint '" + 10003 Twine(OpInfo.ConstraintCode) + "'"); 10004 return; 10005 } 10006 10007 if (DetectWriteToReservedRegister()) 10008 return; 10009 10010 SDLoc dl = getCurSDLoc(); 10011 10012 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, 10013 &Call); 10014 10015 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, false, 10016 0, dl, DAG, AsmNodeOperands); 10017 break; 10018 } 10019 case InlineAsm::isClobber: 10020 // Add the clobbered value to the operand list, so that the register 10021 // allocator is aware that the physreg got clobbered. 10022 if (!OpInfo.AssignedRegs.Regs.empty()) 10023 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::Clobber, 10024 false, 0, getCurSDLoc(), DAG, 10025 AsmNodeOperands); 10026 break; 10027 } 10028 } 10029 10030 // Finish up input operands. Set the input chain and add the flag last. 10031 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 10032 if (Glue.getNode()) AsmNodeOperands.push_back(Glue); 10033 10034 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 10035 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 10036 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 10037 Glue = Chain.getValue(1); 10038 10039 // Do additional work to generate outputs. 10040 10041 SmallVector<EVT, 1> ResultVTs; 10042 SmallVector<SDValue, 1> ResultValues; 10043 SmallVector<SDValue, 8> OutChains; 10044 10045 llvm::Type *CallResultType = Call.getType(); 10046 ArrayRef<Type *> ResultTypes; 10047 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 10048 ResultTypes = StructResult->elements(); 10049 else if (!CallResultType->isVoidTy()) 10050 ResultTypes = ArrayRef(CallResultType); 10051 10052 auto CurResultType = ResultTypes.begin(); 10053 auto handleRegAssign = [&](SDValue V) { 10054 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 10055 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 10056 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 10057 ++CurResultType; 10058 // If the type of the inline asm call site return value is different but has 10059 // same size as the type of the asm output bitcast it. One example of this 10060 // is for vectors with different width / number of elements. This can 10061 // happen for register classes that can contain multiple different value 10062 // types. The preg or vreg allocated may not have the same VT as was 10063 // expected. 10064 // 10065 // This can also happen for a return value that disagrees with the register 10066 // class it is put in, eg. a double in a general-purpose register on a 10067 // 32-bit machine. 10068 if (ResultVT != V.getValueType() && 10069 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 10070 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 10071 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 10072 V.getValueType().isInteger()) { 10073 // If a result value was tied to an input value, the computed result 10074 // may have a wider width than the expected result. Extract the 10075 // relevant portion. 10076 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 10077 } 10078 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 10079 ResultVTs.push_back(ResultVT); 10080 ResultValues.push_back(V); 10081 }; 10082 10083 // Deal with output operands. 10084 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 10085 if (OpInfo.Type == InlineAsm::isOutput) { 10086 SDValue Val; 10087 // Skip trivial output operands. 10088 if (OpInfo.AssignedRegs.Regs.empty()) 10089 continue; 10090 10091 switch (OpInfo.ConstraintType) { 10092 case TargetLowering::C_Register: 10093 case TargetLowering::C_RegisterClass: 10094 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 10095 Chain, &Glue, &Call); 10096 break; 10097 case TargetLowering::C_Immediate: 10098 case TargetLowering::C_Other: 10099 Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(), 10100 OpInfo, DAG); 10101 break; 10102 case TargetLowering::C_Memory: 10103 break; // Already handled. 10104 case TargetLowering::C_Address: 10105 break; // Silence warning. 10106 case TargetLowering::C_Unknown: 10107 assert(false && "Unexpected unknown constraint"); 10108 } 10109 10110 // Indirect output manifest as stores. Record output chains. 10111 if (OpInfo.isIndirect) { 10112 const Value *Ptr = OpInfo.CallOperandVal; 10113 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 10114 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 10115 MachinePointerInfo(Ptr)); 10116 OutChains.push_back(Store); 10117 } else { 10118 // generate CopyFromRegs to associated registers. 10119 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 10120 if (Val.getOpcode() == ISD::MERGE_VALUES) { 10121 for (const SDValue &V : Val->op_values()) 10122 handleRegAssign(V); 10123 } else 10124 handleRegAssign(Val); 10125 } 10126 } 10127 } 10128 10129 // Set results. 10130 if (!ResultValues.empty()) { 10131 assert(CurResultType == ResultTypes.end() && 10132 "Mismatch in number of ResultTypes"); 10133 assert(ResultValues.size() == ResultTypes.size() && 10134 "Mismatch in number of output operands in asm result"); 10135 10136 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 10137 DAG.getVTList(ResultVTs), ResultValues); 10138 setValue(&Call, V); 10139 } 10140 10141 // Collect store chains. 10142 if (!OutChains.empty()) 10143 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 10144 10145 if (EmitEHLabels) { 10146 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 10147 } 10148 10149 // Only Update Root if inline assembly has a memory effect. 10150 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 10151 EmitEHLabels) 10152 DAG.setRoot(Chain); 10153 } 10154 10155 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 10156 const Twine &Message) { 10157 LLVMContext &Ctx = *DAG.getContext(); 10158 Ctx.emitError(&Call, Message); 10159 10160 // Make sure we leave the DAG in a valid state 10161 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10162 SmallVector<EVT, 1> ValueVTs; 10163 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 10164 10165 if (ValueVTs.empty()) 10166 return; 10167 10168 SmallVector<SDValue, 1> Ops; 10169 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 10170 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 10171 10172 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 10173 } 10174 10175 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 10176 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 10177 MVT::Other, getRoot(), 10178 getValue(I.getArgOperand(0)), 10179 DAG.getSrcValue(I.getArgOperand(0)))); 10180 } 10181 10182 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 10183 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10184 const DataLayout &DL = DAG.getDataLayout(); 10185 SDValue V = DAG.getVAArg( 10186 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 10187 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 10188 DL.getABITypeAlign(I.getType()).value()); 10189 DAG.setRoot(V.getValue(1)); 10190 10191 if (I.getType()->isPointerTy()) 10192 V = DAG.getPtrExtOrTrunc( 10193 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 10194 setValue(&I, V); 10195 } 10196 10197 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 10198 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 10199 MVT::Other, getRoot(), 10200 getValue(I.getArgOperand(0)), 10201 DAG.getSrcValue(I.getArgOperand(0)))); 10202 } 10203 10204 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 10205 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 10206 MVT::Other, getRoot(), 10207 getValue(I.getArgOperand(0)), 10208 getValue(I.getArgOperand(1)), 10209 DAG.getSrcValue(I.getArgOperand(0)), 10210 DAG.getSrcValue(I.getArgOperand(1)))); 10211 } 10212 10213 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 10214 const Instruction &I, 10215 SDValue Op) { 10216 const MDNode *Range = getRangeMetadata(I); 10217 if (!Range) 10218 return Op; 10219 10220 ConstantRange CR = getConstantRangeFromMetadata(*Range); 10221 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 10222 return Op; 10223 10224 APInt Lo = CR.getUnsignedMin(); 10225 if (!Lo.isMinValue()) 10226 return Op; 10227 10228 APInt Hi = CR.getUnsignedMax(); 10229 unsigned Bits = std::max(Hi.getActiveBits(), 10230 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 10231 10232 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 10233 10234 SDLoc SL = getCurSDLoc(); 10235 10236 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 10237 DAG.getValueType(SmallVT)); 10238 unsigned NumVals = Op.getNode()->getNumValues(); 10239 if (NumVals == 1) 10240 return ZExt; 10241 10242 SmallVector<SDValue, 4> Ops; 10243 10244 Ops.push_back(ZExt); 10245 for (unsigned I = 1; I != NumVals; ++I) 10246 Ops.push_back(Op.getValue(I)); 10247 10248 return DAG.getMergeValues(Ops, SL); 10249 } 10250 10251 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 10252 /// the call being lowered. 10253 /// 10254 /// This is a helper for lowering intrinsics that follow a target calling 10255 /// convention or require stack pointer adjustment. Only a subset of the 10256 /// intrinsic's operands need to participate in the calling convention. 10257 void SelectionDAGBuilder::populateCallLoweringInfo( 10258 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 10259 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 10260 AttributeSet RetAttrs, bool IsPatchPoint) { 10261 TargetLowering::ArgListTy Args; 10262 Args.reserve(NumArgs); 10263 10264 // Populate the argument list. 10265 // Attributes for args start at offset 1, after the return attribute. 10266 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 10267 ArgI != ArgE; ++ArgI) { 10268 const Value *V = Call->getOperand(ArgI); 10269 10270 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 10271 10272 TargetLowering::ArgListEntry Entry; 10273 Entry.Node = getValue(V); 10274 Entry.Ty = V->getType(); 10275 Entry.setAttributes(Call, ArgI); 10276 Args.push_back(Entry); 10277 } 10278 10279 CLI.setDebugLoc(getCurSDLoc()) 10280 .setChain(getRoot()) 10281 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args), 10282 RetAttrs) 10283 .setDiscardResult(Call->use_empty()) 10284 .setIsPatchPoint(IsPatchPoint) 10285 .setIsPreallocated( 10286 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 10287 } 10288 10289 /// Add a stack map intrinsic call's live variable operands to a stackmap 10290 /// or patchpoint target node's operand list. 10291 /// 10292 /// Constants are converted to TargetConstants purely as an optimization to 10293 /// avoid constant materialization and register allocation. 10294 /// 10295 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 10296 /// generate addess computation nodes, and so FinalizeISel can convert the 10297 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 10298 /// address materialization and register allocation, but may also be required 10299 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 10300 /// alloca in the entry block, then the runtime may assume that the alloca's 10301 /// StackMap location can be read immediately after compilation and that the 10302 /// location is valid at any point during execution (this is similar to the 10303 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 10304 /// only available in a register, then the runtime would need to trap when 10305 /// execution reaches the StackMap in order to read the alloca's location. 10306 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 10307 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 10308 SelectionDAGBuilder &Builder) { 10309 SelectionDAG &DAG = Builder.DAG; 10310 for (unsigned I = StartIdx; I < Call.arg_size(); I++) { 10311 SDValue Op = Builder.getValue(Call.getArgOperand(I)); 10312 10313 // Things on the stack are pointer-typed, meaning that they are already 10314 // legal and can be emitted directly to target nodes. 10315 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) { 10316 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType())); 10317 } else { 10318 // Otherwise emit a target independent node to be legalised. 10319 Ops.push_back(Builder.getValue(Call.getArgOperand(I))); 10320 } 10321 } 10322 } 10323 10324 /// Lower llvm.experimental.stackmap. 10325 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 10326 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>, 10327 // [live variables...]) 10328 10329 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 10330 10331 SDValue Chain, InGlue, Callee; 10332 SmallVector<SDValue, 32> Ops; 10333 10334 SDLoc DL = getCurSDLoc(); 10335 Callee = getValue(CI.getCalledOperand()); 10336 10337 // The stackmap intrinsic only records the live variables (the arguments 10338 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 10339 // intrinsic, this won't be lowered to a function call. This means we don't 10340 // have to worry about calling conventions and target specific lowering code. 10341 // Instead we perform the call lowering right here. 10342 // 10343 // chain, flag = CALLSEQ_START(chain, 0, 0) 10344 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 10345 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 10346 // 10347 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 10348 InGlue = Chain.getValue(1); 10349 10350 // Add the STACKMAP operands, starting with DAG house-keeping. 10351 Ops.push_back(Chain); 10352 Ops.push_back(InGlue); 10353 10354 // Add the <id>, <numShadowBytes> operands. 10355 // 10356 // These do not require legalisation, and can be emitted directly to target 10357 // constant nodes. 10358 SDValue ID = getValue(CI.getArgOperand(0)); 10359 assert(ID.getValueType() == MVT::i64); 10360 SDValue IDConst = 10361 DAG.getTargetConstant(ID->getAsZExtVal(), DL, ID.getValueType()); 10362 Ops.push_back(IDConst); 10363 10364 SDValue Shad = getValue(CI.getArgOperand(1)); 10365 assert(Shad.getValueType() == MVT::i32); 10366 SDValue ShadConst = 10367 DAG.getTargetConstant(Shad->getAsZExtVal(), DL, Shad.getValueType()); 10368 Ops.push_back(ShadConst); 10369 10370 // Add the live variables. 10371 addStackMapLiveVars(CI, 2, DL, Ops, *this); 10372 10373 // Create the STACKMAP node. 10374 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10375 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops); 10376 InGlue = Chain.getValue(1); 10377 10378 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL); 10379 10380 // Stackmaps don't generate values, so nothing goes into the NodeMap. 10381 10382 // Set the root to the target-lowered call chain. 10383 DAG.setRoot(Chain); 10384 10385 // Inform the Frame Information that we have a stackmap in this function. 10386 FuncInfo.MF->getFrameInfo().setHasStackMap(); 10387 } 10388 10389 /// Lower llvm.experimental.patchpoint directly to its target opcode. 10390 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 10391 const BasicBlock *EHPadBB) { 10392 // <ty> @llvm.experimental.patchpoint.<ty>(i64 <id>, 10393 // i32 <numBytes>, 10394 // i8* <target>, 10395 // i32 <numArgs>, 10396 // [Args...], 10397 // [live variables...]) 10398 10399 CallingConv::ID CC = CB.getCallingConv(); 10400 bool IsAnyRegCC = CC == CallingConv::AnyReg; 10401 bool HasDef = !CB.getType()->isVoidTy(); 10402 SDLoc dl = getCurSDLoc(); 10403 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 10404 10405 // Handle immediate and symbolic callees. 10406 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 10407 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 10408 /*isTarget=*/true); 10409 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 10410 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 10411 SDLoc(SymbolicCallee), 10412 SymbolicCallee->getValueType(0)); 10413 10414 // Get the real number of arguments participating in the call <numArgs> 10415 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 10416 unsigned NumArgs = NArgVal->getAsZExtVal(); 10417 10418 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 10419 // Intrinsics include all meta-operands up to but not including CC. 10420 unsigned NumMetaOpers = PatchPointOpers::CCPos; 10421 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 10422 "Not enough arguments provided to the patchpoint intrinsic"); 10423 10424 // For AnyRegCC the arguments are lowered later on manually. 10425 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 10426 Type *ReturnTy = 10427 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 10428 10429 TargetLowering::CallLoweringInfo CLI(DAG); 10430 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 10431 ReturnTy, CB.getAttributes().getRetAttrs(), true); 10432 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 10433 10434 SDNode *CallEnd = Result.second.getNode(); 10435 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 10436 CallEnd = CallEnd->getOperand(0).getNode(); 10437 10438 /// Get a call instruction from the call sequence chain. 10439 /// Tail calls are not allowed. 10440 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 10441 "Expected a callseq node."); 10442 SDNode *Call = CallEnd->getOperand(0).getNode(); 10443 bool HasGlue = Call->getGluedNode(); 10444 10445 // Replace the target specific call node with the patchable intrinsic. 10446 SmallVector<SDValue, 8> Ops; 10447 10448 // Push the chain. 10449 Ops.push_back(*(Call->op_begin())); 10450 10451 // Optionally, push the glue (if any). 10452 if (HasGlue) 10453 Ops.push_back(*(Call->op_end() - 1)); 10454 10455 // Push the register mask info. 10456 if (HasGlue) 10457 Ops.push_back(*(Call->op_end() - 2)); 10458 else 10459 Ops.push_back(*(Call->op_end() - 1)); 10460 10461 // Add the <id> and <numBytes> constants. 10462 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 10463 Ops.push_back(DAG.getTargetConstant(IDVal->getAsZExtVal(), dl, MVT::i64)); 10464 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 10465 Ops.push_back(DAG.getTargetConstant(NBytesVal->getAsZExtVal(), dl, MVT::i32)); 10466 10467 // Add the callee. 10468 Ops.push_back(Callee); 10469 10470 // Adjust <numArgs> to account for any arguments that have been passed on the 10471 // stack instead. 10472 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 10473 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 10474 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 10475 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 10476 10477 // Add the calling convention 10478 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 10479 10480 // Add the arguments we omitted previously. The register allocator should 10481 // place these in any free register. 10482 if (IsAnyRegCC) 10483 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 10484 Ops.push_back(getValue(CB.getArgOperand(i))); 10485 10486 // Push the arguments from the call instruction. 10487 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 10488 Ops.append(Call->op_begin() + 2, e); 10489 10490 // Push live variables for the stack map. 10491 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 10492 10493 SDVTList NodeTys; 10494 if (IsAnyRegCC && HasDef) { 10495 // Create the return types based on the intrinsic definition 10496 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10497 SmallVector<EVT, 3> ValueVTs; 10498 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 10499 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 10500 10501 // There is always a chain and a glue type at the end 10502 ValueVTs.push_back(MVT::Other); 10503 ValueVTs.push_back(MVT::Glue); 10504 NodeTys = DAG.getVTList(ValueVTs); 10505 } else 10506 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10507 10508 // Replace the target specific call node with a PATCHPOINT node. 10509 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops); 10510 10511 // Update the NodeMap. 10512 if (HasDef) { 10513 if (IsAnyRegCC) 10514 setValue(&CB, SDValue(PPV.getNode(), 0)); 10515 else 10516 setValue(&CB, Result.first); 10517 } 10518 10519 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 10520 // call sequence. Furthermore the location of the chain and glue can change 10521 // when the AnyReg calling convention is used and the intrinsic returns a 10522 // value. 10523 if (IsAnyRegCC && HasDef) { 10524 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 10525 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)}; 10526 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 10527 } else 10528 DAG.ReplaceAllUsesWith(Call, PPV.getNode()); 10529 DAG.DeleteNode(Call); 10530 10531 // Inform the Frame Information that we have a patchpoint in this function. 10532 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 10533 } 10534 10535 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 10536 unsigned Intrinsic) { 10537 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10538 SDValue Op1 = getValue(I.getArgOperand(0)); 10539 SDValue Op2; 10540 if (I.arg_size() > 1) 10541 Op2 = getValue(I.getArgOperand(1)); 10542 SDLoc dl = getCurSDLoc(); 10543 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 10544 SDValue Res; 10545 SDNodeFlags SDFlags; 10546 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 10547 SDFlags.copyFMF(*FPMO); 10548 10549 switch (Intrinsic) { 10550 case Intrinsic::vector_reduce_fadd: 10551 if (SDFlags.hasAllowReassociation()) 10552 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 10553 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 10554 SDFlags); 10555 else 10556 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 10557 break; 10558 case Intrinsic::vector_reduce_fmul: 10559 if (SDFlags.hasAllowReassociation()) 10560 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 10561 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 10562 SDFlags); 10563 else 10564 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 10565 break; 10566 case Intrinsic::vector_reduce_add: 10567 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 10568 break; 10569 case Intrinsic::vector_reduce_mul: 10570 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 10571 break; 10572 case Intrinsic::vector_reduce_and: 10573 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 10574 break; 10575 case Intrinsic::vector_reduce_or: 10576 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 10577 break; 10578 case Intrinsic::vector_reduce_xor: 10579 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 10580 break; 10581 case Intrinsic::vector_reduce_smax: 10582 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 10583 break; 10584 case Intrinsic::vector_reduce_smin: 10585 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 10586 break; 10587 case Intrinsic::vector_reduce_umax: 10588 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 10589 break; 10590 case Intrinsic::vector_reduce_umin: 10591 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 10592 break; 10593 case Intrinsic::vector_reduce_fmax: 10594 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 10595 break; 10596 case Intrinsic::vector_reduce_fmin: 10597 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 10598 break; 10599 case Intrinsic::vector_reduce_fmaximum: 10600 Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags); 10601 break; 10602 case Intrinsic::vector_reduce_fminimum: 10603 Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags); 10604 break; 10605 default: 10606 llvm_unreachable("Unhandled vector reduce intrinsic"); 10607 } 10608 setValue(&I, Res); 10609 } 10610 10611 /// Returns an AttributeList representing the attributes applied to the return 10612 /// value of the given call. 10613 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 10614 SmallVector<Attribute::AttrKind, 2> Attrs; 10615 if (CLI.RetSExt) 10616 Attrs.push_back(Attribute::SExt); 10617 if (CLI.RetZExt) 10618 Attrs.push_back(Attribute::ZExt); 10619 if (CLI.IsInReg) 10620 Attrs.push_back(Attribute::InReg); 10621 10622 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 10623 Attrs); 10624 } 10625 10626 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 10627 /// implementation, which just calls LowerCall. 10628 /// FIXME: When all targets are 10629 /// migrated to using LowerCall, this hook should be integrated into SDISel. 10630 std::pair<SDValue, SDValue> 10631 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 10632 // Handle the incoming return values from the call. 10633 CLI.Ins.clear(); 10634 Type *OrigRetTy = CLI.RetTy; 10635 SmallVector<EVT, 4> RetTys; 10636 SmallVector<TypeSize, 4> Offsets; 10637 auto &DL = CLI.DAG.getDataLayout(); 10638 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 10639 10640 if (CLI.IsPostTypeLegalization) { 10641 // If we are lowering a libcall after legalization, split the return type. 10642 SmallVector<EVT, 4> OldRetTys; 10643 SmallVector<TypeSize, 4> OldOffsets; 10644 RetTys.swap(OldRetTys); 10645 Offsets.swap(OldOffsets); 10646 10647 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 10648 EVT RetVT = OldRetTys[i]; 10649 uint64_t Offset = OldOffsets[i]; 10650 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 10651 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 10652 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 10653 RetTys.append(NumRegs, RegisterVT); 10654 for (unsigned j = 0; j != NumRegs; ++j) 10655 Offsets.push_back(TypeSize::getFixed(Offset + j * RegisterVTByteSZ)); 10656 } 10657 } 10658 10659 SmallVector<ISD::OutputArg, 4> Outs; 10660 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 10661 10662 bool CanLowerReturn = 10663 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 10664 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 10665 10666 SDValue DemoteStackSlot; 10667 int DemoteStackIdx = -100; 10668 if (!CanLowerReturn) { 10669 // FIXME: equivalent assert? 10670 // assert(!CS.hasInAllocaArgument() && 10671 // "sret demotion is incompatible with inalloca"); 10672 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 10673 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 10674 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10675 DemoteStackIdx = 10676 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 10677 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 10678 DL.getAllocaAddrSpace()); 10679 10680 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 10681 ArgListEntry Entry; 10682 Entry.Node = DemoteStackSlot; 10683 Entry.Ty = StackSlotPtrType; 10684 Entry.IsSExt = false; 10685 Entry.IsZExt = false; 10686 Entry.IsInReg = false; 10687 Entry.IsSRet = true; 10688 Entry.IsNest = false; 10689 Entry.IsByVal = false; 10690 Entry.IsByRef = false; 10691 Entry.IsReturned = false; 10692 Entry.IsSwiftSelf = false; 10693 Entry.IsSwiftAsync = false; 10694 Entry.IsSwiftError = false; 10695 Entry.IsCFGuardTarget = false; 10696 Entry.Alignment = Alignment; 10697 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 10698 CLI.NumFixedArgs += 1; 10699 CLI.getArgs()[0].IndirectType = CLI.RetTy; 10700 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 10701 10702 // sret demotion isn't compatible with tail-calls, since the sret argument 10703 // points into the callers stack frame. 10704 CLI.IsTailCall = false; 10705 } else { 10706 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10707 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL); 10708 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 10709 ISD::ArgFlagsTy Flags; 10710 if (NeedsRegBlock) { 10711 Flags.setInConsecutiveRegs(); 10712 if (I == RetTys.size() - 1) 10713 Flags.setInConsecutiveRegsLast(); 10714 } 10715 EVT VT = RetTys[I]; 10716 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10717 CLI.CallConv, VT); 10718 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10719 CLI.CallConv, VT); 10720 for (unsigned i = 0; i != NumRegs; ++i) { 10721 ISD::InputArg MyFlags; 10722 MyFlags.Flags = Flags; 10723 MyFlags.VT = RegisterVT; 10724 MyFlags.ArgVT = VT; 10725 MyFlags.Used = CLI.IsReturnValueUsed; 10726 if (CLI.RetTy->isPointerTy()) { 10727 MyFlags.Flags.setPointer(); 10728 MyFlags.Flags.setPointerAddrSpace( 10729 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 10730 } 10731 if (CLI.RetSExt) 10732 MyFlags.Flags.setSExt(); 10733 if (CLI.RetZExt) 10734 MyFlags.Flags.setZExt(); 10735 if (CLI.IsInReg) 10736 MyFlags.Flags.setInReg(); 10737 CLI.Ins.push_back(MyFlags); 10738 } 10739 } 10740 } 10741 10742 // We push in swifterror return as the last element of CLI.Ins. 10743 ArgListTy &Args = CLI.getArgs(); 10744 if (supportSwiftError()) { 10745 for (const ArgListEntry &Arg : Args) { 10746 if (Arg.IsSwiftError) { 10747 ISD::InputArg MyFlags; 10748 MyFlags.VT = getPointerTy(DL); 10749 MyFlags.ArgVT = EVT(getPointerTy(DL)); 10750 MyFlags.Flags.setSwiftError(); 10751 CLI.Ins.push_back(MyFlags); 10752 } 10753 } 10754 } 10755 10756 // Handle all of the outgoing arguments. 10757 CLI.Outs.clear(); 10758 CLI.OutVals.clear(); 10759 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 10760 SmallVector<EVT, 4> ValueVTs; 10761 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 10762 // FIXME: Split arguments if CLI.IsPostTypeLegalization 10763 Type *FinalType = Args[i].Ty; 10764 if (Args[i].IsByVal) 10765 FinalType = Args[i].IndirectType; 10766 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10767 FinalType, CLI.CallConv, CLI.IsVarArg, DL); 10768 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 10769 ++Value) { 10770 EVT VT = ValueVTs[Value]; 10771 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 10772 SDValue Op = SDValue(Args[i].Node.getNode(), 10773 Args[i].Node.getResNo() + Value); 10774 ISD::ArgFlagsTy Flags; 10775 10776 // Certain targets (such as MIPS), may have a different ABI alignment 10777 // for a type depending on the context. Give the target a chance to 10778 // specify the alignment it wants. 10779 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 10780 Flags.setOrigAlign(OriginalAlignment); 10781 10782 if (Args[i].Ty->isPointerTy()) { 10783 Flags.setPointer(); 10784 Flags.setPointerAddrSpace( 10785 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 10786 } 10787 if (Args[i].IsZExt) 10788 Flags.setZExt(); 10789 if (Args[i].IsSExt) 10790 Flags.setSExt(); 10791 if (Args[i].IsInReg) { 10792 // If we are using vectorcall calling convention, a structure that is 10793 // passed InReg - is surely an HVA 10794 if (CLI.CallConv == CallingConv::X86_VectorCall && 10795 isa<StructType>(FinalType)) { 10796 // The first value of a structure is marked 10797 if (0 == Value) 10798 Flags.setHvaStart(); 10799 Flags.setHva(); 10800 } 10801 // Set InReg Flag 10802 Flags.setInReg(); 10803 } 10804 if (Args[i].IsSRet) 10805 Flags.setSRet(); 10806 if (Args[i].IsSwiftSelf) 10807 Flags.setSwiftSelf(); 10808 if (Args[i].IsSwiftAsync) 10809 Flags.setSwiftAsync(); 10810 if (Args[i].IsSwiftError) 10811 Flags.setSwiftError(); 10812 if (Args[i].IsCFGuardTarget) 10813 Flags.setCFGuardTarget(); 10814 if (Args[i].IsByVal) 10815 Flags.setByVal(); 10816 if (Args[i].IsByRef) 10817 Flags.setByRef(); 10818 if (Args[i].IsPreallocated) { 10819 Flags.setPreallocated(); 10820 // Set the byval flag for CCAssignFn callbacks that don't know about 10821 // preallocated. This way we can know how many bytes we should've 10822 // allocated and how many bytes a callee cleanup function will pop. If 10823 // we port preallocated to more targets, we'll have to add custom 10824 // preallocated handling in the various CC lowering callbacks. 10825 Flags.setByVal(); 10826 } 10827 if (Args[i].IsInAlloca) { 10828 Flags.setInAlloca(); 10829 // Set the byval flag for CCAssignFn callbacks that don't know about 10830 // inalloca. This way we can know how many bytes we should've allocated 10831 // and how many bytes a callee cleanup function will pop. If we port 10832 // inalloca to more targets, we'll have to add custom inalloca handling 10833 // in the various CC lowering callbacks. 10834 Flags.setByVal(); 10835 } 10836 Align MemAlign; 10837 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 10838 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType); 10839 Flags.setByValSize(FrameSize); 10840 10841 // info is not there but there are cases it cannot get right. 10842 if (auto MA = Args[i].Alignment) 10843 MemAlign = *MA; 10844 else 10845 MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL)); 10846 } else if (auto MA = Args[i].Alignment) { 10847 MemAlign = *MA; 10848 } else { 10849 MemAlign = OriginalAlignment; 10850 } 10851 Flags.setMemAlign(MemAlign); 10852 if (Args[i].IsNest) 10853 Flags.setNest(); 10854 if (NeedsRegBlock) 10855 Flags.setInConsecutiveRegs(); 10856 10857 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10858 CLI.CallConv, VT); 10859 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10860 CLI.CallConv, VT); 10861 SmallVector<SDValue, 4> Parts(NumParts); 10862 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 10863 10864 if (Args[i].IsSExt) 10865 ExtendKind = ISD::SIGN_EXTEND; 10866 else if (Args[i].IsZExt) 10867 ExtendKind = ISD::ZERO_EXTEND; 10868 10869 // Conservatively only handle 'returned' on non-vectors that can be lowered, 10870 // for now. 10871 if (Args[i].IsReturned && !Op.getValueType().isVector() && 10872 CanLowerReturn) { 10873 assert((CLI.RetTy == Args[i].Ty || 10874 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 10875 CLI.RetTy->getPointerAddressSpace() == 10876 Args[i].Ty->getPointerAddressSpace())) && 10877 RetTys.size() == NumValues && "unexpected use of 'returned'"); 10878 // Before passing 'returned' to the target lowering code, ensure that 10879 // either the register MVT and the actual EVT are the same size or that 10880 // the return value and argument are extended in the same way; in these 10881 // cases it's safe to pass the argument register value unchanged as the 10882 // return register value (although it's at the target's option whether 10883 // to do so) 10884 // TODO: allow code generation to take advantage of partially preserved 10885 // registers rather than clobbering the entire register when the 10886 // parameter extension method is not compatible with the return 10887 // extension method 10888 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 10889 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 10890 CLI.RetZExt == Args[i].IsZExt)) 10891 Flags.setReturned(); 10892 } 10893 10894 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 10895 CLI.CallConv, ExtendKind); 10896 10897 for (unsigned j = 0; j != NumParts; ++j) { 10898 // if it isn't first piece, alignment must be 1 10899 // For scalable vectors the scalable part is currently handled 10900 // by individual targets, so we just use the known minimum size here. 10901 ISD::OutputArg MyFlags( 10902 Flags, Parts[j].getValueType().getSimpleVT(), VT, 10903 i < CLI.NumFixedArgs, i, 10904 j * Parts[j].getValueType().getStoreSize().getKnownMinValue()); 10905 if (NumParts > 1 && j == 0) 10906 MyFlags.Flags.setSplit(); 10907 else if (j != 0) { 10908 MyFlags.Flags.setOrigAlign(Align(1)); 10909 if (j == NumParts - 1) 10910 MyFlags.Flags.setSplitEnd(); 10911 } 10912 10913 CLI.Outs.push_back(MyFlags); 10914 CLI.OutVals.push_back(Parts[j]); 10915 } 10916 10917 if (NeedsRegBlock && Value == NumValues - 1) 10918 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 10919 } 10920 } 10921 10922 SmallVector<SDValue, 4> InVals; 10923 CLI.Chain = LowerCall(CLI, InVals); 10924 10925 // Update CLI.InVals to use outside of this function. 10926 CLI.InVals = InVals; 10927 10928 // Verify that the target's LowerCall behaved as expected. 10929 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 10930 "LowerCall didn't return a valid chain!"); 10931 assert((!CLI.IsTailCall || InVals.empty()) && 10932 "LowerCall emitted a return value for a tail call!"); 10933 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 10934 "LowerCall didn't emit the correct number of values!"); 10935 10936 // For a tail call, the return value is merely live-out and there aren't 10937 // any nodes in the DAG representing it. Return a special value to 10938 // indicate that a tail call has been emitted and no more Instructions 10939 // should be processed in the current block. 10940 if (CLI.IsTailCall) { 10941 CLI.DAG.setRoot(CLI.Chain); 10942 return std::make_pair(SDValue(), SDValue()); 10943 } 10944 10945 #ifndef NDEBUG 10946 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 10947 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 10948 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 10949 "LowerCall emitted a value with the wrong type!"); 10950 } 10951 #endif 10952 10953 SmallVector<SDValue, 4> ReturnValues; 10954 if (!CanLowerReturn) { 10955 // The instruction result is the result of loading from the 10956 // hidden sret parameter. 10957 SmallVector<EVT, 1> PVTs; 10958 Type *PtrRetTy = 10959 PointerType::get(OrigRetTy->getContext(), DL.getAllocaAddrSpace()); 10960 10961 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 10962 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 10963 EVT PtrVT = PVTs[0]; 10964 10965 unsigned NumValues = RetTys.size(); 10966 ReturnValues.resize(NumValues); 10967 SmallVector<SDValue, 4> Chains(NumValues); 10968 10969 // An aggregate return value cannot wrap around the address space, so 10970 // offsets to its parts don't wrap either. 10971 SDNodeFlags Flags; 10972 Flags.setNoUnsignedWrap(true); 10973 10974 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10975 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 10976 for (unsigned i = 0; i < NumValues; ++i) { 10977 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 10978 CLI.DAG.getConstant(Offsets[i], CLI.DL, 10979 PtrVT), Flags); 10980 SDValue L = CLI.DAG.getLoad( 10981 RetTys[i], CLI.DL, CLI.Chain, Add, 10982 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 10983 DemoteStackIdx, Offsets[i]), 10984 HiddenSRetAlign); 10985 ReturnValues[i] = L; 10986 Chains[i] = L.getValue(1); 10987 } 10988 10989 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 10990 } else { 10991 // Collect the legal value parts into potentially illegal values 10992 // that correspond to the original function's return values. 10993 std::optional<ISD::NodeType> AssertOp; 10994 if (CLI.RetSExt) 10995 AssertOp = ISD::AssertSext; 10996 else if (CLI.RetZExt) 10997 AssertOp = ISD::AssertZext; 10998 unsigned CurReg = 0; 10999 for (EVT VT : RetTys) { 11000 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 11001 CLI.CallConv, VT); 11002 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 11003 CLI.CallConv, VT); 11004 11005 ReturnValues.push_back(getCopyFromParts( 11006 CLI.DAG, CLI.DL, &InVals[CurReg], NumRegs, RegisterVT, VT, nullptr, 11007 CLI.Chain, CLI.CallConv, AssertOp)); 11008 CurReg += NumRegs; 11009 } 11010 11011 // For a function returning void, there is no return value. We can't create 11012 // such a node, so we just return a null return value in that case. In 11013 // that case, nothing will actually look at the value. 11014 if (ReturnValues.empty()) 11015 return std::make_pair(SDValue(), CLI.Chain); 11016 } 11017 11018 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 11019 CLI.DAG.getVTList(RetTys), ReturnValues); 11020 return std::make_pair(Res, CLI.Chain); 11021 } 11022 11023 /// Places new result values for the node in Results (their number 11024 /// and types must exactly match those of the original return values of 11025 /// the node), or leaves Results empty, which indicates that the node is not 11026 /// to be custom lowered after all. 11027 void TargetLowering::LowerOperationWrapper(SDNode *N, 11028 SmallVectorImpl<SDValue> &Results, 11029 SelectionDAG &DAG) const { 11030 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 11031 11032 if (!Res.getNode()) 11033 return; 11034 11035 // If the original node has one result, take the return value from 11036 // LowerOperation as is. It might not be result number 0. 11037 if (N->getNumValues() == 1) { 11038 Results.push_back(Res); 11039 return; 11040 } 11041 11042 // If the original node has multiple results, then the return node should 11043 // have the same number of results. 11044 assert((N->getNumValues() == Res->getNumValues()) && 11045 "Lowering returned the wrong number of results!"); 11046 11047 // Places new result values base on N result number. 11048 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 11049 Results.push_back(Res.getValue(I)); 11050 } 11051 11052 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 11053 llvm_unreachable("LowerOperation not implemented for this target!"); 11054 } 11055 11056 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, 11057 unsigned Reg, 11058 ISD::NodeType ExtendType) { 11059 SDValue Op = getNonRegisterValue(V); 11060 assert((Op.getOpcode() != ISD::CopyFromReg || 11061 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 11062 "Copy from a reg to the same reg!"); 11063 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 11064 11065 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11066 // If this is an InlineAsm we have to match the registers required, not the 11067 // notional registers required by the type. 11068 11069 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 11070 std::nullopt); // This is not an ABI copy. 11071 SDValue Chain = DAG.getEntryNode(); 11072 11073 if (ExtendType == ISD::ANY_EXTEND) { 11074 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V); 11075 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end()) 11076 ExtendType = PreferredExtendIt->second; 11077 } 11078 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 11079 PendingExports.push_back(Chain); 11080 } 11081 11082 #include "llvm/CodeGen/SelectionDAGISel.h" 11083 11084 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 11085 /// entry block, return true. This includes arguments used by switches, since 11086 /// the switch may expand into multiple basic blocks. 11087 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 11088 // With FastISel active, we may be splitting blocks, so force creation 11089 // of virtual registers for all non-dead arguments. 11090 if (FastISel) 11091 return A->use_empty(); 11092 11093 const BasicBlock &Entry = A->getParent()->front(); 11094 for (const User *U : A->users()) 11095 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 11096 return false; // Use not in entry block. 11097 11098 return true; 11099 } 11100 11101 using ArgCopyElisionMapTy = 11102 DenseMap<const Argument *, 11103 std::pair<const AllocaInst *, const StoreInst *>>; 11104 11105 /// Scan the entry block of the function in FuncInfo for arguments that look 11106 /// like copies into a local alloca. Record any copied arguments in 11107 /// ArgCopyElisionCandidates. 11108 static void 11109 findArgumentCopyElisionCandidates(const DataLayout &DL, 11110 FunctionLoweringInfo *FuncInfo, 11111 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 11112 // Record the state of every static alloca used in the entry block. Argument 11113 // allocas are all used in the entry block, so we need approximately as many 11114 // entries as we have arguments. 11115 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 11116 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 11117 unsigned NumArgs = FuncInfo->Fn->arg_size(); 11118 StaticAllocas.reserve(NumArgs * 2); 11119 11120 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 11121 if (!V) 11122 return nullptr; 11123 V = V->stripPointerCasts(); 11124 const auto *AI = dyn_cast<AllocaInst>(V); 11125 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 11126 return nullptr; 11127 auto Iter = StaticAllocas.insert({AI, Unknown}); 11128 return &Iter.first->second; 11129 }; 11130 11131 // Look for stores of arguments to static allocas. Look through bitcasts and 11132 // GEPs to handle type coercions, as long as the alloca is fully initialized 11133 // by the store. Any non-store use of an alloca escapes it and any subsequent 11134 // unanalyzed store might write it. 11135 // FIXME: Handle structs initialized with multiple stores. 11136 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 11137 // Look for stores, and handle non-store uses conservatively. 11138 const auto *SI = dyn_cast<StoreInst>(&I); 11139 if (!SI) { 11140 // We will look through cast uses, so ignore them completely. 11141 if (I.isCast()) 11142 continue; 11143 // Ignore debug info and pseudo op intrinsics, they don't escape or store 11144 // to allocas. 11145 if (I.isDebugOrPseudoInst()) 11146 continue; 11147 // This is an unknown instruction. Assume it escapes or writes to all 11148 // static alloca operands. 11149 for (const Use &U : I.operands()) { 11150 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 11151 *Info = StaticAllocaInfo::Clobbered; 11152 } 11153 continue; 11154 } 11155 11156 // If the stored value is a static alloca, mark it as escaped. 11157 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 11158 *Info = StaticAllocaInfo::Clobbered; 11159 11160 // Check if the destination is a static alloca. 11161 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 11162 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 11163 if (!Info) 11164 continue; 11165 const AllocaInst *AI = cast<AllocaInst>(Dst); 11166 11167 // Skip allocas that have been initialized or clobbered. 11168 if (*Info != StaticAllocaInfo::Unknown) 11169 continue; 11170 11171 // Check if the stored value is an argument, and that this store fully 11172 // initializes the alloca. 11173 // If the argument type has padding bits we can't directly forward a pointer 11174 // as the upper bits may contain garbage. 11175 // Don't elide copies from the same argument twice. 11176 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 11177 const auto *Arg = dyn_cast<Argument>(Val); 11178 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 11179 Arg->getType()->isEmptyTy() || 11180 DL.getTypeStoreSize(Arg->getType()) != 11181 DL.getTypeAllocSize(AI->getAllocatedType()) || 11182 !DL.typeSizeEqualsStoreSize(Arg->getType()) || 11183 ArgCopyElisionCandidates.count(Arg)) { 11184 *Info = StaticAllocaInfo::Clobbered; 11185 continue; 11186 } 11187 11188 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 11189 << '\n'); 11190 11191 // Mark this alloca and store for argument copy elision. 11192 *Info = StaticAllocaInfo::Elidable; 11193 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 11194 11195 // Stop scanning if we've seen all arguments. This will happen early in -O0 11196 // builds, which is useful, because -O0 builds have large entry blocks and 11197 // many allocas. 11198 if (ArgCopyElisionCandidates.size() == NumArgs) 11199 break; 11200 } 11201 } 11202 11203 /// Try to elide argument copies from memory into a local alloca. Succeeds if 11204 /// ArgVal is a load from a suitable fixed stack object. 11205 static void tryToElideArgumentCopy( 11206 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 11207 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 11208 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 11209 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 11210 ArrayRef<SDValue> ArgVals, bool &ArgHasUses) { 11211 // Check if this is a load from a fixed stack object. 11212 auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]); 11213 if (!LNode) 11214 return; 11215 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 11216 if (!FINode) 11217 return; 11218 11219 // Check that the fixed stack object is the right size and alignment. 11220 // Look at the alignment that the user wrote on the alloca instead of looking 11221 // at the stack object. 11222 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 11223 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 11224 const AllocaInst *AI = ArgCopyIter->second.first; 11225 int FixedIndex = FINode->getIndex(); 11226 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 11227 int OldIndex = AllocaIndex; 11228 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 11229 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 11230 LLVM_DEBUG( 11231 dbgs() << " argument copy elision failed due to bad fixed stack " 11232 "object size\n"); 11233 return; 11234 } 11235 Align RequiredAlignment = AI->getAlign(); 11236 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 11237 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 11238 "greater than stack argument alignment (" 11239 << DebugStr(RequiredAlignment) << " vs " 11240 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 11241 return; 11242 } 11243 11244 // Perform the elision. Delete the old stack object and replace its only use 11245 // in the variable info map. Mark the stack object as mutable and aliased. 11246 LLVM_DEBUG({ 11247 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 11248 << " Replacing frame index " << OldIndex << " with " << FixedIndex 11249 << '\n'; 11250 }); 11251 MFI.RemoveStackObject(OldIndex); 11252 MFI.setIsImmutableObjectIndex(FixedIndex, false); 11253 MFI.setIsAliasedObjectIndex(FixedIndex, true); 11254 AllocaIndex = FixedIndex; 11255 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 11256 for (SDValue ArgVal : ArgVals) 11257 Chains.push_back(ArgVal.getValue(1)); 11258 11259 // Avoid emitting code for the store implementing the copy. 11260 const StoreInst *SI = ArgCopyIter->second.second; 11261 ElidedArgCopyInstrs.insert(SI); 11262 11263 // Check for uses of the argument again so that we can avoid exporting ArgVal 11264 // if it is't used by anything other than the store. 11265 for (const Value *U : Arg.users()) { 11266 if (U != SI) { 11267 ArgHasUses = true; 11268 break; 11269 } 11270 } 11271 } 11272 11273 void SelectionDAGISel::LowerArguments(const Function &F) { 11274 SelectionDAG &DAG = SDB->DAG; 11275 SDLoc dl = SDB->getCurSDLoc(); 11276 const DataLayout &DL = DAG.getDataLayout(); 11277 SmallVector<ISD::InputArg, 16> Ins; 11278 11279 // In Naked functions we aren't going to save any registers. 11280 if (F.hasFnAttribute(Attribute::Naked)) 11281 return; 11282 11283 if (!FuncInfo->CanLowerReturn) { 11284 // Put in an sret pointer parameter before all the other parameters. 11285 SmallVector<EVT, 1> ValueVTs; 11286 ComputeValueVTs(*TLI, DAG.getDataLayout(), 11287 PointerType::get(F.getContext(), 11288 DAG.getDataLayout().getAllocaAddrSpace()), 11289 ValueVTs); 11290 11291 // NOTE: Assuming that a pointer will never break down to more than one VT 11292 // or one register. 11293 ISD::ArgFlagsTy Flags; 11294 Flags.setSRet(); 11295 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 11296 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 11297 ISD::InputArg::NoArgIndex, 0); 11298 Ins.push_back(RetArg); 11299 } 11300 11301 // Look for stores of arguments to static allocas. Mark such arguments with a 11302 // flag to ask the target to give us the memory location of that argument if 11303 // available. 11304 ArgCopyElisionMapTy ArgCopyElisionCandidates; 11305 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 11306 ArgCopyElisionCandidates); 11307 11308 // Set up the incoming argument description vector. 11309 for (const Argument &Arg : F.args()) { 11310 unsigned ArgNo = Arg.getArgNo(); 11311 SmallVector<EVT, 4> ValueVTs; 11312 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 11313 bool isArgValueUsed = !Arg.use_empty(); 11314 unsigned PartBase = 0; 11315 Type *FinalType = Arg.getType(); 11316 if (Arg.hasAttribute(Attribute::ByVal)) 11317 FinalType = Arg.getParamByValType(); 11318 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 11319 FinalType, F.getCallingConv(), F.isVarArg(), DL); 11320 for (unsigned Value = 0, NumValues = ValueVTs.size(); 11321 Value != NumValues; ++Value) { 11322 EVT VT = ValueVTs[Value]; 11323 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 11324 ISD::ArgFlagsTy Flags; 11325 11326 11327 if (Arg.getType()->isPointerTy()) { 11328 Flags.setPointer(); 11329 Flags.setPointerAddrSpace( 11330 cast<PointerType>(Arg.getType())->getAddressSpace()); 11331 } 11332 if (Arg.hasAttribute(Attribute::ZExt)) 11333 Flags.setZExt(); 11334 if (Arg.hasAttribute(Attribute::SExt)) 11335 Flags.setSExt(); 11336 if (Arg.hasAttribute(Attribute::InReg)) { 11337 // If we are using vectorcall calling convention, a structure that is 11338 // passed InReg - is surely an HVA 11339 if (F.getCallingConv() == CallingConv::X86_VectorCall && 11340 isa<StructType>(Arg.getType())) { 11341 // The first value of a structure is marked 11342 if (0 == Value) 11343 Flags.setHvaStart(); 11344 Flags.setHva(); 11345 } 11346 // Set InReg Flag 11347 Flags.setInReg(); 11348 } 11349 if (Arg.hasAttribute(Attribute::StructRet)) 11350 Flags.setSRet(); 11351 if (Arg.hasAttribute(Attribute::SwiftSelf)) 11352 Flags.setSwiftSelf(); 11353 if (Arg.hasAttribute(Attribute::SwiftAsync)) 11354 Flags.setSwiftAsync(); 11355 if (Arg.hasAttribute(Attribute::SwiftError)) 11356 Flags.setSwiftError(); 11357 if (Arg.hasAttribute(Attribute::ByVal)) 11358 Flags.setByVal(); 11359 if (Arg.hasAttribute(Attribute::ByRef)) 11360 Flags.setByRef(); 11361 if (Arg.hasAttribute(Attribute::InAlloca)) { 11362 Flags.setInAlloca(); 11363 // Set the byval flag for CCAssignFn callbacks that don't know about 11364 // inalloca. This way we can know how many bytes we should've allocated 11365 // and how many bytes a callee cleanup function will pop. If we port 11366 // inalloca to more targets, we'll have to add custom inalloca handling 11367 // in the various CC lowering callbacks. 11368 Flags.setByVal(); 11369 } 11370 if (Arg.hasAttribute(Attribute::Preallocated)) { 11371 Flags.setPreallocated(); 11372 // Set the byval flag for CCAssignFn callbacks that don't know about 11373 // preallocated. This way we can know how many bytes we should've 11374 // allocated and how many bytes a callee cleanup function will pop. If 11375 // we port preallocated to more targets, we'll have to add custom 11376 // preallocated handling in the various CC lowering callbacks. 11377 Flags.setByVal(); 11378 } 11379 11380 // Certain targets (such as MIPS), may have a different ABI alignment 11381 // for a type depending on the context. Give the target a chance to 11382 // specify the alignment it wants. 11383 const Align OriginalAlignment( 11384 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 11385 Flags.setOrigAlign(OriginalAlignment); 11386 11387 Align MemAlign; 11388 Type *ArgMemTy = nullptr; 11389 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 11390 Flags.isByRef()) { 11391 if (!ArgMemTy) 11392 ArgMemTy = Arg.getPointeeInMemoryValueType(); 11393 11394 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 11395 11396 // For in-memory arguments, size and alignment should be passed from FE. 11397 // BE will guess if this info is not there but there are cases it cannot 11398 // get right. 11399 if (auto ParamAlign = Arg.getParamStackAlign()) 11400 MemAlign = *ParamAlign; 11401 else if ((ParamAlign = Arg.getParamAlign())) 11402 MemAlign = *ParamAlign; 11403 else 11404 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 11405 if (Flags.isByRef()) 11406 Flags.setByRefSize(MemSize); 11407 else 11408 Flags.setByValSize(MemSize); 11409 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 11410 MemAlign = *ParamAlign; 11411 } else { 11412 MemAlign = OriginalAlignment; 11413 } 11414 Flags.setMemAlign(MemAlign); 11415 11416 if (Arg.hasAttribute(Attribute::Nest)) 11417 Flags.setNest(); 11418 if (NeedsRegBlock) 11419 Flags.setInConsecutiveRegs(); 11420 if (ArgCopyElisionCandidates.count(&Arg)) 11421 Flags.setCopyElisionCandidate(); 11422 if (Arg.hasAttribute(Attribute::Returned)) 11423 Flags.setReturned(); 11424 11425 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 11426 *CurDAG->getContext(), F.getCallingConv(), VT); 11427 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 11428 *CurDAG->getContext(), F.getCallingConv(), VT); 11429 for (unsigned i = 0; i != NumRegs; ++i) { 11430 // For scalable vectors, use the minimum size; individual targets 11431 // are responsible for handling scalable vector arguments and 11432 // return values. 11433 ISD::InputArg MyFlags( 11434 Flags, RegisterVT, VT, isArgValueUsed, ArgNo, 11435 PartBase + i * RegisterVT.getStoreSize().getKnownMinValue()); 11436 if (NumRegs > 1 && i == 0) 11437 MyFlags.Flags.setSplit(); 11438 // if it isn't first piece, alignment must be 1 11439 else if (i > 0) { 11440 MyFlags.Flags.setOrigAlign(Align(1)); 11441 if (i == NumRegs - 1) 11442 MyFlags.Flags.setSplitEnd(); 11443 } 11444 Ins.push_back(MyFlags); 11445 } 11446 if (NeedsRegBlock && Value == NumValues - 1) 11447 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 11448 PartBase += VT.getStoreSize().getKnownMinValue(); 11449 } 11450 } 11451 11452 // Call the target to set up the argument values. 11453 SmallVector<SDValue, 8> InVals; 11454 SDValue NewRoot = TLI->LowerFormalArguments( 11455 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 11456 11457 // Verify that the target's LowerFormalArguments behaved as expected. 11458 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 11459 "LowerFormalArguments didn't return a valid chain!"); 11460 assert(InVals.size() == Ins.size() && 11461 "LowerFormalArguments didn't emit the correct number of values!"); 11462 LLVM_DEBUG({ 11463 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 11464 assert(InVals[i].getNode() && 11465 "LowerFormalArguments emitted a null value!"); 11466 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 11467 "LowerFormalArguments emitted a value with the wrong type!"); 11468 } 11469 }); 11470 11471 // Update the DAG with the new chain value resulting from argument lowering. 11472 DAG.setRoot(NewRoot); 11473 11474 // Set up the argument values. 11475 unsigned i = 0; 11476 if (!FuncInfo->CanLowerReturn) { 11477 // Create a virtual register for the sret pointer, and put in a copy 11478 // from the sret argument into it. 11479 SmallVector<EVT, 1> ValueVTs; 11480 ComputeValueVTs(*TLI, DAG.getDataLayout(), 11481 PointerType::get(F.getContext(), 11482 DAG.getDataLayout().getAllocaAddrSpace()), 11483 ValueVTs); 11484 MVT VT = ValueVTs[0].getSimpleVT(); 11485 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 11486 std::optional<ISD::NodeType> AssertOp; 11487 SDValue ArgValue = 11488 getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, nullptr, NewRoot, 11489 F.getCallingConv(), AssertOp); 11490 11491 MachineFunction& MF = SDB->DAG.getMachineFunction(); 11492 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 11493 Register SRetReg = 11494 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 11495 FuncInfo->DemoteRegister = SRetReg; 11496 NewRoot = 11497 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 11498 DAG.setRoot(NewRoot); 11499 11500 // i indexes lowered arguments. Bump it past the hidden sret argument. 11501 ++i; 11502 } 11503 11504 SmallVector<SDValue, 4> Chains; 11505 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 11506 for (const Argument &Arg : F.args()) { 11507 SmallVector<SDValue, 4> ArgValues; 11508 SmallVector<EVT, 4> ValueVTs; 11509 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 11510 unsigned NumValues = ValueVTs.size(); 11511 if (NumValues == 0) 11512 continue; 11513 11514 bool ArgHasUses = !Arg.use_empty(); 11515 11516 // Elide the copying store if the target loaded this argument from a 11517 // suitable fixed stack object. 11518 if (Ins[i].Flags.isCopyElisionCandidate()) { 11519 unsigned NumParts = 0; 11520 for (EVT VT : ValueVTs) 11521 NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), 11522 F.getCallingConv(), VT); 11523 11524 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 11525 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 11526 ArrayRef(&InVals[i], NumParts), ArgHasUses); 11527 } 11528 11529 // If this argument is unused then remember its value. It is used to generate 11530 // debugging information. 11531 bool isSwiftErrorArg = 11532 TLI->supportSwiftError() && 11533 Arg.hasAttribute(Attribute::SwiftError); 11534 if (!ArgHasUses && !isSwiftErrorArg) { 11535 SDB->setUnusedArgValue(&Arg, InVals[i]); 11536 11537 // Also remember any frame index for use in FastISel. 11538 if (FrameIndexSDNode *FI = 11539 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 11540 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11541 } 11542 11543 for (unsigned Val = 0; Val != NumValues; ++Val) { 11544 EVT VT = ValueVTs[Val]; 11545 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 11546 F.getCallingConv(), VT); 11547 unsigned NumParts = TLI->getNumRegistersForCallingConv( 11548 *CurDAG->getContext(), F.getCallingConv(), VT); 11549 11550 // Even an apparent 'unused' swifterror argument needs to be returned. So 11551 // we do generate a copy for it that can be used on return from the 11552 // function. 11553 if (ArgHasUses || isSwiftErrorArg) { 11554 std::optional<ISD::NodeType> AssertOp; 11555 if (Arg.hasAttribute(Attribute::SExt)) 11556 AssertOp = ISD::AssertSext; 11557 else if (Arg.hasAttribute(Attribute::ZExt)) 11558 AssertOp = ISD::AssertZext; 11559 11560 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 11561 PartVT, VT, nullptr, NewRoot, 11562 F.getCallingConv(), AssertOp)); 11563 } 11564 11565 i += NumParts; 11566 } 11567 11568 // We don't need to do anything else for unused arguments. 11569 if (ArgValues.empty()) 11570 continue; 11571 11572 // Note down frame index. 11573 if (FrameIndexSDNode *FI = 11574 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 11575 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11576 11577 SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues), 11578 SDB->getCurSDLoc()); 11579 11580 SDB->setValue(&Arg, Res); 11581 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 11582 // We want to associate the argument with the frame index, among 11583 // involved operands, that correspond to the lowest address. The 11584 // getCopyFromParts function, called earlier, is swapping the order of 11585 // the operands to BUILD_PAIR depending on endianness. The result of 11586 // that swapping is that the least significant bits of the argument will 11587 // be in the first operand of the BUILD_PAIR node, and the most 11588 // significant bits will be in the second operand. 11589 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 11590 if (LoadSDNode *LNode = 11591 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 11592 if (FrameIndexSDNode *FI = 11593 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 11594 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11595 } 11596 11597 // Analyses past this point are naive and don't expect an assertion. 11598 if (Res.getOpcode() == ISD::AssertZext) 11599 Res = Res.getOperand(0); 11600 11601 // Update the SwiftErrorVRegDefMap. 11602 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 11603 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 11604 if (Register::isVirtualRegister(Reg)) 11605 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 11606 Reg); 11607 } 11608 11609 // If this argument is live outside of the entry block, insert a copy from 11610 // wherever we got it to the vreg that other BB's will reference it as. 11611 if (Res.getOpcode() == ISD::CopyFromReg) { 11612 // If we can, though, try to skip creating an unnecessary vreg. 11613 // FIXME: This isn't very clean... it would be nice to make this more 11614 // general. 11615 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 11616 if (Register::isVirtualRegister(Reg)) { 11617 FuncInfo->ValueMap[&Arg] = Reg; 11618 continue; 11619 } 11620 } 11621 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 11622 FuncInfo->InitializeRegForValue(&Arg); 11623 SDB->CopyToExportRegsIfNeeded(&Arg); 11624 } 11625 } 11626 11627 if (!Chains.empty()) { 11628 Chains.push_back(NewRoot); 11629 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 11630 } 11631 11632 DAG.setRoot(NewRoot); 11633 11634 assert(i == InVals.size() && "Argument register count mismatch!"); 11635 11636 // If any argument copy elisions occurred and we have debug info, update the 11637 // stale frame indices used in the dbg.declare variable info table. 11638 if (!ArgCopyElisionFrameIndexMap.empty()) { 11639 for (MachineFunction::VariableDbgInfo &VI : 11640 MF->getInStackSlotVariableDbgInfo()) { 11641 auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot()); 11642 if (I != ArgCopyElisionFrameIndexMap.end()) 11643 VI.updateStackSlot(I->second); 11644 } 11645 } 11646 11647 // Finally, if the target has anything special to do, allow it to do so. 11648 emitFunctionEntryCode(); 11649 } 11650 11651 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 11652 /// ensure constants are generated when needed. Remember the virtual registers 11653 /// that need to be added to the Machine PHI nodes as input. We cannot just 11654 /// directly add them, because expansion might result in multiple MBB's for one 11655 /// BB. As such, the start of the BB might correspond to a different MBB than 11656 /// the end. 11657 void 11658 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 11659 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11660 11661 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 11662 11663 // Check PHI nodes in successors that expect a value to be available from this 11664 // block. 11665 for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) { 11666 if (!isa<PHINode>(SuccBB->begin())) continue; 11667 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 11668 11669 // If this terminator has multiple identical successors (common for 11670 // switches), only handle each succ once. 11671 if (!SuccsHandled.insert(SuccMBB).second) 11672 continue; 11673 11674 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 11675 11676 // At this point we know that there is a 1-1 correspondence between LLVM PHI 11677 // nodes and Machine PHI nodes, but the incoming operands have not been 11678 // emitted yet. 11679 for (const PHINode &PN : SuccBB->phis()) { 11680 // Ignore dead phi's. 11681 if (PN.use_empty()) 11682 continue; 11683 11684 // Skip empty types 11685 if (PN.getType()->isEmptyTy()) 11686 continue; 11687 11688 unsigned Reg; 11689 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 11690 11691 if (const auto *C = dyn_cast<Constant>(PHIOp)) { 11692 unsigned &RegOut = ConstantsOut[C]; 11693 if (RegOut == 0) { 11694 RegOut = FuncInfo.CreateRegs(C); 11695 // We need to zero/sign extend ConstantInt phi operands to match 11696 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo. 11697 ISD::NodeType ExtendType = ISD::ANY_EXTEND; 11698 if (auto *CI = dyn_cast<ConstantInt>(C)) 11699 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND 11700 : ISD::ZERO_EXTEND; 11701 CopyValueToVirtualRegister(C, RegOut, ExtendType); 11702 } 11703 Reg = RegOut; 11704 } else { 11705 DenseMap<const Value *, Register>::iterator I = 11706 FuncInfo.ValueMap.find(PHIOp); 11707 if (I != FuncInfo.ValueMap.end()) 11708 Reg = I->second; 11709 else { 11710 assert(isa<AllocaInst>(PHIOp) && 11711 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 11712 "Didn't codegen value into a register!??"); 11713 Reg = FuncInfo.CreateRegs(PHIOp); 11714 CopyValueToVirtualRegister(PHIOp, Reg); 11715 } 11716 } 11717 11718 // Remember that this register needs to added to the machine PHI node as 11719 // the input for this MBB. 11720 SmallVector<EVT, 4> ValueVTs; 11721 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 11722 for (EVT VT : ValueVTs) { 11723 const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 11724 for (unsigned i = 0; i != NumRegisters; ++i) 11725 FuncInfo.PHINodesToUpdate.push_back( 11726 std::make_pair(&*MBBI++, Reg + i)); 11727 Reg += NumRegisters; 11728 } 11729 } 11730 } 11731 11732 ConstantsOut.clear(); 11733 } 11734 11735 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 11736 MachineFunction::iterator I(MBB); 11737 if (++I == FuncInfo.MF->end()) 11738 return nullptr; 11739 return &*I; 11740 } 11741 11742 /// During lowering new call nodes can be created (such as memset, etc.). 11743 /// Those will become new roots of the current DAG, but complications arise 11744 /// when they are tail calls. In such cases, the call lowering will update 11745 /// the root, but the builder still needs to know that a tail call has been 11746 /// lowered in order to avoid generating an additional return. 11747 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 11748 // If the node is null, we do have a tail call. 11749 if (MaybeTC.getNode() != nullptr) 11750 DAG.setRoot(MaybeTC); 11751 else 11752 HasTailCall = true; 11753 } 11754 11755 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 11756 MachineBasicBlock *SwitchMBB, 11757 MachineBasicBlock *DefaultMBB) { 11758 MachineFunction *CurMF = FuncInfo.MF; 11759 MachineBasicBlock *NextMBB = nullptr; 11760 MachineFunction::iterator BBI(W.MBB); 11761 if (++BBI != FuncInfo.MF->end()) 11762 NextMBB = &*BBI; 11763 11764 unsigned Size = W.LastCluster - W.FirstCluster + 1; 11765 11766 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11767 11768 if (Size == 2 && W.MBB == SwitchMBB) { 11769 // If any two of the cases has the same destination, and if one value 11770 // is the same as the other, but has one bit unset that the other has set, 11771 // use bit manipulation to do two compares at once. For example: 11772 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 11773 // TODO: This could be extended to merge any 2 cases in switches with 3 11774 // cases. 11775 // TODO: Handle cases where W.CaseBB != SwitchBB. 11776 CaseCluster &Small = *W.FirstCluster; 11777 CaseCluster &Big = *W.LastCluster; 11778 11779 if (Small.Low == Small.High && Big.Low == Big.High && 11780 Small.MBB == Big.MBB) { 11781 const APInt &SmallValue = Small.Low->getValue(); 11782 const APInt &BigValue = Big.Low->getValue(); 11783 11784 // Check that there is only one bit different. 11785 APInt CommonBit = BigValue ^ SmallValue; 11786 if (CommonBit.isPowerOf2()) { 11787 SDValue CondLHS = getValue(Cond); 11788 EVT VT = CondLHS.getValueType(); 11789 SDLoc DL = getCurSDLoc(); 11790 11791 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 11792 DAG.getConstant(CommonBit, DL, VT)); 11793 SDValue Cond = DAG.getSetCC( 11794 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 11795 ISD::SETEQ); 11796 11797 // Update successor info. 11798 // Both Small and Big will jump to Small.BB, so we sum up the 11799 // probabilities. 11800 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 11801 if (BPI) 11802 addSuccessorWithProb( 11803 SwitchMBB, DefaultMBB, 11804 // The default destination is the first successor in IR. 11805 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 11806 else 11807 addSuccessorWithProb(SwitchMBB, DefaultMBB); 11808 11809 // Insert the true branch. 11810 SDValue BrCond = 11811 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 11812 DAG.getBasicBlock(Small.MBB)); 11813 // Insert the false branch. 11814 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 11815 DAG.getBasicBlock(DefaultMBB)); 11816 11817 DAG.setRoot(BrCond); 11818 return; 11819 } 11820 } 11821 } 11822 11823 if (TM.getOptLevel() != CodeGenOptLevel::None) { 11824 // Here, we order cases by probability so the most likely case will be 11825 // checked first. However, two clusters can have the same probability in 11826 // which case their relative ordering is non-deterministic. So we use Low 11827 // as a tie-breaker as clusters are guaranteed to never overlap. 11828 llvm::sort(W.FirstCluster, W.LastCluster + 1, 11829 [](const CaseCluster &a, const CaseCluster &b) { 11830 return a.Prob != b.Prob ? 11831 a.Prob > b.Prob : 11832 a.Low->getValue().slt(b.Low->getValue()); 11833 }); 11834 11835 // Rearrange the case blocks so that the last one falls through if possible 11836 // without changing the order of probabilities. 11837 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 11838 --I; 11839 if (I->Prob > W.LastCluster->Prob) 11840 break; 11841 if (I->Kind == CC_Range && I->MBB == NextMBB) { 11842 std::swap(*I, *W.LastCluster); 11843 break; 11844 } 11845 } 11846 } 11847 11848 // Compute total probability. 11849 BranchProbability DefaultProb = W.DefaultProb; 11850 BranchProbability UnhandledProbs = DefaultProb; 11851 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 11852 UnhandledProbs += I->Prob; 11853 11854 MachineBasicBlock *CurMBB = W.MBB; 11855 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 11856 bool FallthroughUnreachable = false; 11857 MachineBasicBlock *Fallthrough; 11858 if (I == W.LastCluster) { 11859 // For the last cluster, fall through to the default destination. 11860 Fallthrough = DefaultMBB; 11861 FallthroughUnreachable = isa<UnreachableInst>( 11862 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 11863 } else { 11864 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 11865 CurMF->insert(BBI, Fallthrough); 11866 // Put Cond in a virtual register to make it available from the new blocks. 11867 ExportFromCurrentBlock(Cond); 11868 } 11869 UnhandledProbs -= I->Prob; 11870 11871 switch (I->Kind) { 11872 case CC_JumpTable: { 11873 // FIXME: Optimize away range check based on pivot comparisons. 11874 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 11875 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 11876 11877 // The jump block hasn't been inserted yet; insert it here. 11878 MachineBasicBlock *JumpMBB = JT->MBB; 11879 CurMF->insert(BBI, JumpMBB); 11880 11881 auto JumpProb = I->Prob; 11882 auto FallthroughProb = UnhandledProbs; 11883 11884 // If the default statement is a target of the jump table, we evenly 11885 // distribute the default probability to successors of CurMBB. Also 11886 // update the probability on the edge from JumpMBB to Fallthrough. 11887 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 11888 SE = JumpMBB->succ_end(); 11889 SI != SE; ++SI) { 11890 if (*SI == DefaultMBB) { 11891 JumpProb += DefaultProb / 2; 11892 FallthroughProb -= DefaultProb / 2; 11893 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 11894 JumpMBB->normalizeSuccProbs(); 11895 break; 11896 } 11897 } 11898 11899 // If the default clause is unreachable, propagate that knowledge into 11900 // JTH->FallthroughUnreachable which will use it to suppress the range 11901 // check. 11902 // 11903 // However, don't do this if we're doing branch target enforcement, 11904 // because a table branch _without_ a range check can be a tempting JOP 11905 // gadget - out-of-bounds inputs that are impossible in correct 11906 // execution become possible again if an attacker can influence the 11907 // control flow. So if an attacker doesn't already have a BTI bypass 11908 // available, we don't want them to be able to get one out of this 11909 // table branch. 11910 if (FallthroughUnreachable) { 11911 Function &CurFunc = CurMF->getFunction(); 11912 bool HasBranchTargetEnforcement = false; 11913 if (CurFunc.hasFnAttribute("branch-target-enforcement")) { 11914 HasBranchTargetEnforcement = 11915 CurFunc.getFnAttribute("branch-target-enforcement") 11916 .getValueAsBool(); 11917 } else { 11918 HasBranchTargetEnforcement = 11919 CurMF->getMMI().getModule()->getModuleFlag( 11920 "branch-target-enforcement"); 11921 } 11922 if (!HasBranchTargetEnforcement) 11923 JTH->FallthroughUnreachable = true; 11924 } 11925 11926 if (!JTH->FallthroughUnreachable) 11927 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 11928 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 11929 CurMBB->normalizeSuccProbs(); 11930 11931 // The jump table header will be inserted in our current block, do the 11932 // range check, and fall through to our fallthrough block. 11933 JTH->HeaderBB = CurMBB; 11934 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 11935 11936 // If we're in the right place, emit the jump table header right now. 11937 if (CurMBB == SwitchMBB) { 11938 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 11939 JTH->Emitted = true; 11940 } 11941 break; 11942 } 11943 case CC_BitTests: { 11944 // FIXME: Optimize away range check based on pivot comparisons. 11945 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 11946 11947 // The bit test blocks haven't been inserted yet; insert them here. 11948 for (BitTestCase &BTC : BTB->Cases) 11949 CurMF->insert(BBI, BTC.ThisBB); 11950 11951 // Fill in fields of the BitTestBlock. 11952 BTB->Parent = CurMBB; 11953 BTB->Default = Fallthrough; 11954 11955 BTB->DefaultProb = UnhandledProbs; 11956 // If the cases in bit test don't form a contiguous range, we evenly 11957 // distribute the probability on the edge to Fallthrough to two 11958 // successors of CurMBB. 11959 if (!BTB->ContiguousRange) { 11960 BTB->Prob += DefaultProb / 2; 11961 BTB->DefaultProb -= DefaultProb / 2; 11962 } 11963 11964 if (FallthroughUnreachable) 11965 BTB->FallthroughUnreachable = true; 11966 11967 // If we're in the right place, emit the bit test header right now. 11968 if (CurMBB == SwitchMBB) { 11969 visitBitTestHeader(*BTB, SwitchMBB); 11970 BTB->Emitted = true; 11971 } 11972 break; 11973 } 11974 case CC_Range: { 11975 const Value *RHS, *LHS, *MHS; 11976 ISD::CondCode CC; 11977 if (I->Low == I->High) { 11978 // Check Cond == I->Low. 11979 CC = ISD::SETEQ; 11980 LHS = Cond; 11981 RHS=I->Low; 11982 MHS = nullptr; 11983 } else { 11984 // Check I->Low <= Cond <= I->High. 11985 CC = ISD::SETLE; 11986 LHS = I->Low; 11987 MHS = Cond; 11988 RHS = I->High; 11989 } 11990 11991 // If Fallthrough is unreachable, fold away the comparison. 11992 if (FallthroughUnreachable) 11993 CC = ISD::SETTRUE; 11994 11995 // The false probability is the sum of all unhandled cases. 11996 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 11997 getCurSDLoc(), I->Prob, UnhandledProbs); 11998 11999 if (CurMBB == SwitchMBB) 12000 visitSwitchCase(CB, SwitchMBB); 12001 else 12002 SL->SwitchCases.push_back(CB); 12003 12004 break; 12005 } 12006 } 12007 CurMBB = Fallthrough; 12008 } 12009 } 12010 12011 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 12012 const SwitchWorkListItem &W, 12013 Value *Cond, 12014 MachineBasicBlock *SwitchMBB) { 12015 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 12016 "Clusters not sorted?"); 12017 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 12018 12019 auto [LastLeft, FirstRight, LeftProb, RightProb] = 12020 SL->computeSplitWorkItemInfo(W); 12021 12022 // Use the first element on the right as pivot since we will make less-than 12023 // comparisons against it. 12024 CaseClusterIt PivotCluster = FirstRight; 12025 assert(PivotCluster > W.FirstCluster); 12026 assert(PivotCluster <= W.LastCluster); 12027 12028 CaseClusterIt FirstLeft = W.FirstCluster; 12029 CaseClusterIt LastRight = W.LastCluster; 12030 12031 const ConstantInt *Pivot = PivotCluster->Low; 12032 12033 // New blocks will be inserted immediately after the current one. 12034 MachineFunction::iterator BBI(W.MBB); 12035 ++BBI; 12036 12037 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 12038 // we can branch to its destination directly if it's squeezed exactly in 12039 // between the known lower bound and Pivot - 1. 12040 MachineBasicBlock *LeftMBB; 12041 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 12042 FirstLeft->Low == W.GE && 12043 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 12044 LeftMBB = FirstLeft->MBB; 12045 } else { 12046 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 12047 FuncInfo.MF->insert(BBI, LeftMBB); 12048 WorkList.push_back( 12049 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 12050 // Put Cond in a virtual register to make it available from the new blocks. 12051 ExportFromCurrentBlock(Cond); 12052 } 12053 12054 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 12055 // single cluster, RHS.Low == Pivot, and we can branch to its destination 12056 // directly if RHS.High equals the current upper bound. 12057 MachineBasicBlock *RightMBB; 12058 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 12059 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 12060 RightMBB = FirstRight->MBB; 12061 } else { 12062 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 12063 FuncInfo.MF->insert(BBI, RightMBB); 12064 WorkList.push_back( 12065 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 12066 // Put Cond in a virtual register to make it available from the new blocks. 12067 ExportFromCurrentBlock(Cond); 12068 } 12069 12070 // Create the CaseBlock record that will be used to lower the branch. 12071 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 12072 getCurSDLoc(), LeftProb, RightProb); 12073 12074 if (W.MBB == SwitchMBB) 12075 visitSwitchCase(CB, SwitchMBB); 12076 else 12077 SL->SwitchCases.push_back(CB); 12078 } 12079 12080 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 12081 // from the swith statement. 12082 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 12083 BranchProbability PeeledCaseProb) { 12084 if (PeeledCaseProb == BranchProbability::getOne()) 12085 return BranchProbability::getZero(); 12086 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 12087 12088 uint32_t Numerator = CaseProb.getNumerator(); 12089 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 12090 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 12091 } 12092 12093 // Try to peel the top probability case if it exceeds the threshold. 12094 // Return current MachineBasicBlock for the switch statement if the peeling 12095 // does not occur. 12096 // If the peeling is performed, return the newly created MachineBasicBlock 12097 // for the peeled switch statement. Also update Clusters to remove the peeled 12098 // case. PeeledCaseProb is the BranchProbability for the peeled case. 12099 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 12100 const SwitchInst &SI, CaseClusterVector &Clusters, 12101 BranchProbability &PeeledCaseProb) { 12102 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 12103 // Don't perform if there is only one cluster or optimizing for size. 12104 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 12105 TM.getOptLevel() == CodeGenOptLevel::None || 12106 SwitchMBB->getParent()->getFunction().hasMinSize()) 12107 return SwitchMBB; 12108 12109 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 12110 unsigned PeeledCaseIndex = 0; 12111 bool SwitchPeeled = false; 12112 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 12113 CaseCluster &CC = Clusters[Index]; 12114 if (CC.Prob < TopCaseProb) 12115 continue; 12116 TopCaseProb = CC.Prob; 12117 PeeledCaseIndex = Index; 12118 SwitchPeeled = true; 12119 } 12120 if (!SwitchPeeled) 12121 return SwitchMBB; 12122 12123 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 12124 << TopCaseProb << "\n"); 12125 12126 // Record the MBB for the peeled switch statement. 12127 MachineFunction::iterator BBI(SwitchMBB); 12128 ++BBI; 12129 MachineBasicBlock *PeeledSwitchMBB = 12130 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 12131 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 12132 12133 ExportFromCurrentBlock(SI.getCondition()); 12134 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 12135 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 12136 nullptr, nullptr, TopCaseProb.getCompl()}; 12137 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 12138 12139 Clusters.erase(PeeledCaseIt); 12140 for (CaseCluster &CC : Clusters) { 12141 LLVM_DEBUG( 12142 dbgs() << "Scale the probablity for one cluster, before scaling: " 12143 << CC.Prob << "\n"); 12144 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 12145 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 12146 } 12147 PeeledCaseProb = TopCaseProb; 12148 return PeeledSwitchMBB; 12149 } 12150 12151 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 12152 // Extract cases from the switch. 12153 BranchProbabilityInfo *BPI = FuncInfo.BPI; 12154 CaseClusterVector Clusters; 12155 Clusters.reserve(SI.getNumCases()); 12156 for (auto I : SI.cases()) { 12157 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 12158 const ConstantInt *CaseVal = I.getCaseValue(); 12159 BranchProbability Prob = 12160 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 12161 : BranchProbability(1, SI.getNumCases() + 1); 12162 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 12163 } 12164 12165 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 12166 12167 // Cluster adjacent cases with the same destination. We do this at all 12168 // optimization levels because it's cheap to do and will make codegen faster 12169 // if there are many clusters. 12170 sortAndRangeify(Clusters); 12171 12172 // The branch probablity of the peeled case. 12173 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 12174 MachineBasicBlock *PeeledSwitchMBB = 12175 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 12176 12177 // If there is only the default destination, jump there directly. 12178 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 12179 if (Clusters.empty()) { 12180 assert(PeeledSwitchMBB == SwitchMBB); 12181 SwitchMBB->addSuccessor(DefaultMBB); 12182 if (DefaultMBB != NextBlock(SwitchMBB)) { 12183 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 12184 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 12185 } 12186 return; 12187 } 12188 12189 SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(), 12190 DAG.getBFI()); 12191 SL->findBitTestClusters(Clusters, &SI); 12192 12193 LLVM_DEBUG({ 12194 dbgs() << "Case clusters: "; 12195 for (const CaseCluster &C : Clusters) { 12196 if (C.Kind == CC_JumpTable) 12197 dbgs() << "JT:"; 12198 if (C.Kind == CC_BitTests) 12199 dbgs() << "BT:"; 12200 12201 C.Low->getValue().print(dbgs(), true); 12202 if (C.Low != C.High) { 12203 dbgs() << '-'; 12204 C.High->getValue().print(dbgs(), true); 12205 } 12206 dbgs() << ' '; 12207 } 12208 dbgs() << '\n'; 12209 }); 12210 12211 assert(!Clusters.empty()); 12212 SwitchWorkList WorkList; 12213 CaseClusterIt First = Clusters.begin(); 12214 CaseClusterIt Last = Clusters.end() - 1; 12215 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 12216 // Scale the branchprobability for DefaultMBB if the peel occurs and 12217 // DefaultMBB is not replaced. 12218 if (PeeledCaseProb != BranchProbability::getZero() && 12219 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 12220 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 12221 WorkList.push_back( 12222 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 12223 12224 while (!WorkList.empty()) { 12225 SwitchWorkListItem W = WorkList.pop_back_val(); 12226 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 12227 12228 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None && 12229 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 12230 // For optimized builds, lower large range as a balanced binary tree. 12231 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 12232 continue; 12233 } 12234 12235 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 12236 } 12237 } 12238 12239 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 12240 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12241 auto DL = getCurSDLoc(); 12242 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12243 setValue(&I, DAG.getStepVector(DL, ResultVT)); 12244 } 12245 12246 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 12247 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12248 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12249 12250 SDLoc DL = getCurSDLoc(); 12251 SDValue V = getValue(I.getOperand(0)); 12252 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 12253 12254 if (VT.isScalableVector()) { 12255 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 12256 return; 12257 } 12258 12259 // Use VECTOR_SHUFFLE for the fixed-length vector 12260 // to maintain existing behavior. 12261 SmallVector<int, 8> Mask; 12262 unsigned NumElts = VT.getVectorMinNumElements(); 12263 for (unsigned i = 0; i != NumElts; ++i) 12264 Mask.push_back(NumElts - 1 - i); 12265 12266 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 12267 } 12268 12269 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) { 12270 auto DL = getCurSDLoc(); 12271 SDValue InVec = getValue(I.getOperand(0)); 12272 EVT OutVT = 12273 InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 12274 12275 unsigned OutNumElts = OutVT.getVectorMinNumElements(); 12276 12277 // ISD Node needs the input vectors split into two equal parts 12278 SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 12279 DAG.getVectorIdxConstant(0, DL)); 12280 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 12281 DAG.getVectorIdxConstant(OutNumElts, DL)); 12282 12283 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 12284 // legalisation and combines. 12285 if (OutVT.isFixedLengthVector()) { 12286 SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 12287 createStrideMask(0, 2, OutNumElts)); 12288 SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 12289 createStrideMask(1, 2, OutNumElts)); 12290 SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc()); 12291 setValue(&I, Res); 12292 return; 12293 } 12294 12295 SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL, 12296 DAG.getVTList(OutVT, OutVT), Lo, Hi); 12297 setValue(&I, Res); 12298 } 12299 12300 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) { 12301 auto DL = getCurSDLoc(); 12302 EVT InVT = getValue(I.getOperand(0)).getValueType(); 12303 SDValue InVec0 = getValue(I.getOperand(0)); 12304 SDValue InVec1 = getValue(I.getOperand(1)); 12305 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12306 EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12307 12308 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 12309 // legalisation and combines. 12310 if (OutVT.isFixedLengthVector()) { 12311 unsigned NumElts = InVT.getVectorMinNumElements(); 12312 SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1); 12313 setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT), 12314 createInterleaveMask(NumElts, 2))); 12315 return; 12316 } 12317 12318 SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, 12319 DAG.getVTList(InVT, InVT), InVec0, InVec1); 12320 Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0), 12321 Res.getValue(1)); 12322 setValue(&I, Res); 12323 } 12324 12325 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 12326 SmallVector<EVT, 4> ValueVTs; 12327 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 12328 ValueVTs); 12329 unsigned NumValues = ValueVTs.size(); 12330 if (NumValues == 0) return; 12331 12332 SmallVector<SDValue, 4> Values(NumValues); 12333 SDValue Op = getValue(I.getOperand(0)); 12334 12335 for (unsigned i = 0; i != NumValues; ++i) 12336 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 12337 SDValue(Op.getNode(), Op.getResNo() + i)); 12338 12339 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 12340 DAG.getVTList(ValueVTs), Values)); 12341 } 12342 12343 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 12344 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12345 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12346 12347 SDLoc DL = getCurSDLoc(); 12348 SDValue V1 = getValue(I.getOperand(0)); 12349 SDValue V2 = getValue(I.getOperand(1)); 12350 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 12351 12352 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 12353 if (VT.isScalableVector()) { 12354 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 12355 DAG.getVectorIdxConstant(Imm, DL))); 12356 return; 12357 } 12358 12359 unsigned NumElts = VT.getVectorNumElements(); 12360 12361 uint64_t Idx = (NumElts + Imm) % NumElts; 12362 12363 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 12364 SmallVector<int, 8> Mask; 12365 for (unsigned i = 0; i < NumElts; ++i) 12366 Mask.push_back(Idx + i); 12367 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 12368 } 12369 12370 // Consider the following MIR after SelectionDAG, which produces output in 12371 // phyregs in the first case or virtregs in the second case. 12372 // 12373 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx 12374 // %5:gr32 = COPY $ebx 12375 // %6:gr32 = COPY $edx 12376 // %1:gr32 = COPY %6:gr32 12377 // %0:gr32 = COPY %5:gr32 12378 // 12379 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32 12380 // %1:gr32 = COPY %6:gr32 12381 // %0:gr32 = COPY %5:gr32 12382 // 12383 // Given %0, we'd like to return $ebx in the first case and %5 in the second. 12384 // Given %1, we'd like to return $edx in the first case and %6 in the second. 12385 // 12386 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap 12387 // to a single virtreg (such as %0). The remaining outputs monotonically 12388 // increase in virtreg number from there. If a callbr has no outputs, then it 12389 // should not have a corresponding callbr landingpad; in fact, the callbr 12390 // landingpad would not even be able to refer to such a callbr. 12391 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) { 12392 MachineInstr *MI = MRI.def_begin(Reg)->getParent(); 12393 // There is definitely at least one copy. 12394 assert(MI->getOpcode() == TargetOpcode::COPY && 12395 "start of copy chain MUST be COPY"); 12396 Reg = MI->getOperand(1).getReg(); 12397 MI = MRI.def_begin(Reg)->getParent(); 12398 // There may be an optional second copy. 12399 if (MI->getOpcode() == TargetOpcode::COPY) { 12400 assert(Reg.isVirtual() && "expected COPY of virtual register"); 12401 Reg = MI->getOperand(1).getReg(); 12402 assert(Reg.isPhysical() && "expected COPY of physical register"); 12403 MI = MRI.def_begin(Reg)->getParent(); 12404 } 12405 // The start of the chain must be an INLINEASM_BR. 12406 assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR && 12407 "end of copy chain MUST be INLINEASM_BR"); 12408 return Reg; 12409 } 12410 12411 // We must do this walk rather than the simpler 12412 // setValue(&I, getCopyFromRegs(CBR, CBR->getType())); 12413 // otherwise we will end up with copies of virtregs only valid along direct 12414 // edges. 12415 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) { 12416 SmallVector<EVT, 8> ResultVTs; 12417 SmallVector<SDValue, 8> ResultValues; 12418 const auto *CBR = 12419 cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator()); 12420 12421 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12422 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 12423 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 12424 12425 unsigned InitialDef = FuncInfo.ValueMap[CBR]; 12426 SDValue Chain = DAG.getRoot(); 12427 12428 // Re-parse the asm constraints string. 12429 TargetLowering::AsmOperandInfoVector TargetConstraints = 12430 TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR); 12431 for (auto &T : TargetConstraints) { 12432 SDISelAsmOperandInfo OpInfo(T); 12433 if (OpInfo.Type != InlineAsm::isOutput) 12434 continue; 12435 12436 // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the 12437 // individual constraint. 12438 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 12439 12440 switch (OpInfo.ConstraintType) { 12441 case TargetLowering::C_Register: 12442 case TargetLowering::C_RegisterClass: { 12443 // Fill in OpInfo.AssignedRegs.Regs. 12444 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo); 12445 12446 // getRegistersForValue may produce 1 to many registers based on whether 12447 // the OpInfo.ConstraintVT is legal on the target or not. 12448 for (size_t i = 0, e = OpInfo.AssignedRegs.Regs.size(); i != e; ++i) { 12449 Register OriginalDef = FollowCopyChain(MRI, InitialDef++); 12450 if (Register::isPhysicalRegister(OriginalDef)) 12451 FuncInfo.MBB->addLiveIn(OriginalDef); 12452 // Update the assigned registers to use the original defs. 12453 OpInfo.AssignedRegs.Regs[i] = OriginalDef; 12454 } 12455 12456 SDValue V = OpInfo.AssignedRegs.getCopyFromRegs( 12457 DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR); 12458 ResultValues.push_back(V); 12459 ResultVTs.push_back(OpInfo.ConstraintVT); 12460 break; 12461 } 12462 case TargetLowering::C_Other: { 12463 SDValue Flag; 12464 SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 12465 OpInfo, DAG); 12466 ++InitialDef; 12467 ResultValues.push_back(V); 12468 ResultVTs.push_back(OpInfo.ConstraintVT); 12469 break; 12470 } 12471 default: 12472 break; 12473 } 12474 } 12475 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 12476 DAG.getVTList(ResultVTs), ResultValues); 12477 setValue(&I, V); 12478 } 12479