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/Triple.h" 23 #include "llvm/ADT/Twine.h" 24 #include "llvm/Analysis/AliasAnalysis.h" 25 #include "llvm/Analysis/BranchProbabilityInfo.h" 26 #include "llvm/Analysis/ConstantFolding.h" 27 #include "llvm/Analysis/EHPersonalities.h" 28 #include "llvm/Analysis/Loads.h" 29 #include "llvm/Analysis/MemoryLocation.h" 30 #include "llvm/Analysis/TargetLibraryInfo.h" 31 #include "llvm/Analysis/ValueTracking.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/MachineBasicBlock.h" 38 #include "llvm/CodeGen/MachineFrameInfo.h" 39 #include "llvm/CodeGen/MachineFunction.h" 40 #include "llvm/CodeGen/MachineInstrBuilder.h" 41 #include "llvm/CodeGen/MachineInstrBundleIterator.h" 42 #include "llvm/CodeGen/MachineMemOperand.h" 43 #include "llvm/CodeGen/MachineModuleInfo.h" 44 #include "llvm/CodeGen/MachineOperand.h" 45 #include "llvm/CodeGen/MachineRegisterInfo.h" 46 #include "llvm/CodeGen/RuntimeLibcalls.h" 47 #include "llvm/CodeGen/SelectionDAG.h" 48 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 49 #include "llvm/CodeGen/StackMaps.h" 50 #include "llvm/CodeGen/SwiftErrorValueTracking.h" 51 #include "llvm/CodeGen/TargetFrameLowering.h" 52 #include "llvm/CodeGen/TargetInstrInfo.h" 53 #include "llvm/CodeGen/TargetOpcodes.h" 54 #include "llvm/CodeGen/TargetRegisterInfo.h" 55 #include "llvm/CodeGen/TargetSubtargetInfo.h" 56 #include "llvm/CodeGen/WinEHFuncInfo.h" 57 #include "llvm/IR/Argument.h" 58 #include "llvm/IR/Attributes.h" 59 #include "llvm/IR/BasicBlock.h" 60 #include "llvm/IR/CFG.h" 61 #include "llvm/IR/CallingConv.h" 62 #include "llvm/IR/Constant.h" 63 #include "llvm/IR/ConstantRange.h" 64 #include "llvm/IR/Constants.h" 65 #include "llvm/IR/DataLayout.h" 66 #include "llvm/IR/DebugInfo.h" 67 #include "llvm/IR/DebugInfoMetadata.h" 68 #include "llvm/IR/DerivedTypes.h" 69 #include "llvm/IR/DiagnosticInfo.h" 70 #include "llvm/IR/Function.h" 71 #include "llvm/IR/GetElementPtrTypeIterator.h" 72 #include "llvm/IR/InlineAsm.h" 73 #include "llvm/IR/InstrTypes.h" 74 #include "llvm/IR/Instructions.h" 75 #include "llvm/IR/IntrinsicInst.h" 76 #include "llvm/IR/Intrinsics.h" 77 #include "llvm/IR/IntrinsicsAArch64.h" 78 #include "llvm/IR/IntrinsicsWebAssembly.h" 79 #include "llvm/IR/LLVMContext.h" 80 #include "llvm/IR/Metadata.h" 81 #include "llvm/IR/Module.h" 82 #include "llvm/IR/Operator.h" 83 #include "llvm/IR/PatternMatch.h" 84 #include "llvm/IR/Statepoint.h" 85 #include "llvm/IR/Type.h" 86 #include "llvm/IR/User.h" 87 #include "llvm/IR/Value.h" 88 #include "llvm/MC/MCContext.h" 89 #include "llvm/Support/AtomicOrdering.h" 90 #include "llvm/Support/Casting.h" 91 #include "llvm/Support/CommandLine.h" 92 #include "llvm/Support/Compiler.h" 93 #include "llvm/Support/Debug.h" 94 #include "llvm/Support/MathExtras.h" 95 #include "llvm/Support/raw_ostream.h" 96 #include "llvm/Target/TargetIntrinsicInfo.h" 97 #include "llvm/Target/TargetMachine.h" 98 #include "llvm/Target/TargetOptions.h" 99 #include "llvm/Transforms/Utils/Local.h" 100 #include <cstddef> 101 #include <iterator> 102 #include <limits> 103 #include <optional> 104 #include <tuple> 105 106 using namespace llvm; 107 using namespace PatternMatch; 108 using namespace SwitchCG; 109 110 #define DEBUG_TYPE "isel" 111 112 /// LimitFloatPrecision - Generate low-precision inline sequences for 113 /// some float libcalls (6, 8 or 12 bits). 114 static unsigned LimitFloatPrecision; 115 116 static cl::opt<bool> 117 InsertAssertAlign("insert-assert-align", cl::init(true), 118 cl::desc("Insert the experimental `assertalign` node."), 119 cl::ReallyHidden); 120 121 static cl::opt<unsigned, true> 122 LimitFPPrecision("limit-float-precision", 123 cl::desc("Generate low-precision inline sequences " 124 "for some float libcalls"), 125 cl::location(LimitFloatPrecision), cl::Hidden, 126 cl::init(0)); 127 128 static cl::opt<unsigned> SwitchPeelThreshold( 129 "switch-peel-threshold", cl::Hidden, cl::init(66), 130 cl::desc("Set the case probability threshold for peeling the case from a " 131 "switch statement. A value greater than 100 will void this " 132 "optimization")); 133 134 // Limit the width of DAG chains. This is important in general to prevent 135 // DAG-based analysis from blowing up. For example, alias analysis and 136 // load clustering may not complete in reasonable time. It is difficult to 137 // recognize and avoid this situation within each individual analysis, and 138 // future analyses are likely to have the same behavior. Limiting DAG width is 139 // the safe approach and will be especially important with global DAGs. 140 // 141 // MaxParallelChains default is arbitrarily high to avoid affecting 142 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 143 // sequence over this should have been converted to llvm.memcpy by the 144 // frontend. It is easy to induce this behavior with .ll code such as: 145 // %buffer = alloca [4096 x i8] 146 // %data = load [4096 x i8]* %argPtr 147 // store [4096 x i8] %data, [4096 x i8]* %buffer 148 static const unsigned MaxParallelChains = 64; 149 150 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 151 const SDValue *Parts, unsigned NumParts, 152 MVT PartVT, EVT ValueVT, const Value *V, 153 std::optional<CallingConv::ID> CC); 154 155 /// getCopyFromParts - Create a value that contains the specified legal parts 156 /// combined into the value they represent. If the parts combine to a type 157 /// larger than ValueVT then AssertOp can be used to specify whether the extra 158 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 159 /// (ISD::AssertSext). 160 static SDValue 161 getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, 162 unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V, 163 std::optional<CallingConv::ID> CC = std::nullopt, 164 std::optional<ISD::NodeType> AssertOp = std::nullopt) { 165 // Let the target assemble the parts if it wants to 166 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 167 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts, 168 PartVT, ValueVT, CC)) 169 return Val; 170 171 if (ValueVT.isVector()) 172 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 173 CC); 174 175 assert(NumParts > 0 && "No parts to assemble!"); 176 SDValue Val = Parts[0]; 177 178 if (NumParts > 1) { 179 // Assemble the value from multiple parts. 180 if (ValueVT.isInteger()) { 181 unsigned PartBits = PartVT.getSizeInBits(); 182 unsigned ValueBits = ValueVT.getSizeInBits(); 183 184 // Assemble the power of 2 part. 185 unsigned RoundParts = 186 (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts; 187 unsigned RoundBits = PartBits * RoundParts; 188 EVT RoundVT = RoundBits == ValueBits ? 189 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 190 SDValue Lo, Hi; 191 192 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 193 194 if (RoundParts > 2) { 195 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 196 PartVT, HalfVT, V); 197 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 198 RoundParts / 2, PartVT, HalfVT, V); 199 } else { 200 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 201 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 202 } 203 204 if (DAG.getDataLayout().isBigEndian()) 205 std::swap(Lo, Hi); 206 207 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 208 209 if (RoundParts < NumParts) { 210 // Assemble the trailing non-power-of-2 part. 211 unsigned OddParts = NumParts - RoundParts; 212 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 213 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 214 OddVT, V, CC); 215 216 // Combine the round and odd parts. 217 Lo = Val; 218 if (DAG.getDataLayout().isBigEndian()) 219 std::swap(Lo, Hi); 220 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 221 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 222 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 223 DAG.getConstant(Lo.getValueSizeInBits(), DL, 224 TLI.getShiftAmountTy( 225 TotalVT, DAG.getDataLayout()))); 226 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 227 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 228 } 229 } else if (PartVT.isFloatingPoint()) { 230 // FP split into multiple FP parts (for ppcf128) 231 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 232 "Unexpected split"); 233 SDValue Lo, Hi; 234 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 235 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 236 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 237 std::swap(Lo, Hi); 238 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 239 } else { 240 // FP split into integer parts (soft fp) 241 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 242 !PartVT.isVector() && "Unexpected split"); 243 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 244 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 245 } 246 } 247 248 // There is now one part, held in Val. Correct it to match ValueVT. 249 // PartEVT is the type of the register class that holds the value. 250 // ValueVT is the type of the inline asm operation. 251 EVT PartEVT = Val.getValueType(); 252 253 if (PartEVT == ValueVT) 254 return Val; 255 256 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 257 ValueVT.bitsLT(PartEVT)) { 258 // For an FP value in an integer part, we need to truncate to the right 259 // width first. 260 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 261 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 262 } 263 264 // Handle types that have the same size. 265 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 266 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 267 268 // Handle types with different sizes. 269 if (PartEVT.isInteger() && ValueVT.isInteger()) { 270 if (ValueVT.bitsLT(PartEVT)) { 271 // For a truncate, see if we have any information to 272 // indicate whether the truncated bits will always be 273 // zero or sign-extension. 274 if (AssertOp) 275 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 276 DAG.getValueType(ValueVT)); 277 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 278 } 279 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 280 } 281 282 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 283 // FP_ROUND's are always exact here. 284 if (ValueVT.bitsLT(Val.getValueType())) 285 return DAG.getNode( 286 ISD::FP_ROUND, DL, ValueVT, Val, 287 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 288 289 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 290 } 291 292 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 293 // then truncating. 294 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 295 ValueVT.bitsLT(PartEVT)) { 296 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 297 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 298 } 299 300 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 301 } 302 303 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 304 const Twine &ErrMsg) { 305 const Instruction *I = dyn_cast_or_null<Instruction>(V); 306 if (!V) 307 return Ctx.emitError(ErrMsg); 308 309 const char *AsmError = ", possible invalid constraint for vector type"; 310 if (const CallInst *CI = dyn_cast<CallInst>(I)) 311 if (CI->isInlineAsm()) 312 return Ctx.emitError(I, ErrMsg + AsmError); 313 314 return Ctx.emitError(I, ErrMsg); 315 } 316 317 /// getCopyFromPartsVector - Create a value that contains the specified legal 318 /// parts combined into the value they represent. If the parts combine to a 319 /// type larger than ValueVT then AssertOp can be used to specify whether the 320 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 321 /// ValueVT (ISD::AssertSext). 322 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 323 const SDValue *Parts, unsigned NumParts, 324 MVT PartVT, EVT ValueVT, const Value *V, 325 std::optional<CallingConv::ID> CallConv) { 326 assert(ValueVT.isVector() && "Not a vector value"); 327 assert(NumParts > 0 && "No parts to assemble!"); 328 const bool IsABIRegCopy = CallConv.has_value(); 329 330 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 331 SDValue Val = Parts[0]; 332 333 // Handle a multi-element vector. 334 if (NumParts > 1) { 335 EVT IntermediateVT; 336 MVT RegisterVT; 337 unsigned NumIntermediates; 338 unsigned NumRegs; 339 340 if (IsABIRegCopy) { 341 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 342 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, 343 NumIntermediates, RegisterVT); 344 } else { 345 NumRegs = 346 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 347 NumIntermediates, RegisterVT); 348 } 349 350 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 351 NumParts = NumRegs; // Silence a compiler warning. 352 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 353 assert(RegisterVT.getSizeInBits() == 354 Parts[0].getSimpleValueType().getSizeInBits() && 355 "Part type sizes don't match!"); 356 357 // Assemble the parts into intermediate operands. 358 SmallVector<SDValue, 8> Ops(NumIntermediates); 359 if (NumIntermediates == NumParts) { 360 // If the register was not expanded, truncate or copy the value, 361 // as appropriate. 362 for (unsigned i = 0; i != NumParts; ++i) 363 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 364 PartVT, IntermediateVT, V, CallConv); 365 } else if (NumParts > 0) { 366 // If the intermediate type was expanded, build the intermediate 367 // operands from the parts. 368 assert(NumParts % NumIntermediates == 0 && 369 "Must expand into a divisible number of parts!"); 370 unsigned Factor = NumParts / NumIntermediates; 371 for (unsigned i = 0; i != NumIntermediates; ++i) 372 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 373 PartVT, IntermediateVT, V, CallConv); 374 } 375 376 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 377 // intermediate operands. 378 EVT BuiltVectorTy = 379 IntermediateVT.isVector() 380 ? EVT::getVectorVT( 381 *DAG.getContext(), IntermediateVT.getScalarType(), 382 IntermediateVT.getVectorElementCount() * NumParts) 383 : EVT::getVectorVT(*DAG.getContext(), 384 IntermediateVT.getScalarType(), 385 NumIntermediates); 386 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 387 : ISD::BUILD_VECTOR, 388 DL, BuiltVectorTy, Ops); 389 } 390 391 // There is now one part, held in Val. Correct it to match ValueVT. 392 EVT PartEVT = Val.getValueType(); 393 394 if (PartEVT == ValueVT) 395 return Val; 396 397 if (PartEVT.isVector()) { 398 // Vector/Vector bitcast. 399 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 400 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 401 402 // If the parts vector has more elements than the value vector, then we 403 // have a vector widening case (e.g. <2 x float> -> <4 x float>). 404 // Extract the elements we want. 405 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) { 406 assert((PartEVT.getVectorElementCount().getKnownMinValue() > 407 ValueVT.getVectorElementCount().getKnownMinValue()) && 408 (PartEVT.getVectorElementCount().isScalable() == 409 ValueVT.getVectorElementCount().isScalable()) && 410 "Cannot narrow, it would be a lossy transformation"); 411 PartEVT = 412 EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(), 413 ValueVT.getVectorElementCount()); 414 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val, 415 DAG.getVectorIdxConstant(0, DL)); 416 if (PartEVT == ValueVT) 417 return Val; 418 if (PartEVT.isInteger() && ValueVT.isFloatingPoint()) 419 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 420 } 421 422 // Promoted vector extract 423 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 424 } 425 426 // Trivial bitcast if the types are the same size and the destination 427 // vector type is legal. 428 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 429 TLI.isTypeLegal(ValueVT)) 430 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 431 432 if (ValueVT.getVectorNumElements() != 1) { 433 // Certain ABIs require that vectors are passed as integers. For vectors 434 // are the same size, this is an obvious bitcast. 435 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 436 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 437 } else if (ValueVT.bitsLT(PartEVT)) { 438 const uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 439 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 440 // Drop the extra bits. 441 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 442 return DAG.getBitcast(ValueVT, Val); 443 } 444 445 diagnosePossiblyInvalidConstraint( 446 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 447 return DAG.getUNDEF(ValueVT); 448 } 449 450 // Handle cases such as i8 -> <1 x i1> 451 EVT ValueSVT = ValueVT.getVectorElementType(); 452 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 453 unsigned ValueSize = ValueSVT.getSizeInBits(); 454 if (ValueSize == PartEVT.getSizeInBits()) { 455 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 456 } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) { 457 // It's possible a scalar floating point type gets softened to integer and 458 // then promoted to a larger integer. If PartEVT is the larger integer 459 // we need to truncate it and then bitcast to the FP type. 460 assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types"); 461 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 462 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 463 Val = DAG.getBitcast(ValueSVT, Val); 464 } else { 465 Val = ValueVT.isFloatingPoint() 466 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 467 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 468 } 469 } 470 471 return DAG.getBuildVector(ValueVT, DL, Val); 472 } 473 474 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 475 SDValue Val, SDValue *Parts, unsigned NumParts, 476 MVT PartVT, const Value *V, 477 std::optional<CallingConv::ID> CallConv); 478 479 /// getCopyToParts - Create a series of nodes that contain the specified value 480 /// split into legal parts. If the parts contain more bits than Val, then, for 481 /// integers, ExtendKind can be used to specify how to generate the extra bits. 482 static void 483 getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 484 unsigned NumParts, MVT PartVT, const Value *V, 485 std::optional<CallingConv::ID> CallConv = std::nullopt, 486 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 487 // Let the target split the parts if it wants to 488 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 489 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 490 CallConv)) 491 return; 492 EVT ValueVT = Val.getValueType(); 493 494 // Handle the vector case separately. 495 if (ValueVT.isVector()) 496 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 497 CallConv); 498 499 unsigned PartBits = PartVT.getSizeInBits(); 500 unsigned OrigNumParts = NumParts; 501 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 502 "Copying to an illegal type!"); 503 504 if (NumParts == 0) 505 return; 506 507 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 508 EVT PartEVT = PartVT; 509 if (PartEVT == ValueVT) { 510 assert(NumParts == 1 && "No-op copy with multiple parts!"); 511 Parts[0] = Val; 512 return; 513 } 514 515 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 516 // If the parts cover more bits than the value has, promote the value. 517 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 518 assert(NumParts == 1 && "Do not know what to promote to!"); 519 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 520 } else { 521 if (ValueVT.isFloatingPoint()) { 522 // FP values need to be bitcast, then extended if they are being put 523 // into a larger container. 524 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 525 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 526 } 527 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 528 ValueVT.isInteger() && 529 "Unknown mismatch!"); 530 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 531 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 532 if (PartVT == MVT::x86mmx) 533 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 534 } 535 } else if (PartBits == ValueVT.getSizeInBits()) { 536 // Different types of the same size. 537 assert(NumParts == 1 && PartEVT != ValueVT); 538 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 539 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 540 // If the parts cover less bits than value has, truncate the value. 541 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 542 ValueVT.isInteger() && 543 "Unknown mismatch!"); 544 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 545 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 546 if (PartVT == MVT::x86mmx) 547 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 548 } 549 550 // The value may have changed - recompute ValueVT. 551 ValueVT = Val.getValueType(); 552 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 553 "Failed to tile the value with PartVT!"); 554 555 if (NumParts == 1) { 556 if (PartEVT != ValueVT) { 557 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 558 "scalar-to-vector conversion failed"); 559 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 560 } 561 562 Parts[0] = Val; 563 return; 564 } 565 566 // Expand the value into multiple parts. 567 if (NumParts & (NumParts - 1)) { 568 // The number of parts is not a power of 2. Split off and copy the tail. 569 assert(PartVT.isInteger() && ValueVT.isInteger() && 570 "Do not know what to expand to!"); 571 unsigned RoundParts = 1 << Log2_32(NumParts); 572 unsigned RoundBits = RoundParts * PartBits; 573 unsigned OddParts = NumParts - RoundParts; 574 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 575 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL)); 576 577 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 578 CallConv); 579 580 if (DAG.getDataLayout().isBigEndian()) 581 // The odd parts were reversed by getCopyToParts - unreverse them. 582 std::reverse(Parts + RoundParts, Parts + NumParts); 583 584 NumParts = RoundParts; 585 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 586 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 587 } 588 589 // The number of parts is a power of 2. Repeatedly bisect the value using 590 // EXTRACT_ELEMENT. 591 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 592 EVT::getIntegerVT(*DAG.getContext(), 593 ValueVT.getSizeInBits()), 594 Val); 595 596 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 597 for (unsigned i = 0; i < NumParts; i += StepSize) { 598 unsigned ThisBits = StepSize * PartBits / 2; 599 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 600 SDValue &Part0 = Parts[i]; 601 SDValue &Part1 = Parts[i+StepSize/2]; 602 603 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 604 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 605 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 606 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 607 608 if (ThisBits == PartBits && ThisVT != PartVT) { 609 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 610 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 611 } 612 } 613 } 614 615 if (DAG.getDataLayout().isBigEndian()) 616 std::reverse(Parts, Parts + OrigNumParts); 617 } 618 619 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val, 620 const SDLoc &DL, EVT PartVT) { 621 if (!PartVT.isVector()) 622 return SDValue(); 623 624 EVT ValueVT = Val.getValueType(); 625 ElementCount PartNumElts = PartVT.getVectorElementCount(); 626 ElementCount ValueNumElts = ValueVT.getVectorElementCount(); 627 628 // We only support widening vectors with equivalent element types and 629 // fixed/scalable properties. If a target needs to widen a fixed-length type 630 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below. 631 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) || 632 PartNumElts.isScalable() != ValueNumElts.isScalable() || 633 PartVT.getVectorElementType() != ValueVT.getVectorElementType()) 634 return SDValue(); 635 636 // Widening a scalable vector to another scalable vector is done by inserting 637 // the vector into a larger undef one. 638 if (PartNumElts.isScalable()) 639 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 640 Val, DAG.getVectorIdxConstant(0, DL)); 641 642 EVT ElementVT = PartVT.getVectorElementType(); 643 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 644 // undef elements. 645 SmallVector<SDValue, 16> Ops; 646 DAG.ExtractVectorElements(Val, Ops); 647 SDValue EltUndef = DAG.getUNDEF(ElementVT); 648 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef); 649 650 // FIXME: Use CONCAT for 2x -> 4x. 651 return DAG.getBuildVector(PartVT, DL, Ops); 652 } 653 654 /// getCopyToPartsVector - Create a series of nodes that contain the specified 655 /// value split into legal parts. 656 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 657 SDValue Val, SDValue *Parts, unsigned NumParts, 658 MVT PartVT, const Value *V, 659 std::optional<CallingConv::ID> CallConv) { 660 EVT ValueVT = Val.getValueType(); 661 assert(ValueVT.isVector() && "Not a vector"); 662 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 663 const bool IsABIRegCopy = CallConv.has_value(); 664 665 if (NumParts == 1) { 666 EVT PartEVT = PartVT; 667 if (PartEVT == ValueVT) { 668 // Nothing to do. 669 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 670 // Bitconvert vector->vector case. 671 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 672 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 673 Val = Widened; 674 } else if (PartVT.isVector() && 675 PartEVT.getVectorElementType().bitsGE( 676 ValueVT.getVectorElementType()) && 677 PartEVT.getVectorElementCount() == 678 ValueVT.getVectorElementCount()) { 679 680 // Promoted vector extract 681 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 682 } else if (PartEVT.isVector() && 683 PartEVT.getVectorElementType() != 684 ValueVT.getVectorElementType() && 685 TLI.getTypeAction(*DAG.getContext(), ValueVT) == 686 TargetLowering::TypeWidenVector) { 687 // Combination of widening and promotion. 688 EVT WidenVT = 689 EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(), 690 PartVT.getVectorElementCount()); 691 SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT); 692 Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT); 693 } else { 694 // Don't extract an integer from a float vector. This can happen if the 695 // FP type gets softened to integer and then promoted. The promotion 696 // prevents it from being picked up by the earlier bitcast case. 697 if (ValueVT.getVectorElementCount().isScalar() && 698 (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) { 699 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 700 DAG.getVectorIdxConstant(0, DL)); 701 } else { 702 uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 703 assert(PartVT.getFixedSizeInBits() > ValueSize && 704 "lossy conversion of vector to scalar type"); 705 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 706 Val = DAG.getBitcast(IntermediateType, Val); 707 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 708 } 709 } 710 711 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 712 Parts[0] = Val; 713 return; 714 } 715 716 // Handle a multi-element vector. 717 EVT IntermediateVT; 718 MVT RegisterVT; 719 unsigned NumIntermediates; 720 unsigned NumRegs; 721 if (IsABIRegCopy) { 722 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 723 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates, 724 RegisterVT); 725 } else { 726 NumRegs = 727 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 728 NumIntermediates, RegisterVT); 729 } 730 731 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 732 NumParts = NumRegs; // Silence a compiler warning. 733 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 734 735 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 736 "Mixing scalable and fixed vectors when copying in parts"); 737 738 std::optional<ElementCount> DestEltCnt; 739 740 if (IntermediateVT.isVector()) 741 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 742 else 743 DestEltCnt = ElementCount::getFixed(NumIntermediates); 744 745 EVT BuiltVectorTy = EVT::getVectorVT( 746 *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt); 747 748 if (ValueVT == BuiltVectorTy) { 749 // Nothing to do. 750 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) { 751 // Bitconvert vector->vector case. 752 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 753 } else { 754 if (BuiltVectorTy.getVectorElementType().bitsGT( 755 ValueVT.getVectorElementType())) { 756 // Integer promotion. 757 ValueVT = EVT::getVectorVT(*DAG.getContext(), 758 BuiltVectorTy.getVectorElementType(), 759 ValueVT.getVectorElementCount()); 760 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 761 } 762 763 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) { 764 Val = Widened; 765 } 766 } 767 768 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type"); 769 770 // Split the vector into intermediate operands. 771 SmallVector<SDValue, 8> Ops(NumIntermediates); 772 for (unsigned i = 0; i != NumIntermediates; ++i) { 773 if (IntermediateVT.isVector()) { 774 // This does something sensible for scalable vectors - see the 775 // definition of EXTRACT_SUBVECTOR for further details. 776 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 777 Ops[i] = 778 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 779 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 780 } else { 781 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 782 DAG.getVectorIdxConstant(i, DL)); 783 } 784 } 785 786 // Split the intermediate operands into legal parts. 787 if (NumParts == NumIntermediates) { 788 // If the register was not expanded, promote or copy the value, 789 // as appropriate. 790 for (unsigned i = 0; i != NumParts; ++i) 791 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 792 } else if (NumParts > 0) { 793 // If the intermediate type was expanded, split each the value into 794 // legal parts. 795 assert(NumIntermediates != 0 && "division by zero"); 796 assert(NumParts % NumIntermediates == 0 && 797 "Must expand into a divisible number of parts!"); 798 unsigned Factor = NumParts / NumIntermediates; 799 for (unsigned i = 0; i != NumIntermediates; ++i) 800 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 801 CallConv); 802 } 803 } 804 805 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 806 EVT valuevt, std::optional<CallingConv::ID> CC) 807 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 808 RegCount(1, regs.size()), CallConv(CC) {} 809 810 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 811 const DataLayout &DL, unsigned Reg, Type *Ty, 812 std::optional<CallingConv::ID> CC) { 813 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 814 815 CallConv = CC; 816 817 for (EVT ValueVT : ValueVTs) { 818 unsigned NumRegs = 819 isABIMangled() 820 ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT) 821 : TLI.getNumRegisters(Context, ValueVT); 822 MVT RegisterVT = 823 isABIMangled() 824 ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT) 825 : TLI.getRegisterType(Context, ValueVT); 826 for (unsigned i = 0; i != NumRegs; ++i) 827 Regs.push_back(Reg + i); 828 RegVTs.push_back(RegisterVT); 829 RegCount.push_back(NumRegs); 830 Reg += NumRegs; 831 } 832 } 833 834 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 835 FunctionLoweringInfo &FuncInfo, 836 const SDLoc &dl, SDValue &Chain, 837 SDValue *Flag, const Value *V) const { 838 // A Value with type {} or [0 x %t] needs no registers. 839 if (ValueVTs.empty()) 840 return SDValue(); 841 842 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 843 844 // Assemble the legal parts into the final values. 845 SmallVector<SDValue, 4> Values(ValueVTs.size()); 846 SmallVector<SDValue, 8> Parts; 847 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 848 // Copy the legal parts from the registers. 849 EVT ValueVT = ValueVTs[Value]; 850 unsigned NumRegs = RegCount[Value]; 851 MVT RegisterVT = isABIMangled() 852 ? TLI.getRegisterTypeForCallingConv( 853 *DAG.getContext(), *CallConv, RegVTs[Value]) 854 : RegVTs[Value]; 855 856 Parts.resize(NumRegs); 857 for (unsigned i = 0; i != NumRegs; ++i) { 858 SDValue P; 859 if (!Flag) { 860 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 861 } else { 862 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 863 *Flag = P.getValue(2); 864 } 865 866 Chain = P.getValue(1); 867 Parts[i] = P; 868 869 // If the source register was virtual and if we know something about it, 870 // add an assert node. 871 if (!Register::isVirtualRegister(Regs[Part + i]) || 872 !RegisterVT.isInteger()) 873 continue; 874 875 const FunctionLoweringInfo::LiveOutInfo *LOI = 876 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 877 if (!LOI) 878 continue; 879 880 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 881 unsigned NumSignBits = LOI->NumSignBits; 882 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 883 884 if (NumZeroBits == RegSize) { 885 // The current value is a zero. 886 // Explicitly express that as it would be easier for 887 // optimizations to kick in. 888 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 889 continue; 890 } 891 892 // FIXME: We capture more information than the dag can represent. For 893 // now, just use the tightest assertzext/assertsext possible. 894 bool isSExt; 895 EVT FromVT(MVT::Other); 896 if (NumZeroBits) { 897 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 898 isSExt = false; 899 } else if (NumSignBits > 1) { 900 FromVT = 901 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 902 isSExt = true; 903 } else { 904 continue; 905 } 906 // Add an assertion node. 907 assert(FromVT != MVT::Other); 908 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 909 RegisterVT, P, DAG.getValueType(FromVT)); 910 } 911 912 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 913 RegisterVT, ValueVT, V, CallConv); 914 Part += NumRegs; 915 Parts.clear(); 916 } 917 918 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 919 } 920 921 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 922 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 923 const Value *V, 924 ISD::NodeType PreferredExtendType) const { 925 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 926 ISD::NodeType ExtendKind = PreferredExtendType; 927 928 // Get the list of the values's legal parts. 929 unsigned NumRegs = Regs.size(); 930 SmallVector<SDValue, 8> Parts(NumRegs); 931 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 932 unsigned NumParts = RegCount[Value]; 933 934 MVT RegisterVT = isABIMangled() 935 ? TLI.getRegisterTypeForCallingConv( 936 *DAG.getContext(), *CallConv, RegVTs[Value]) 937 : RegVTs[Value]; 938 939 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 940 ExtendKind = ISD::ZERO_EXTEND; 941 942 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 943 NumParts, RegisterVT, V, CallConv, ExtendKind); 944 Part += NumParts; 945 } 946 947 // Copy the parts into the registers. 948 SmallVector<SDValue, 8> Chains(NumRegs); 949 for (unsigned i = 0; i != NumRegs; ++i) { 950 SDValue Part; 951 if (!Flag) { 952 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 953 } else { 954 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 955 *Flag = Part.getValue(1); 956 } 957 958 Chains[i] = Part.getValue(0); 959 } 960 961 if (NumRegs == 1 || Flag) 962 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 963 // flagged to it. That is the CopyToReg nodes and the user are considered 964 // a single scheduling unit. If we create a TokenFactor and return it as 965 // chain, then the TokenFactor is both a predecessor (operand) of the 966 // user as well as a successor (the TF operands are flagged to the user). 967 // c1, f1 = CopyToReg 968 // c2, f2 = CopyToReg 969 // c3 = TokenFactor c1, c2 970 // ... 971 // = op c3, ..., f2 972 Chain = Chains[NumRegs-1]; 973 else 974 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 975 } 976 977 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 978 unsigned MatchingIdx, const SDLoc &dl, 979 SelectionDAG &DAG, 980 std::vector<SDValue> &Ops) const { 981 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 982 983 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 984 if (HasMatching) 985 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 986 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 987 // Put the register class of the virtual registers in the flag word. That 988 // way, later passes can recompute register class constraints for inline 989 // assembly as well as normal instructions. 990 // Don't do this for tied operands that can use the regclass information 991 // from the def. 992 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 993 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 994 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 995 } 996 997 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 998 Ops.push_back(Res); 999 1000 if (Code == InlineAsm::Kind_Clobber) { 1001 // Clobbers should always have a 1:1 mapping with registers, and may 1002 // reference registers that have illegal (e.g. vector) types. Hence, we 1003 // shouldn't try to apply any sort of splitting logic to them. 1004 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 1005 "No 1:1 mapping from clobbers to regs?"); 1006 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 1007 (void)SP; 1008 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 1009 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 1010 assert( 1011 (Regs[I] != SP || 1012 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 1013 "If we clobbered the stack pointer, MFI should know about it."); 1014 } 1015 return; 1016 } 1017 1018 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 1019 MVT RegisterVT = RegVTs[Value]; 1020 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value], 1021 RegisterVT); 1022 for (unsigned i = 0; i != NumRegs; ++i) { 1023 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 1024 unsigned TheReg = Regs[Reg++]; 1025 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 1026 } 1027 } 1028 } 1029 1030 SmallVector<std::pair<unsigned, TypeSize>, 4> 1031 RegsForValue::getRegsAndSizes() const { 1032 SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec; 1033 unsigned I = 0; 1034 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1035 unsigned RegCount = std::get<0>(CountAndVT); 1036 MVT RegisterVT = std::get<1>(CountAndVT); 1037 TypeSize RegisterSize = RegisterVT.getSizeInBits(); 1038 for (unsigned E = I + RegCount; I != E; ++I) 1039 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1040 } 1041 return OutVec; 1042 } 1043 1044 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1045 AssumptionCache *ac, 1046 const TargetLibraryInfo *li) { 1047 AA = aa; 1048 AC = ac; 1049 GFI = gfi; 1050 LibInfo = li; 1051 Context = DAG.getContext(); 1052 LPadToCallSiteMap.clear(); 1053 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1054 } 1055 1056 void SelectionDAGBuilder::clear() { 1057 NodeMap.clear(); 1058 UnusedArgNodeMap.clear(); 1059 PendingLoads.clear(); 1060 PendingExports.clear(); 1061 PendingConstrainedFP.clear(); 1062 PendingConstrainedFPStrict.clear(); 1063 CurInst = nullptr; 1064 HasTailCall = false; 1065 SDNodeOrder = LowestSDNodeOrder; 1066 StatepointLowering.clear(); 1067 } 1068 1069 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1070 DanglingDebugInfoMap.clear(); 1071 } 1072 1073 // Update DAG root to include dependencies on Pending chains. 1074 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1075 SDValue Root = DAG.getRoot(); 1076 1077 if (Pending.empty()) 1078 return Root; 1079 1080 // Add current root to PendingChains, unless we already indirectly 1081 // depend on it. 1082 if (Root.getOpcode() != ISD::EntryToken) { 1083 unsigned i = 0, e = Pending.size(); 1084 for (; i != e; ++i) { 1085 assert(Pending[i].getNode()->getNumOperands() > 1); 1086 if (Pending[i].getNode()->getOperand(0) == Root) 1087 break; // Don't add the root if we already indirectly depend on it. 1088 } 1089 1090 if (i == e) 1091 Pending.push_back(Root); 1092 } 1093 1094 if (Pending.size() == 1) 1095 Root = Pending[0]; 1096 else 1097 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1098 1099 DAG.setRoot(Root); 1100 Pending.clear(); 1101 return Root; 1102 } 1103 1104 SDValue SelectionDAGBuilder::getMemoryRoot() { 1105 return updateRoot(PendingLoads); 1106 } 1107 1108 SDValue SelectionDAGBuilder::getRoot() { 1109 // Chain up all pending constrained intrinsics together with all 1110 // pending loads, by simply appending them to PendingLoads and 1111 // then calling getMemoryRoot(). 1112 PendingLoads.reserve(PendingLoads.size() + 1113 PendingConstrainedFP.size() + 1114 PendingConstrainedFPStrict.size()); 1115 PendingLoads.append(PendingConstrainedFP.begin(), 1116 PendingConstrainedFP.end()); 1117 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1118 PendingConstrainedFPStrict.end()); 1119 PendingConstrainedFP.clear(); 1120 PendingConstrainedFPStrict.clear(); 1121 return getMemoryRoot(); 1122 } 1123 1124 SDValue SelectionDAGBuilder::getControlRoot() { 1125 // We need to emit pending fpexcept.strict constrained intrinsics, 1126 // so append them to the PendingExports list. 1127 PendingExports.append(PendingConstrainedFPStrict.begin(), 1128 PendingConstrainedFPStrict.end()); 1129 PendingConstrainedFPStrict.clear(); 1130 return updateRoot(PendingExports); 1131 } 1132 1133 void SelectionDAGBuilder::visit(const Instruction &I) { 1134 // Set up outgoing PHI node register values before emitting the terminator. 1135 if (I.isTerminator()) { 1136 HandlePHINodesInSuccessorBlocks(I.getParent()); 1137 } 1138 1139 // Add SDDbgValue nodes for any var locs here. Do so before updating 1140 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1141 if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) { 1142 // Add SDDbgValue nodes for any var locs here. Do so before updating 1143 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1144 for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I); 1145 It != End; ++It) { 1146 auto *Var = FnVarLocs->getDILocalVariable(It->VariableID); 1147 dropDanglingDebugInfo(Var, It->Expr); 1148 if (!handleDebugValue(It->V, Var, It->Expr, It->DL, SDNodeOrder, 1149 /*IsVariadic=*/false)) 1150 addDanglingDebugInfo(It, SDNodeOrder); 1151 } 1152 } 1153 1154 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1155 if (!isa<DbgInfoIntrinsic>(I)) 1156 ++SDNodeOrder; 1157 1158 CurInst = &I; 1159 1160 // Set inserted listener only if required. 1161 bool NodeInserted = false; 1162 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener; 1163 MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections); 1164 if (PCSectionsMD) { 1165 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>( 1166 DAG, [&](SDNode *) { NodeInserted = true; }); 1167 } 1168 1169 visit(I.getOpcode(), I); 1170 1171 if (!I.isTerminator() && !HasTailCall && 1172 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1173 CopyToExportRegsIfNeeded(&I); 1174 1175 // Handle metadata. 1176 if (PCSectionsMD) { 1177 auto It = NodeMap.find(&I); 1178 if (It != NodeMap.end()) { 1179 DAG.addPCSections(It->second.getNode(), PCSectionsMD); 1180 } else if (NodeInserted) { 1181 // This should not happen; if it does, don't let it go unnoticed so we can 1182 // fix it. Relevant visit*() function is probably missing a setValue(). 1183 errs() << "warning: loosing !pcsections metadata [" 1184 << I.getModule()->getName() << "]\n"; 1185 LLVM_DEBUG(I.dump()); 1186 assert(false); 1187 } 1188 } 1189 1190 CurInst = nullptr; 1191 } 1192 1193 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1194 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1195 } 1196 1197 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1198 // Note: this doesn't use InstVisitor, because it has to work with 1199 // ConstantExpr's in addition to instructions. 1200 switch (Opcode) { 1201 default: llvm_unreachable("Unknown instruction type encountered!"); 1202 // Build the switch statement using the Instruction.def file. 1203 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1204 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1205 #include "llvm/IR/Instruction.def" 1206 } 1207 } 1208 1209 void SelectionDAGBuilder::addDanglingDebugInfo(const VarLocInfo *VarLoc, 1210 unsigned Order) { 1211 DanglingDebugInfoMap[VarLoc->V].emplace_back(VarLoc, Order); 1212 } 1213 1214 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI, 1215 unsigned Order) { 1216 // We treat variadic dbg_values differently at this stage. 1217 if (DI->hasArgList()) { 1218 // For variadic dbg_values we will now insert an undef. 1219 // FIXME: We can potentially recover these! 1220 SmallVector<SDDbgOperand, 2> Locs; 1221 for (const Value *V : DI->getValues()) { 1222 auto Undef = UndefValue::get(V->getType()); 1223 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1224 } 1225 SDDbgValue *SDV = DAG.getDbgValueList( 1226 DI->getVariable(), DI->getExpression(), Locs, {}, 1227 /*IsIndirect=*/false, DI->getDebugLoc(), Order, /*IsVariadic=*/true); 1228 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1229 } else { 1230 // TODO: Dangling debug info will eventually either be resolved or produce 1231 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1232 // between the original dbg.value location and its resolved DBG_VALUE, 1233 // which we should ideally fill with an extra Undef DBG_VALUE. 1234 assert(DI->getNumVariableLocationOps() == 1 && 1235 "DbgValueInst without an ArgList should have a single location " 1236 "operand."); 1237 DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, Order); 1238 } 1239 } 1240 1241 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1242 const DIExpression *Expr) { 1243 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1244 DIVariable *DanglingVariable = DDI.getVariable(DAG.getFunctionVarLocs()); 1245 DIExpression *DanglingExpr = DDI.getExpression(); 1246 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1247 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << printDDI(DDI) 1248 << "\n"); 1249 return true; 1250 } 1251 return false; 1252 }; 1253 1254 for (auto &DDIMI : DanglingDebugInfoMap) { 1255 DanglingDebugInfoVector &DDIV = DDIMI.second; 1256 1257 // If debug info is to be dropped, run it through final checks to see 1258 // whether it can be salvaged. 1259 for (auto &DDI : DDIV) 1260 if (isMatchingDbgValue(DDI)) 1261 salvageUnresolvedDbgValue(DDI); 1262 1263 erase_if(DDIV, isMatchingDbgValue); 1264 } 1265 } 1266 1267 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1268 // generate the debug data structures now that we've seen its definition. 1269 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1270 SDValue Val) { 1271 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1272 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1273 return; 1274 1275 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1276 for (auto &DDI : DDIV) { 1277 DebugLoc DL = DDI.getDebugLoc(); 1278 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1279 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1280 DILocalVariable *Variable = DDI.getVariable(DAG.getFunctionVarLocs()); 1281 DIExpression *Expr = DDI.getExpression(); 1282 assert(Variable->isValidLocationForIntrinsic(DL) && 1283 "Expected inlined-at fields to agree"); 1284 SDDbgValue *SDV; 1285 if (Val.getNode()) { 1286 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1287 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1288 // we couldn't resolve it directly when examining the DbgValue intrinsic 1289 // in the first place we should not be more successful here). Unless we 1290 // have some test case that prove this to be correct we should avoid 1291 // calling EmitFuncArgumentDbgValue here. 1292 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL, 1293 FuncArgumentDbgValueKind::Value, Val)) { 1294 LLVM_DEBUG(dbgs() << "Resolve dangling debug info for " << printDDI(DDI) 1295 << "\n"); 1296 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1297 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1298 // inserted after the definition of Val when emitting the instructions 1299 // after ISel. An alternative could be to teach 1300 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1301 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1302 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1303 << ValSDNodeOrder << "\n"); 1304 SDV = getDbgValue(Val, Variable, Expr, DL, 1305 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1306 DAG.AddDbgValue(SDV, false); 1307 } else 1308 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " 1309 << printDDI(DDI) << " in EmitFuncArgumentDbgValue\n"); 1310 } else { 1311 LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(DDI) << "\n"); 1312 auto Undef = UndefValue::get(V->getType()); 1313 auto SDV = 1314 DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder); 1315 DAG.AddDbgValue(SDV, false); 1316 } 1317 } 1318 DDIV.clear(); 1319 } 1320 1321 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1322 // TODO: For the variadic implementation, instead of only checking the fail 1323 // state of `handleDebugValue`, we need know specifically which values were 1324 // invalid, so that we attempt to salvage only those values when processing 1325 // a DIArgList. 1326 Value *V = DDI.getVariableLocationOp(0); 1327 Value *OrigV = V; 1328 DILocalVariable *Var = DDI.getVariable(DAG.getFunctionVarLocs()); 1329 DIExpression *Expr = DDI.getExpression(); 1330 DebugLoc DL = DDI.getDebugLoc(); 1331 unsigned SDOrder = DDI.getSDNodeOrder(); 1332 1333 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1334 // that DW_OP_stack_value is desired. 1335 bool StackValue = true; 1336 1337 // Can this Value can be encoded without any further work? 1338 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) 1339 return; 1340 1341 // Attempt to salvage back through as many instructions as possible. Bail if 1342 // a non-instruction is seen, such as a constant expression or global 1343 // variable. FIXME: Further work could recover those too. 1344 while (isa<Instruction>(V)) { 1345 Instruction &VAsInst = *cast<Instruction>(V); 1346 // Temporary "0", awaiting real implementation. 1347 SmallVector<uint64_t, 16> Ops; 1348 SmallVector<Value *, 4> AdditionalValues; 1349 V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops, 1350 AdditionalValues); 1351 // If we cannot salvage any further, and haven't yet found a suitable debug 1352 // expression, bail out. 1353 if (!V) 1354 break; 1355 1356 // TODO: If AdditionalValues isn't empty, then the salvage can only be 1357 // represented with a DBG_VALUE_LIST, so we give up. When we have support 1358 // here for variadic dbg_values, remove that condition. 1359 if (!AdditionalValues.empty()) 1360 break; 1361 1362 // New value and expr now represent this debuginfo. 1363 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue); 1364 1365 // Some kind of simplification occurred: check whether the operand of the 1366 // salvaged debug expression can be encoded in this DAG. 1367 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) { 1368 LLVM_DEBUG( 1369 dbgs() << "Salvaged debug location info for:\n " << *Var << "\n" 1370 << *OrigV << "\nBy stripping back to:\n " << *V << "\n"); 1371 return; 1372 } 1373 } 1374 1375 // This was the final opportunity to salvage this debug information, and it 1376 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1377 // any earlier variable location. 1378 assert(OrigV && "V shouldn't be null"); 1379 auto *Undef = UndefValue::get(OrigV->getType()); 1380 auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1381 DAG.AddDbgValue(SDV, false); 1382 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << printDDI(DDI) 1383 << "\n"); 1384 } 1385 1386 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1387 DILocalVariable *Var, 1388 DIExpression *Expr, DebugLoc DbgLoc, 1389 unsigned Order, bool IsVariadic) { 1390 if (Values.empty()) 1391 return true; 1392 SmallVector<SDDbgOperand> LocationOps; 1393 SmallVector<SDNode *> Dependencies; 1394 for (const Value *V : Values) { 1395 // Constant value. 1396 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1397 isa<ConstantPointerNull>(V)) { 1398 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1399 continue; 1400 } 1401 1402 // Look through IntToPtr constants. 1403 if (auto *CE = dyn_cast<ConstantExpr>(V)) 1404 if (CE->getOpcode() == Instruction::IntToPtr) { 1405 LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0))); 1406 continue; 1407 } 1408 1409 // If the Value is a frame index, we can create a FrameIndex debug value 1410 // without relying on the DAG at all. 1411 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1412 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1413 if (SI != FuncInfo.StaticAllocaMap.end()) { 1414 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1415 continue; 1416 } 1417 } 1418 1419 // Do not use getValue() in here; we don't want to generate code at 1420 // this point if it hasn't been done yet. 1421 SDValue N = NodeMap[V]; 1422 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1423 N = UnusedArgNodeMap[V]; 1424 if (N.getNode()) { 1425 // Only emit func arg dbg value for non-variadic dbg.values for now. 1426 if (!IsVariadic && 1427 EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc, 1428 FuncArgumentDbgValueKind::Value, N)) 1429 return true; 1430 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1431 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1432 // describe stack slot locations. 1433 // 1434 // Consider "int x = 0; int *px = &x;". There are two kinds of 1435 // interesting debug values here after optimization: 1436 // 1437 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1438 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1439 // 1440 // Both describe the direct values of their associated variables. 1441 Dependencies.push_back(N.getNode()); 1442 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1443 continue; 1444 } 1445 LocationOps.emplace_back( 1446 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1447 continue; 1448 } 1449 1450 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1451 // Special rules apply for the first dbg.values of parameter variables in a 1452 // function. Identify them by the fact they reference Argument Values, that 1453 // they're parameters, and they are parameters of the current function. We 1454 // need to let them dangle until they get an SDNode. 1455 bool IsParamOfFunc = 1456 isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt(); 1457 if (IsParamOfFunc) 1458 return false; 1459 1460 // The value is not used in this block yet (or it would have an SDNode). 1461 // We still want the value to appear for the user if possible -- if it has 1462 // an associated VReg, we can refer to that instead. 1463 auto VMI = FuncInfo.ValueMap.find(V); 1464 if (VMI != FuncInfo.ValueMap.end()) { 1465 unsigned Reg = VMI->second; 1466 // If this is a PHI node, it may be split up into several MI PHI nodes 1467 // (in FunctionLoweringInfo::set). 1468 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1469 V->getType(), std::nullopt); 1470 if (RFV.occupiesMultipleRegs()) { 1471 // FIXME: We could potentially support variadic dbg_values here. 1472 if (IsVariadic) 1473 return false; 1474 unsigned Offset = 0; 1475 unsigned BitsToDescribe = 0; 1476 if (auto VarSize = Var->getSizeInBits()) 1477 BitsToDescribe = *VarSize; 1478 if (auto Fragment = Expr->getFragmentInfo()) 1479 BitsToDescribe = Fragment->SizeInBits; 1480 for (const auto &RegAndSize : RFV.getRegsAndSizes()) { 1481 // Bail out if all bits are described already. 1482 if (Offset >= BitsToDescribe) 1483 break; 1484 // TODO: handle scalable vectors. 1485 unsigned RegisterSize = RegAndSize.second; 1486 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1487 ? BitsToDescribe - Offset 1488 : RegisterSize; 1489 auto FragmentExpr = DIExpression::createFragmentExpression( 1490 Expr, Offset, FragmentSize); 1491 if (!FragmentExpr) 1492 continue; 1493 SDDbgValue *SDV = DAG.getVRegDbgValue( 1494 Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, SDNodeOrder); 1495 DAG.AddDbgValue(SDV, false); 1496 Offset += RegisterSize; 1497 } 1498 return true; 1499 } 1500 // We can use simple vreg locations for variadic dbg_values as well. 1501 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1502 continue; 1503 } 1504 // We failed to create a SDDbgOperand for V. 1505 return false; 1506 } 1507 1508 // We have created a SDDbgOperand for each Value in Values. 1509 // Should use Order instead of SDNodeOrder? 1510 assert(!LocationOps.empty()); 1511 SDDbgValue *SDV = DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1512 /*IsIndirect=*/false, DbgLoc, 1513 SDNodeOrder, IsVariadic); 1514 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1515 return true; 1516 } 1517 1518 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1519 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1520 for (auto &Pair : DanglingDebugInfoMap) 1521 for (auto &DDI : Pair.second) 1522 salvageUnresolvedDbgValue(DDI); 1523 clearDanglingDebugInfo(); 1524 } 1525 1526 /// getCopyFromRegs - If there was virtual register allocated for the value V 1527 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1528 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1529 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1530 SDValue Result; 1531 1532 if (It != FuncInfo.ValueMap.end()) { 1533 Register InReg = It->second; 1534 1535 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1536 DAG.getDataLayout(), InReg, Ty, 1537 std::nullopt); // This is not an ABI copy. 1538 SDValue Chain = DAG.getEntryNode(); 1539 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1540 V); 1541 resolveDanglingDebugInfo(V, Result); 1542 } 1543 1544 return Result; 1545 } 1546 1547 /// getValue - Return an SDValue for the given Value. 1548 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1549 // If we already have an SDValue for this value, use it. It's important 1550 // to do this first, so that we don't create a CopyFromReg if we already 1551 // have a regular SDValue. 1552 SDValue &N = NodeMap[V]; 1553 if (N.getNode()) return N; 1554 1555 // If there's a virtual register allocated and initialized for this 1556 // value, use it. 1557 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1558 return copyFromReg; 1559 1560 // Otherwise create a new SDValue and remember it. 1561 SDValue Val = getValueImpl(V); 1562 NodeMap[V] = Val; 1563 resolveDanglingDebugInfo(V, Val); 1564 return Val; 1565 } 1566 1567 /// getNonRegisterValue - Return an SDValue for the given Value, but 1568 /// don't look in FuncInfo.ValueMap for a virtual register. 1569 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1570 // If we already have an SDValue for this value, use it. 1571 SDValue &N = NodeMap[V]; 1572 if (N.getNode()) { 1573 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1574 // Remove the debug location from the node as the node is about to be used 1575 // in a location which may differ from the original debug location. This 1576 // is relevant to Constant and ConstantFP nodes because they can appear 1577 // as constant expressions inside PHI nodes. 1578 N->setDebugLoc(DebugLoc()); 1579 } 1580 return N; 1581 } 1582 1583 // Otherwise create a new SDValue and remember it. 1584 SDValue Val = getValueImpl(V); 1585 NodeMap[V] = Val; 1586 resolveDanglingDebugInfo(V, Val); 1587 return Val; 1588 } 1589 1590 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1591 /// Create an SDValue for the given value. 1592 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1593 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1594 1595 if (const Constant *C = dyn_cast<Constant>(V)) { 1596 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1597 1598 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1599 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1600 1601 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1602 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1603 1604 if (isa<ConstantPointerNull>(C)) { 1605 unsigned AS = V->getType()->getPointerAddressSpace(); 1606 return DAG.getConstant(0, getCurSDLoc(), 1607 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1608 } 1609 1610 if (match(C, m_VScale(DAG.getDataLayout()))) 1611 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1612 1613 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1614 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1615 1616 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1617 return DAG.getUNDEF(VT); 1618 1619 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1620 visit(CE->getOpcode(), *CE); 1621 SDValue N1 = NodeMap[V]; 1622 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1623 return N1; 1624 } 1625 1626 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1627 SmallVector<SDValue, 4> Constants; 1628 for (const Use &U : C->operands()) { 1629 SDNode *Val = getValue(U).getNode(); 1630 // If the operand is an empty aggregate, there are no values. 1631 if (!Val) continue; 1632 // Add each leaf value from the operand to the Constants list 1633 // to form a flattened list of all the values. 1634 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1635 Constants.push_back(SDValue(Val, i)); 1636 } 1637 1638 return DAG.getMergeValues(Constants, getCurSDLoc()); 1639 } 1640 1641 if (const ConstantDataSequential *CDS = 1642 dyn_cast<ConstantDataSequential>(C)) { 1643 SmallVector<SDValue, 4> Ops; 1644 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1645 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1646 // Add each leaf value from the operand to the Constants list 1647 // to form a flattened list of all the values. 1648 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1649 Ops.push_back(SDValue(Val, i)); 1650 } 1651 1652 if (isa<ArrayType>(CDS->getType())) 1653 return DAG.getMergeValues(Ops, getCurSDLoc()); 1654 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1655 } 1656 1657 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1658 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1659 "Unknown struct or array constant!"); 1660 1661 SmallVector<EVT, 4> ValueVTs; 1662 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1663 unsigned NumElts = ValueVTs.size(); 1664 if (NumElts == 0) 1665 return SDValue(); // empty struct 1666 SmallVector<SDValue, 4> Constants(NumElts); 1667 for (unsigned i = 0; i != NumElts; ++i) { 1668 EVT EltVT = ValueVTs[i]; 1669 if (isa<UndefValue>(C)) 1670 Constants[i] = DAG.getUNDEF(EltVT); 1671 else if (EltVT.isFloatingPoint()) 1672 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1673 else 1674 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1675 } 1676 1677 return DAG.getMergeValues(Constants, getCurSDLoc()); 1678 } 1679 1680 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1681 return DAG.getBlockAddress(BA, VT); 1682 1683 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1684 return getValue(Equiv->getGlobalValue()); 1685 1686 if (const auto *NC = dyn_cast<NoCFIValue>(C)) 1687 return getValue(NC->getGlobalValue()); 1688 1689 VectorType *VecTy = cast<VectorType>(V->getType()); 1690 1691 // Now that we know the number and type of the elements, get that number of 1692 // elements into the Ops array based on what kind of constant it is. 1693 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1694 SmallVector<SDValue, 16> Ops; 1695 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1696 for (unsigned i = 0; i != NumElements; ++i) 1697 Ops.push_back(getValue(CV->getOperand(i))); 1698 1699 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1700 } 1701 1702 if (isa<ConstantAggregateZero>(C)) { 1703 EVT EltVT = 1704 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1705 1706 SDValue Op; 1707 if (EltVT.isFloatingPoint()) 1708 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1709 else 1710 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1711 1712 return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op); 1713 } 1714 1715 llvm_unreachable("Unknown vector constant"); 1716 } 1717 1718 // If this is a static alloca, generate it as the frameindex instead of 1719 // computation. 1720 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1721 DenseMap<const AllocaInst*, int>::iterator SI = 1722 FuncInfo.StaticAllocaMap.find(AI); 1723 if (SI != FuncInfo.StaticAllocaMap.end()) 1724 return DAG.getFrameIndex( 1725 SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType())); 1726 } 1727 1728 // If this is an instruction which fast-isel has deferred, select it now. 1729 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1730 Register InReg = FuncInfo.InitializeRegForValue(Inst); 1731 1732 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1733 Inst->getType(), std::nullopt); 1734 SDValue Chain = DAG.getEntryNode(); 1735 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1736 } 1737 1738 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) 1739 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1740 1741 if (const auto *BB = dyn_cast<BasicBlock>(V)) 1742 return DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 1743 1744 llvm_unreachable("Can't get register for value!"); 1745 } 1746 1747 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1748 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1749 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1750 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1751 bool IsSEH = isAsynchronousEHPersonality(Pers); 1752 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1753 if (!IsSEH) 1754 CatchPadMBB->setIsEHScopeEntry(); 1755 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1756 if (IsMSVCCXX || IsCoreCLR) 1757 CatchPadMBB->setIsEHFuncletEntry(); 1758 } 1759 1760 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1761 // Update machine-CFG edge. 1762 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1763 FuncInfo.MBB->addSuccessor(TargetMBB); 1764 TargetMBB->setIsEHCatchretTarget(true); 1765 DAG.getMachineFunction().setHasEHCatchret(true); 1766 1767 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1768 bool IsSEH = isAsynchronousEHPersonality(Pers); 1769 if (IsSEH) { 1770 // If this is not a fall-through branch or optimizations are switched off, 1771 // emit the branch. 1772 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1773 TM.getOptLevel() == CodeGenOpt::None) 1774 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1775 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1776 return; 1777 } 1778 1779 // Figure out the funclet membership for the catchret's successor. 1780 // This will be used by the FuncletLayout pass to determine how to order the 1781 // BB's. 1782 // A 'catchret' returns to the outer scope's color. 1783 Value *ParentPad = I.getCatchSwitchParentPad(); 1784 const BasicBlock *SuccessorColor; 1785 if (isa<ConstantTokenNone>(ParentPad)) 1786 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1787 else 1788 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1789 assert(SuccessorColor && "No parent funclet for catchret!"); 1790 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1791 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1792 1793 // Create the terminator node. 1794 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1795 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1796 DAG.getBasicBlock(SuccessorColorMBB)); 1797 DAG.setRoot(Ret); 1798 } 1799 1800 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1801 // Don't emit any special code for the cleanuppad instruction. It just marks 1802 // the start of an EH scope/funclet. 1803 FuncInfo.MBB->setIsEHScopeEntry(); 1804 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1805 if (Pers != EHPersonality::Wasm_CXX) { 1806 FuncInfo.MBB->setIsEHFuncletEntry(); 1807 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1808 } 1809 } 1810 1811 // In wasm EH, even though a catchpad may not catch an exception if a tag does 1812 // not match, it is OK to add only the first unwind destination catchpad to the 1813 // successors, because there will be at least one invoke instruction within the 1814 // catch scope that points to the next unwind destination, if one exists, so 1815 // CFGSort cannot mess up with BB sorting order. 1816 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 1817 // call within them, and catchpads only consisting of 'catch (...)' have a 1818 // '__cxa_end_catch' call within them, both of which generate invokes in case 1819 // the next unwind destination exists, i.e., the next unwind destination is not 1820 // the caller.) 1821 // 1822 // Having at most one EH pad successor is also simpler and helps later 1823 // transformations. 1824 // 1825 // For example, 1826 // current: 1827 // invoke void @foo to ... unwind label %catch.dispatch 1828 // catch.dispatch: 1829 // %0 = catchswitch within ... [label %catch.start] unwind label %next 1830 // catch.start: 1831 // ... 1832 // ... in this BB or some other child BB dominated by this BB there will be an 1833 // invoke that points to 'next' BB as an unwind destination 1834 // 1835 // next: ; We don't need to add this to 'current' BB's successor 1836 // ... 1837 static void findWasmUnwindDestinations( 1838 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1839 BranchProbability Prob, 1840 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1841 &UnwindDests) { 1842 while (EHPadBB) { 1843 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1844 if (isa<CleanupPadInst>(Pad)) { 1845 // Stop on cleanup pads. 1846 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1847 UnwindDests.back().first->setIsEHScopeEntry(); 1848 break; 1849 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1850 // Add the catchpad handlers to the possible destinations. We don't 1851 // continue to the unwind destination of the catchswitch for wasm. 1852 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1853 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1854 UnwindDests.back().first->setIsEHScopeEntry(); 1855 } 1856 break; 1857 } else { 1858 continue; 1859 } 1860 } 1861 } 1862 1863 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1864 /// many places it could ultimately go. In the IR, we have a single unwind 1865 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1866 /// This function skips over imaginary basic blocks that hold catchswitch 1867 /// instructions, and finds all the "real" machine 1868 /// basic block destinations. As those destinations may not be successors of 1869 /// EHPadBB, here we also calculate the edge probability to those destinations. 1870 /// The passed-in Prob is the edge probability to EHPadBB. 1871 static void findUnwindDestinations( 1872 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1873 BranchProbability Prob, 1874 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1875 &UnwindDests) { 1876 EHPersonality Personality = 1877 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1878 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1879 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1880 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1881 bool IsSEH = isAsynchronousEHPersonality(Personality); 1882 1883 if (IsWasmCXX) { 1884 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1885 assert(UnwindDests.size() <= 1 && 1886 "There should be at most one unwind destination for wasm"); 1887 return; 1888 } 1889 1890 while (EHPadBB) { 1891 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1892 BasicBlock *NewEHPadBB = nullptr; 1893 if (isa<LandingPadInst>(Pad)) { 1894 // Stop on landingpads. They are not funclets. 1895 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1896 break; 1897 } else if (isa<CleanupPadInst>(Pad)) { 1898 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1899 // personalities. 1900 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1901 UnwindDests.back().first->setIsEHScopeEntry(); 1902 UnwindDests.back().first->setIsEHFuncletEntry(); 1903 break; 1904 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1905 // Add the catchpad handlers to the possible destinations. 1906 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1907 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1908 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1909 if (IsMSVCCXX || IsCoreCLR) 1910 UnwindDests.back().first->setIsEHFuncletEntry(); 1911 if (!IsSEH) 1912 UnwindDests.back().first->setIsEHScopeEntry(); 1913 } 1914 NewEHPadBB = CatchSwitch->getUnwindDest(); 1915 } else { 1916 continue; 1917 } 1918 1919 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1920 if (BPI && NewEHPadBB) 1921 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1922 EHPadBB = NewEHPadBB; 1923 } 1924 } 1925 1926 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1927 // Update successor info. 1928 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1929 auto UnwindDest = I.getUnwindDest(); 1930 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1931 BranchProbability UnwindDestProb = 1932 (BPI && UnwindDest) 1933 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1934 : BranchProbability::getZero(); 1935 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1936 for (auto &UnwindDest : UnwindDests) { 1937 UnwindDest.first->setIsEHPad(); 1938 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1939 } 1940 FuncInfo.MBB->normalizeSuccProbs(); 1941 1942 // Create the terminator node. 1943 SDValue Ret = 1944 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1945 DAG.setRoot(Ret); 1946 } 1947 1948 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1949 report_fatal_error("visitCatchSwitch not yet implemented!"); 1950 } 1951 1952 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1953 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1954 auto &DL = DAG.getDataLayout(); 1955 SDValue Chain = getControlRoot(); 1956 SmallVector<ISD::OutputArg, 8> Outs; 1957 SmallVector<SDValue, 8> OutVals; 1958 1959 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1960 // lower 1961 // 1962 // %val = call <ty> @llvm.experimental.deoptimize() 1963 // ret <ty> %val 1964 // 1965 // differently. 1966 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1967 LowerDeoptimizingReturn(); 1968 return; 1969 } 1970 1971 if (!FuncInfo.CanLowerReturn) { 1972 unsigned DemoteReg = FuncInfo.DemoteRegister; 1973 const Function *F = I.getParent()->getParent(); 1974 1975 // Emit a store of the return value through the virtual register. 1976 // Leave Outs empty so that LowerReturn won't try to load return 1977 // registers the usual way. 1978 SmallVector<EVT, 1> PtrValueVTs; 1979 ComputeValueVTs(TLI, DL, 1980 F->getReturnType()->getPointerTo( 1981 DAG.getDataLayout().getAllocaAddrSpace()), 1982 PtrValueVTs); 1983 1984 SDValue RetPtr = 1985 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]); 1986 SDValue RetOp = getValue(I.getOperand(0)); 1987 1988 SmallVector<EVT, 4> ValueVTs, MemVTs; 1989 SmallVector<uint64_t, 4> Offsets; 1990 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1991 &Offsets); 1992 unsigned NumValues = ValueVTs.size(); 1993 1994 SmallVector<SDValue, 4> Chains(NumValues); 1995 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 1996 for (unsigned i = 0; i != NumValues; ++i) { 1997 // An aggregate return value cannot wrap around the address space, so 1998 // offsets to its parts don't wrap either. 1999 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 2000 TypeSize::Fixed(Offsets[i])); 2001 2002 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 2003 if (MemVTs[i] != ValueVTs[i]) 2004 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 2005 Chains[i] = DAG.getStore( 2006 Chain, getCurSDLoc(), Val, 2007 // FIXME: better loc info would be nice. 2008 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 2009 commonAlignment(BaseAlign, Offsets[i])); 2010 } 2011 2012 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 2013 MVT::Other, Chains); 2014 } else if (I.getNumOperands() != 0) { 2015 SmallVector<EVT, 4> ValueVTs; 2016 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 2017 unsigned NumValues = ValueVTs.size(); 2018 if (NumValues) { 2019 SDValue RetOp = getValue(I.getOperand(0)); 2020 2021 const Function *F = I.getParent()->getParent(); 2022 2023 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 2024 I.getOperand(0)->getType(), F->getCallingConv(), 2025 /*IsVarArg*/ false, DL); 2026 2027 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 2028 if (F->getAttributes().hasRetAttr(Attribute::SExt)) 2029 ExtendKind = ISD::SIGN_EXTEND; 2030 else if (F->getAttributes().hasRetAttr(Attribute::ZExt)) 2031 ExtendKind = ISD::ZERO_EXTEND; 2032 2033 LLVMContext &Context = F->getContext(); 2034 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg); 2035 2036 for (unsigned j = 0; j != NumValues; ++j) { 2037 EVT VT = ValueVTs[j]; 2038 2039 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 2040 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 2041 2042 CallingConv::ID CC = F->getCallingConv(); 2043 2044 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 2045 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 2046 SmallVector<SDValue, 4> Parts(NumParts); 2047 getCopyToParts(DAG, getCurSDLoc(), 2048 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 2049 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 2050 2051 // 'inreg' on function refers to return value 2052 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2053 if (RetInReg) 2054 Flags.setInReg(); 2055 2056 if (I.getOperand(0)->getType()->isPointerTy()) { 2057 Flags.setPointer(); 2058 Flags.setPointerAddrSpace( 2059 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 2060 } 2061 2062 if (NeedsRegBlock) { 2063 Flags.setInConsecutiveRegs(); 2064 if (j == NumValues - 1) 2065 Flags.setInConsecutiveRegsLast(); 2066 } 2067 2068 // Propagate extension type if any 2069 if (ExtendKind == ISD::SIGN_EXTEND) 2070 Flags.setSExt(); 2071 else if (ExtendKind == ISD::ZERO_EXTEND) 2072 Flags.setZExt(); 2073 2074 for (unsigned i = 0; i < NumParts; ++i) { 2075 Outs.push_back(ISD::OutputArg(Flags, 2076 Parts[i].getValueType().getSimpleVT(), 2077 VT, /*isfixed=*/true, 0, 0)); 2078 OutVals.push_back(Parts[i]); 2079 } 2080 } 2081 } 2082 } 2083 2084 // Push in swifterror virtual register as the last element of Outs. This makes 2085 // sure swifterror virtual register will be returned in the swifterror 2086 // physical register. 2087 const Function *F = I.getParent()->getParent(); 2088 if (TLI.supportSwiftError() && 2089 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2090 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2091 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2092 Flags.setSwiftError(); 2093 Outs.push_back(ISD::OutputArg( 2094 Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)), 2095 /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0)); 2096 // Create SDNode for the swifterror virtual register. 2097 OutVals.push_back( 2098 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2099 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2100 EVT(TLI.getPointerTy(DL)))); 2101 } 2102 2103 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2104 CallingConv::ID CallConv = 2105 DAG.getMachineFunction().getFunction().getCallingConv(); 2106 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2107 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2108 2109 // Verify that the target's LowerReturn behaved as expected. 2110 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2111 "LowerReturn didn't return a valid chain!"); 2112 2113 // Update the DAG with the new chain value resulting from return lowering. 2114 DAG.setRoot(Chain); 2115 } 2116 2117 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2118 /// created for it, emit nodes to copy the value into the virtual 2119 /// registers. 2120 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2121 // Skip empty types 2122 if (V->getType()->isEmptyTy()) 2123 return; 2124 2125 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2126 if (VMI != FuncInfo.ValueMap.end()) { 2127 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 2128 CopyValueToVirtualRegister(V, VMI->second); 2129 } 2130 } 2131 2132 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2133 /// the current basic block, add it to ValueMap now so that we'll get a 2134 /// CopyTo/FromReg. 2135 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2136 // No need to export constants. 2137 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2138 2139 // Already exported? 2140 if (FuncInfo.isExportedInst(V)) return; 2141 2142 Register Reg = FuncInfo.InitializeRegForValue(V); 2143 CopyValueToVirtualRegister(V, Reg); 2144 } 2145 2146 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2147 const BasicBlock *FromBB) { 2148 // The operands of the setcc have to be in this block. We don't know 2149 // how to export them from some other block. 2150 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2151 // Can export from current BB. 2152 if (VI->getParent() == FromBB) 2153 return true; 2154 2155 // Is already exported, noop. 2156 return FuncInfo.isExportedInst(V); 2157 } 2158 2159 // If this is an argument, we can export it if the BB is the entry block or 2160 // if it is already exported. 2161 if (isa<Argument>(V)) { 2162 if (FromBB->isEntryBlock()) 2163 return true; 2164 2165 // Otherwise, can only export this if it is already exported. 2166 return FuncInfo.isExportedInst(V); 2167 } 2168 2169 // Otherwise, constants can always be exported. 2170 return true; 2171 } 2172 2173 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2174 BranchProbability 2175 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2176 const MachineBasicBlock *Dst) const { 2177 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2178 const BasicBlock *SrcBB = Src->getBasicBlock(); 2179 const BasicBlock *DstBB = Dst->getBasicBlock(); 2180 if (!BPI) { 2181 // If BPI is not available, set the default probability as 1 / N, where N is 2182 // the number of successors. 2183 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2184 return BranchProbability(1, SuccSize); 2185 } 2186 return BPI->getEdgeProbability(SrcBB, DstBB); 2187 } 2188 2189 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2190 MachineBasicBlock *Dst, 2191 BranchProbability Prob) { 2192 if (!FuncInfo.BPI) 2193 Src->addSuccessorWithoutProb(Dst); 2194 else { 2195 if (Prob.isUnknown()) 2196 Prob = getEdgeProbability(Src, Dst); 2197 Src->addSuccessor(Dst, Prob); 2198 } 2199 } 2200 2201 static bool InBlock(const Value *V, const BasicBlock *BB) { 2202 if (const Instruction *I = dyn_cast<Instruction>(V)) 2203 return I->getParent() == BB; 2204 return true; 2205 } 2206 2207 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2208 /// This function emits a branch and is used at the leaves of an OR or an 2209 /// AND operator tree. 2210 void 2211 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2212 MachineBasicBlock *TBB, 2213 MachineBasicBlock *FBB, 2214 MachineBasicBlock *CurBB, 2215 MachineBasicBlock *SwitchBB, 2216 BranchProbability TProb, 2217 BranchProbability FProb, 2218 bool InvertCond) { 2219 const BasicBlock *BB = CurBB->getBasicBlock(); 2220 2221 // If the leaf of the tree is a comparison, merge the condition into 2222 // the caseblock. 2223 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2224 // The operands of the cmp have to be in this block. We don't know 2225 // how to export them from some other block. If this is the first block 2226 // of the sequence, no exporting is needed. 2227 if (CurBB == SwitchBB || 2228 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2229 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2230 ISD::CondCode Condition; 2231 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2232 ICmpInst::Predicate Pred = 2233 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2234 Condition = getICmpCondCode(Pred); 2235 } else { 2236 const FCmpInst *FC = cast<FCmpInst>(Cond); 2237 FCmpInst::Predicate Pred = 2238 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2239 Condition = getFCmpCondCode(Pred); 2240 if (TM.Options.NoNaNsFPMath) 2241 Condition = getFCmpCodeWithoutNaN(Condition); 2242 } 2243 2244 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2245 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2246 SL->SwitchCases.push_back(CB); 2247 return; 2248 } 2249 } 2250 2251 // Create a CaseBlock record representing this branch. 2252 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2253 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2254 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2255 SL->SwitchCases.push_back(CB); 2256 } 2257 2258 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2259 MachineBasicBlock *TBB, 2260 MachineBasicBlock *FBB, 2261 MachineBasicBlock *CurBB, 2262 MachineBasicBlock *SwitchBB, 2263 Instruction::BinaryOps Opc, 2264 BranchProbability TProb, 2265 BranchProbability FProb, 2266 bool InvertCond) { 2267 // Skip over not part of the tree and remember to invert op and operands at 2268 // next level. 2269 Value *NotCond; 2270 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2271 InBlock(NotCond, CurBB->getBasicBlock())) { 2272 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2273 !InvertCond); 2274 return; 2275 } 2276 2277 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2278 const Value *BOpOp0, *BOpOp1; 2279 // Compute the effective opcode for Cond, taking into account whether it needs 2280 // to be inverted, e.g. 2281 // and (not (or A, B)), C 2282 // gets lowered as 2283 // and (and (not A, not B), C) 2284 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2285 if (BOp) { 2286 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2287 ? Instruction::And 2288 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2289 ? Instruction::Or 2290 : (Instruction::BinaryOps)0); 2291 if (InvertCond) { 2292 if (BOpc == Instruction::And) 2293 BOpc = Instruction::Or; 2294 else if (BOpc == Instruction::Or) 2295 BOpc = Instruction::And; 2296 } 2297 } 2298 2299 // If this node is not part of the or/and tree, emit it as a branch. 2300 // Note that all nodes in the tree should have same opcode. 2301 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2302 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2303 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2304 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2305 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2306 TProb, FProb, InvertCond); 2307 return; 2308 } 2309 2310 // Create TmpBB after CurBB. 2311 MachineFunction::iterator BBI(CurBB); 2312 MachineFunction &MF = DAG.getMachineFunction(); 2313 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2314 CurBB->getParent()->insert(++BBI, TmpBB); 2315 2316 if (Opc == Instruction::Or) { 2317 // Codegen X | Y as: 2318 // BB1: 2319 // jmp_if_X TBB 2320 // jmp TmpBB 2321 // TmpBB: 2322 // jmp_if_Y TBB 2323 // jmp FBB 2324 // 2325 2326 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2327 // The requirement is that 2328 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2329 // = TrueProb for original BB. 2330 // Assuming the original probabilities are A and B, one choice is to set 2331 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2332 // A/(1+B) and 2B/(1+B). This choice assumes that 2333 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2334 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2335 // TmpBB, but the math is more complicated. 2336 2337 auto NewTrueProb = TProb / 2; 2338 auto NewFalseProb = TProb / 2 + FProb; 2339 // Emit the LHS condition. 2340 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2341 NewFalseProb, InvertCond); 2342 2343 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2344 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2345 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2346 // Emit the RHS condition into TmpBB. 2347 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2348 Probs[1], InvertCond); 2349 } else { 2350 assert(Opc == Instruction::And && "Unknown merge op!"); 2351 // Codegen X & Y as: 2352 // BB1: 2353 // jmp_if_X TmpBB 2354 // jmp FBB 2355 // TmpBB: 2356 // jmp_if_Y TBB 2357 // jmp FBB 2358 // 2359 // This requires creation of TmpBB after CurBB. 2360 2361 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2362 // The requirement is that 2363 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2364 // = FalseProb for original BB. 2365 // Assuming the original probabilities are A and B, one choice is to set 2366 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2367 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2368 // TrueProb for BB1 * FalseProb for TmpBB. 2369 2370 auto NewTrueProb = TProb + FProb / 2; 2371 auto NewFalseProb = FProb / 2; 2372 // Emit the LHS condition. 2373 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2374 NewFalseProb, InvertCond); 2375 2376 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2377 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2378 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2379 // Emit the RHS condition into TmpBB. 2380 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2381 Probs[1], InvertCond); 2382 } 2383 } 2384 2385 /// If the set of cases should be emitted as a series of branches, return true. 2386 /// If we should emit this as a bunch of and/or'd together conditions, return 2387 /// false. 2388 bool 2389 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2390 if (Cases.size() != 2) return true; 2391 2392 // If this is two comparisons of the same values or'd or and'd together, they 2393 // will get folded into a single comparison, so don't emit two blocks. 2394 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2395 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2396 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2397 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2398 return false; 2399 } 2400 2401 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2402 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2403 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2404 Cases[0].CC == Cases[1].CC && 2405 isa<Constant>(Cases[0].CmpRHS) && 2406 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2407 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2408 return false; 2409 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2410 return false; 2411 } 2412 2413 return true; 2414 } 2415 2416 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2417 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2418 2419 // Update machine-CFG edges. 2420 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2421 2422 if (I.isUnconditional()) { 2423 // Update machine-CFG edges. 2424 BrMBB->addSuccessor(Succ0MBB); 2425 2426 // If this is not a fall-through branch or optimizations are switched off, 2427 // emit the branch. 2428 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2429 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2430 MVT::Other, getControlRoot(), 2431 DAG.getBasicBlock(Succ0MBB))); 2432 2433 return; 2434 } 2435 2436 // If this condition is one of the special cases we handle, do special stuff 2437 // now. 2438 const Value *CondVal = I.getCondition(); 2439 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2440 2441 // If this is a series of conditions that are or'd or and'd together, emit 2442 // this as a sequence of branches instead of setcc's with and/or operations. 2443 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2444 // unpredictable branches, and vector extracts because those jumps are likely 2445 // expensive for any target), this should improve performance. 2446 // For example, instead of something like: 2447 // cmp A, B 2448 // C = seteq 2449 // cmp D, E 2450 // F = setle 2451 // or C, F 2452 // jnz foo 2453 // Emit: 2454 // cmp A, B 2455 // je foo 2456 // cmp D, E 2457 // jle foo 2458 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2459 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2460 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2461 Value *Vec; 2462 const Value *BOp0, *BOp1; 2463 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2464 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2465 Opcode = Instruction::And; 2466 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2467 Opcode = Instruction::Or; 2468 2469 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2470 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2471 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2472 getEdgeProbability(BrMBB, Succ0MBB), 2473 getEdgeProbability(BrMBB, Succ1MBB), 2474 /*InvertCond=*/false); 2475 // If the compares in later blocks need to use values not currently 2476 // exported from this block, export them now. This block should always 2477 // be the first entry. 2478 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2479 2480 // Allow some cases to be rejected. 2481 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2482 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2483 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2484 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2485 } 2486 2487 // Emit the branch for this block. 2488 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2489 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2490 return; 2491 } 2492 2493 // Okay, we decided not to do this, remove any inserted MBB's and clear 2494 // SwitchCases. 2495 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2496 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2497 2498 SL->SwitchCases.clear(); 2499 } 2500 } 2501 2502 // Create a CaseBlock record representing this branch. 2503 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2504 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2505 2506 // Use visitSwitchCase to actually insert the fast branch sequence for this 2507 // cond branch. 2508 visitSwitchCase(CB, BrMBB); 2509 } 2510 2511 /// visitSwitchCase - Emits the necessary code to represent a single node in 2512 /// the binary search tree resulting from lowering a switch instruction. 2513 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2514 MachineBasicBlock *SwitchBB) { 2515 SDValue Cond; 2516 SDValue CondLHS = getValue(CB.CmpLHS); 2517 SDLoc dl = CB.DL; 2518 2519 if (CB.CC == ISD::SETTRUE) { 2520 // Branch or fall through to TrueBB. 2521 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2522 SwitchBB->normalizeSuccProbs(); 2523 if (CB.TrueBB != NextBlock(SwitchBB)) { 2524 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2525 DAG.getBasicBlock(CB.TrueBB))); 2526 } 2527 return; 2528 } 2529 2530 auto &TLI = DAG.getTargetLoweringInfo(); 2531 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2532 2533 // Build the setcc now. 2534 if (!CB.CmpMHS) { 2535 // Fold "(X == true)" to X and "(X == false)" to !X to 2536 // handle common cases produced by branch lowering. 2537 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2538 CB.CC == ISD::SETEQ) 2539 Cond = CondLHS; 2540 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2541 CB.CC == ISD::SETEQ) { 2542 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2543 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2544 } else { 2545 SDValue CondRHS = getValue(CB.CmpRHS); 2546 2547 // If a pointer's DAG type is larger than its memory type then the DAG 2548 // values are zero-extended. This breaks signed comparisons so truncate 2549 // back to the underlying type before doing the compare. 2550 if (CondLHS.getValueType() != MemVT) { 2551 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2552 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2553 } 2554 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2555 } 2556 } else { 2557 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2558 2559 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2560 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2561 2562 SDValue CmpOp = getValue(CB.CmpMHS); 2563 EVT VT = CmpOp.getValueType(); 2564 2565 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2566 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2567 ISD::SETLE); 2568 } else { 2569 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2570 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2571 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2572 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2573 } 2574 } 2575 2576 // Update successor info 2577 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2578 // TrueBB and FalseBB are always different unless the incoming IR is 2579 // degenerate. This only happens when running llc on weird IR. 2580 if (CB.TrueBB != CB.FalseBB) 2581 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2582 SwitchBB->normalizeSuccProbs(); 2583 2584 // If the lhs block is the next block, invert the condition so that we can 2585 // fall through to the lhs instead of the rhs block. 2586 if (CB.TrueBB == NextBlock(SwitchBB)) { 2587 std::swap(CB.TrueBB, CB.FalseBB); 2588 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2589 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2590 } 2591 2592 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2593 MVT::Other, getControlRoot(), Cond, 2594 DAG.getBasicBlock(CB.TrueBB)); 2595 2596 setValue(CurInst, BrCond); 2597 2598 // Insert the false branch. Do this even if it's a fall through branch, 2599 // this makes it easier to do DAG optimizations which require inverting 2600 // the branch condition. 2601 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2602 DAG.getBasicBlock(CB.FalseBB)); 2603 2604 DAG.setRoot(BrCond); 2605 } 2606 2607 /// visitJumpTable - Emit JumpTable node in the current MBB 2608 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2609 // Emit the code for the jump table 2610 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2611 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2612 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2613 JT.Reg, PTy); 2614 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2615 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2616 MVT::Other, Index.getValue(1), 2617 Table, Index); 2618 DAG.setRoot(BrJumpTable); 2619 } 2620 2621 /// visitJumpTableHeader - This function emits necessary code to produce index 2622 /// in the JumpTable from switch case. 2623 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2624 JumpTableHeader &JTH, 2625 MachineBasicBlock *SwitchBB) { 2626 SDLoc dl = getCurSDLoc(); 2627 2628 // Subtract the lowest switch case value from the value being switched on. 2629 SDValue SwitchOp = getValue(JTH.SValue); 2630 EVT VT = SwitchOp.getValueType(); 2631 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2632 DAG.getConstant(JTH.First, dl, VT)); 2633 2634 // The SDNode we just created, which holds the value being switched on minus 2635 // the smallest case value, needs to be copied to a virtual register so it 2636 // can be used as an index into the jump table in a subsequent basic block. 2637 // This value may be smaller or larger than the target's pointer type, and 2638 // therefore require extension or truncating. 2639 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2640 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2641 2642 unsigned JumpTableReg = 2643 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2644 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2645 JumpTableReg, SwitchOp); 2646 JT.Reg = JumpTableReg; 2647 2648 if (!JTH.FallthroughUnreachable) { 2649 // Emit the range check for the jump table, and branch to the default block 2650 // for the switch statement if the value being switched on exceeds the 2651 // largest case in the switch. 2652 SDValue CMP = DAG.getSetCC( 2653 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2654 Sub.getValueType()), 2655 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2656 2657 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2658 MVT::Other, CopyTo, CMP, 2659 DAG.getBasicBlock(JT.Default)); 2660 2661 // Avoid emitting unnecessary branches to the next block. 2662 if (JT.MBB != NextBlock(SwitchBB)) 2663 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2664 DAG.getBasicBlock(JT.MBB)); 2665 2666 DAG.setRoot(BrCond); 2667 } else { 2668 // Avoid emitting unnecessary branches to the next block. 2669 if (JT.MBB != NextBlock(SwitchBB)) 2670 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2671 DAG.getBasicBlock(JT.MBB))); 2672 else 2673 DAG.setRoot(CopyTo); 2674 } 2675 } 2676 2677 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2678 /// variable if there exists one. 2679 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2680 SDValue &Chain) { 2681 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2682 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2683 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2684 MachineFunction &MF = DAG.getMachineFunction(); 2685 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2686 MachineSDNode *Node = 2687 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2688 if (Global) { 2689 MachinePointerInfo MPInfo(Global); 2690 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2691 MachineMemOperand::MODereferenceable; 2692 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2693 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2694 DAG.setNodeMemRefs(Node, {MemRef}); 2695 } 2696 if (PtrTy != PtrMemTy) 2697 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2698 return SDValue(Node, 0); 2699 } 2700 2701 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2702 /// tail spliced into a stack protector check success bb. 2703 /// 2704 /// For a high level explanation of how this fits into the stack protector 2705 /// generation see the comment on the declaration of class 2706 /// StackProtectorDescriptor. 2707 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2708 MachineBasicBlock *ParentBB) { 2709 2710 // First create the loads to the guard/stack slot for the comparison. 2711 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2712 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2713 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2714 2715 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2716 int FI = MFI.getStackProtectorIndex(); 2717 2718 SDValue Guard; 2719 SDLoc dl = getCurSDLoc(); 2720 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2721 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2722 Align Align = 2723 DAG.getDataLayout().getPrefTypeAlign(Type::getInt8PtrTy(M.getContext())); 2724 2725 // Generate code to load the content of the guard slot. 2726 SDValue GuardVal = DAG.getLoad( 2727 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2728 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2729 MachineMemOperand::MOVolatile); 2730 2731 if (TLI.useStackGuardXorFP()) 2732 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2733 2734 // Retrieve guard check function, nullptr if instrumentation is inlined. 2735 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2736 // The target provides a guard check function to validate the guard value. 2737 // Generate a call to that function with the content of the guard slot as 2738 // argument. 2739 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2740 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2741 2742 TargetLowering::ArgListTy Args; 2743 TargetLowering::ArgListEntry Entry; 2744 Entry.Node = GuardVal; 2745 Entry.Ty = FnTy->getParamType(0); 2746 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg)) 2747 Entry.IsInReg = true; 2748 Args.push_back(Entry); 2749 2750 TargetLowering::CallLoweringInfo CLI(DAG); 2751 CLI.setDebugLoc(getCurSDLoc()) 2752 .setChain(DAG.getEntryNode()) 2753 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2754 getValue(GuardCheckFn), std::move(Args)); 2755 2756 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2757 DAG.setRoot(Result.second); 2758 return; 2759 } 2760 2761 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2762 // Otherwise, emit a volatile load to retrieve the stack guard value. 2763 SDValue Chain = DAG.getEntryNode(); 2764 if (TLI.useLoadStackGuardNode()) { 2765 Guard = getLoadStackGuard(DAG, dl, Chain); 2766 } else { 2767 const Value *IRGuard = TLI.getSDagStackGuard(M); 2768 SDValue GuardPtr = getValue(IRGuard); 2769 2770 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2771 MachinePointerInfo(IRGuard, 0), Align, 2772 MachineMemOperand::MOVolatile); 2773 } 2774 2775 // Perform the comparison via a getsetcc. 2776 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2777 *DAG.getContext(), 2778 Guard.getValueType()), 2779 Guard, GuardVal, ISD::SETNE); 2780 2781 // If the guard/stackslot do not equal, branch to failure MBB. 2782 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2783 MVT::Other, GuardVal.getOperand(0), 2784 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2785 // Otherwise branch to success MBB. 2786 SDValue Br = DAG.getNode(ISD::BR, dl, 2787 MVT::Other, BrCond, 2788 DAG.getBasicBlock(SPD.getSuccessMBB())); 2789 2790 DAG.setRoot(Br); 2791 } 2792 2793 /// Codegen the failure basic block for a stack protector check. 2794 /// 2795 /// A failure stack protector machine basic block consists simply of a call to 2796 /// __stack_chk_fail(). 2797 /// 2798 /// For a high level explanation of how this fits into the stack protector 2799 /// generation see the comment on the declaration of class 2800 /// StackProtectorDescriptor. 2801 void 2802 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2803 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2804 TargetLowering::MakeLibCallOptions CallOptions; 2805 CallOptions.setDiscardResult(true); 2806 SDValue Chain = 2807 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2808 std::nullopt, CallOptions, getCurSDLoc()) 2809 .second; 2810 // On PS4/PS5, the "return address" must still be within the calling 2811 // function, even if it's at the very end, so emit an explicit TRAP here. 2812 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2813 if (TM.getTargetTriple().isPS()) 2814 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2815 // WebAssembly needs an unreachable instruction after a non-returning call, 2816 // because the function return type can be different from __stack_chk_fail's 2817 // return type (void). 2818 if (TM.getTargetTriple().isWasm()) 2819 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2820 2821 DAG.setRoot(Chain); 2822 } 2823 2824 /// visitBitTestHeader - This function emits necessary code to produce value 2825 /// suitable for "bit tests" 2826 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2827 MachineBasicBlock *SwitchBB) { 2828 SDLoc dl = getCurSDLoc(); 2829 2830 // Subtract the minimum value. 2831 SDValue SwitchOp = getValue(B.SValue); 2832 EVT VT = SwitchOp.getValueType(); 2833 SDValue RangeSub = 2834 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2835 2836 // Determine the type of the test operands. 2837 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2838 bool UsePtrType = false; 2839 if (!TLI.isTypeLegal(VT)) { 2840 UsePtrType = true; 2841 } else { 2842 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2843 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2844 // Switch table case range are encoded into series of masks. 2845 // Just use pointer type, it's guaranteed to fit. 2846 UsePtrType = true; 2847 break; 2848 } 2849 } 2850 SDValue Sub = RangeSub; 2851 if (UsePtrType) { 2852 VT = TLI.getPointerTy(DAG.getDataLayout()); 2853 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2854 } 2855 2856 B.RegVT = VT.getSimpleVT(); 2857 B.Reg = FuncInfo.CreateReg(B.RegVT); 2858 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2859 2860 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2861 2862 if (!B.FallthroughUnreachable) 2863 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2864 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2865 SwitchBB->normalizeSuccProbs(); 2866 2867 SDValue Root = CopyTo; 2868 if (!B.FallthroughUnreachable) { 2869 // Conditional branch to the default block. 2870 SDValue RangeCmp = DAG.getSetCC(dl, 2871 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2872 RangeSub.getValueType()), 2873 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2874 ISD::SETUGT); 2875 2876 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2877 DAG.getBasicBlock(B.Default)); 2878 } 2879 2880 // Avoid emitting unnecessary branches to the next block. 2881 if (MBB != NextBlock(SwitchBB)) 2882 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2883 2884 DAG.setRoot(Root); 2885 } 2886 2887 /// visitBitTestCase - this function produces one "bit test" 2888 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2889 MachineBasicBlock* NextMBB, 2890 BranchProbability BranchProbToNext, 2891 unsigned Reg, 2892 BitTestCase &B, 2893 MachineBasicBlock *SwitchBB) { 2894 SDLoc dl = getCurSDLoc(); 2895 MVT VT = BB.RegVT; 2896 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2897 SDValue Cmp; 2898 unsigned PopCount = countPopulation(B.Mask); 2899 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2900 if (PopCount == 1) { 2901 // Testing for a single bit; just compare the shift count with what it 2902 // would need to be to shift a 1 bit in that position. 2903 Cmp = DAG.getSetCC( 2904 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2905 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2906 ISD::SETEQ); 2907 } else if (PopCount == BB.Range) { 2908 // There is only one zero bit in the range, test for it directly. 2909 Cmp = DAG.getSetCC( 2910 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2911 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2912 ISD::SETNE); 2913 } else { 2914 // Make desired shift 2915 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2916 DAG.getConstant(1, dl, VT), ShiftOp); 2917 2918 // Emit bit tests and jumps 2919 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2920 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2921 Cmp = DAG.getSetCC( 2922 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2923 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2924 } 2925 2926 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2927 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2928 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2929 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2930 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2931 // one as they are relative probabilities (and thus work more like weights), 2932 // and hence we need to normalize them to let the sum of them become one. 2933 SwitchBB->normalizeSuccProbs(); 2934 2935 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2936 MVT::Other, getControlRoot(), 2937 Cmp, DAG.getBasicBlock(B.TargetBB)); 2938 2939 // Avoid emitting unnecessary branches to the next block. 2940 if (NextMBB != NextBlock(SwitchBB)) 2941 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2942 DAG.getBasicBlock(NextMBB)); 2943 2944 DAG.setRoot(BrAnd); 2945 } 2946 2947 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2948 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2949 2950 // Retrieve successors. Look through artificial IR level blocks like 2951 // catchswitch for successors. 2952 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2953 const BasicBlock *EHPadBB = I.getSuccessor(1); 2954 2955 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2956 // have to do anything here to lower funclet bundles. 2957 assert(!I.hasOperandBundlesOtherThan( 2958 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 2959 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 2960 LLVMContext::OB_cfguardtarget, 2961 LLVMContext::OB_clang_arc_attachedcall}) && 2962 "Cannot lower invokes with arbitrary operand bundles yet!"); 2963 2964 const Value *Callee(I.getCalledOperand()); 2965 const Function *Fn = dyn_cast<Function>(Callee); 2966 if (isa<InlineAsm>(Callee)) 2967 visitInlineAsm(I, EHPadBB); 2968 else if (Fn && Fn->isIntrinsic()) { 2969 switch (Fn->getIntrinsicID()) { 2970 default: 2971 llvm_unreachable("Cannot invoke this intrinsic"); 2972 case Intrinsic::donothing: 2973 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2974 case Intrinsic::seh_try_begin: 2975 case Intrinsic::seh_scope_begin: 2976 case Intrinsic::seh_try_end: 2977 case Intrinsic::seh_scope_end: 2978 break; 2979 case Intrinsic::experimental_patchpoint_void: 2980 case Intrinsic::experimental_patchpoint_i64: 2981 visitPatchpoint(I, EHPadBB); 2982 break; 2983 case Intrinsic::experimental_gc_statepoint: 2984 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 2985 break; 2986 case Intrinsic::wasm_rethrow: { 2987 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2988 // special because it can be invoked, so we manually lower it to a DAG 2989 // node here. 2990 SmallVector<SDValue, 8> Ops; 2991 Ops.push_back(getRoot()); // inchain 2992 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2993 Ops.push_back( 2994 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 2995 TLI.getPointerTy(DAG.getDataLayout()))); 2996 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2997 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2998 break; 2999 } 3000 } 3001 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 3002 // Currently we do not lower any intrinsic calls with deopt operand bundles. 3003 // Eventually we will support lowering the @llvm.experimental.deoptimize 3004 // intrinsic, and right now there are no plans to support other intrinsics 3005 // with deopt state. 3006 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 3007 } else { 3008 LowerCallTo(I, getValue(Callee), false, false, EHPadBB); 3009 } 3010 3011 // If the value of the invoke is used outside of its defining block, make it 3012 // available as a virtual register. 3013 // We already took care of the exported value for the statepoint instruction 3014 // during call to the LowerStatepoint. 3015 if (!isa<GCStatepointInst>(I)) { 3016 CopyToExportRegsIfNeeded(&I); 3017 } 3018 3019 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 3020 BranchProbabilityInfo *BPI = FuncInfo.BPI; 3021 BranchProbability EHPadBBProb = 3022 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 3023 : BranchProbability::getZero(); 3024 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 3025 3026 // Update successor info. 3027 addSuccessorWithProb(InvokeMBB, Return); 3028 for (auto &UnwindDest : UnwindDests) { 3029 UnwindDest.first->setIsEHPad(); 3030 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 3031 } 3032 InvokeMBB->normalizeSuccProbs(); 3033 3034 // Drop into normal successor. 3035 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 3036 DAG.getBasicBlock(Return))); 3037 } 3038 3039 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 3040 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 3041 3042 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3043 // have to do anything here to lower funclet bundles. 3044 assert(!I.hasOperandBundlesOtherThan( 3045 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 3046 "Cannot lower callbrs with arbitrary operand bundles yet!"); 3047 3048 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 3049 visitInlineAsm(I); 3050 CopyToExportRegsIfNeeded(&I); 3051 3052 // Retrieve successors. 3053 SmallPtrSet<BasicBlock *, 8> Dests; 3054 Dests.insert(I.getDefaultDest()); 3055 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 3056 3057 // Update successor info. 3058 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 3059 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 3060 BasicBlock *Dest = I.getIndirectDest(i); 3061 MachineBasicBlock *Target = FuncInfo.MBBMap[Dest]; 3062 Target->setIsInlineAsmBrIndirectTarget(); 3063 Target->setMachineBlockAddressTaken(); 3064 Target->setLabelMustBeEmitted(); 3065 // Don't add duplicate machine successors. 3066 if (Dests.insert(Dest).second) 3067 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 3068 } 3069 CallBrMBB->normalizeSuccProbs(); 3070 3071 // Drop into default successor. 3072 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 3073 MVT::Other, getControlRoot(), 3074 DAG.getBasicBlock(Return))); 3075 } 3076 3077 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 3078 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 3079 } 3080 3081 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 3082 assert(FuncInfo.MBB->isEHPad() && 3083 "Call to landingpad not in landing pad!"); 3084 3085 // If there aren't registers to copy the values into (e.g., during SjLj 3086 // exceptions), then don't bother to create these DAG nodes. 3087 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3088 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 3089 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 3090 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 3091 return; 3092 3093 // If landingpad's return type is token type, we don't create DAG nodes 3094 // for its exception pointer and selector value. The extraction of exception 3095 // pointer or selector value from token type landingpads is not currently 3096 // supported. 3097 if (LP.getType()->isTokenTy()) 3098 return; 3099 3100 SmallVector<EVT, 2> ValueVTs; 3101 SDLoc dl = getCurSDLoc(); 3102 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3103 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3104 3105 // Get the two live-in registers as SDValues. The physregs have already been 3106 // copied into virtual registers. 3107 SDValue Ops[2]; 3108 if (FuncInfo.ExceptionPointerVirtReg) { 3109 Ops[0] = DAG.getZExtOrTrunc( 3110 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3111 FuncInfo.ExceptionPointerVirtReg, 3112 TLI.getPointerTy(DAG.getDataLayout())), 3113 dl, ValueVTs[0]); 3114 } else { 3115 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3116 } 3117 Ops[1] = DAG.getZExtOrTrunc( 3118 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3119 FuncInfo.ExceptionSelectorVirtReg, 3120 TLI.getPointerTy(DAG.getDataLayout())), 3121 dl, ValueVTs[1]); 3122 3123 // Merge into one. 3124 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3125 DAG.getVTList(ValueVTs), Ops); 3126 setValue(&LP, Res); 3127 } 3128 3129 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3130 MachineBasicBlock *Last) { 3131 // Update JTCases. 3132 for (JumpTableBlock &JTB : SL->JTCases) 3133 if (JTB.first.HeaderBB == First) 3134 JTB.first.HeaderBB = Last; 3135 3136 // Update BitTestCases. 3137 for (BitTestBlock &BTB : SL->BitTestCases) 3138 if (BTB.Parent == First) 3139 BTB.Parent = Last; 3140 } 3141 3142 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3143 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3144 3145 // Update machine-CFG edges with unique successors. 3146 SmallSet<BasicBlock*, 32> Done; 3147 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3148 BasicBlock *BB = I.getSuccessor(i); 3149 bool Inserted = Done.insert(BB).second; 3150 if (!Inserted) 3151 continue; 3152 3153 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3154 addSuccessorWithProb(IndirectBrMBB, Succ); 3155 } 3156 IndirectBrMBB->normalizeSuccProbs(); 3157 3158 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3159 MVT::Other, getControlRoot(), 3160 getValue(I.getAddress()))); 3161 } 3162 3163 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3164 if (!DAG.getTarget().Options.TrapUnreachable) 3165 return; 3166 3167 // We may be able to ignore unreachable behind a noreturn call. 3168 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3169 const BasicBlock &BB = *I.getParent(); 3170 if (&I != &BB.front()) { 3171 BasicBlock::const_iterator PredI = 3172 std::prev(BasicBlock::const_iterator(&I)); 3173 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 3174 if (Call->doesNotReturn()) 3175 return; 3176 } 3177 } 3178 } 3179 3180 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3181 } 3182 3183 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3184 SDNodeFlags Flags; 3185 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3186 Flags.copyFMF(*FPOp); 3187 3188 SDValue Op = getValue(I.getOperand(0)); 3189 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3190 Op, Flags); 3191 setValue(&I, UnNodeValue); 3192 } 3193 3194 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3195 SDNodeFlags Flags; 3196 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3197 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3198 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3199 } 3200 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3201 Flags.setExact(ExactOp->isExact()); 3202 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3203 Flags.copyFMF(*FPOp); 3204 3205 SDValue Op1 = getValue(I.getOperand(0)); 3206 SDValue Op2 = getValue(I.getOperand(1)); 3207 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3208 Op1, Op2, Flags); 3209 setValue(&I, BinNodeValue); 3210 } 3211 3212 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3213 SDValue Op1 = getValue(I.getOperand(0)); 3214 SDValue Op2 = getValue(I.getOperand(1)); 3215 3216 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3217 Op1.getValueType(), DAG.getDataLayout()); 3218 3219 // Coerce the shift amount to the right type if we can. This exposes the 3220 // truncate or zext to optimization early. 3221 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3222 assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) && 3223 "Unexpected shift type"); 3224 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy); 3225 } 3226 3227 bool nuw = false; 3228 bool nsw = false; 3229 bool exact = false; 3230 3231 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3232 3233 if (const OverflowingBinaryOperator *OFBinOp = 3234 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3235 nuw = OFBinOp->hasNoUnsignedWrap(); 3236 nsw = OFBinOp->hasNoSignedWrap(); 3237 } 3238 if (const PossiblyExactOperator *ExactOp = 3239 dyn_cast<const PossiblyExactOperator>(&I)) 3240 exact = ExactOp->isExact(); 3241 } 3242 SDNodeFlags Flags; 3243 Flags.setExact(exact); 3244 Flags.setNoSignedWrap(nsw); 3245 Flags.setNoUnsignedWrap(nuw); 3246 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3247 Flags); 3248 setValue(&I, Res); 3249 } 3250 3251 void SelectionDAGBuilder::visitSDiv(const User &I) { 3252 SDValue Op1 = getValue(I.getOperand(0)); 3253 SDValue Op2 = getValue(I.getOperand(1)); 3254 3255 SDNodeFlags Flags; 3256 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3257 cast<PossiblyExactOperator>(&I)->isExact()); 3258 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3259 Op2, Flags)); 3260 } 3261 3262 void SelectionDAGBuilder::visitICmp(const User &I) { 3263 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3264 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3265 predicate = IC->getPredicate(); 3266 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3267 predicate = ICmpInst::Predicate(IC->getPredicate()); 3268 SDValue Op1 = getValue(I.getOperand(0)); 3269 SDValue Op2 = getValue(I.getOperand(1)); 3270 ISD::CondCode Opcode = getICmpCondCode(predicate); 3271 3272 auto &TLI = DAG.getTargetLoweringInfo(); 3273 EVT MemVT = 3274 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3275 3276 // If a pointer's DAG type is larger than its memory type then the DAG values 3277 // are zero-extended. This breaks signed comparisons so truncate back to the 3278 // underlying type before doing the compare. 3279 if (Op1.getValueType() != MemVT) { 3280 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3281 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3282 } 3283 3284 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3285 I.getType()); 3286 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3287 } 3288 3289 void SelectionDAGBuilder::visitFCmp(const User &I) { 3290 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3291 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3292 predicate = FC->getPredicate(); 3293 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3294 predicate = FCmpInst::Predicate(FC->getPredicate()); 3295 SDValue Op1 = getValue(I.getOperand(0)); 3296 SDValue Op2 = getValue(I.getOperand(1)); 3297 3298 ISD::CondCode Condition = getFCmpCondCode(predicate); 3299 auto *FPMO = cast<FPMathOperator>(&I); 3300 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3301 Condition = getFCmpCodeWithoutNaN(Condition); 3302 3303 SDNodeFlags Flags; 3304 Flags.copyFMF(*FPMO); 3305 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3306 3307 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3308 I.getType()); 3309 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3310 } 3311 3312 // Check if the condition of the select has one use or two users that are both 3313 // selects with the same condition. 3314 static bool hasOnlySelectUsers(const Value *Cond) { 3315 return llvm::all_of(Cond->users(), [](const Value *V) { 3316 return isa<SelectInst>(V); 3317 }); 3318 } 3319 3320 void SelectionDAGBuilder::visitSelect(const User &I) { 3321 SmallVector<EVT, 4> ValueVTs; 3322 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3323 ValueVTs); 3324 unsigned NumValues = ValueVTs.size(); 3325 if (NumValues == 0) return; 3326 3327 SmallVector<SDValue, 4> Values(NumValues); 3328 SDValue Cond = getValue(I.getOperand(0)); 3329 SDValue LHSVal = getValue(I.getOperand(1)); 3330 SDValue RHSVal = getValue(I.getOperand(2)); 3331 SmallVector<SDValue, 1> BaseOps(1, Cond); 3332 ISD::NodeType OpCode = 3333 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3334 3335 bool IsUnaryAbs = false; 3336 bool Negate = false; 3337 3338 SDNodeFlags Flags; 3339 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3340 Flags.copyFMF(*FPOp); 3341 3342 // Min/max matching is only viable if all output VTs are the same. 3343 if (all_equal(ValueVTs)) { 3344 EVT VT = ValueVTs[0]; 3345 LLVMContext &Ctx = *DAG.getContext(); 3346 auto &TLI = DAG.getTargetLoweringInfo(); 3347 3348 // We care about the legality of the operation after it has been type 3349 // legalized. 3350 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3351 VT = TLI.getTypeToTransformTo(Ctx, VT); 3352 3353 // If the vselect is legal, assume we want to leave this as a vector setcc + 3354 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3355 // min/max is legal on the scalar type. 3356 bool UseScalarMinMax = VT.isVector() && 3357 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3358 3359 Value *LHS, *RHS; 3360 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3361 ISD::NodeType Opc = ISD::DELETED_NODE; 3362 switch (SPR.Flavor) { 3363 case SPF_UMAX: Opc = ISD::UMAX; break; 3364 case SPF_UMIN: Opc = ISD::UMIN; break; 3365 case SPF_SMAX: Opc = ISD::SMAX; break; 3366 case SPF_SMIN: Opc = ISD::SMIN; break; 3367 case SPF_FMINNUM: 3368 switch (SPR.NaNBehavior) { 3369 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3370 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3371 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3372 case SPNB_RETURNS_ANY: { 3373 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3374 Opc = ISD::FMINNUM; 3375 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3376 Opc = ISD::FMINIMUM; 3377 else if (UseScalarMinMax) 3378 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3379 ISD::FMINNUM : ISD::FMINIMUM; 3380 break; 3381 } 3382 } 3383 break; 3384 case SPF_FMAXNUM: 3385 switch (SPR.NaNBehavior) { 3386 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3387 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3388 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3389 case SPNB_RETURNS_ANY: 3390 3391 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3392 Opc = ISD::FMAXNUM; 3393 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3394 Opc = ISD::FMAXIMUM; 3395 else if (UseScalarMinMax) 3396 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3397 ISD::FMAXNUM : ISD::FMAXIMUM; 3398 break; 3399 } 3400 break; 3401 case SPF_NABS: 3402 Negate = true; 3403 [[fallthrough]]; 3404 case SPF_ABS: 3405 IsUnaryAbs = true; 3406 Opc = ISD::ABS; 3407 break; 3408 default: break; 3409 } 3410 3411 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3412 (TLI.isOperationLegalOrCustom(Opc, VT) || 3413 (UseScalarMinMax && 3414 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3415 // If the underlying comparison instruction is used by any other 3416 // instruction, the consumed instructions won't be destroyed, so it is 3417 // not profitable to convert to a min/max. 3418 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3419 OpCode = Opc; 3420 LHSVal = getValue(LHS); 3421 RHSVal = getValue(RHS); 3422 BaseOps.clear(); 3423 } 3424 3425 if (IsUnaryAbs) { 3426 OpCode = Opc; 3427 LHSVal = getValue(LHS); 3428 BaseOps.clear(); 3429 } 3430 } 3431 3432 if (IsUnaryAbs) { 3433 for (unsigned i = 0; i != NumValues; ++i) { 3434 SDLoc dl = getCurSDLoc(); 3435 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3436 Values[i] = 3437 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3438 if (Negate) 3439 Values[i] = DAG.getNegative(Values[i], dl, VT); 3440 } 3441 } else { 3442 for (unsigned i = 0; i != NumValues; ++i) { 3443 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3444 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3445 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3446 Values[i] = DAG.getNode( 3447 OpCode, getCurSDLoc(), 3448 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3449 } 3450 } 3451 3452 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3453 DAG.getVTList(ValueVTs), Values)); 3454 } 3455 3456 void SelectionDAGBuilder::visitTrunc(const User &I) { 3457 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3458 SDValue N = getValue(I.getOperand(0)); 3459 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3460 I.getType()); 3461 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3462 } 3463 3464 void SelectionDAGBuilder::visitZExt(const User &I) { 3465 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3466 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3467 SDValue N = getValue(I.getOperand(0)); 3468 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3469 I.getType()); 3470 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3471 } 3472 3473 void SelectionDAGBuilder::visitSExt(const User &I) { 3474 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3475 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3476 SDValue N = getValue(I.getOperand(0)); 3477 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3478 I.getType()); 3479 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3480 } 3481 3482 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3483 // FPTrunc is never a no-op cast, no need to check 3484 SDValue N = getValue(I.getOperand(0)); 3485 SDLoc dl = getCurSDLoc(); 3486 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3487 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3488 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3489 DAG.getTargetConstant( 3490 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3491 } 3492 3493 void SelectionDAGBuilder::visitFPExt(const User &I) { 3494 // FPExt is never a no-op cast, no need to check 3495 SDValue N = getValue(I.getOperand(0)); 3496 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3497 I.getType()); 3498 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3499 } 3500 3501 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3502 // FPToUI is never a no-op cast, no need to check 3503 SDValue N = getValue(I.getOperand(0)); 3504 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3505 I.getType()); 3506 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3507 } 3508 3509 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3510 // FPToSI is never a no-op cast, no need to check 3511 SDValue N = getValue(I.getOperand(0)); 3512 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3513 I.getType()); 3514 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3515 } 3516 3517 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3518 // UIToFP is never a no-op cast, no need to check 3519 SDValue N = getValue(I.getOperand(0)); 3520 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3521 I.getType()); 3522 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3523 } 3524 3525 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3526 // SIToFP is never a no-op cast, no need to check 3527 SDValue N = getValue(I.getOperand(0)); 3528 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3529 I.getType()); 3530 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3531 } 3532 3533 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3534 // What to do depends on the size of the integer and the size of the pointer. 3535 // We can either truncate, zero extend, or no-op, accordingly. 3536 SDValue N = getValue(I.getOperand(0)); 3537 auto &TLI = DAG.getTargetLoweringInfo(); 3538 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3539 I.getType()); 3540 EVT PtrMemVT = 3541 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3542 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3543 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3544 setValue(&I, N); 3545 } 3546 3547 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3548 // What to do depends on the size of the integer and the size of the pointer. 3549 // We can either truncate, zero extend, or no-op, accordingly. 3550 SDValue N = getValue(I.getOperand(0)); 3551 auto &TLI = DAG.getTargetLoweringInfo(); 3552 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3553 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3554 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3555 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3556 setValue(&I, N); 3557 } 3558 3559 void SelectionDAGBuilder::visitBitCast(const User &I) { 3560 SDValue N = getValue(I.getOperand(0)); 3561 SDLoc dl = getCurSDLoc(); 3562 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3563 I.getType()); 3564 3565 // BitCast assures us that source and destination are the same size so this is 3566 // either a BITCAST or a no-op. 3567 if (DestVT != N.getValueType()) 3568 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3569 DestVT, N)); // convert types. 3570 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3571 // might fold any kind of constant expression to an integer constant and that 3572 // is not what we are looking for. Only recognize a bitcast of a genuine 3573 // constant integer as an opaque constant. 3574 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3575 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3576 /*isOpaque*/true)); 3577 else 3578 setValue(&I, N); // noop cast. 3579 } 3580 3581 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3582 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3583 const Value *SV = I.getOperand(0); 3584 SDValue N = getValue(SV); 3585 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3586 3587 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3588 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3589 3590 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3591 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3592 3593 setValue(&I, N); 3594 } 3595 3596 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3597 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3598 SDValue InVec = getValue(I.getOperand(0)); 3599 SDValue InVal = getValue(I.getOperand(1)); 3600 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3601 TLI.getVectorIdxTy(DAG.getDataLayout())); 3602 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3603 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3604 InVec, InVal, InIdx)); 3605 } 3606 3607 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3608 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3609 SDValue InVec = getValue(I.getOperand(0)); 3610 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3611 TLI.getVectorIdxTy(DAG.getDataLayout())); 3612 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3613 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3614 InVec, InIdx)); 3615 } 3616 3617 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3618 SDValue Src1 = getValue(I.getOperand(0)); 3619 SDValue Src2 = getValue(I.getOperand(1)); 3620 ArrayRef<int> Mask; 3621 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3622 Mask = SVI->getShuffleMask(); 3623 else 3624 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3625 SDLoc DL = getCurSDLoc(); 3626 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3627 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3628 EVT SrcVT = Src1.getValueType(); 3629 3630 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3631 VT.isScalableVector()) { 3632 // Canonical splat form of first element of first input vector. 3633 SDValue FirstElt = 3634 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3635 DAG.getVectorIdxConstant(0, DL)); 3636 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3637 return; 3638 } 3639 3640 // For now, we only handle splats for scalable vectors. 3641 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3642 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3643 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3644 3645 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3646 unsigned MaskNumElts = Mask.size(); 3647 3648 if (SrcNumElts == MaskNumElts) { 3649 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3650 return; 3651 } 3652 3653 // Normalize the shuffle vector since mask and vector length don't match. 3654 if (SrcNumElts < MaskNumElts) { 3655 // Mask is longer than the source vectors. We can use concatenate vector to 3656 // make the mask and vectors lengths match. 3657 3658 if (MaskNumElts % SrcNumElts == 0) { 3659 // Mask length is a multiple of the source vector length. 3660 // Check if the shuffle is some kind of concatenation of the input 3661 // vectors. 3662 unsigned NumConcat = MaskNumElts / SrcNumElts; 3663 bool IsConcat = true; 3664 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3665 for (unsigned i = 0; i != MaskNumElts; ++i) { 3666 int Idx = Mask[i]; 3667 if (Idx < 0) 3668 continue; 3669 // Ensure the indices in each SrcVT sized piece are sequential and that 3670 // the same source is used for the whole piece. 3671 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3672 (ConcatSrcs[i / SrcNumElts] >= 0 && 3673 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3674 IsConcat = false; 3675 break; 3676 } 3677 // Remember which source this index came from. 3678 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3679 } 3680 3681 // The shuffle is concatenating multiple vectors together. Just emit 3682 // a CONCAT_VECTORS operation. 3683 if (IsConcat) { 3684 SmallVector<SDValue, 8> ConcatOps; 3685 for (auto Src : ConcatSrcs) { 3686 if (Src < 0) 3687 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3688 else if (Src == 0) 3689 ConcatOps.push_back(Src1); 3690 else 3691 ConcatOps.push_back(Src2); 3692 } 3693 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3694 return; 3695 } 3696 } 3697 3698 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3699 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3700 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3701 PaddedMaskNumElts); 3702 3703 // Pad both vectors with undefs to make them the same length as the mask. 3704 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3705 3706 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3707 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3708 MOps1[0] = Src1; 3709 MOps2[0] = Src2; 3710 3711 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3712 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3713 3714 // Readjust mask for new input vector length. 3715 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3716 for (unsigned i = 0; i != MaskNumElts; ++i) { 3717 int Idx = Mask[i]; 3718 if (Idx >= (int)SrcNumElts) 3719 Idx -= SrcNumElts - PaddedMaskNumElts; 3720 MappedOps[i] = Idx; 3721 } 3722 3723 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3724 3725 // If the concatenated vector was padded, extract a subvector with the 3726 // correct number of elements. 3727 if (MaskNumElts != PaddedMaskNumElts) 3728 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3729 DAG.getVectorIdxConstant(0, DL)); 3730 3731 setValue(&I, Result); 3732 return; 3733 } 3734 3735 if (SrcNumElts > MaskNumElts) { 3736 // Analyze the access pattern of the vector to see if we can extract 3737 // two subvectors and do the shuffle. 3738 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3739 bool CanExtract = true; 3740 for (int Idx : Mask) { 3741 unsigned Input = 0; 3742 if (Idx < 0) 3743 continue; 3744 3745 if (Idx >= (int)SrcNumElts) { 3746 Input = 1; 3747 Idx -= SrcNumElts; 3748 } 3749 3750 // If all the indices come from the same MaskNumElts sized portion of 3751 // the sources we can use extract. Also make sure the extract wouldn't 3752 // extract past the end of the source. 3753 int NewStartIdx = alignDown(Idx, MaskNumElts); 3754 if (NewStartIdx + MaskNumElts > SrcNumElts || 3755 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3756 CanExtract = false; 3757 // Make sure we always update StartIdx as we use it to track if all 3758 // elements are undef. 3759 StartIdx[Input] = NewStartIdx; 3760 } 3761 3762 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3763 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3764 return; 3765 } 3766 if (CanExtract) { 3767 // Extract appropriate subvector and generate a vector shuffle 3768 for (unsigned Input = 0; Input < 2; ++Input) { 3769 SDValue &Src = Input == 0 ? Src1 : Src2; 3770 if (StartIdx[Input] < 0) 3771 Src = DAG.getUNDEF(VT); 3772 else { 3773 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3774 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3775 } 3776 } 3777 3778 // Calculate new mask. 3779 SmallVector<int, 8> MappedOps(Mask); 3780 for (int &Idx : MappedOps) { 3781 if (Idx >= (int)SrcNumElts) 3782 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3783 else if (Idx >= 0) 3784 Idx -= StartIdx[0]; 3785 } 3786 3787 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3788 return; 3789 } 3790 } 3791 3792 // We can't use either concat vectors or extract subvectors so fall back to 3793 // replacing the shuffle with extract and build vector. 3794 // to insert and build vector. 3795 EVT EltVT = VT.getVectorElementType(); 3796 SmallVector<SDValue,8> Ops; 3797 for (int Idx : Mask) { 3798 SDValue Res; 3799 3800 if (Idx < 0) { 3801 Res = DAG.getUNDEF(EltVT); 3802 } else { 3803 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3804 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3805 3806 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3807 DAG.getVectorIdxConstant(Idx, DL)); 3808 } 3809 3810 Ops.push_back(Res); 3811 } 3812 3813 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3814 } 3815 3816 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) { 3817 ArrayRef<unsigned> Indices = I.getIndices(); 3818 const Value *Op0 = I.getOperand(0); 3819 const Value *Op1 = I.getOperand(1); 3820 Type *AggTy = I.getType(); 3821 Type *ValTy = Op1->getType(); 3822 bool IntoUndef = isa<UndefValue>(Op0); 3823 bool FromUndef = isa<UndefValue>(Op1); 3824 3825 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3826 3827 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3828 SmallVector<EVT, 4> AggValueVTs; 3829 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3830 SmallVector<EVT, 4> ValValueVTs; 3831 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3832 3833 unsigned NumAggValues = AggValueVTs.size(); 3834 unsigned NumValValues = ValValueVTs.size(); 3835 SmallVector<SDValue, 4> Values(NumAggValues); 3836 3837 // Ignore an insertvalue that produces an empty object 3838 if (!NumAggValues) { 3839 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3840 return; 3841 } 3842 3843 SDValue Agg = getValue(Op0); 3844 unsigned i = 0; 3845 // Copy the beginning value(s) from the original aggregate. 3846 for (; i != LinearIndex; ++i) 3847 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3848 SDValue(Agg.getNode(), Agg.getResNo() + i); 3849 // Copy values from the inserted value(s). 3850 if (NumValValues) { 3851 SDValue Val = getValue(Op1); 3852 for (; i != LinearIndex + NumValValues; ++i) 3853 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3854 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3855 } 3856 // Copy remaining value(s) from the original aggregate. 3857 for (; i != NumAggValues; ++i) 3858 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3859 SDValue(Agg.getNode(), Agg.getResNo() + i); 3860 3861 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3862 DAG.getVTList(AggValueVTs), Values)); 3863 } 3864 3865 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) { 3866 ArrayRef<unsigned> Indices = I.getIndices(); 3867 const Value *Op0 = I.getOperand(0); 3868 Type *AggTy = Op0->getType(); 3869 Type *ValTy = I.getType(); 3870 bool OutOfUndef = isa<UndefValue>(Op0); 3871 3872 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3873 3874 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3875 SmallVector<EVT, 4> ValValueVTs; 3876 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3877 3878 unsigned NumValValues = ValValueVTs.size(); 3879 3880 // Ignore a extractvalue that produces an empty object 3881 if (!NumValValues) { 3882 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3883 return; 3884 } 3885 3886 SmallVector<SDValue, 4> Values(NumValValues); 3887 3888 SDValue Agg = getValue(Op0); 3889 // Copy out the selected value(s). 3890 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3891 Values[i - LinearIndex] = 3892 OutOfUndef ? 3893 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3894 SDValue(Agg.getNode(), Agg.getResNo() + i); 3895 3896 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3897 DAG.getVTList(ValValueVTs), Values)); 3898 } 3899 3900 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3901 Value *Op0 = I.getOperand(0); 3902 // Note that the pointer operand may be a vector of pointers. Take the scalar 3903 // element which holds a pointer. 3904 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3905 SDValue N = getValue(Op0); 3906 SDLoc dl = getCurSDLoc(); 3907 auto &TLI = DAG.getTargetLoweringInfo(); 3908 3909 // Normalize Vector GEP - all scalar operands should be converted to the 3910 // splat vector. 3911 bool IsVectorGEP = I.getType()->isVectorTy(); 3912 ElementCount VectorElementCount = 3913 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3914 : ElementCount::getFixed(0); 3915 3916 if (IsVectorGEP && !N.getValueType().isVector()) { 3917 LLVMContext &Context = *DAG.getContext(); 3918 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3919 N = DAG.getSplat(VT, dl, N); 3920 } 3921 3922 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3923 GTI != E; ++GTI) { 3924 const Value *Idx = GTI.getOperand(); 3925 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3926 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3927 if (Field) { 3928 // N = N + Offset 3929 uint64_t Offset = 3930 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field); 3931 3932 // In an inbounds GEP with an offset that is nonnegative even when 3933 // interpreted as signed, assume there is no unsigned overflow. 3934 SDNodeFlags Flags; 3935 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3936 Flags.setNoUnsignedWrap(true); 3937 3938 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3939 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3940 } 3941 } else { 3942 // IdxSize is the width of the arithmetic according to IR semantics. 3943 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3944 // (and fix up the result later). 3945 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3946 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3947 TypeSize ElementSize = 3948 DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType()); 3949 // We intentionally mask away the high bits here; ElementSize may not 3950 // fit in IdxTy. 3951 APInt ElementMul(IdxSize, ElementSize.getKnownMinValue()); 3952 bool ElementScalable = ElementSize.isScalable(); 3953 3954 // If this is a scalar constant or a splat vector of constants, 3955 // handle it quickly. 3956 const auto *C = dyn_cast<Constant>(Idx); 3957 if (C && isa<VectorType>(C->getType())) 3958 C = C->getSplatValue(); 3959 3960 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 3961 if (CI && CI->isZero()) 3962 continue; 3963 if (CI && !ElementScalable) { 3964 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 3965 LLVMContext &Context = *DAG.getContext(); 3966 SDValue OffsVal; 3967 if (IsVectorGEP) 3968 OffsVal = DAG.getConstant( 3969 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 3970 else 3971 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 3972 3973 // In an inbounds GEP with an offset that is nonnegative even when 3974 // interpreted as signed, assume there is no unsigned overflow. 3975 SDNodeFlags Flags; 3976 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3977 Flags.setNoUnsignedWrap(true); 3978 3979 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3980 3981 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3982 continue; 3983 } 3984 3985 // N = N + Idx * ElementMul; 3986 SDValue IdxN = getValue(Idx); 3987 3988 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 3989 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 3990 VectorElementCount); 3991 IdxN = DAG.getSplat(VT, dl, IdxN); 3992 } 3993 3994 // If the index is smaller or larger than intptr_t, truncate or extend 3995 // it. 3996 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3997 3998 if (ElementScalable) { 3999 EVT VScaleTy = N.getValueType().getScalarType(); 4000 SDValue VScale = DAG.getNode( 4001 ISD::VSCALE, dl, VScaleTy, 4002 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 4003 if (IsVectorGEP) 4004 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 4005 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 4006 } else { 4007 // If this is a multiply by a power of two, turn it into a shl 4008 // immediately. This is a very common case. 4009 if (ElementMul != 1) { 4010 if (ElementMul.isPowerOf2()) { 4011 unsigned Amt = ElementMul.logBase2(); 4012 IdxN = DAG.getNode(ISD::SHL, dl, 4013 N.getValueType(), IdxN, 4014 DAG.getConstant(Amt, dl, IdxN.getValueType())); 4015 } else { 4016 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 4017 IdxN.getValueType()); 4018 IdxN = DAG.getNode(ISD::MUL, dl, 4019 N.getValueType(), IdxN, Scale); 4020 } 4021 } 4022 } 4023 4024 N = DAG.getNode(ISD::ADD, dl, 4025 N.getValueType(), N, IdxN); 4026 } 4027 } 4028 4029 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 4030 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 4031 if (IsVectorGEP) { 4032 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 4033 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 4034 } 4035 4036 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 4037 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 4038 4039 setValue(&I, N); 4040 } 4041 4042 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 4043 // If this is a fixed sized alloca in the entry block of the function, 4044 // allocate it statically on the stack. 4045 if (FuncInfo.StaticAllocaMap.count(&I)) 4046 return; // getValue will auto-populate this. 4047 4048 SDLoc dl = getCurSDLoc(); 4049 Type *Ty = I.getAllocatedType(); 4050 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4051 auto &DL = DAG.getDataLayout(); 4052 TypeSize TySize = DL.getTypeAllocSize(Ty); 4053 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 4054 4055 SDValue AllocSize = getValue(I.getArraySize()); 4056 4057 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), I.getAddressSpace()); 4058 if (AllocSize.getValueType() != IntPtr) 4059 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 4060 4061 if (TySize.isScalable()) 4062 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4063 DAG.getVScale(dl, IntPtr, 4064 APInt(IntPtr.getScalarSizeInBits(), 4065 TySize.getKnownMinValue()))); 4066 else 4067 AllocSize = 4068 DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4069 DAG.getConstant(TySize.getFixedValue(), dl, IntPtr)); 4070 4071 // Handle alignment. If the requested alignment is less than or equal to 4072 // the stack alignment, ignore it. If the size is greater than or equal to 4073 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4074 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 4075 if (*Alignment <= StackAlign) 4076 Alignment = std::nullopt; 4077 4078 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4079 // Round the size of the allocation up to the stack alignment size 4080 // by add SA-1 to the size. This doesn't overflow because we're computing 4081 // an address inside an alloca. 4082 SDNodeFlags Flags; 4083 Flags.setNoUnsignedWrap(true); 4084 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4085 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4086 4087 // Mask out the low bits for alignment purposes. 4088 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4089 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 4090 4091 SDValue Ops[] = { 4092 getRoot(), AllocSize, 4093 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4094 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4095 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4096 setValue(&I, DSA); 4097 DAG.setRoot(DSA.getValue(1)); 4098 4099 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4100 } 4101 4102 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4103 if (I.isAtomic()) 4104 return visitAtomicLoad(I); 4105 4106 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4107 const Value *SV = I.getOperand(0); 4108 if (TLI.supportSwiftError()) { 4109 // Swifterror values can come from either a function parameter with 4110 // swifterror attribute or an alloca with swifterror attribute. 4111 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4112 if (Arg->hasSwiftErrorAttr()) 4113 return visitLoadFromSwiftError(I); 4114 } 4115 4116 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4117 if (Alloca->isSwiftError()) 4118 return visitLoadFromSwiftError(I); 4119 } 4120 } 4121 4122 SDValue Ptr = getValue(SV); 4123 4124 Type *Ty = I.getType(); 4125 SmallVector<EVT, 4> ValueVTs, MemVTs; 4126 SmallVector<uint64_t, 4> Offsets; 4127 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4128 unsigned NumValues = ValueVTs.size(); 4129 if (NumValues == 0) 4130 return; 4131 4132 Align Alignment = I.getAlign(); 4133 AAMDNodes AAInfo = I.getAAMetadata(); 4134 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4135 bool isVolatile = I.isVolatile(); 4136 MachineMemOperand::Flags MMOFlags = 4137 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4138 4139 SDValue Root; 4140 bool ConstantMemory = false; 4141 if (isVolatile) 4142 // Serialize volatile loads with other side effects. 4143 Root = getRoot(); 4144 else if (NumValues > MaxParallelChains) 4145 Root = getMemoryRoot(); 4146 else if (AA && 4147 AA->pointsToConstantMemory(MemoryLocation( 4148 SV, 4149 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4150 AAInfo))) { 4151 // Do not serialize (non-volatile) loads of constant memory with anything. 4152 Root = DAG.getEntryNode(); 4153 ConstantMemory = true; 4154 MMOFlags |= MachineMemOperand::MOInvariant; 4155 } else { 4156 // Do not serialize non-volatile loads against each other. 4157 Root = DAG.getRoot(); 4158 } 4159 4160 if (isDereferenceableAndAlignedPointer(SV, Ty, Alignment, DAG.getDataLayout(), 4161 &I, AC, nullptr, LibInfo)) 4162 MMOFlags |= MachineMemOperand::MODereferenceable; 4163 4164 SDLoc dl = getCurSDLoc(); 4165 4166 if (isVolatile) 4167 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4168 4169 // An aggregate load cannot wrap around the address space, so offsets to its 4170 // parts don't wrap either. 4171 SDNodeFlags Flags; 4172 Flags.setNoUnsignedWrap(true); 4173 4174 SmallVector<SDValue, 4> Values(NumValues); 4175 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4176 EVT PtrVT = Ptr.getValueType(); 4177 4178 unsigned ChainI = 0; 4179 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4180 // Serializing loads here may result in excessive register pressure, and 4181 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4182 // could recover a bit by hoisting nodes upward in the chain by recognizing 4183 // they are side-effect free or do not alias. The optimizer should really 4184 // avoid this case by converting large object/array copies to llvm.memcpy 4185 // (MaxParallelChains should always remain as failsafe). 4186 if (ChainI == MaxParallelChains) { 4187 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4188 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4189 ArrayRef(Chains.data(), ChainI)); 4190 Root = Chain; 4191 ChainI = 0; 4192 } 4193 SDValue A = DAG.getNode(ISD::ADD, dl, 4194 PtrVT, Ptr, 4195 DAG.getConstant(Offsets[i], dl, PtrVT), 4196 Flags); 4197 4198 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4199 MachinePointerInfo(SV, Offsets[i]), Alignment, 4200 MMOFlags, AAInfo, Ranges); 4201 Chains[ChainI] = L.getValue(1); 4202 4203 if (MemVTs[i] != ValueVTs[i]) 4204 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4205 4206 Values[i] = L; 4207 } 4208 4209 if (!ConstantMemory) { 4210 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4211 ArrayRef(Chains.data(), ChainI)); 4212 if (isVolatile) 4213 DAG.setRoot(Chain); 4214 else 4215 PendingLoads.push_back(Chain); 4216 } 4217 4218 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4219 DAG.getVTList(ValueVTs), Values)); 4220 } 4221 4222 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4223 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4224 "call visitStoreToSwiftError when backend supports swifterror"); 4225 4226 SmallVector<EVT, 4> ValueVTs; 4227 SmallVector<uint64_t, 4> Offsets; 4228 const Value *SrcV = I.getOperand(0); 4229 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4230 SrcV->getType(), ValueVTs, &Offsets); 4231 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4232 "expect a single EVT for swifterror"); 4233 4234 SDValue Src = getValue(SrcV); 4235 // Create a virtual register, then update the virtual register. 4236 Register VReg = 4237 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4238 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4239 // Chain can be getRoot or getControlRoot. 4240 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4241 SDValue(Src.getNode(), Src.getResNo())); 4242 DAG.setRoot(CopyNode); 4243 } 4244 4245 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4246 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4247 "call visitLoadFromSwiftError when backend supports swifterror"); 4248 4249 assert(!I.isVolatile() && 4250 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4251 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4252 "Support volatile, non temporal, invariant for load_from_swift_error"); 4253 4254 const Value *SV = I.getOperand(0); 4255 Type *Ty = I.getType(); 4256 assert( 4257 (!AA || 4258 !AA->pointsToConstantMemory(MemoryLocation( 4259 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4260 I.getAAMetadata()))) && 4261 "load_from_swift_error should not be constant memory"); 4262 4263 SmallVector<EVT, 4> ValueVTs; 4264 SmallVector<uint64_t, 4> Offsets; 4265 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4266 ValueVTs, &Offsets); 4267 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4268 "expect a single EVT for swifterror"); 4269 4270 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4271 SDValue L = DAG.getCopyFromReg( 4272 getRoot(), getCurSDLoc(), 4273 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4274 4275 setValue(&I, L); 4276 } 4277 4278 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4279 if (I.isAtomic()) 4280 return visitAtomicStore(I); 4281 4282 const Value *SrcV = I.getOperand(0); 4283 const Value *PtrV = I.getOperand(1); 4284 4285 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4286 if (TLI.supportSwiftError()) { 4287 // Swifterror values can come from either a function parameter with 4288 // swifterror attribute or an alloca with swifterror attribute. 4289 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4290 if (Arg->hasSwiftErrorAttr()) 4291 return visitStoreToSwiftError(I); 4292 } 4293 4294 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4295 if (Alloca->isSwiftError()) 4296 return visitStoreToSwiftError(I); 4297 } 4298 } 4299 4300 SmallVector<EVT, 4> ValueVTs, MemVTs; 4301 SmallVector<uint64_t, 4> Offsets; 4302 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4303 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4304 unsigned NumValues = ValueVTs.size(); 4305 if (NumValues == 0) 4306 return; 4307 4308 // Get the lowered operands. Note that we do this after 4309 // checking if NumResults is zero, because with zero results 4310 // the operands won't have values in the map. 4311 SDValue Src = getValue(SrcV); 4312 SDValue Ptr = getValue(PtrV); 4313 4314 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4315 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4316 SDLoc dl = getCurSDLoc(); 4317 Align Alignment = I.getAlign(); 4318 AAMDNodes AAInfo = I.getAAMetadata(); 4319 4320 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4321 4322 // An aggregate load cannot wrap around the address space, so offsets to its 4323 // parts don't wrap either. 4324 SDNodeFlags Flags; 4325 Flags.setNoUnsignedWrap(true); 4326 4327 unsigned ChainI = 0; 4328 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4329 // See visitLoad comments. 4330 if (ChainI == MaxParallelChains) { 4331 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4332 ArrayRef(Chains.data(), ChainI)); 4333 Root = Chain; 4334 ChainI = 0; 4335 } 4336 SDValue Add = 4337 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags); 4338 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4339 if (MemVTs[i] != ValueVTs[i]) 4340 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4341 SDValue St = 4342 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4343 Alignment, MMOFlags, AAInfo); 4344 Chains[ChainI] = St; 4345 } 4346 4347 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4348 ArrayRef(Chains.data(), ChainI)); 4349 setValue(&I, StoreNode); 4350 DAG.setRoot(StoreNode); 4351 } 4352 4353 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4354 bool IsCompressing) { 4355 SDLoc sdl = getCurSDLoc(); 4356 4357 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4358 MaybeAlign &Alignment) { 4359 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4360 Src0 = I.getArgOperand(0); 4361 Ptr = I.getArgOperand(1); 4362 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4363 Mask = I.getArgOperand(3); 4364 }; 4365 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4366 MaybeAlign &Alignment) { 4367 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4368 Src0 = I.getArgOperand(0); 4369 Ptr = I.getArgOperand(1); 4370 Mask = I.getArgOperand(2); 4371 Alignment = std::nullopt; 4372 }; 4373 4374 Value *PtrOperand, *MaskOperand, *Src0Operand; 4375 MaybeAlign Alignment; 4376 if (IsCompressing) 4377 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4378 else 4379 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4380 4381 SDValue Ptr = getValue(PtrOperand); 4382 SDValue Src0 = getValue(Src0Operand); 4383 SDValue Mask = getValue(MaskOperand); 4384 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4385 4386 EVT VT = Src0.getValueType(); 4387 if (!Alignment) 4388 Alignment = DAG.getEVTAlign(VT); 4389 4390 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4391 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4392 MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata()); 4393 SDValue StoreNode = 4394 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4395 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4396 DAG.setRoot(StoreNode); 4397 setValue(&I, StoreNode); 4398 } 4399 4400 // Get a uniform base for the Gather/Scatter intrinsic. 4401 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4402 // We try to represent it as a base pointer + vector of indices. 4403 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4404 // The first operand of the GEP may be a single pointer or a vector of pointers 4405 // Example: 4406 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4407 // or 4408 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4409 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4410 // 4411 // When the first GEP operand is a single pointer - it is the uniform base we 4412 // are looking for. If first operand of the GEP is a splat vector - we 4413 // extract the splat value and use it as a uniform base. 4414 // In all other cases the function returns 'false'. 4415 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4416 ISD::MemIndexType &IndexType, SDValue &Scale, 4417 SelectionDAGBuilder *SDB, const BasicBlock *CurBB, 4418 uint64_t ElemSize) { 4419 SelectionDAG& DAG = SDB->DAG; 4420 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4421 const DataLayout &DL = DAG.getDataLayout(); 4422 4423 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type"); 4424 4425 // Handle splat constant pointer. 4426 if (auto *C = dyn_cast<Constant>(Ptr)) { 4427 C = C->getSplatValue(); 4428 if (!C) 4429 return false; 4430 4431 Base = SDB->getValue(C); 4432 4433 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); 4434 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4435 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4436 IndexType = ISD::SIGNED_SCALED; 4437 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4438 return true; 4439 } 4440 4441 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4442 if (!GEP || GEP->getParent() != CurBB) 4443 return false; 4444 4445 if (GEP->getNumOperands() != 2) 4446 return false; 4447 4448 const Value *BasePtr = GEP->getPointerOperand(); 4449 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4450 4451 // Make sure the base is scalar and the index is a vector. 4452 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4453 return false; 4454 4455 uint64_t ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType()); 4456 4457 // Target may not support the required addressing mode. 4458 if (ScaleVal != 1 && 4459 !TLI.isLegalScaleForGatherScatter(ScaleVal, ElemSize)) 4460 return false; 4461 4462 Base = SDB->getValue(BasePtr); 4463 Index = SDB->getValue(IndexVal); 4464 IndexType = ISD::SIGNED_SCALED; 4465 4466 Scale = 4467 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4468 return true; 4469 } 4470 4471 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4472 SDLoc sdl = getCurSDLoc(); 4473 4474 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4475 const Value *Ptr = I.getArgOperand(1); 4476 SDValue Src0 = getValue(I.getArgOperand(0)); 4477 SDValue Mask = getValue(I.getArgOperand(3)); 4478 EVT VT = Src0.getValueType(); 4479 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4480 ->getMaybeAlignValue() 4481 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4482 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4483 4484 SDValue Base; 4485 SDValue Index; 4486 ISD::MemIndexType IndexType; 4487 SDValue Scale; 4488 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4489 I.getParent(), VT.getScalarStoreSize()); 4490 4491 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4492 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4493 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4494 // TODO: Make MachineMemOperands aware of scalable 4495 // vectors. 4496 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata()); 4497 if (!UniformBase) { 4498 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4499 Index = getValue(Ptr); 4500 IndexType = ISD::SIGNED_SCALED; 4501 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4502 } 4503 4504 EVT IdxVT = Index.getValueType(); 4505 EVT EltTy = IdxVT.getVectorElementType(); 4506 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4507 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4508 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4509 } 4510 4511 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4512 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4513 Ops, MMO, IndexType, false); 4514 DAG.setRoot(Scatter); 4515 setValue(&I, Scatter); 4516 } 4517 4518 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4519 SDLoc sdl = getCurSDLoc(); 4520 4521 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4522 MaybeAlign &Alignment) { 4523 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4524 Ptr = I.getArgOperand(0); 4525 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4526 Mask = I.getArgOperand(2); 4527 Src0 = I.getArgOperand(3); 4528 }; 4529 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4530 MaybeAlign &Alignment) { 4531 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4532 Ptr = I.getArgOperand(0); 4533 Alignment = std::nullopt; 4534 Mask = I.getArgOperand(1); 4535 Src0 = I.getArgOperand(2); 4536 }; 4537 4538 Value *PtrOperand, *MaskOperand, *Src0Operand; 4539 MaybeAlign Alignment; 4540 if (IsExpanding) 4541 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4542 else 4543 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4544 4545 SDValue Ptr = getValue(PtrOperand); 4546 SDValue Src0 = getValue(Src0Operand); 4547 SDValue Mask = getValue(MaskOperand); 4548 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4549 4550 EVT VT = Src0.getValueType(); 4551 if (!Alignment) 4552 Alignment = DAG.getEVTAlign(VT); 4553 4554 AAMDNodes AAInfo = I.getAAMetadata(); 4555 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4556 4557 // Do not serialize masked loads of constant memory with anything. 4558 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 4559 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4560 4561 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4562 4563 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4564 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4565 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 4566 4567 SDValue Load = 4568 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4569 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4570 if (AddToChain) 4571 PendingLoads.push_back(Load.getValue(1)); 4572 setValue(&I, Load); 4573 } 4574 4575 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4576 SDLoc sdl = getCurSDLoc(); 4577 4578 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4579 const Value *Ptr = I.getArgOperand(0); 4580 SDValue Src0 = getValue(I.getArgOperand(3)); 4581 SDValue Mask = getValue(I.getArgOperand(2)); 4582 4583 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4584 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4585 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4586 ->getMaybeAlignValue() 4587 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4588 4589 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4590 4591 SDValue Root = DAG.getRoot(); 4592 SDValue Base; 4593 SDValue Index; 4594 ISD::MemIndexType IndexType; 4595 SDValue Scale; 4596 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4597 I.getParent(), VT.getScalarStoreSize()); 4598 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4599 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4600 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4601 // TODO: Make MachineMemOperands aware of scalable 4602 // vectors. 4603 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges); 4604 4605 if (!UniformBase) { 4606 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4607 Index = getValue(Ptr); 4608 IndexType = ISD::SIGNED_SCALED; 4609 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4610 } 4611 4612 EVT IdxVT = Index.getValueType(); 4613 EVT EltTy = IdxVT.getVectorElementType(); 4614 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4615 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4616 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4617 } 4618 4619 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4620 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4621 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4622 4623 PendingLoads.push_back(Gather.getValue(1)); 4624 setValue(&I, Gather); 4625 } 4626 4627 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4628 SDLoc dl = getCurSDLoc(); 4629 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4630 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4631 SyncScope::ID SSID = I.getSyncScopeID(); 4632 4633 SDValue InChain = getRoot(); 4634 4635 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4636 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4637 4638 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4639 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4640 4641 MachineFunction &MF = DAG.getMachineFunction(); 4642 MachineMemOperand *MMO = MF.getMachineMemOperand( 4643 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4644 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4645 FailureOrdering); 4646 4647 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4648 dl, MemVT, VTs, InChain, 4649 getValue(I.getPointerOperand()), 4650 getValue(I.getCompareOperand()), 4651 getValue(I.getNewValOperand()), MMO); 4652 4653 SDValue OutChain = L.getValue(2); 4654 4655 setValue(&I, L); 4656 DAG.setRoot(OutChain); 4657 } 4658 4659 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4660 SDLoc dl = getCurSDLoc(); 4661 ISD::NodeType NT; 4662 switch (I.getOperation()) { 4663 default: llvm_unreachable("Unknown atomicrmw operation"); 4664 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4665 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4666 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4667 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4668 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4669 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4670 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4671 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4672 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4673 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4674 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4675 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4676 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4677 case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break; 4678 case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break; 4679 } 4680 AtomicOrdering Ordering = I.getOrdering(); 4681 SyncScope::ID SSID = I.getSyncScopeID(); 4682 4683 SDValue InChain = getRoot(); 4684 4685 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4686 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4687 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4688 4689 MachineFunction &MF = DAG.getMachineFunction(); 4690 MachineMemOperand *MMO = MF.getMachineMemOperand( 4691 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4692 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4693 4694 SDValue L = 4695 DAG.getAtomic(NT, dl, MemVT, InChain, 4696 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4697 MMO); 4698 4699 SDValue OutChain = L.getValue(1); 4700 4701 setValue(&I, L); 4702 DAG.setRoot(OutChain); 4703 } 4704 4705 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4706 SDLoc dl = getCurSDLoc(); 4707 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4708 SDValue Ops[3]; 4709 Ops[0] = getRoot(); 4710 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4711 TLI.getFenceOperandTy(DAG.getDataLayout())); 4712 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4713 TLI.getFenceOperandTy(DAG.getDataLayout())); 4714 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops); 4715 setValue(&I, N); 4716 DAG.setRoot(N); 4717 } 4718 4719 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4720 SDLoc dl = getCurSDLoc(); 4721 AtomicOrdering Order = I.getOrdering(); 4722 SyncScope::ID SSID = I.getSyncScopeID(); 4723 4724 SDValue InChain = getRoot(); 4725 4726 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4727 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4728 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4729 4730 if (!TLI.supportsUnalignedAtomics() && 4731 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4732 report_fatal_error("Cannot generate unaligned atomic load"); 4733 4734 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4735 4736 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4737 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4738 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4739 4740 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4741 4742 SDValue Ptr = getValue(I.getPointerOperand()); 4743 4744 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4745 // TODO: Once this is better exercised by tests, it should be merged with 4746 // the normal path for loads to prevent future divergence. 4747 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4748 if (MemVT != VT) 4749 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4750 4751 setValue(&I, L); 4752 SDValue OutChain = L.getValue(1); 4753 if (!I.isUnordered()) 4754 DAG.setRoot(OutChain); 4755 else 4756 PendingLoads.push_back(OutChain); 4757 return; 4758 } 4759 4760 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4761 Ptr, MMO); 4762 4763 SDValue OutChain = L.getValue(1); 4764 if (MemVT != VT) 4765 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4766 4767 setValue(&I, L); 4768 DAG.setRoot(OutChain); 4769 } 4770 4771 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4772 SDLoc dl = getCurSDLoc(); 4773 4774 AtomicOrdering Ordering = I.getOrdering(); 4775 SyncScope::ID SSID = I.getSyncScopeID(); 4776 4777 SDValue InChain = getRoot(); 4778 4779 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4780 EVT MemVT = 4781 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4782 4783 if (!TLI.supportsUnalignedAtomics() && 4784 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4785 report_fatal_error("Cannot generate unaligned atomic store"); 4786 4787 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4788 4789 MachineFunction &MF = DAG.getMachineFunction(); 4790 MachineMemOperand *MMO = MF.getMachineMemOperand( 4791 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4792 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4793 4794 SDValue Val = getValue(I.getValueOperand()); 4795 if (Val.getValueType() != MemVT) 4796 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4797 SDValue Ptr = getValue(I.getPointerOperand()); 4798 4799 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4800 // TODO: Once this is better exercised by tests, it should be merged with 4801 // the normal path for stores to prevent future divergence. 4802 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4803 setValue(&I, S); 4804 DAG.setRoot(S); 4805 return; 4806 } 4807 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4808 Ptr, Val, MMO); 4809 4810 setValue(&I, OutChain); 4811 DAG.setRoot(OutChain); 4812 } 4813 4814 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4815 /// node. 4816 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4817 unsigned Intrinsic) { 4818 // Ignore the callsite's attributes. A specific call site may be marked with 4819 // readnone, but the lowering code will expect the chain based on the 4820 // definition. 4821 const Function *F = I.getCalledFunction(); 4822 bool HasChain = !F->doesNotAccessMemory(); 4823 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4824 4825 // Build the operand list. 4826 SmallVector<SDValue, 8> Ops; 4827 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4828 if (OnlyLoad) { 4829 // We don't need to serialize loads against other loads. 4830 Ops.push_back(DAG.getRoot()); 4831 } else { 4832 Ops.push_back(getRoot()); 4833 } 4834 } 4835 4836 // Info is set by getTgtMemIntrinsic 4837 TargetLowering::IntrinsicInfo Info; 4838 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4839 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4840 DAG.getMachineFunction(), 4841 Intrinsic); 4842 4843 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4844 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4845 Info.opc == ISD::INTRINSIC_W_CHAIN) 4846 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4847 TLI.getPointerTy(DAG.getDataLayout()))); 4848 4849 // Add all operands of the call to the operand list. 4850 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) { 4851 const Value *Arg = I.getArgOperand(i); 4852 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4853 Ops.push_back(getValue(Arg)); 4854 continue; 4855 } 4856 4857 // Use TargetConstant instead of a regular constant for immarg. 4858 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true); 4859 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4860 assert(CI->getBitWidth() <= 64 && 4861 "large intrinsic immediates not handled"); 4862 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4863 } else { 4864 Ops.push_back( 4865 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4866 } 4867 } 4868 4869 SmallVector<EVT, 4> ValueVTs; 4870 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4871 4872 if (HasChain) 4873 ValueVTs.push_back(MVT::Other); 4874 4875 SDVTList VTs = DAG.getVTList(ValueVTs); 4876 4877 // Propagate fast-math-flags from IR to node(s). 4878 SDNodeFlags Flags; 4879 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 4880 Flags.copyFMF(*FPMO); 4881 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 4882 4883 // Create the node. 4884 SDValue Result; 4885 // In some cases, custom collection of operands from CallInst I may be needed. 4886 TLI.CollectTargetIntrinsicOperands(I, Ops, DAG); 4887 if (IsTgtIntrinsic) { 4888 // This is target intrinsic that touches memory 4889 // 4890 // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic 4891 // didn't yield anything useful. 4892 MachinePointerInfo MPI; 4893 if (Info.ptrVal) 4894 MPI = MachinePointerInfo(Info.ptrVal, Info.offset); 4895 else if (Info.fallbackAddressSpace) 4896 MPI = MachinePointerInfo(*Info.fallbackAddressSpace); 4897 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, 4898 Info.memVT, MPI, Info.align, Info.flags, 4899 Info.size, I.getAAMetadata()); 4900 } else if (!HasChain) { 4901 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4902 } else if (!I.getType()->isVoidTy()) { 4903 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4904 } else { 4905 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4906 } 4907 4908 if (HasChain) { 4909 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4910 if (OnlyLoad) 4911 PendingLoads.push_back(Chain); 4912 else 4913 DAG.setRoot(Chain); 4914 } 4915 4916 if (!I.getType()->isVoidTy()) { 4917 if (!isa<VectorType>(I.getType())) 4918 Result = lowerRangeToAssertZExt(DAG, I, Result); 4919 4920 MaybeAlign Alignment = I.getRetAlign(); 4921 if (!Alignment) 4922 Alignment = F->getAttributes().getRetAlignment(); 4923 // Insert `assertalign` node if there's an alignment. 4924 if (InsertAssertAlign && Alignment) { 4925 Result = 4926 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 4927 } 4928 4929 setValue(&I, Result); 4930 } 4931 } 4932 4933 /// GetSignificand - Get the significand and build it into a floating-point 4934 /// number with exponent of 1: 4935 /// 4936 /// Op = (Op & 0x007fffff) | 0x3f800000; 4937 /// 4938 /// where Op is the hexadecimal representation of floating point value. 4939 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4940 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4941 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4942 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4943 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4944 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4945 } 4946 4947 /// GetExponent - Get the exponent: 4948 /// 4949 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4950 /// 4951 /// where Op is the hexadecimal representation of floating point value. 4952 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4953 const TargetLowering &TLI, const SDLoc &dl) { 4954 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4955 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4956 SDValue t1 = DAG.getNode( 4957 ISD::SRL, dl, MVT::i32, t0, 4958 DAG.getConstant(23, dl, 4959 TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout()))); 4960 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4961 DAG.getConstant(127, dl, MVT::i32)); 4962 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4963 } 4964 4965 /// getF32Constant - Get 32-bit floating point constant. 4966 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4967 const SDLoc &dl) { 4968 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4969 MVT::f32); 4970 } 4971 4972 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4973 SelectionDAG &DAG) { 4974 // TODO: What fast-math-flags should be set on the floating-point nodes? 4975 4976 // IntegerPartOfX = ((int32_t)(t0); 4977 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4978 4979 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4980 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4981 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4982 4983 // IntegerPartOfX <<= 23; 4984 IntegerPartOfX = 4985 DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4986 DAG.getConstant(23, dl, 4987 DAG.getTargetLoweringInfo().getShiftAmountTy( 4988 MVT::i32, DAG.getDataLayout()))); 4989 4990 SDValue TwoToFractionalPartOfX; 4991 if (LimitFloatPrecision <= 6) { 4992 // For floating-point precision of 6: 4993 // 4994 // TwoToFractionalPartOfX = 4995 // 0.997535578f + 4996 // (0.735607626f + 0.252464424f * x) * x; 4997 // 4998 // error 0.0144103317, which is 6 bits 4999 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5000 getF32Constant(DAG, 0x3e814304, dl)); 5001 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5002 getF32Constant(DAG, 0x3f3c50c8, dl)); 5003 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5004 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5005 getF32Constant(DAG, 0x3f7f5e7e, dl)); 5006 } else if (LimitFloatPrecision <= 12) { 5007 // For floating-point precision of 12: 5008 // 5009 // TwoToFractionalPartOfX = 5010 // 0.999892986f + 5011 // (0.696457318f + 5012 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 5013 // 5014 // error 0.000107046256, which is 13 to 14 bits 5015 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5016 getF32Constant(DAG, 0x3da235e3, dl)); 5017 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5018 getF32Constant(DAG, 0x3e65b8f3, dl)); 5019 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5020 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5021 getF32Constant(DAG, 0x3f324b07, dl)); 5022 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5023 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5024 getF32Constant(DAG, 0x3f7ff8fd, dl)); 5025 } else { // LimitFloatPrecision <= 18 5026 // For floating-point precision of 18: 5027 // 5028 // TwoToFractionalPartOfX = 5029 // 0.999999982f + 5030 // (0.693148872f + 5031 // (0.240227044f + 5032 // (0.554906021e-1f + 5033 // (0.961591928e-2f + 5034 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 5035 // error 2.47208000*10^(-7), which is better than 18 bits 5036 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5037 getF32Constant(DAG, 0x3924b03e, dl)); 5038 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5039 getF32Constant(DAG, 0x3ab24b87, dl)); 5040 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5041 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5042 getF32Constant(DAG, 0x3c1d8c17, dl)); 5043 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5044 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5045 getF32Constant(DAG, 0x3d634a1d, dl)); 5046 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5047 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5048 getF32Constant(DAG, 0x3e75fe14, dl)); 5049 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5050 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 5051 getF32Constant(DAG, 0x3f317234, dl)); 5052 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 5053 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 5054 getF32Constant(DAG, 0x3f800000, dl)); 5055 } 5056 5057 // Add the exponent into the result in integer domain. 5058 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 5059 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5060 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 5061 } 5062 5063 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5064 /// limited-precision mode. 5065 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5066 const TargetLowering &TLI, SDNodeFlags Flags) { 5067 if (Op.getValueType() == MVT::f32 && 5068 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5069 5070 // Put the exponent in the right bit position for later addition to the 5071 // final result: 5072 // 5073 // t0 = Op * log2(e) 5074 5075 // TODO: What fast-math-flags should be set here? 5076 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5077 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5078 return getLimitedPrecisionExp2(t0, dl, DAG); 5079 } 5080 5081 // No special expansion. 5082 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5083 } 5084 5085 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5086 /// limited-precision mode. 5087 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5088 const TargetLowering &TLI, SDNodeFlags Flags) { 5089 // TODO: What fast-math-flags should be set on the floating-point nodes? 5090 5091 if (Op.getValueType() == MVT::f32 && 5092 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5093 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5094 5095 // Scale the exponent by log(2). 5096 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5097 SDValue LogOfExponent = 5098 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5099 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5100 5101 // Get the significand and build it into a floating-point number with 5102 // exponent of 1. 5103 SDValue X = GetSignificand(DAG, Op1, dl); 5104 5105 SDValue LogOfMantissa; 5106 if (LimitFloatPrecision <= 6) { 5107 // For floating-point precision of 6: 5108 // 5109 // LogofMantissa = 5110 // -1.1609546f + 5111 // (1.4034025f - 0.23903021f * x) * x; 5112 // 5113 // error 0.0034276066, which is better than 8 bits 5114 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5115 getF32Constant(DAG, 0xbe74c456, dl)); 5116 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5117 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5118 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5119 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5120 getF32Constant(DAG, 0x3f949a29, dl)); 5121 } else if (LimitFloatPrecision <= 12) { 5122 // For floating-point precision of 12: 5123 // 5124 // LogOfMantissa = 5125 // -1.7417939f + 5126 // (2.8212026f + 5127 // (-1.4699568f + 5128 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5129 // 5130 // error 0.000061011436, which is 14 bits 5131 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5132 getF32Constant(DAG, 0xbd67b6d6, dl)); 5133 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5134 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5135 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5136 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5137 getF32Constant(DAG, 0x3fbc278b, dl)); 5138 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5139 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5140 getF32Constant(DAG, 0x40348e95, dl)); 5141 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5142 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5143 getF32Constant(DAG, 0x3fdef31a, dl)); 5144 } else { // LimitFloatPrecision <= 18 5145 // For floating-point precision of 18: 5146 // 5147 // LogOfMantissa = 5148 // -2.1072184f + 5149 // (4.2372794f + 5150 // (-3.7029485f + 5151 // (2.2781945f + 5152 // (-0.87823314f + 5153 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5154 // 5155 // error 0.0000023660568, which is better than 18 bits 5156 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5157 getF32Constant(DAG, 0xbc91e5ac, dl)); 5158 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5159 getF32Constant(DAG, 0x3e4350aa, dl)); 5160 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5161 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5162 getF32Constant(DAG, 0x3f60d3e3, dl)); 5163 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5164 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5165 getF32Constant(DAG, 0x4011cdf0, dl)); 5166 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5167 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5168 getF32Constant(DAG, 0x406cfd1c, dl)); 5169 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5170 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5171 getF32Constant(DAG, 0x408797cb, dl)); 5172 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5173 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5174 getF32Constant(DAG, 0x4006dcab, dl)); 5175 } 5176 5177 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5178 } 5179 5180 // No special expansion. 5181 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5182 } 5183 5184 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5185 /// limited-precision mode. 5186 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5187 const TargetLowering &TLI, SDNodeFlags Flags) { 5188 // TODO: What fast-math-flags should be set on the floating-point nodes? 5189 5190 if (Op.getValueType() == MVT::f32 && 5191 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5192 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5193 5194 // Get the exponent. 5195 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5196 5197 // Get the significand and build it into a floating-point number with 5198 // exponent of 1. 5199 SDValue X = GetSignificand(DAG, Op1, dl); 5200 5201 // Different possible minimax approximations of significand in 5202 // floating-point for various degrees of accuracy over [1,2]. 5203 SDValue Log2ofMantissa; 5204 if (LimitFloatPrecision <= 6) { 5205 // For floating-point precision of 6: 5206 // 5207 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5208 // 5209 // error 0.0049451742, which is more than 7 bits 5210 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5211 getF32Constant(DAG, 0xbeb08fe0, dl)); 5212 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5213 getF32Constant(DAG, 0x40019463, dl)); 5214 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5215 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5216 getF32Constant(DAG, 0x3fd6633d, dl)); 5217 } else if (LimitFloatPrecision <= 12) { 5218 // For floating-point precision of 12: 5219 // 5220 // Log2ofMantissa = 5221 // -2.51285454f + 5222 // (4.07009056f + 5223 // (-2.12067489f + 5224 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5225 // 5226 // error 0.0000876136000, which is better than 13 bits 5227 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5228 getF32Constant(DAG, 0xbda7262e, dl)); 5229 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5230 getF32Constant(DAG, 0x3f25280b, dl)); 5231 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5232 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5233 getF32Constant(DAG, 0x4007b923, dl)); 5234 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5235 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5236 getF32Constant(DAG, 0x40823e2f, dl)); 5237 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5238 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5239 getF32Constant(DAG, 0x4020d29c, dl)); 5240 } else { // LimitFloatPrecision <= 18 5241 // For floating-point precision of 18: 5242 // 5243 // Log2ofMantissa = 5244 // -3.0400495f + 5245 // (6.1129976f + 5246 // (-5.3420409f + 5247 // (3.2865683f + 5248 // (-1.2669343f + 5249 // (0.27515199f - 5250 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5251 // 5252 // error 0.0000018516, which is better than 18 bits 5253 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5254 getF32Constant(DAG, 0xbcd2769e, dl)); 5255 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5256 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5257 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5258 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5259 getF32Constant(DAG, 0x3fa22ae7, dl)); 5260 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5261 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5262 getF32Constant(DAG, 0x40525723, dl)); 5263 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5264 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5265 getF32Constant(DAG, 0x40aaf200, dl)); 5266 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5267 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5268 getF32Constant(DAG, 0x40c39dad, dl)); 5269 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5270 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5271 getF32Constant(DAG, 0x4042902c, dl)); 5272 } 5273 5274 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5275 } 5276 5277 // No special expansion. 5278 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5279 } 5280 5281 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5282 /// limited-precision mode. 5283 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5284 const TargetLowering &TLI, SDNodeFlags Flags) { 5285 // TODO: What fast-math-flags should be set on the floating-point nodes? 5286 5287 if (Op.getValueType() == MVT::f32 && 5288 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5289 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5290 5291 // Scale the exponent by log10(2) [0.30102999f]. 5292 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5293 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5294 getF32Constant(DAG, 0x3e9a209a, dl)); 5295 5296 // Get the significand and build it into a floating-point number with 5297 // exponent of 1. 5298 SDValue X = GetSignificand(DAG, Op1, dl); 5299 5300 SDValue Log10ofMantissa; 5301 if (LimitFloatPrecision <= 6) { 5302 // For floating-point precision of 6: 5303 // 5304 // Log10ofMantissa = 5305 // -0.50419619f + 5306 // (0.60948995f - 0.10380950f * x) * x; 5307 // 5308 // error 0.0014886165, which is 6 bits 5309 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5310 getF32Constant(DAG, 0xbdd49a13, dl)); 5311 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5312 getF32Constant(DAG, 0x3f1c0789, dl)); 5313 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5314 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5315 getF32Constant(DAG, 0x3f011300, dl)); 5316 } else if (LimitFloatPrecision <= 12) { 5317 // For floating-point precision of 12: 5318 // 5319 // Log10ofMantissa = 5320 // -0.64831180f + 5321 // (0.91751397f + 5322 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5323 // 5324 // error 0.00019228036, which is better than 12 bits 5325 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5326 getF32Constant(DAG, 0x3d431f31, dl)); 5327 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5328 getF32Constant(DAG, 0x3ea21fb2, dl)); 5329 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5330 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5331 getF32Constant(DAG, 0x3f6ae232, dl)); 5332 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5333 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5334 getF32Constant(DAG, 0x3f25f7c3, dl)); 5335 } else { // LimitFloatPrecision <= 18 5336 // For floating-point precision of 18: 5337 // 5338 // Log10ofMantissa = 5339 // -0.84299375f + 5340 // (1.5327582f + 5341 // (-1.0688956f + 5342 // (0.49102474f + 5343 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5344 // 5345 // error 0.0000037995730, which is better than 18 bits 5346 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5347 getF32Constant(DAG, 0x3c5d51ce, dl)); 5348 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5349 getF32Constant(DAG, 0x3e00685a, dl)); 5350 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5351 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5352 getF32Constant(DAG, 0x3efb6798, dl)); 5353 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5354 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5355 getF32Constant(DAG, 0x3f88d192, dl)); 5356 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5357 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5358 getF32Constant(DAG, 0x3fc4316c, dl)); 5359 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5360 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5361 getF32Constant(DAG, 0x3f57ce70, dl)); 5362 } 5363 5364 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5365 } 5366 5367 // No special expansion. 5368 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5369 } 5370 5371 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5372 /// limited-precision mode. 5373 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5374 const TargetLowering &TLI, SDNodeFlags Flags) { 5375 if (Op.getValueType() == MVT::f32 && 5376 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5377 return getLimitedPrecisionExp2(Op, dl, DAG); 5378 5379 // No special expansion. 5380 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5381 } 5382 5383 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5384 /// limited-precision mode with x == 10.0f. 5385 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5386 SelectionDAG &DAG, const TargetLowering &TLI, 5387 SDNodeFlags Flags) { 5388 bool IsExp10 = false; 5389 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5390 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5391 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5392 APFloat Ten(10.0f); 5393 IsExp10 = LHSC->isExactlyValue(Ten); 5394 } 5395 } 5396 5397 // TODO: What fast-math-flags should be set on the FMUL node? 5398 if (IsExp10) { 5399 // Put the exponent in the right bit position for later addition to the 5400 // final result: 5401 // 5402 // #define LOG2OF10 3.3219281f 5403 // t0 = Op * LOG2OF10; 5404 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5405 getF32Constant(DAG, 0x40549a78, dl)); 5406 return getLimitedPrecisionExp2(t0, dl, DAG); 5407 } 5408 5409 // No special expansion. 5410 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5411 } 5412 5413 /// ExpandPowI - Expand a llvm.powi intrinsic. 5414 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5415 SelectionDAG &DAG) { 5416 // If RHS is a constant, we can expand this out to a multiplication tree if 5417 // it's beneficial on the target, otherwise we end up lowering to a call to 5418 // __powidf2 (for example). 5419 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5420 unsigned Val = RHSC->getSExtValue(); 5421 5422 // powi(x, 0) -> 1.0 5423 if (Val == 0) 5424 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5425 5426 if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI( 5427 Val, DAG.shouldOptForSize())) { 5428 // Get the exponent as a positive value. 5429 if ((int)Val < 0) 5430 Val = -Val; 5431 // We use the simple binary decomposition method to generate the multiply 5432 // sequence. There are more optimal ways to do this (for example, 5433 // powi(x,15) generates one more multiply than it should), but this has 5434 // the benefit of being both really simple and much better than a libcall. 5435 SDValue Res; // Logically starts equal to 1.0 5436 SDValue CurSquare = LHS; 5437 // TODO: Intrinsics should have fast-math-flags that propagate to these 5438 // nodes. 5439 while (Val) { 5440 if (Val & 1) { 5441 if (Res.getNode()) 5442 Res = 5443 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare); 5444 else 5445 Res = CurSquare; // 1.0*CurSquare. 5446 } 5447 5448 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5449 CurSquare, CurSquare); 5450 Val >>= 1; 5451 } 5452 5453 // If the original was negative, invert the result, producing 1/(x*x*x). 5454 if (RHSC->getSExtValue() < 0) 5455 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5456 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5457 return Res; 5458 } 5459 } 5460 5461 // Otherwise, expand to a libcall. 5462 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5463 } 5464 5465 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5466 SDValue LHS, SDValue RHS, SDValue Scale, 5467 SelectionDAG &DAG, const TargetLowering &TLI) { 5468 EVT VT = LHS.getValueType(); 5469 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5470 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5471 LLVMContext &Ctx = *DAG.getContext(); 5472 5473 // If the type is legal but the operation isn't, this node might survive all 5474 // the way to operation legalization. If we end up there and we do not have 5475 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5476 // node. 5477 5478 // Coax the legalizer into expanding the node during type legalization instead 5479 // by bumping the size by one bit. This will force it to Promote, enabling the 5480 // early expansion and avoiding the need to expand later. 5481 5482 // We don't have to do this if Scale is 0; that can always be expanded, unless 5483 // it's a saturating signed operation. Those can experience true integer 5484 // division overflow, a case which we must avoid. 5485 5486 // FIXME: We wouldn't have to do this (or any of the early 5487 // expansion/promotion) if it was possible to expand a libcall of an 5488 // illegal type during operation legalization. But it's not, so things 5489 // get a bit hacky. 5490 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5491 if ((ScaleInt > 0 || (Saturating && Signed)) && 5492 (TLI.isTypeLegal(VT) || 5493 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5494 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5495 Opcode, VT, ScaleInt); 5496 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5497 EVT PromVT; 5498 if (VT.isScalarInteger()) 5499 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5500 else if (VT.isVector()) { 5501 PromVT = VT.getVectorElementType(); 5502 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5503 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5504 } else 5505 llvm_unreachable("Wrong VT for DIVFIX?"); 5506 if (Signed) { 5507 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5508 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5509 } else { 5510 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5511 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5512 } 5513 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5514 // For saturating operations, we need to shift up the LHS to get the 5515 // proper saturation width, and then shift down again afterwards. 5516 if (Saturating) 5517 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5518 DAG.getConstant(1, DL, ShiftTy)); 5519 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5520 if (Saturating) 5521 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5522 DAG.getConstant(1, DL, ShiftTy)); 5523 return DAG.getZExtOrTrunc(Res, DL, VT); 5524 } 5525 } 5526 5527 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5528 } 5529 5530 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5531 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5532 static void 5533 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5534 const SDValue &N) { 5535 switch (N.getOpcode()) { 5536 case ISD::CopyFromReg: { 5537 SDValue Op = N.getOperand(1); 5538 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5539 Op.getValueType().getSizeInBits()); 5540 return; 5541 } 5542 case ISD::BITCAST: 5543 case ISD::AssertZext: 5544 case ISD::AssertSext: 5545 case ISD::TRUNCATE: 5546 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5547 return; 5548 case ISD::BUILD_PAIR: 5549 case ISD::BUILD_VECTOR: 5550 case ISD::CONCAT_VECTORS: 5551 for (SDValue Op : N->op_values()) 5552 getUnderlyingArgRegs(Regs, Op); 5553 return; 5554 default: 5555 return; 5556 } 5557 } 5558 5559 /// If the DbgValueInst is a dbg_value of a function argument, create the 5560 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5561 /// instruction selection, they will be inserted to the entry BB. 5562 /// We don't currently support this for variadic dbg_values, as they shouldn't 5563 /// appear for function arguments or in the prologue. 5564 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5565 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5566 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) { 5567 const Argument *Arg = dyn_cast<Argument>(V); 5568 if (!Arg) 5569 return false; 5570 5571 MachineFunction &MF = DAG.getMachineFunction(); 5572 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5573 5574 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind 5575 // we've been asked to pursue. 5576 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr, 5577 bool Indirect) { 5578 if (Reg.isVirtual() && MF.useDebugInstrRef()) { 5579 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF 5580 // pointing at the VReg, which will be patched up later. 5581 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF); 5582 SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg( 5583 /* Reg */ Reg, /* isDef */ false, /* isImp */ false, 5584 /* isKill */ false, /* isDead */ false, 5585 /* isUndef */ false, /* isEarlyClobber */ false, 5586 /* SubReg */ 0, /* isDebug */ true)}); 5587 5588 auto *NewDIExpr = FragExpr; 5589 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into 5590 // the DIExpression. 5591 if (Indirect) 5592 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore); 5593 SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0}); 5594 NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops); 5595 return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr); 5596 } else { 5597 // Create a completely standard DBG_VALUE. 5598 auto &Inst = TII->get(TargetOpcode::DBG_VALUE); 5599 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr); 5600 } 5601 }; 5602 5603 if (Kind == FuncArgumentDbgValueKind::Value) { 5604 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5605 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5606 // the entry block. 5607 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5608 if (!IsInEntryBlock) 5609 return false; 5610 5611 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5612 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5613 // variable that also is a param. 5614 // 5615 // Although, if we are at the top of the entry block already, we can still 5616 // emit using ArgDbgValue. This might catch some situations when the 5617 // dbg.value refers to an argument that isn't used in the entry block, so 5618 // any CopyToReg node would be optimized out and the only way to express 5619 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5620 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5621 // we should only emit as ArgDbgValue if the Variable is an argument to the 5622 // current function, and the dbg.value intrinsic is found in the entry 5623 // block. 5624 bool VariableIsFunctionInputArg = Variable->isParameter() && 5625 !DL->getInlinedAt(); 5626 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5627 if (!IsInPrologue && !VariableIsFunctionInputArg) 5628 return false; 5629 5630 // Here we assume that a function argument on IR level only can be used to 5631 // describe one input parameter on source level. If we for example have 5632 // source code like this 5633 // 5634 // struct A { long x, y; }; 5635 // void foo(struct A a, long b) { 5636 // ... 5637 // b = a.x; 5638 // ... 5639 // } 5640 // 5641 // and IR like this 5642 // 5643 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5644 // entry: 5645 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5646 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5647 // call void @llvm.dbg.value(metadata i32 %b, "b", 5648 // ... 5649 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5650 // ... 5651 // 5652 // then the last dbg.value is describing a parameter "b" using a value that 5653 // is an argument. But since we already has used %a1 to describe a parameter 5654 // we should not handle that last dbg.value here (that would result in an 5655 // incorrect hoisting of the DBG_VALUE to the function entry). 5656 // Notice that we allow one dbg.value per IR level argument, to accommodate 5657 // for the situation with fragments above. 5658 if (VariableIsFunctionInputArg) { 5659 unsigned ArgNo = Arg->getArgNo(); 5660 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5661 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5662 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5663 return false; 5664 FuncInfo.DescribedArgs.set(ArgNo); 5665 } 5666 } 5667 5668 bool IsIndirect = false; 5669 std::optional<MachineOperand> Op; 5670 // Some arguments' frame index is recorded during argument lowering. 5671 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5672 if (FI != std::numeric_limits<int>::max()) 5673 Op = MachineOperand::CreateFI(FI); 5674 5675 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 5676 if (!Op && N.getNode()) { 5677 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5678 Register Reg; 5679 if (ArgRegsAndSizes.size() == 1) 5680 Reg = ArgRegsAndSizes.front().first; 5681 5682 if (Reg && Reg.isVirtual()) { 5683 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5684 Register PR = RegInfo.getLiveInPhysReg(Reg); 5685 if (PR) 5686 Reg = PR; 5687 } 5688 if (Reg) { 5689 Op = MachineOperand::CreateReg(Reg, false); 5690 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5691 } 5692 } 5693 5694 if (!Op && N.getNode()) { 5695 // Check if frame index is available. 5696 SDValue LCandidate = peekThroughBitcasts(N); 5697 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5698 if (FrameIndexSDNode *FINode = 5699 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5700 Op = MachineOperand::CreateFI(FINode->getIndex()); 5701 } 5702 5703 if (!Op) { 5704 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5705 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 5706 SplitRegs) { 5707 unsigned Offset = 0; 5708 for (const auto &RegAndSize : SplitRegs) { 5709 // If the expression is already a fragment, the current register 5710 // offset+size might extend beyond the fragment. In this case, only 5711 // the register bits that are inside the fragment are relevant. 5712 int RegFragmentSizeInBits = RegAndSize.second; 5713 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5714 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5715 // The register is entirely outside the expression fragment, 5716 // so is irrelevant for debug info. 5717 if (Offset >= ExprFragmentSizeInBits) 5718 break; 5719 // The register is partially outside the expression fragment, only 5720 // the low bits within the fragment are relevant for debug info. 5721 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5722 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5723 } 5724 } 5725 5726 auto FragmentExpr = DIExpression::createFragmentExpression( 5727 Expr, Offset, RegFragmentSizeInBits); 5728 Offset += RegAndSize.second; 5729 // If a valid fragment expression cannot be created, the variable's 5730 // correct value cannot be determined and so it is set as Undef. 5731 if (!FragmentExpr) { 5732 SDDbgValue *SDV = DAG.getConstantDbgValue( 5733 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5734 DAG.AddDbgValue(SDV, false); 5735 continue; 5736 } 5737 MachineInstr *NewMI = 5738 MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, 5739 Kind != FuncArgumentDbgValueKind::Value); 5740 FuncInfo.ArgDbgValues.push_back(NewMI); 5741 } 5742 }; 5743 5744 // Check if ValueMap has reg number. 5745 DenseMap<const Value *, Register>::const_iterator 5746 VMI = FuncInfo.ValueMap.find(V); 5747 if (VMI != FuncInfo.ValueMap.end()) { 5748 const auto &TLI = DAG.getTargetLoweringInfo(); 5749 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5750 V->getType(), std::nullopt); 5751 if (RFV.occupiesMultipleRegs()) { 5752 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5753 return true; 5754 } 5755 5756 Op = MachineOperand::CreateReg(VMI->second, false); 5757 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5758 } else if (ArgRegsAndSizes.size() > 1) { 5759 // This was split due to the calling convention, and no virtual register 5760 // mapping exists for the value. 5761 splitMultiRegDbgValue(ArgRegsAndSizes); 5762 return true; 5763 } 5764 } 5765 5766 if (!Op) 5767 return false; 5768 5769 assert(Variable->isValidLocationForIntrinsic(DL) && 5770 "Expected inlined-at fields to agree"); 5771 MachineInstr *NewMI = nullptr; 5772 5773 if (Op->isReg()) 5774 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect); 5775 else 5776 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op, 5777 Variable, Expr); 5778 5779 // Otherwise, use ArgDbgValues. 5780 FuncInfo.ArgDbgValues.push_back(NewMI); 5781 return true; 5782 } 5783 5784 /// Return the appropriate SDDbgValue based on N. 5785 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5786 DILocalVariable *Variable, 5787 DIExpression *Expr, 5788 const DebugLoc &dl, 5789 unsigned DbgSDNodeOrder) { 5790 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5791 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5792 // stack slot locations. 5793 // 5794 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5795 // debug values here after optimization: 5796 // 5797 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5798 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5799 // 5800 // Both describe the direct values of their associated variables. 5801 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5802 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5803 } 5804 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5805 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5806 } 5807 5808 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5809 switch (Intrinsic) { 5810 case Intrinsic::smul_fix: 5811 return ISD::SMULFIX; 5812 case Intrinsic::umul_fix: 5813 return ISD::UMULFIX; 5814 case Intrinsic::smul_fix_sat: 5815 return ISD::SMULFIXSAT; 5816 case Intrinsic::umul_fix_sat: 5817 return ISD::UMULFIXSAT; 5818 case Intrinsic::sdiv_fix: 5819 return ISD::SDIVFIX; 5820 case Intrinsic::udiv_fix: 5821 return ISD::UDIVFIX; 5822 case Intrinsic::sdiv_fix_sat: 5823 return ISD::SDIVFIXSAT; 5824 case Intrinsic::udiv_fix_sat: 5825 return ISD::UDIVFIXSAT; 5826 default: 5827 llvm_unreachable("Unhandled fixed point intrinsic"); 5828 } 5829 } 5830 5831 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5832 const char *FunctionName) { 5833 assert(FunctionName && "FunctionName must not be nullptr"); 5834 SDValue Callee = DAG.getExternalSymbol( 5835 FunctionName, 5836 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5837 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 5838 } 5839 5840 /// Given a @llvm.call.preallocated.setup, return the corresponding 5841 /// preallocated call. 5842 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5843 assert(cast<CallBase>(PreallocatedSetup) 5844 ->getCalledFunction() 5845 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5846 "expected call_preallocated_setup Value"); 5847 for (const auto *U : PreallocatedSetup->users()) { 5848 auto *UseCall = cast<CallBase>(U); 5849 const Function *Fn = UseCall->getCalledFunction(); 5850 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5851 return UseCall; 5852 } 5853 } 5854 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5855 } 5856 5857 /// Lower the call to the specified intrinsic function. 5858 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5859 unsigned Intrinsic) { 5860 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5861 SDLoc sdl = getCurSDLoc(); 5862 DebugLoc dl = getCurDebugLoc(); 5863 SDValue Res; 5864 5865 SDNodeFlags Flags; 5866 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 5867 Flags.copyFMF(*FPOp); 5868 5869 switch (Intrinsic) { 5870 default: 5871 // By default, turn this into a target intrinsic node. 5872 visitTargetIntrinsic(I, Intrinsic); 5873 return; 5874 case Intrinsic::vscale: { 5875 match(&I, m_VScale(DAG.getDataLayout())); 5876 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5877 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1))); 5878 return; 5879 } 5880 case Intrinsic::vastart: visitVAStart(I); return; 5881 case Intrinsic::vaend: visitVAEnd(I); return; 5882 case Intrinsic::vacopy: visitVACopy(I); return; 5883 case Intrinsic::returnaddress: 5884 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5885 TLI.getValueType(DAG.getDataLayout(), I.getType()), 5886 getValue(I.getArgOperand(0)))); 5887 return; 5888 case Intrinsic::addressofreturnaddress: 5889 setValue(&I, 5890 DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5891 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 5892 return; 5893 case Intrinsic::sponentry: 5894 setValue(&I, 5895 DAG.getNode(ISD::SPONENTRY, sdl, 5896 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 5897 return; 5898 case Intrinsic::frameaddress: 5899 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5900 TLI.getFrameIndexTy(DAG.getDataLayout()), 5901 getValue(I.getArgOperand(0)))); 5902 return; 5903 case Intrinsic::read_volatile_register: 5904 case Intrinsic::read_register: { 5905 Value *Reg = I.getArgOperand(0); 5906 SDValue Chain = getRoot(); 5907 SDValue RegName = 5908 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5909 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5910 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5911 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5912 setValue(&I, Res); 5913 DAG.setRoot(Res.getValue(1)); 5914 return; 5915 } 5916 case Intrinsic::write_register: { 5917 Value *Reg = I.getArgOperand(0); 5918 Value *RegValue = I.getArgOperand(1); 5919 SDValue Chain = getRoot(); 5920 SDValue RegName = 5921 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5922 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5923 RegName, getValue(RegValue))); 5924 return; 5925 } 5926 case Intrinsic::memcpy: { 5927 const auto &MCI = cast<MemCpyInst>(I); 5928 SDValue Op1 = getValue(I.getArgOperand(0)); 5929 SDValue Op2 = getValue(I.getArgOperand(1)); 5930 SDValue Op3 = getValue(I.getArgOperand(2)); 5931 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5932 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5933 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5934 Align Alignment = std::min(DstAlign, SrcAlign); 5935 bool isVol = MCI.isVolatile(); 5936 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5937 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5938 // node. 5939 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5940 SDValue MC = DAG.getMemcpy( 5941 Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5942 /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)), 5943 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 5944 updateDAGForMaybeTailCall(MC); 5945 return; 5946 } 5947 case Intrinsic::memcpy_inline: { 5948 const auto &MCI = cast<MemCpyInlineInst>(I); 5949 SDValue Dst = getValue(I.getArgOperand(0)); 5950 SDValue Src = getValue(I.getArgOperand(1)); 5951 SDValue Size = getValue(I.getArgOperand(2)); 5952 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 5953 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 5954 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5955 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5956 Align Alignment = std::min(DstAlign, SrcAlign); 5957 bool isVol = MCI.isVolatile(); 5958 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5959 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5960 // node. 5961 SDValue MC = DAG.getMemcpy( 5962 getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 5963 /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)), 5964 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 5965 updateDAGForMaybeTailCall(MC); 5966 return; 5967 } 5968 case Intrinsic::memset: { 5969 const auto &MSI = cast<MemSetInst>(I); 5970 SDValue Op1 = getValue(I.getArgOperand(0)); 5971 SDValue Op2 = getValue(I.getArgOperand(1)); 5972 SDValue Op3 = getValue(I.getArgOperand(2)); 5973 // @llvm.memset defines 0 and 1 to both mean no alignment. 5974 Align Alignment = MSI.getDestAlign().valueOrOne(); 5975 bool isVol = MSI.isVolatile(); 5976 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5977 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5978 SDValue MS = DAG.getMemset( 5979 Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false, 5980 isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata()); 5981 updateDAGForMaybeTailCall(MS); 5982 return; 5983 } 5984 case Intrinsic::memset_inline: { 5985 const auto &MSII = cast<MemSetInlineInst>(I); 5986 SDValue Dst = getValue(I.getArgOperand(0)); 5987 SDValue Value = getValue(I.getArgOperand(1)); 5988 SDValue Size = getValue(I.getArgOperand(2)); 5989 assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size"); 5990 // @llvm.memset defines 0 and 1 to both mean no alignment. 5991 Align DstAlign = MSII.getDestAlign().valueOrOne(); 5992 bool isVol = MSII.isVolatile(); 5993 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5994 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5995 SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol, 5996 /* AlwaysInline */ true, isTC, 5997 MachinePointerInfo(I.getArgOperand(0)), 5998 I.getAAMetadata()); 5999 updateDAGForMaybeTailCall(MC); 6000 return; 6001 } 6002 case Intrinsic::memmove: { 6003 const auto &MMI = cast<MemMoveInst>(I); 6004 SDValue Op1 = getValue(I.getArgOperand(0)); 6005 SDValue Op2 = getValue(I.getArgOperand(1)); 6006 SDValue Op3 = getValue(I.getArgOperand(2)); 6007 // @llvm.memmove defines 0 and 1 to both mean no alignment. 6008 Align DstAlign = MMI.getDestAlign().valueOrOne(); 6009 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 6010 Align Alignment = std::min(DstAlign, SrcAlign); 6011 bool isVol = MMI.isVolatile(); 6012 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6013 // FIXME: Support passing different dest/src alignments to the memmove DAG 6014 // node. 6015 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6016 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6017 isTC, MachinePointerInfo(I.getArgOperand(0)), 6018 MachinePointerInfo(I.getArgOperand(1)), 6019 I.getAAMetadata(), AA); 6020 updateDAGForMaybeTailCall(MM); 6021 return; 6022 } 6023 case Intrinsic::memcpy_element_unordered_atomic: { 6024 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 6025 SDValue Dst = getValue(MI.getRawDest()); 6026 SDValue Src = getValue(MI.getRawSource()); 6027 SDValue Length = getValue(MI.getLength()); 6028 6029 Type *LengthTy = MI.getLength()->getType(); 6030 unsigned ElemSz = MI.getElementSizeInBytes(); 6031 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6032 SDValue MC = 6033 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6034 isTC, MachinePointerInfo(MI.getRawDest()), 6035 MachinePointerInfo(MI.getRawSource())); 6036 updateDAGForMaybeTailCall(MC); 6037 return; 6038 } 6039 case Intrinsic::memmove_element_unordered_atomic: { 6040 auto &MI = cast<AtomicMemMoveInst>(I); 6041 SDValue Dst = getValue(MI.getRawDest()); 6042 SDValue Src = getValue(MI.getRawSource()); 6043 SDValue Length = getValue(MI.getLength()); 6044 6045 Type *LengthTy = MI.getLength()->getType(); 6046 unsigned ElemSz = MI.getElementSizeInBytes(); 6047 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6048 SDValue MC = 6049 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6050 isTC, MachinePointerInfo(MI.getRawDest()), 6051 MachinePointerInfo(MI.getRawSource())); 6052 updateDAGForMaybeTailCall(MC); 6053 return; 6054 } 6055 case Intrinsic::memset_element_unordered_atomic: { 6056 auto &MI = cast<AtomicMemSetInst>(I); 6057 SDValue Dst = getValue(MI.getRawDest()); 6058 SDValue Val = getValue(MI.getValue()); 6059 SDValue Length = getValue(MI.getLength()); 6060 6061 Type *LengthTy = MI.getLength()->getType(); 6062 unsigned ElemSz = MI.getElementSizeInBytes(); 6063 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6064 SDValue MC = 6065 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz, 6066 isTC, MachinePointerInfo(MI.getRawDest())); 6067 updateDAGForMaybeTailCall(MC); 6068 return; 6069 } 6070 case Intrinsic::call_preallocated_setup: { 6071 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 6072 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6073 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 6074 getRoot(), SrcValue); 6075 setValue(&I, Res); 6076 DAG.setRoot(Res); 6077 return; 6078 } 6079 case Intrinsic::call_preallocated_arg: { 6080 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 6081 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6082 SDValue Ops[3]; 6083 Ops[0] = getRoot(); 6084 Ops[1] = SrcValue; 6085 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 6086 MVT::i32); // arg index 6087 SDValue Res = DAG.getNode( 6088 ISD::PREALLOCATED_ARG, sdl, 6089 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 6090 setValue(&I, Res); 6091 DAG.setRoot(Res.getValue(1)); 6092 return; 6093 } 6094 case Intrinsic::dbg_addr: 6095 case Intrinsic::dbg_declare: { 6096 // Debug intrinsics are handled seperately in assignment tracking mode. 6097 if (getEnableAssignmentTracking()) 6098 return; 6099 // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e. 6100 // they are non-variadic. 6101 const auto &DI = cast<DbgVariableIntrinsic>(I); 6102 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 6103 DILocalVariable *Variable = DI.getVariable(); 6104 DIExpression *Expression = DI.getExpression(); 6105 dropDanglingDebugInfo(Variable, Expression); 6106 assert(Variable && "Missing variable"); 6107 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 6108 << "\n"); 6109 // Check if address has undef value. 6110 const Value *Address = DI.getVariableLocationOp(0); 6111 if (!Address || isa<UndefValue>(Address) || 6112 (Address->use_empty() && !isa<Argument>(Address))) { 6113 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6114 << " (bad/undef/unused-arg address)\n"); 6115 return; 6116 } 6117 6118 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 6119 6120 // Check if this variable can be described by a frame index, typically 6121 // either as a static alloca or a byval parameter. 6122 int FI = std::numeric_limits<int>::max(); 6123 if (const auto *AI = 6124 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 6125 if (AI->isStaticAlloca()) { 6126 auto I = FuncInfo.StaticAllocaMap.find(AI); 6127 if (I != FuncInfo.StaticAllocaMap.end()) 6128 FI = I->second; 6129 } 6130 } else if (const auto *Arg = dyn_cast<Argument>( 6131 Address->stripInBoundsConstantOffsets())) { 6132 FI = FuncInfo.getArgumentFrameIndex(Arg); 6133 } 6134 6135 // llvm.dbg.addr is control dependent and always generates indirect 6136 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 6137 // the MachineFunction variable table. 6138 if (FI != std::numeric_limits<int>::max()) { 6139 if (Intrinsic == Intrinsic::dbg_addr) { 6140 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 6141 Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true, 6142 dl, SDNodeOrder); 6143 DAG.AddDbgValue(SDV, isParameter); 6144 } else { 6145 LLVM_DEBUG(dbgs() << "Skipping " << DI 6146 << " (variable info stashed in MF side table)\n"); 6147 } 6148 return; 6149 } 6150 6151 SDValue &N = NodeMap[Address]; 6152 if (!N.getNode() && isa<Argument>(Address)) 6153 // Check unused arguments map. 6154 N = UnusedArgNodeMap[Address]; 6155 SDDbgValue *SDV; 6156 if (N.getNode()) { 6157 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 6158 Address = BCI->getOperand(0); 6159 // Parameters are handled specially. 6160 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 6161 if (isParameter && FINode) { 6162 // Byval parameter. We have a frame index at this point. 6163 SDV = 6164 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 6165 /*IsIndirect*/ true, dl, SDNodeOrder); 6166 } else if (isa<Argument>(Address)) { 6167 // Address is an argument, so try to emit its dbg value using 6168 // virtual register info from the FuncInfo.ValueMap. 6169 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 6170 FuncArgumentDbgValueKind::Declare, N); 6171 return; 6172 } else { 6173 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 6174 true, dl, SDNodeOrder); 6175 } 6176 DAG.AddDbgValue(SDV, isParameter); 6177 } else { 6178 // If Address is an argument then try to emit its dbg value using 6179 // virtual register info from the FuncInfo.ValueMap. 6180 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 6181 FuncArgumentDbgValueKind::Declare, N)) { 6182 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6183 << " (could not emit func-arg dbg_value)\n"); 6184 } 6185 } 6186 return; 6187 } 6188 case Intrinsic::dbg_label: { 6189 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6190 DILabel *Label = DI.getLabel(); 6191 assert(Label && "Missing label"); 6192 6193 SDDbgLabel *SDV; 6194 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6195 DAG.AddDbgLabel(SDV); 6196 return; 6197 } 6198 case Intrinsic::dbg_assign: { 6199 // Debug intrinsics are handled seperately in assignment tracking mode. 6200 assert(getEnableAssignmentTracking() && 6201 "expected assignment tracking to be enabled"); 6202 return; 6203 } 6204 case Intrinsic::dbg_value: { 6205 // Debug intrinsics are handled seperately in assignment tracking mode. 6206 if (getEnableAssignmentTracking()) 6207 return; 6208 const DbgValueInst &DI = cast<DbgValueInst>(I); 6209 assert(DI.getVariable() && "Missing variable"); 6210 6211 DILocalVariable *Variable = DI.getVariable(); 6212 DIExpression *Expression = DI.getExpression(); 6213 dropDanglingDebugInfo(Variable, Expression); 6214 SmallVector<Value *, 4> Values(DI.getValues()); 6215 if (Values.empty()) 6216 return; 6217 6218 if (llvm::is_contained(Values, nullptr)) 6219 return; 6220 6221 bool IsVariadic = DI.hasArgList(); 6222 if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(), 6223 SDNodeOrder, IsVariadic)) 6224 addDanglingDebugInfo(&DI, SDNodeOrder); 6225 return; 6226 } 6227 6228 case Intrinsic::eh_typeid_for: { 6229 // Find the type id for the given typeinfo. 6230 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6231 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6232 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6233 setValue(&I, Res); 6234 return; 6235 } 6236 6237 case Intrinsic::eh_return_i32: 6238 case Intrinsic::eh_return_i64: 6239 DAG.getMachineFunction().setCallsEHReturn(true); 6240 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6241 MVT::Other, 6242 getControlRoot(), 6243 getValue(I.getArgOperand(0)), 6244 getValue(I.getArgOperand(1)))); 6245 return; 6246 case Intrinsic::eh_unwind_init: 6247 DAG.getMachineFunction().setCallsUnwindInit(true); 6248 return; 6249 case Intrinsic::eh_dwarf_cfa: 6250 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6251 TLI.getPointerTy(DAG.getDataLayout()), 6252 getValue(I.getArgOperand(0)))); 6253 return; 6254 case Intrinsic::eh_sjlj_callsite: { 6255 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6256 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0)); 6257 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6258 6259 MMI.setCurrentCallSite(CI->getZExtValue()); 6260 return; 6261 } 6262 case Intrinsic::eh_sjlj_functioncontext: { 6263 // Get and store the index of the function context. 6264 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6265 AllocaInst *FnCtx = 6266 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6267 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6268 MFI.setFunctionContextIndex(FI); 6269 return; 6270 } 6271 case Intrinsic::eh_sjlj_setjmp: { 6272 SDValue Ops[2]; 6273 Ops[0] = getRoot(); 6274 Ops[1] = getValue(I.getArgOperand(0)); 6275 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6276 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6277 setValue(&I, Op.getValue(0)); 6278 DAG.setRoot(Op.getValue(1)); 6279 return; 6280 } 6281 case Intrinsic::eh_sjlj_longjmp: 6282 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6283 getRoot(), getValue(I.getArgOperand(0)))); 6284 return; 6285 case Intrinsic::eh_sjlj_setup_dispatch: 6286 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6287 getRoot())); 6288 return; 6289 case Intrinsic::masked_gather: 6290 visitMaskedGather(I); 6291 return; 6292 case Intrinsic::masked_load: 6293 visitMaskedLoad(I); 6294 return; 6295 case Intrinsic::masked_scatter: 6296 visitMaskedScatter(I); 6297 return; 6298 case Intrinsic::masked_store: 6299 visitMaskedStore(I); 6300 return; 6301 case Intrinsic::masked_expandload: 6302 visitMaskedLoad(I, true /* IsExpanding */); 6303 return; 6304 case Intrinsic::masked_compressstore: 6305 visitMaskedStore(I, true /* IsCompressing */); 6306 return; 6307 case Intrinsic::powi: 6308 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6309 getValue(I.getArgOperand(1)), DAG)); 6310 return; 6311 case Intrinsic::log: 6312 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6313 return; 6314 case Intrinsic::log2: 6315 setValue(&I, 6316 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6317 return; 6318 case Intrinsic::log10: 6319 setValue(&I, 6320 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6321 return; 6322 case Intrinsic::exp: 6323 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6324 return; 6325 case Intrinsic::exp2: 6326 setValue(&I, 6327 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6328 return; 6329 case Intrinsic::pow: 6330 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6331 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6332 return; 6333 case Intrinsic::sqrt: 6334 case Intrinsic::fabs: 6335 case Intrinsic::sin: 6336 case Intrinsic::cos: 6337 case Intrinsic::floor: 6338 case Intrinsic::ceil: 6339 case Intrinsic::trunc: 6340 case Intrinsic::rint: 6341 case Intrinsic::nearbyint: 6342 case Intrinsic::round: 6343 case Intrinsic::roundeven: 6344 case Intrinsic::canonicalize: { 6345 unsigned Opcode; 6346 switch (Intrinsic) { 6347 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6348 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6349 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6350 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6351 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6352 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6353 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6354 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6355 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6356 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6357 case Intrinsic::round: Opcode = ISD::FROUND; break; 6358 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6359 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6360 } 6361 6362 setValue(&I, DAG.getNode(Opcode, sdl, 6363 getValue(I.getArgOperand(0)).getValueType(), 6364 getValue(I.getArgOperand(0)), Flags)); 6365 return; 6366 } 6367 case Intrinsic::lround: 6368 case Intrinsic::llround: 6369 case Intrinsic::lrint: 6370 case Intrinsic::llrint: { 6371 unsigned Opcode; 6372 switch (Intrinsic) { 6373 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6374 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6375 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6376 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6377 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6378 } 6379 6380 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6381 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6382 getValue(I.getArgOperand(0)))); 6383 return; 6384 } 6385 case Intrinsic::minnum: 6386 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6387 getValue(I.getArgOperand(0)).getValueType(), 6388 getValue(I.getArgOperand(0)), 6389 getValue(I.getArgOperand(1)), Flags)); 6390 return; 6391 case Intrinsic::maxnum: 6392 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6393 getValue(I.getArgOperand(0)).getValueType(), 6394 getValue(I.getArgOperand(0)), 6395 getValue(I.getArgOperand(1)), Flags)); 6396 return; 6397 case Intrinsic::minimum: 6398 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6399 getValue(I.getArgOperand(0)).getValueType(), 6400 getValue(I.getArgOperand(0)), 6401 getValue(I.getArgOperand(1)), Flags)); 6402 return; 6403 case Intrinsic::maximum: 6404 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6405 getValue(I.getArgOperand(0)).getValueType(), 6406 getValue(I.getArgOperand(0)), 6407 getValue(I.getArgOperand(1)), Flags)); 6408 return; 6409 case Intrinsic::copysign: 6410 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6411 getValue(I.getArgOperand(0)).getValueType(), 6412 getValue(I.getArgOperand(0)), 6413 getValue(I.getArgOperand(1)), Flags)); 6414 return; 6415 case Intrinsic::arithmetic_fence: { 6416 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl, 6417 getValue(I.getArgOperand(0)).getValueType(), 6418 getValue(I.getArgOperand(0)), Flags)); 6419 return; 6420 } 6421 case Intrinsic::fma: 6422 setValue(&I, DAG.getNode( 6423 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6424 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6425 getValue(I.getArgOperand(2)), Flags)); 6426 return; 6427 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6428 case Intrinsic::INTRINSIC: 6429 #include "llvm/IR/ConstrainedOps.def" 6430 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6431 return; 6432 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6433 #include "llvm/IR/VPIntrinsics.def" 6434 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6435 return; 6436 case Intrinsic::fptrunc_round: { 6437 // Get the last argument, the metadata and convert it to an integer in the 6438 // call 6439 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata(); 6440 std::optional<RoundingMode> RoundMode = 6441 convertStrToRoundingMode(cast<MDString>(MD)->getString()); 6442 6443 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6444 6445 // Propagate fast-math-flags from IR to node(s). 6446 SDNodeFlags Flags; 6447 Flags.copyFMF(*cast<FPMathOperator>(&I)); 6448 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 6449 6450 SDValue Result; 6451 Result = DAG.getNode( 6452 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)), 6453 DAG.getTargetConstant((int)*RoundMode, sdl, 6454 TLI.getPointerTy(DAG.getDataLayout()))); 6455 setValue(&I, Result); 6456 6457 return; 6458 } 6459 case Intrinsic::fmuladd: { 6460 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6461 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6462 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6463 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6464 getValue(I.getArgOperand(0)).getValueType(), 6465 getValue(I.getArgOperand(0)), 6466 getValue(I.getArgOperand(1)), 6467 getValue(I.getArgOperand(2)), Flags)); 6468 } else { 6469 // TODO: Intrinsic calls should have fast-math-flags. 6470 SDValue Mul = DAG.getNode( 6471 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6472 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6473 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6474 getValue(I.getArgOperand(0)).getValueType(), 6475 Mul, getValue(I.getArgOperand(2)), Flags); 6476 setValue(&I, Add); 6477 } 6478 return; 6479 } 6480 case Intrinsic::convert_to_fp16: 6481 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6482 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6483 getValue(I.getArgOperand(0)), 6484 DAG.getTargetConstant(0, sdl, 6485 MVT::i32)))); 6486 return; 6487 case Intrinsic::convert_from_fp16: 6488 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6489 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6490 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6491 getValue(I.getArgOperand(0))))); 6492 return; 6493 case Intrinsic::fptosi_sat: { 6494 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6495 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 6496 getValue(I.getArgOperand(0)), 6497 DAG.getValueType(VT.getScalarType()))); 6498 return; 6499 } 6500 case Intrinsic::fptoui_sat: { 6501 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6502 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 6503 getValue(I.getArgOperand(0)), 6504 DAG.getValueType(VT.getScalarType()))); 6505 return; 6506 } 6507 case Intrinsic::set_rounding: 6508 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6509 {getRoot(), getValue(I.getArgOperand(0))}); 6510 setValue(&I, Res); 6511 DAG.setRoot(Res.getValue(0)); 6512 return; 6513 case Intrinsic::is_fpclass: { 6514 const DataLayout DLayout = DAG.getDataLayout(); 6515 EVT DestVT = TLI.getValueType(DLayout, I.getType()); 6516 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType()); 6517 unsigned Test = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6518 MachineFunction &MF = DAG.getMachineFunction(); 6519 const Function &F = MF.getFunction(); 6520 SDValue Op = getValue(I.getArgOperand(0)); 6521 SDNodeFlags Flags; 6522 Flags.setNoFPExcept( 6523 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP)); 6524 // If ISD::IS_FPCLASS should be expanded, do it right now, because the 6525 // expansion can use illegal types. Making expansion early allows 6526 // legalizing these types prior to selection. 6527 if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) { 6528 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG); 6529 setValue(&I, Result); 6530 return; 6531 } 6532 6533 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32); 6534 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags); 6535 setValue(&I, V); 6536 return; 6537 } 6538 case Intrinsic::pcmarker: { 6539 SDValue Tmp = getValue(I.getArgOperand(0)); 6540 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6541 return; 6542 } 6543 case Intrinsic::readcyclecounter: { 6544 SDValue Op = getRoot(); 6545 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6546 DAG.getVTList(MVT::i64, MVT::Other), Op); 6547 setValue(&I, Res); 6548 DAG.setRoot(Res.getValue(1)); 6549 return; 6550 } 6551 case Intrinsic::bitreverse: 6552 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6553 getValue(I.getArgOperand(0)).getValueType(), 6554 getValue(I.getArgOperand(0)))); 6555 return; 6556 case Intrinsic::bswap: 6557 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6558 getValue(I.getArgOperand(0)).getValueType(), 6559 getValue(I.getArgOperand(0)))); 6560 return; 6561 case Intrinsic::cttz: { 6562 SDValue Arg = getValue(I.getArgOperand(0)); 6563 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6564 EVT Ty = Arg.getValueType(); 6565 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6566 sdl, Ty, Arg)); 6567 return; 6568 } 6569 case Intrinsic::ctlz: { 6570 SDValue Arg = getValue(I.getArgOperand(0)); 6571 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6572 EVT Ty = Arg.getValueType(); 6573 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6574 sdl, Ty, Arg)); 6575 return; 6576 } 6577 case Intrinsic::ctpop: { 6578 SDValue Arg = getValue(I.getArgOperand(0)); 6579 EVT Ty = Arg.getValueType(); 6580 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6581 return; 6582 } 6583 case Intrinsic::fshl: 6584 case Intrinsic::fshr: { 6585 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6586 SDValue X = getValue(I.getArgOperand(0)); 6587 SDValue Y = getValue(I.getArgOperand(1)); 6588 SDValue Z = getValue(I.getArgOperand(2)); 6589 EVT VT = X.getValueType(); 6590 6591 if (X == Y) { 6592 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6593 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6594 } else { 6595 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6596 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6597 } 6598 return; 6599 } 6600 case Intrinsic::sadd_sat: { 6601 SDValue Op1 = getValue(I.getArgOperand(0)); 6602 SDValue Op2 = getValue(I.getArgOperand(1)); 6603 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6604 return; 6605 } 6606 case Intrinsic::uadd_sat: { 6607 SDValue Op1 = getValue(I.getArgOperand(0)); 6608 SDValue Op2 = getValue(I.getArgOperand(1)); 6609 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6610 return; 6611 } 6612 case Intrinsic::ssub_sat: { 6613 SDValue Op1 = getValue(I.getArgOperand(0)); 6614 SDValue Op2 = getValue(I.getArgOperand(1)); 6615 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6616 return; 6617 } 6618 case Intrinsic::usub_sat: { 6619 SDValue Op1 = getValue(I.getArgOperand(0)); 6620 SDValue Op2 = getValue(I.getArgOperand(1)); 6621 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6622 return; 6623 } 6624 case Intrinsic::sshl_sat: { 6625 SDValue Op1 = getValue(I.getArgOperand(0)); 6626 SDValue Op2 = getValue(I.getArgOperand(1)); 6627 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6628 return; 6629 } 6630 case Intrinsic::ushl_sat: { 6631 SDValue Op1 = getValue(I.getArgOperand(0)); 6632 SDValue Op2 = getValue(I.getArgOperand(1)); 6633 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6634 return; 6635 } 6636 case Intrinsic::smul_fix: 6637 case Intrinsic::umul_fix: 6638 case Intrinsic::smul_fix_sat: 6639 case Intrinsic::umul_fix_sat: { 6640 SDValue Op1 = getValue(I.getArgOperand(0)); 6641 SDValue Op2 = getValue(I.getArgOperand(1)); 6642 SDValue Op3 = getValue(I.getArgOperand(2)); 6643 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6644 Op1.getValueType(), Op1, Op2, Op3)); 6645 return; 6646 } 6647 case Intrinsic::sdiv_fix: 6648 case Intrinsic::udiv_fix: 6649 case Intrinsic::sdiv_fix_sat: 6650 case Intrinsic::udiv_fix_sat: { 6651 SDValue Op1 = getValue(I.getArgOperand(0)); 6652 SDValue Op2 = getValue(I.getArgOperand(1)); 6653 SDValue Op3 = getValue(I.getArgOperand(2)); 6654 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6655 Op1, Op2, Op3, DAG, TLI)); 6656 return; 6657 } 6658 case Intrinsic::smax: { 6659 SDValue Op1 = getValue(I.getArgOperand(0)); 6660 SDValue Op2 = getValue(I.getArgOperand(1)); 6661 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6662 return; 6663 } 6664 case Intrinsic::smin: { 6665 SDValue Op1 = getValue(I.getArgOperand(0)); 6666 SDValue Op2 = getValue(I.getArgOperand(1)); 6667 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6668 return; 6669 } 6670 case Intrinsic::umax: { 6671 SDValue Op1 = getValue(I.getArgOperand(0)); 6672 SDValue Op2 = getValue(I.getArgOperand(1)); 6673 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6674 return; 6675 } 6676 case Intrinsic::umin: { 6677 SDValue Op1 = getValue(I.getArgOperand(0)); 6678 SDValue Op2 = getValue(I.getArgOperand(1)); 6679 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6680 return; 6681 } 6682 case Intrinsic::abs: { 6683 // TODO: Preserve "int min is poison" arg in SDAG? 6684 SDValue Op1 = getValue(I.getArgOperand(0)); 6685 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6686 return; 6687 } 6688 case Intrinsic::stacksave: { 6689 SDValue Op = getRoot(); 6690 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6691 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6692 setValue(&I, Res); 6693 DAG.setRoot(Res.getValue(1)); 6694 return; 6695 } 6696 case Intrinsic::stackrestore: 6697 Res = getValue(I.getArgOperand(0)); 6698 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6699 return; 6700 case Intrinsic::get_dynamic_area_offset: { 6701 SDValue Op = getRoot(); 6702 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6703 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6704 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6705 // target. 6706 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 6707 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6708 " intrinsic!"); 6709 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6710 Op); 6711 DAG.setRoot(Op); 6712 setValue(&I, Res); 6713 return; 6714 } 6715 case Intrinsic::stackguard: { 6716 MachineFunction &MF = DAG.getMachineFunction(); 6717 const Module &M = *MF.getFunction().getParent(); 6718 SDValue Chain = getRoot(); 6719 if (TLI.useLoadStackGuardNode()) { 6720 Res = getLoadStackGuard(DAG, sdl, Chain); 6721 } else { 6722 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6723 const Value *Global = TLI.getSDagStackGuard(M); 6724 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType()); 6725 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6726 MachinePointerInfo(Global, 0), Align, 6727 MachineMemOperand::MOVolatile); 6728 } 6729 if (TLI.useStackGuardXorFP()) 6730 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6731 DAG.setRoot(Chain); 6732 setValue(&I, Res); 6733 return; 6734 } 6735 case Intrinsic::stackprotector: { 6736 // Emit code into the DAG to store the stack guard onto the stack. 6737 MachineFunction &MF = DAG.getMachineFunction(); 6738 MachineFrameInfo &MFI = MF.getFrameInfo(); 6739 SDValue Src, Chain = getRoot(); 6740 6741 if (TLI.useLoadStackGuardNode()) 6742 Src = getLoadStackGuard(DAG, sdl, Chain); 6743 else 6744 Src = getValue(I.getArgOperand(0)); // The guard's value. 6745 6746 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6747 6748 int FI = FuncInfo.StaticAllocaMap[Slot]; 6749 MFI.setStackProtectorIndex(FI); 6750 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6751 6752 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6753 6754 // Store the stack protector onto the stack. 6755 Res = DAG.getStore( 6756 Chain, sdl, Src, FIN, 6757 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 6758 MaybeAlign(), MachineMemOperand::MOVolatile); 6759 setValue(&I, Res); 6760 DAG.setRoot(Res); 6761 return; 6762 } 6763 case Intrinsic::objectsize: 6764 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6765 6766 case Intrinsic::is_constant: 6767 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6768 6769 case Intrinsic::annotation: 6770 case Intrinsic::ptr_annotation: 6771 case Intrinsic::launder_invariant_group: 6772 case Intrinsic::strip_invariant_group: 6773 // Drop the intrinsic, but forward the value 6774 setValue(&I, getValue(I.getOperand(0))); 6775 return; 6776 6777 case Intrinsic::assume: 6778 case Intrinsic::experimental_noalias_scope_decl: 6779 case Intrinsic::var_annotation: 6780 case Intrinsic::sideeffect: 6781 // Discard annotate attributes, noalias scope declarations, assumptions, and 6782 // artificial side-effects. 6783 return; 6784 6785 case Intrinsic::codeview_annotation: { 6786 // Emit a label associated with this metadata. 6787 MachineFunction &MF = DAG.getMachineFunction(); 6788 MCSymbol *Label = 6789 MF.getMMI().getContext().createTempSymbol("annotation", true); 6790 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6791 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6792 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6793 DAG.setRoot(Res); 6794 return; 6795 } 6796 6797 case Intrinsic::init_trampoline: { 6798 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6799 6800 SDValue Ops[6]; 6801 Ops[0] = getRoot(); 6802 Ops[1] = getValue(I.getArgOperand(0)); 6803 Ops[2] = getValue(I.getArgOperand(1)); 6804 Ops[3] = getValue(I.getArgOperand(2)); 6805 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6806 Ops[5] = DAG.getSrcValue(F); 6807 6808 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6809 6810 DAG.setRoot(Res); 6811 return; 6812 } 6813 case Intrinsic::adjust_trampoline: 6814 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6815 TLI.getPointerTy(DAG.getDataLayout()), 6816 getValue(I.getArgOperand(0)))); 6817 return; 6818 case Intrinsic::gcroot: { 6819 assert(DAG.getMachineFunction().getFunction().hasGC() && 6820 "only valid in functions with gc specified, enforced by Verifier"); 6821 assert(GFI && "implied by previous"); 6822 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6823 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6824 6825 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6826 GFI->addStackRoot(FI->getIndex(), TypeMap); 6827 return; 6828 } 6829 case Intrinsic::gcread: 6830 case Intrinsic::gcwrite: 6831 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6832 case Intrinsic::get_rounding: 6833 Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot()); 6834 setValue(&I, Res); 6835 DAG.setRoot(Res.getValue(1)); 6836 return; 6837 6838 case Intrinsic::expect: 6839 // Just replace __builtin_expect(exp, c) with EXP. 6840 setValue(&I, getValue(I.getArgOperand(0))); 6841 return; 6842 6843 case Intrinsic::ubsantrap: 6844 case Intrinsic::debugtrap: 6845 case Intrinsic::trap: { 6846 StringRef TrapFuncName = 6847 I.getAttributes().getFnAttr("trap-func-name").getValueAsString(); 6848 if (TrapFuncName.empty()) { 6849 switch (Intrinsic) { 6850 case Intrinsic::trap: 6851 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 6852 break; 6853 case Intrinsic::debugtrap: 6854 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 6855 break; 6856 case Intrinsic::ubsantrap: 6857 DAG.setRoot(DAG.getNode( 6858 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 6859 DAG.getTargetConstant( 6860 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 6861 MVT::i32))); 6862 break; 6863 default: llvm_unreachable("unknown trap intrinsic"); 6864 } 6865 return; 6866 } 6867 TargetLowering::ArgListTy Args; 6868 if (Intrinsic == Intrinsic::ubsantrap) { 6869 Args.push_back(TargetLoweringBase::ArgListEntry()); 6870 Args[0].Val = I.getArgOperand(0); 6871 Args[0].Node = getValue(Args[0].Val); 6872 Args[0].Ty = Args[0].Val->getType(); 6873 } 6874 6875 TargetLowering::CallLoweringInfo CLI(DAG); 6876 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6877 CallingConv::C, I.getType(), 6878 DAG.getExternalSymbol(TrapFuncName.data(), 6879 TLI.getPointerTy(DAG.getDataLayout())), 6880 std::move(Args)); 6881 6882 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6883 DAG.setRoot(Result.second); 6884 return; 6885 } 6886 6887 case Intrinsic::uadd_with_overflow: 6888 case Intrinsic::sadd_with_overflow: 6889 case Intrinsic::usub_with_overflow: 6890 case Intrinsic::ssub_with_overflow: 6891 case Intrinsic::umul_with_overflow: 6892 case Intrinsic::smul_with_overflow: { 6893 ISD::NodeType Op; 6894 switch (Intrinsic) { 6895 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6896 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6897 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6898 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6899 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6900 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6901 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6902 } 6903 SDValue Op1 = getValue(I.getArgOperand(0)); 6904 SDValue Op2 = getValue(I.getArgOperand(1)); 6905 6906 EVT ResultVT = Op1.getValueType(); 6907 EVT OverflowVT = MVT::i1; 6908 if (ResultVT.isVector()) 6909 OverflowVT = EVT::getVectorVT( 6910 *Context, OverflowVT, ResultVT.getVectorElementCount()); 6911 6912 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6913 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6914 return; 6915 } 6916 case Intrinsic::prefetch: { 6917 SDValue Ops[5]; 6918 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6919 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6920 Ops[0] = DAG.getRoot(); 6921 Ops[1] = getValue(I.getArgOperand(0)); 6922 Ops[2] = getValue(I.getArgOperand(1)); 6923 Ops[3] = getValue(I.getArgOperand(2)); 6924 Ops[4] = getValue(I.getArgOperand(3)); 6925 SDValue Result = DAG.getMemIntrinsicNode( 6926 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 6927 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 6928 /* align */ std::nullopt, Flags); 6929 6930 // Chain the prefetch in parallell with any pending loads, to stay out of 6931 // the way of later optimizations. 6932 PendingLoads.push_back(Result); 6933 Result = getRoot(); 6934 DAG.setRoot(Result); 6935 return; 6936 } 6937 case Intrinsic::lifetime_start: 6938 case Intrinsic::lifetime_end: { 6939 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6940 // Stack coloring is not enabled in O0, discard region information. 6941 if (TM.getOptLevel() == CodeGenOpt::None) 6942 return; 6943 6944 const int64_t ObjectSize = 6945 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6946 Value *const ObjectPtr = I.getArgOperand(1); 6947 SmallVector<const Value *, 4> Allocas; 6948 getUnderlyingObjects(ObjectPtr, Allocas); 6949 6950 for (const Value *Alloca : Allocas) { 6951 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 6952 6953 // Could not find an Alloca. 6954 if (!LifetimeObject) 6955 continue; 6956 6957 // First check that the Alloca is static, otherwise it won't have a 6958 // valid frame index. 6959 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6960 if (SI == FuncInfo.StaticAllocaMap.end()) 6961 return; 6962 6963 const int FrameIndex = SI->second; 6964 int64_t Offset; 6965 if (GetPointerBaseWithConstantOffset( 6966 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6967 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6968 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6969 Offset); 6970 DAG.setRoot(Res); 6971 } 6972 return; 6973 } 6974 case Intrinsic::pseudoprobe: { 6975 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 6976 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6977 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 6978 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 6979 DAG.setRoot(Res); 6980 return; 6981 } 6982 case Intrinsic::invariant_start: 6983 // Discard region information. 6984 setValue(&I, 6985 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType()))); 6986 return; 6987 case Intrinsic::invariant_end: 6988 // Discard region information. 6989 return; 6990 case Intrinsic::clear_cache: 6991 /// FunctionName may be null. 6992 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6993 lowerCallToExternalSymbol(I, FunctionName); 6994 return; 6995 case Intrinsic::donothing: 6996 case Intrinsic::seh_try_begin: 6997 case Intrinsic::seh_scope_begin: 6998 case Intrinsic::seh_try_end: 6999 case Intrinsic::seh_scope_end: 7000 // ignore 7001 return; 7002 case Intrinsic::experimental_stackmap: 7003 visitStackmap(I); 7004 return; 7005 case Intrinsic::experimental_patchpoint_void: 7006 case Intrinsic::experimental_patchpoint_i64: 7007 visitPatchpoint(I); 7008 return; 7009 case Intrinsic::experimental_gc_statepoint: 7010 LowerStatepoint(cast<GCStatepointInst>(I)); 7011 return; 7012 case Intrinsic::experimental_gc_result: 7013 visitGCResult(cast<GCResultInst>(I)); 7014 return; 7015 case Intrinsic::experimental_gc_relocate: 7016 visitGCRelocate(cast<GCRelocateInst>(I)); 7017 return; 7018 case Intrinsic::instrprof_cover: 7019 llvm_unreachable("instrprof failed to lower a cover"); 7020 case Intrinsic::instrprof_increment: 7021 llvm_unreachable("instrprof failed to lower an increment"); 7022 case Intrinsic::instrprof_value_profile: 7023 llvm_unreachable("instrprof failed to lower a value profiling call"); 7024 case Intrinsic::localescape: { 7025 MachineFunction &MF = DAG.getMachineFunction(); 7026 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 7027 7028 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 7029 // is the same on all targets. 7030 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) { 7031 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 7032 if (isa<ConstantPointerNull>(Arg)) 7033 continue; // Skip null pointers. They represent a hole in index space. 7034 AllocaInst *Slot = cast<AllocaInst>(Arg); 7035 assert(FuncInfo.StaticAllocaMap.count(Slot) && 7036 "can only escape static allocas"); 7037 int FI = FuncInfo.StaticAllocaMap[Slot]; 7038 MCSymbol *FrameAllocSym = 7039 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7040 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 7041 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 7042 TII->get(TargetOpcode::LOCAL_ESCAPE)) 7043 .addSym(FrameAllocSym) 7044 .addFrameIndex(FI); 7045 } 7046 7047 return; 7048 } 7049 7050 case Intrinsic::localrecover: { 7051 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 7052 MachineFunction &MF = DAG.getMachineFunction(); 7053 7054 // Get the symbol that defines the frame offset. 7055 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 7056 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 7057 unsigned IdxVal = 7058 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 7059 MCSymbol *FrameAllocSym = 7060 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7061 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 7062 7063 Value *FP = I.getArgOperand(1); 7064 SDValue FPVal = getValue(FP); 7065 EVT PtrVT = FPVal.getValueType(); 7066 7067 // Create a MCSymbol for the label to avoid any target lowering 7068 // that would make this PC relative. 7069 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 7070 SDValue OffsetVal = 7071 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 7072 7073 // Add the offset to the FP. 7074 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 7075 setValue(&I, Add); 7076 7077 return; 7078 } 7079 7080 case Intrinsic::eh_exceptionpointer: 7081 case Intrinsic::eh_exceptioncode: { 7082 // Get the exception pointer vreg, copy from it, and resize it to fit. 7083 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 7084 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 7085 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 7086 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 7087 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT); 7088 if (Intrinsic == Intrinsic::eh_exceptioncode) 7089 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32); 7090 setValue(&I, N); 7091 return; 7092 } 7093 case Intrinsic::xray_customevent: { 7094 // Here we want to make sure that the intrinsic behaves as if it has a 7095 // specific calling convention, and only for x86_64. 7096 // FIXME: Support other platforms later. 7097 const auto &Triple = DAG.getTarget().getTargetTriple(); 7098 if (Triple.getArch() != Triple::x86_64) 7099 return; 7100 7101 SmallVector<SDValue, 8> Ops; 7102 7103 // We want to say that we always want the arguments in registers. 7104 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 7105 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 7106 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7107 SDValue Chain = getRoot(); 7108 Ops.push_back(LogEntryVal); 7109 Ops.push_back(StrSizeVal); 7110 Ops.push_back(Chain); 7111 7112 // We need to enforce the calling convention for the callsite, so that 7113 // argument ordering is enforced correctly, and that register allocation can 7114 // see that some registers may be assumed clobbered and have to preserve 7115 // them across calls to the intrinsic. 7116 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 7117 sdl, NodeTys, Ops); 7118 SDValue patchableNode = SDValue(MN, 0); 7119 DAG.setRoot(patchableNode); 7120 setValue(&I, patchableNode); 7121 return; 7122 } 7123 case Intrinsic::xray_typedevent: { 7124 // Here we want to make sure that the intrinsic behaves as if it has a 7125 // specific calling convention, and only for x86_64. 7126 // FIXME: Support other platforms later. 7127 const auto &Triple = DAG.getTarget().getTargetTriple(); 7128 if (Triple.getArch() != Triple::x86_64) 7129 return; 7130 7131 SmallVector<SDValue, 8> Ops; 7132 7133 // We want to say that we always want the arguments in registers. 7134 // It's unclear to me how manipulating the selection DAG here forces callers 7135 // to provide arguments in registers instead of on the stack. 7136 SDValue LogTypeId = getValue(I.getArgOperand(0)); 7137 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 7138 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 7139 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7140 SDValue Chain = getRoot(); 7141 Ops.push_back(LogTypeId); 7142 Ops.push_back(LogEntryVal); 7143 Ops.push_back(StrSizeVal); 7144 Ops.push_back(Chain); 7145 7146 // We need to enforce the calling convention for the callsite, so that 7147 // argument ordering is enforced correctly, and that register allocation can 7148 // see that some registers may be assumed clobbered and have to preserve 7149 // them across calls to the intrinsic. 7150 MachineSDNode *MN = DAG.getMachineNode( 7151 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops); 7152 SDValue patchableNode = SDValue(MN, 0); 7153 DAG.setRoot(patchableNode); 7154 setValue(&I, patchableNode); 7155 return; 7156 } 7157 case Intrinsic::experimental_deoptimize: 7158 LowerDeoptimizeCall(&I); 7159 return; 7160 case Intrinsic::experimental_stepvector: 7161 visitStepVector(I); 7162 return; 7163 case Intrinsic::vector_reduce_fadd: 7164 case Intrinsic::vector_reduce_fmul: 7165 case Intrinsic::vector_reduce_add: 7166 case Intrinsic::vector_reduce_mul: 7167 case Intrinsic::vector_reduce_and: 7168 case Intrinsic::vector_reduce_or: 7169 case Intrinsic::vector_reduce_xor: 7170 case Intrinsic::vector_reduce_smax: 7171 case Intrinsic::vector_reduce_smin: 7172 case Intrinsic::vector_reduce_umax: 7173 case Intrinsic::vector_reduce_umin: 7174 case Intrinsic::vector_reduce_fmax: 7175 case Intrinsic::vector_reduce_fmin: 7176 visitVectorReduce(I, Intrinsic); 7177 return; 7178 7179 case Intrinsic::icall_branch_funnel: { 7180 SmallVector<SDValue, 16> Ops; 7181 Ops.push_back(getValue(I.getArgOperand(0))); 7182 7183 int64_t Offset; 7184 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7185 I.getArgOperand(1), Offset, DAG.getDataLayout())); 7186 if (!Base) 7187 report_fatal_error( 7188 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7189 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0)); 7190 7191 struct BranchFunnelTarget { 7192 int64_t Offset; 7193 SDValue Target; 7194 }; 7195 SmallVector<BranchFunnelTarget, 8> Targets; 7196 7197 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) { 7198 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7199 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7200 if (ElemBase != Base) 7201 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7202 "to the same GlobalValue"); 7203 7204 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7205 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7206 if (!GA) 7207 report_fatal_error( 7208 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7209 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7210 GA->getGlobal(), sdl, Val.getValueType(), 7211 GA->getOffset())}); 7212 } 7213 llvm::sort(Targets, 7214 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7215 return T1.Offset < T2.Offset; 7216 }); 7217 7218 for (auto &T : Targets) { 7219 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32)); 7220 Ops.push_back(T.Target); 7221 } 7222 7223 Ops.push_back(DAG.getRoot()); // Chain 7224 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl, 7225 MVT::Other, Ops), 7226 0); 7227 DAG.setRoot(N); 7228 setValue(&I, N); 7229 HasTailCall = true; 7230 return; 7231 } 7232 7233 case Intrinsic::wasm_landingpad_index: 7234 // Information this intrinsic contained has been transferred to 7235 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7236 // delete it now. 7237 return; 7238 7239 case Intrinsic::aarch64_settag: 7240 case Intrinsic::aarch64_settag_zero: { 7241 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7242 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7243 SDValue Val = TSI.EmitTargetCodeForSetTag( 7244 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)), 7245 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7246 ZeroMemory); 7247 DAG.setRoot(Val); 7248 setValue(&I, Val); 7249 return; 7250 } 7251 case Intrinsic::ptrmask: { 7252 SDValue Ptr = getValue(I.getOperand(0)); 7253 SDValue Const = getValue(I.getOperand(1)); 7254 7255 EVT PtrVT = Ptr.getValueType(); 7256 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, 7257 DAG.getZExtOrTrunc(Const, sdl, PtrVT))); 7258 return; 7259 } 7260 case Intrinsic::threadlocal_address: { 7261 setValue(&I, getValue(I.getOperand(0))); 7262 return; 7263 } 7264 case Intrinsic::get_active_lane_mask: { 7265 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7266 SDValue Index = getValue(I.getOperand(0)); 7267 EVT ElementVT = Index.getValueType(); 7268 7269 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) { 7270 visitTargetIntrinsic(I, Intrinsic); 7271 return; 7272 } 7273 7274 SDValue TripCount = getValue(I.getOperand(1)); 7275 auto VecTy = CCVT.changeVectorElementType(ElementVT); 7276 7277 SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index); 7278 SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount); 7279 SDValue VectorStep = DAG.getStepVector(sdl, VecTy); 7280 SDValue VectorInduction = DAG.getNode( 7281 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep); 7282 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction, 7283 VectorTripCount, ISD::CondCode::SETULT); 7284 setValue(&I, SetCC); 7285 return; 7286 } 7287 case Intrinsic::vector_insert: { 7288 SDValue Vec = getValue(I.getOperand(0)); 7289 SDValue SubVec = getValue(I.getOperand(1)); 7290 SDValue Index = getValue(I.getOperand(2)); 7291 7292 // The intrinsic's index type is i64, but the SDNode requires an index type 7293 // suitable for the target. Convert the index as required. 7294 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7295 if (Index.getValueType() != VectorIdxTy) 7296 Index = DAG.getVectorIdxConstant( 7297 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7298 7299 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7300 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec, 7301 Index)); 7302 return; 7303 } 7304 case Intrinsic::vector_extract: { 7305 SDValue Vec = getValue(I.getOperand(0)); 7306 SDValue Index = getValue(I.getOperand(1)); 7307 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7308 7309 // The intrinsic's index type is i64, but the SDNode requires an index type 7310 // suitable for the target. Convert the index as required. 7311 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7312 if (Index.getValueType() != VectorIdxTy) 7313 Index = DAG.getVectorIdxConstant( 7314 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7315 7316 setValue(&I, 7317 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index)); 7318 return; 7319 } 7320 case Intrinsic::experimental_vector_reverse: 7321 visitVectorReverse(I); 7322 return; 7323 case Intrinsic::experimental_vector_splice: 7324 visitVectorSplice(I); 7325 return; 7326 } 7327 } 7328 7329 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7330 const ConstrainedFPIntrinsic &FPI) { 7331 SDLoc sdl = getCurSDLoc(); 7332 7333 // We do not need to serialize constrained FP intrinsics against 7334 // each other or against (nonvolatile) loads, so they can be 7335 // chained like loads. 7336 SDValue Chain = DAG.getRoot(); 7337 SmallVector<SDValue, 4> Opers; 7338 Opers.push_back(Chain); 7339 if (FPI.isUnaryOp()) { 7340 Opers.push_back(getValue(FPI.getArgOperand(0))); 7341 } else if (FPI.isTernaryOp()) { 7342 Opers.push_back(getValue(FPI.getArgOperand(0))); 7343 Opers.push_back(getValue(FPI.getArgOperand(1))); 7344 Opers.push_back(getValue(FPI.getArgOperand(2))); 7345 } else { 7346 Opers.push_back(getValue(FPI.getArgOperand(0))); 7347 Opers.push_back(getValue(FPI.getArgOperand(1))); 7348 } 7349 7350 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7351 assert(Result.getNode()->getNumValues() == 2); 7352 7353 // Push node to the appropriate list so that future instructions can be 7354 // chained up correctly. 7355 SDValue OutChain = Result.getValue(1); 7356 switch (EB) { 7357 case fp::ExceptionBehavior::ebIgnore: 7358 // The only reason why ebIgnore nodes still need to be chained is that 7359 // they might depend on the current rounding mode, and therefore must 7360 // not be moved across instruction that may change that mode. 7361 [[fallthrough]]; 7362 case fp::ExceptionBehavior::ebMayTrap: 7363 // These must not be moved across calls or instructions that may change 7364 // floating-point exception masks. 7365 PendingConstrainedFP.push_back(OutChain); 7366 break; 7367 case fp::ExceptionBehavior::ebStrict: 7368 // These must not be moved across calls or instructions that may change 7369 // floating-point exception masks or read floating-point exception flags. 7370 // In addition, they cannot be optimized out even if unused. 7371 PendingConstrainedFPStrict.push_back(OutChain); 7372 break; 7373 } 7374 }; 7375 7376 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7377 EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType()); 7378 SDVTList VTs = DAG.getVTList(VT, MVT::Other); 7379 fp::ExceptionBehavior EB = *FPI.getExceptionBehavior(); 7380 7381 SDNodeFlags Flags; 7382 if (EB == fp::ExceptionBehavior::ebIgnore) 7383 Flags.setNoFPExcept(true); 7384 7385 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7386 Flags.copyFMF(*FPOp); 7387 7388 unsigned Opcode; 7389 switch (FPI.getIntrinsicID()) { 7390 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7391 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7392 case Intrinsic::INTRINSIC: \ 7393 Opcode = ISD::STRICT_##DAGN; \ 7394 break; 7395 #include "llvm/IR/ConstrainedOps.def" 7396 case Intrinsic::experimental_constrained_fmuladd: { 7397 Opcode = ISD::STRICT_FMA; 7398 // Break fmuladd into fmul and fadd. 7399 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7400 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 7401 Opers.pop_back(); 7402 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7403 pushOutChain(Mul, EB); 7404 Opcode = ISD::STRICT_FADD; 7405 Opers.clear(); 7406 Opers.push_back(Mul.getValue(1)); 7407 Opers.push_back(Mul.getValue(0)); 7408 Opers.push_back(getValue(FPI.getArgOperand(2))); 7409 } 7410 break; 7411 } 7412 } 7413 7414 // A few strict DAG nodes carry additional operands that are not 7415 // set up by the default code above. 7416 switch (Opcode) { 7417 default: break; 7418 case ISD::STRICT_FP_ROUND: 7419 Opers.push_back( 7420 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7421 break; 7422 case ISD::STRICT_FSETCC: 7423 case ISD::STRICT_FSETCCS: { 7424 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7425 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 7426 if (TM.Options.NoNaNsFPMath) 7427 Condition = getFCmpCodeWithoutNaN(Condition); 7428 Opers.push_back(DAG.getCondCode(Condition)); 7429 break; 7430 } 7431 } 7432 7433 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7434 pushOutChain(Result, EB); 7435 7436 SDValue FPResult = Result.getValue(0); 7437 setValue(&FPI, FPResult); 7438 } 7439 7440 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 7441 std::optional<unsigned> ResOPC; 7442 switch (VPIntrin.getIntrinsicID()) { 7443 case Intrinsic::vp_ctlz: { 7444 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(3))->isOne(); 7445 ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ; 7446 break; 7447 } 7448 case Intrinsic::vp_cttz: { 7449 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(3))->isOne(); 7450 ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ; 7451 break; 7452 } 7453 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \ 7454 case Intrinsic::VPID: \ 7455 ResOPC = ISD::VPSD; \ 7456 break; 7457 #include "llvm/IR/VPIntrinsics.def" 7458 } 7459 7460 if (!ResOPC) 7461 llvm_unreachable( 7462 "Inconsistency: no SDNode available for this VPIntrinsic!"); 7463 7464 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD || 7465 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) { 7466 if (VPIntrin.getFastMathFlags().allowReassoc()) 7467 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD 7468 : ISD::VP_REDUCE_FMUL; 7469 } 7470 7471 return *ResOPC; 7472 } 7473 7474 void SelectionDAGBuilder::visitVPLoad(const VPIntrinsic &VPIntrin, EVT VT, 7475 SmallVector<SDValue, 7> &OpValues) { 7476 SDLoc DL = getCurSDLoc(); 7477 Value *PtrOperand = VPIntrin.getArgOperand(0); 7478 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7479 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7480 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7481 SDValue LD; 7482 bool AddToChain = true; 7483 // Do not serialize variable-length loads of constant memory with 7484 // anything. 7485 if (!Alignment) 7486 Alignment = DAG.getEVTAlign(VT); 7487 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7488 AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7489 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7490 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7491 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7492 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7493 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2], 7494 MMO, false /*IsExpanding */); 7495 if (AddToChain) 7496 PendingLoads.push_back(LD.getValue(1)); 7497 setValue(&VPIntrin, LD); 7498 } 7499 7500 void SelectionDAGBuilder::visitVPGather(const VPIntrinsic &VPIntrin, EVT VT, 7501 SmallVector<SDValue, 7> &OpValues) { 7502 SDLoc DL = getCurSDLoc(); 7503 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7504 Value *PtrOperand = VPIntrin.getArgOperand(0); 7505 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7506 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7507 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7508 SDValue LD; 7509 if (!Alignment) 7510 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7511 unsigned AS = 7512 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7513 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7514 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 7515 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7516 SDValue Base, Index, Scale; 7517 ISD::MemIndexType IndexType; 7518 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7519 this, VPIntrin.getParent(), 7520 VT.getScalarStoreSize()); 7521 if (!UniformBase) { 7522 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7523 Index = getValue(PtrOperand); 7524 IndexType = ISD::SIGNED_SCALED; 7525 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7526 } 7527 EVT IdxVT = Index.getValueType(); 7528 EVT EltTy = IdxVT.getVectorElementType(); 7529 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7530 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7531 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7532 } 7533 LD = DAG.getGatherVP( 7534 DAG.getVTList(VT, MVT::Other), VT, DL, 7535 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO, 7536 IndexType); 7537 PendingLoads.push_back(LD.getValue(1)); 7538 setValue(&VPIntrin, LD); 7539 } 7540 7541 void SelectionDAGBuilder::visitVPStore(const VPIntrinsic &VPIntrin, 7542 SmallVector<SDValue, 7> &OpValues) { 7543 SDLoc DL = getCurSDLoc(); 7544 Value *PtrOperand = VPIntrin.getArgOperand(1); 7545 EVT VT = OpValues[0].getValueType(); 7546 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7547 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7548 SDValue ST; 7549 if (!Alignment) 7550 Alignment = DAG.getEVTAlign(VT); 7551 SDValue Ptr = OpValues[1]; 7552 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 7553 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7554 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7555 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7556 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset, 7557 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED, 7558 /* IsTruncating */ false, /*IsCompressing*/ false); 7559 DAG.setRoot(ST); 7560 setValue(&VPIntrin, ST); 7561 } 7562 7563 void SelectionDAGBuilder::visitVPScatter(const VPIntrinsic &VPIntrin, 7564 SmallVector<SDValue, 7> &OpValues) { 7565 SDLoc DL = getCurSDLoc(); 7566 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7567 Value *PtrOperand = VPIntrin.getArgOperand(1); 7568 EVT VT = OpValues[0].getValueType(); 7569 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7570 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7571 SDValue ST; 7572 if (!Alignment) 7573 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7574 unsigned AS = 7575 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7576 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7577 MachinePointerInfo(AS), MachineMemOperand::MOStore, 7578 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7579 SDValue Base, Index, Scale; 7580 ISD::MemIndexType IndexType; 7581 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7582 this, VPIntrin.getParent(), 7583 VT.getScalarStoreSize()); 7584 if (!UniformBase) { 7585 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7586 Index = getValue(PtrOperand); 7587 IndexType = ISD::SIGNED_SCALED; 7588 Scale = 7589 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7590 } 7591 EVT IdxVT = Index.getValueType(); 7592 EVT EltTy = IdxVT.getVectorElementType(); 7593 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7594 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7595 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7596 } 7597 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL, 7598 {getMemoryRoot(), OpValues[0], Base, Index, Scale, 7599 OpValues[2], OpValues[3]}, 7600 MMO, IndexType); 7601 DAG.setRoot(ST); 7602 setValue(&VPIntrin, ST); 7603 } 7604 7605 void SelectionDAGBuilder::visitVPStridedLoad( 7606 const VPIntrinsic &VPIntrin, EVT VT, SmallVectorImpl<SDValue> &OpValues) { 7607 SDLoc DL = getCurSDLoc(); 7608 Value *PtrOperand = VPIntrin.getArgOperand(0); 7609 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7610 if (!Alignment) 7611 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7612 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7613 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7614 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7615 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7616 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7617 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7618 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7619 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7620 7621 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], 7622 OpValues[2], OpValues[3], MMO, 7623 false /*IsExpanding*/); 7624 7625 if (AddToChain) 7626 PendingLoads.push_back(LD.getValue(1)); 7627 setValue(&VPIntrin, LD); 7628 } 7629 7630 void SelectionDAGBuilder::visitVPStridedStore( 7631 const VPIntrinsic &VPIntrin, SmallVectorImpl<SDValue> &OpValues) { 7632 SDLoc DL = getCurSDLoc(); 7633 Value *PtrOperand = VPIntrin.getArgOperand(1); 7634 EVT VT = OpValues[0].getValueType(); 7635 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7636 if (!Alignment) 7637 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7638 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7639 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7640 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7641 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7642 7643 SDValue ST = DAG.getStridedStoreVP( 7644 getMemoryRoot(), DL, OpValues[0], OpValues[1], 7645 DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3], 7646 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false, 7647 /*IsCompressing*/ false); 7648 7649 DAG.setRoot(ST); 7650 setValue(&VPIntrin, ST); 7651 } 7652 7653 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) { 7654 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7655 SDLoc DL = getCurSDLoc(); 7656 7657 ISD::CondCode Condition; 7658 CmpInst::Predicate CondCode = VPIntrin.getPredicate(); 7659 bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy(); 7660 if (IsFP) { 7661 // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan) 7662 // flags, but calls that don't return floating-point types can't be 7663 // FPMathOperators, like vp.fcmp. This affects constrained fcmp too. 7664 Condition = getFCmpCondCode(CondCode); 7665 if (TM.Options.NoNaNsFPMath) 7666 Condition = getFCmpCodeWithoutNaN(Condition); 7667 } else { 7668 Condition = getICmpCondCode(CondCode); 7669 } 7670 7671 SDValue Op1 = getValue(VPIntrin.getOperand(0)); 7672 SDValue Op2 = getValue(VPIntrin.getOperand(1)); 7673 // #2 is the condition code 7674 SDValue MaskOp = getValue(VPIntrin.getOperand(3)); 7675 SDValue EVL = getValue(VPIntrin.getOperand(4)); 7676 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7677 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7678 "Unexpected target EVL type"); 7679 EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL); 7680 7681 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7682 VPIntrin.getType()); 7683 setValue(&VPIntrin, 7684 DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL)); 7685 } 7686 7687 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 7688 const VPIntrinsic &VPIntrin) { 7689 SDLoc DL = getCurSDLoc(); 7690 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 7691 7692 auto IID = VPIntrin.getIntrinsicID(); 7693 7694 if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin)) 7695 return visitVPCmp(*CmpI); 7696 7697 SmallVector<EVT, 4> ValueVTs; 7698 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7699 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 7700 SDVTList VTs = DAG.getVTList(ValueVTs); 7701 7702 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID); 7703 7704 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7705 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7706 "Unexpected target EVL type"); 7707 7708 // Request operands. 7709 SmallVector<SDValue, 7> OpValues; 7710 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) { 7711 auto Op = getValue(VPIntrin.getArgOperand(I)); 7712 if (I == EVLParamPos) 7713 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op); 7714 OpValues.push_back(Op); 7715 } 7716 7717 switch (Opcode) { 7718 default: { 7719 SDNodeFlags SDFlags; 7720 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 7721 SDFlags.copyFMF(*FPMO); 7722 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags); 7723 setValue(&VPIntrin, Result); 7724 break; 7725 } 7726 case ISD::VP_LOAD: 7727 visitVPLoad(VPIntrin, ValueVTs[0], OpValues); 7728 break; 7729 case ISD::VP_GATHER: 7730 visitVPGather(VPIntrin, ValueVTs[0], OpValues); 7731 break; 7732 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: 7733 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues); 7734 break; 7735 case ISD::VP_STORE: 7736 visitVPStore(VPIntrin, OpValues); 7737 break; 7738 case ISD::VP_SCATTER: 7739 visitVPScatter(VPIntrin, OpValues); 7740 break; 7741 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: 7742 visitVPStridedStore(VPIntrin, OpValues); 7743 break; 7744 case ISD::VP_FMULADD: { 7745 assert(OpValues.size() == 5 && "Unexpected number of operands"); 7746 SDNodeFlags SDFlags; 7747 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 7748 SDFlags.copyFMF(*FPMO); 7749 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 7750 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) { 7751 setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags)); 7752 } else { 7753 SDValue Mul = DAG.getNode( 7754 ISD::VP_FMUL, DL, VTs, 7755 {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags); 7756 SDValue Add = 7757 DAG.getNode(ISD::VP_FADD, DL, VTs, 7758 {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags); 7759 setValue(&VPIntrin, Add); 7760 } 7761 break; 7762 } 7763 case ISD::VP_INTTOPTR: { 7764 SDValue N = OpValues[0]; 7765 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType()); 7766 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType()); 7767 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 7768 OpValues[2]); 7769 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 7770 OpValues[2]); 7771 setValue(&VPIntrin, N); 7772 break; 7773 } 7774 case ISD::VP_PTRTOINT: { 7775 SDValue N = OpValues[0]; 7776 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7777 VPIntrin.getType()); 7778 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), 7779 VPIntrin.getOperand(0)->getType()); 7780 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 7781 OpValues[2]); 7782 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 7783 OpValues[2]); 7784 setValue(&VPIntrin, N); 7785 break; 7786 } 7787 case ISD::VP_ABS: 7788 case ISD::VP_CTLZ: 7789 case ISD::VP_CTLZ_ZERO_UNDEF: 7790 case ISD::VP_CTTZ: 7791 case ISD::VP_CTTZ_ZERO_UNDEF: { 7792 // Pop is_zero_poison operand for cp.ctlz/cttz or 7793 // is_int_min_poison operand for vp.abs. 7794 OpValues.pop_back(); 7795 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues); 7796 setValue(&VPIntrin, Result); 7797 break; 7798 } 7799 } 7800 } 7801 7802 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 7803 const BasicBlock *EHPadBB, 7804 MCSymbol *&BeginLabel) { 7805 MachineFunction &MF = DAG.getMachineFunction(); 7806 MachineModuleInfo &MMI = MF.getMMI(); 7807 7808 // Insert a label before the invoke call to mark the try range. This can be 7809 // used to detect deletion of the invoke via the MachineModuleInfo. 7810 BeginLabel = MMI.getContext().createTempSymbol(); 7811 7812 // For SjLj, keep track of which landing pads go with which invokes 7813 // so as to maintain the ordering of pads in the LSDA. 7814 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7815 if (CallSiteIndex) { 7816 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7817 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7818 7819 // Now that the call site is handled, stop tracking it. 7820 MMI.setCurrentCallSite(0); 7821 } 7822 7823 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 7824 } 7825 7826 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 7827 const BasicBlock *EHPadBB, 7828 MCSymbol *BeginLabel) { 7829 assert(BeginLabel && "BeginLabel should've been set"); 7830 7831 MachineFunction &MF = DAG.getMachineFunction(); 7832 MachineModuleInfo &MMI = MF.getMMI(); 7833 7834 // Insert a label at the end of the invoke call to mark the try range. This 7835 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7836 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7837 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 7838 7839 // Inform MachineModuleInfo of range. 7840 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7841 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7842 // actually use outlined funclets and their LSDA info style. 7843 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7844 assert(II && "II should've been set"); 7845 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 7846 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 7847 } else if (!isScopedEHPersonality(Pers)) { 7848 assert(EHPadBB); 7849 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7850 } 7851 7852 return Chain; 7853 } 7854 7855 std::pair<SDValue, SDValue> 7856 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7857 const BasicBlock *EHPadBB) { 7858 MCSymbol *BeginLabel = nullptr; 7859 7860 if (EHPadBB) { 7861 // Both PendingLoads and PendingExports must be flushed here; 7862 // this call might not return. 7863 (void)getRoot(); 7864 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 7865 CLI.setChain(getRoot()); 7866 } 7867 7868 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7869 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7870 7871 assert((CLI.IsTailCall || Result.second.getNode()) && 7872 "Non-null chain expected with non-tail call!"); 7873 assert((Result.second.getNode() || !Result.first.getNode()) && 7874 "Null value expected with tail call!"); 7875 7876 if (!Result.second.getNode()) { 7877 // As a special case, a null chain means that a tail call has been emitted 7878 // and the DAG root is already updated. 7879 HasTailCall = true; 7880 7881 // Since there's no actual continuation from this block, nothing can be 7882 // relying on us setting vregs for them. 7883 PendingExports.clear(); 7884 } else { 7885 DAG.setRoot(Result.second); 7886 } 7887 7888 if (EHPadBB) { 7889 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 7890 BeginLabel)); 7891 } 7892 7893 return Result; 7894 } 7895 7896 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 7897 bool isTailCall, 7898 bool isMustTailCall, 7899 const BasicBlock *EHPadBB) { 7900 auto &DL = DAG.getDataLayout(); 7901 FunctionType *FTy = CB.getFunctionType(); 7902 Type *RetTy = CB.getType(); 7903 7904 TargetLowering::ArgListTy Args; 7905 Args.reserve(CB.arg_size()); 7906 7907 const Value *SwiftErrorVal = nullptr; 7908 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7909 7910 if (isTailCall) { 7911 // Avoid emitting tail calls in functions with the disable-tail-calls 7912 // attribute. 7913 auto *Caller = CB.getParent()->getParent(); 7914 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7915 "true" && !isMustTailCall) 7916 isTailCall = false; 7917 7918 // We can't tail call inside a function with a swifterror argument. Lowering 7919 // does not support this yet. It would have to move into the swifterror 7920 // register before the call. 7921 if (TLI.supportSwiftError() && 7922 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7923 isTailCall = false; 7924 } 7925 7926 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 7927 TargetLowering::ArgListEntry Entry; 7928 const Value *V = *I; 7929 7930 // Skip empty types 7931 if (V->getType()->isEmptyTy()) 7932 continue; 7933 7934 SDValue ArgNode = getValue(V); 7935 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7936 7937 Entry.setAttributes(&CB, I - CB.arg_begin()); 7938 7939 // Use swifterror virtual register as input to the call. 7940 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7941 SwiftErrorVal = V; 7942 // We find the virtual register for the actual swifterror argument. 7943 // Instead of using the Value, we use the virtual register instead. 7944 Entry.Node = 7945 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 7946 EVT(TLI.getPointerTy(DL))); 7947 } 7948 7949 Args.push_back(Entry); 7950 7951 // If we have an explicit sret argument that is an Instruction, (i.e., it 7952 // might point to function-local memory), we can't meaningfully tail-call. 7953 if (Entry.IsSRet && isa<Instruction>(V)) 7954 isTailCall = false; 7955 } 7956 7957 // If call site has a cfguardtarget operand bundle, create and add an 7958 // additional ArgListEntry. 7959 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7960 TargetLowering::ArgListEntry Entry; 7961 Value *V = Bundle->Inputs[0]; 7962 SDValue ArgNode = getValue(V); 7963 Entry.Node = ArgNode; 7964 Entry.Ty = V->getType(); 7965 Entry.IsCFGuardTarget = true; 7966 Args.push_back(Entry); 7967 } 7968 7969 // Check if target-independent constraints permit a tail call here. 7970 // Target-dependent constraints are checked within TLI->LowerCallTo. 7971 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 7972 isTailCall = false; 7973 7974 // Disable tail calls if there is an swifterror argument. Targets have not 7975 // been updated to support tail calls. 7976 if (TLI.supportSwiftError() && SwiftErrorVal) 7977 isTailCall = false; 7978 7979 ConstantInt *CFIType = nullptr; 7980 if (CB.isIndirectCall()) { 7981 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) { 7982 if (!TLI.supportKCFIBundles()) 7983 report_fatal_error( 7984 "Target doesn't support calls with kcfi operand bundles."); 7985 CFIType = cast<ConstantInt>(Bundle->Inputs[0]); 7986 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type"); 7987 } 7988 } 7989 7990 TargetLowering::CallLoweringInfo CLI(DAG); 7991 CLI.setDebugLoc(getCurSDLoc()) 7992 .setChain(getRoot()) 7993 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 7994 .setTailCall(isTailCall) 7995 .setConvergent(CB.isConvergent()) 7996 .setIsPreallocated( 7997 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0) 7998 .setCFIType(CFIType); 7999 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8000 8001 if (Result.first.getNode()) { 8002 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 8003 setValue(&CB, Result.first); 8004 } 8005 8006 // The last element of CLI.InVals has the SDValue for swifterror return. 8007 // Here we copy it to a virtual register and update SwiftErrorMap for 8008 // book-keeping. 8009 if (SwiftErrorVal && TLI.supportSwiftError()) { 8010 // Get the last element of InVals. 8011 SDValue Src = CLI.InVals.back(); 8012 Register VReg = 8013 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 8014 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 8015 DAG.setRoot(CopyNode); 8016 } 8017 } 8018 8019 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 8020 SelectionDAGBuilder &Builder) { 8021 // Check to see if this load can be trivially constant folded, e.g. if the 8022 // input is from a string literal. 8023 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 8024 // Cast pointer to the type we really want to load. 8025 Type *LoadTy = 8026 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 8027 if (LoadVT.isVector()) 8028 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 8029 8030 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 8031 PointerType::getUnqual(LoadTy)); 8032 8033 if (const Constant *LoadCst = 8034 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput), 8035 LoadTy, Builder.DAG.getDataLayout())) 8036 return Builder.getValue(LoadCst); 8037 } 8038 8039 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 8040 // still constant memory, the input chain can be the entry node. 8041 SDValue Root; 8042 bool ConstantMemory = false; 8043 8044 // Do not serialize (non-volatile) loads of constant memory with anything. 8045 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 8046 Root = Builder.DAG.getEntryNode(); 8047 ConstantMemory = true; 8048 } else { 8049 // Do not serialize non-volatile loads against each other. 8050 Root = Builder.DAG.getRoot(); 8051 } 8052 8053 SDValue Ptr = Builder.getValue(PtrVal); 8054 SDValue LoadVal = 8055 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 8056 MachinePointerInfo(PtrVal), Align(1)); 8057 8058 if (!ConstantMemory) 8059 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 8060 return LoadVal; 8061 } 8062 8063 /// Record the value for an instruction that produces an integer result, 8064 /// converting the type where necessary. 8065 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 8066 SDValue Value, 8067 bool IsSigned) { 8068 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8069 I.getType(), true); 8070 if (IsSigned) 8071 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 8072 else 8073 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 8074 setValue(&I, Value); 8075 } 8076 8077 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 8078 /// true and lower it. Otherwise return false, and it will be lowered like a 8079 /// normal call. 8080 /// The caller already checked that \p I calls the appropriate LibFunc with a 8081 /// correct prototype. 8082 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 8083 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 8084 const Value *Size = I.getArgOperand(2); 8085 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size)); 8086 if (CSize && CSize->getZExtValue() == 0) { 8087 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8088 I.getType(), true); 8089 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 8090 return true; 8091 } 8092 8093 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8094 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 8095 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 8096 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 8097 if (Res.first.getNode()) { 8098 processIntegerCallValue(I, Res.first, true); 8099 PendingLoads.push_back(Res.second); 8100 return true; 8101 } 8102 8103 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 8104 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 8105 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 8106 return false; 8107 8108 // If the target has a fast compare for the given size, it will return a 8109 // preferred load type for that size. Require that the load VT is legal and 8110 // that the target supports unaligned loads of that type. Otherwise, return 8111 // INVALID. 8112 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 8113 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8114 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 8115 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 8116 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 8117 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 8118 // TODO: Check alignment of src and dest ptrs. 8119 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 8120 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 8121 if (!TLI.isTypeLegal(LVT) || 8122 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 8123 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 8124 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 8125 } 8126 8127 return LVT; 8128 }; 8129 8130 // This turns into unaligned loads. We only do this if the target natively 8131 // supports the MVT we'll be loading or if it is small enough (<= 4) that 8132 // we'll only produce a small number of byte loads. 8133 MVT LoadVT; 8134 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 8135 switch (NumBitsToCompare) { 8136 default: 8137 return false; 8138 case 16: 8139 LoadVT = MVT::i16; 8140 break; 8141 case 32: 8142 LoadVT = MVT::i32; 8143 break; 8144 case 64: 8145 case 128: 8146 case 256: 8147 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 8148 break; 8149 } 8150 8151 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 8152 return false; 8153 8154 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 8155 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 8156 8157 // Bitcast to a wide integer type if the loads are vectors. 8158 if (LoadVT.isVector()) { 8159 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 8160 LoadL = DAG.getBitcast(CmpVT, LoadL); 8161 LoadR = DAG.getBitcast(CmpVT, LoadR); 8162 } 8163 8164 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 8165 processIntegerCallValue(I, Cmp, false); 8166 return true; 8167 } 8168 8169 /// See if we can lower a memchr call into an optimized form. If so, return 8170 /// true and lower it. Otherwise return false, and it will be lowered like a 8171 /// normal call. 8172 /// The caller already checked that \p I calls the appropriate LibFunc with a 8173 /// correct prototype. 8174 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 8175 const Value *Src = I.getArgOperand(0); 8176 const Value *Char = I.getArgOperand(1); 8177 const Value *Length = I.getArgOperand(2); 8178 8179 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8180 std::pair<SDValue, SDValue> Res = 8181 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 8182 getValue(Src), getValue(Char), getValue(Length), 8183 MachinePointerInfo(Src)); 8184 if (Res.first.getNode()) { 8185 setValue(&I, Res.first); 8186 PendingLoads.push_back(Res.second); 8187 return true; 8188 } 8189 8190 return false; 8191 } 8192 8193 /// See if we can lower a mempcpy call into an optimized form. If so, return 8194 /// true and lower it. Otherwise return false, and it will be lowered like a 8195 /// normal call. 8196 /// The caller already checked that \p I calls the appropriate LibFunc with a 8197 /// correct prototype. 8198 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 8199 SDValue Dst = getValue(I.getArgOperand(0)); 8200 SDValue Src = getValue(I.getArgOperand(1)); 8201 SDValue Size = getValue(I.getArgOperand(2)); 8202 8203 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 8204 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 8205 // DAG::getMemcpy needs Alignment to be defined. 8206 Align Alignment = std::min(DstAlign, SrcAlign); 8207 8208 bool isVol = false; 8209 SDLoc sdl = getCurSDLoc(); 8210 8211 // In the mempcpy context we need to pass in a false value for isTailCall 8212 // because the return pointer needs to be adjusted by the size of 8213 // the copied memory. 8214 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 8215 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false, 8216 /*isTailCall=*/false, 8217 MachinePointerInfo(I.getArgOperand(0)), 8218 MachinePointerInfo(I.getArgOperand(1)), 8219 I.getAAMetadata()); 8220 assert(MC.getNode() != nullptr && 8221 "** memcpy should not be lowered as TailCall in mempcpy context **"); 8222 DAG.setRoot(MC); 8223 8224 // Check if Size needs to be truncated or extended. 8225 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 8226 8227 // Adjust return pointer to point just past the last dst byte. 8228 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 8229 Dst, Size); 8230 setValue(&I, DstPlusSize); 8231 return true; 8232 } 8233 8234 /// See if we can lower a strcpy call into an optimized form. If so, return 8235 /// true and lower it, otherwise return false and it will be lowered like a 8236 /// normal call. 8237 /// The caller already checked that \p I calls the appropriate LibFunc with a 8238 /// correct prototype. 8239 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 8240 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8241 8242 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8243 std::pair<SDValue, SDValue> Res = 8244 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 8245 getValue(Arg0), getValue(Arg1), 8246 MachinePointerInfo(Arg0), 8247 MachinePointerInfo(Arg1), isStpcpy); 8248 if (Res.first.getNode()) { 8249 setValue(&I, Res.first); 8250 DAG.setRoot(Res.second); 8251 return true; 8252 } 8253 8254 return false; 8255 } 8256 8257 /// See if we can lower a strcmp call into an optimized form. If so, return 8258 /// true and lower it, otherwise return false and it will be lowered like a 8259 /// normal call. 8260 /// The caller already checked that \p I calls the appropriate LibFunc with a 8261 /// correct prototype. 8262 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 8263 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8264 8265 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8266 std::pair<SDValue, SDValue> Res = 8267 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 8268 getValue(Arg0), getValue(Arg1), 8269 MachinePointerInfo(Arg0), 8270 MachinePointerInfo(Arg1)); 8271 if (Res.first.getNode()) { 8272 processIntegerCallValue(I, Res.first, true); 8273 PendingLoads.push_back(Res.second); 8274 return true; 8275 } 8276 8277 return false; 8278 } 8279 8280 /// See if we can lower a strlen call into an optimized form. If so, return 8281 /// true and lower it, otherwise return false and it will be lowered like a 8282 /// normal call. 8283 /// The caller already checked that \p I calls the appropriate LibFunc with a 8284 /// correct prototype. 8285 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 8286 const Value *Arg0 = I.getArgOperand(0); 8287 8288 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8289 std::pair<SDValue, SDValue> Res = 8290 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 8291 getValue(Arg0), MachinePointerInfo(Arg0)); 8292 if (Res.first.getNode()) { 8293 processIntegerCallValue(I, Res.first, false); 8294 PendingLoads.push_back(Res.second); 8295 return true; 8296 } 8297 8298 return false; 8299 } 8300 8301 /// See if we can lower a strnlen call into an optimized form. If so, return 8302 /// true and lower it, otherwise return false and it will be lowered like a 8303 /// normal call. 8304 /// The caller already checked that \p I calls the appropriate LibFunc with a 8305 /// correct prototype. 8306 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 8307 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8308 8309 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8310 std::pair<SDValue, SDValue> Res = 8311 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 8312 getValue(Arg0), getValue(Arg1), 8313 MachinePointerInfo(Arg0)); 8314 if (Res.first.getNode()) { 8315 processIntegerCallValue(I, Res.first, false); 8316 PendingLoads.push_back(Res.second); 8317 return true; 8318 } 8319 8320 return false; 8321 } 8322 8323 /// See if we can lower a unary floating-point operation into an SDNode with 8324 /// the specified Opcode. If so, return true and lower it, otherwise return 8325 /// false and it will be lowered like a normal call. 8326 /// The caller already checked that \p I calls the appropriate LibFunc with a 8327 /// correct prototype. 8328 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 8329 unsigned Opcode) { 8330 // We already checked this call's prototype; verify it doesn't modify errno. 8331 if (!I.onlyReadsMemory()) 8332 return false; 8333 8334 SDNodeFlags Flags; 8335 Flags.copyFMF(cast<FPMathOperator>(I)); 8336 8337 SDValue Tmp = getValue(I.getArgOperand(0)); 8338 setValue(&I, 8339 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 8340 return true; 8341 } 8342 8343 /// See if we can lower a binary floating-point operation into an SDNode with 8344 /// the specified Opcode. If so, return true and lower it. Otherwise return 8345 /// false, and it will be lowered like a normal call. 8346 /// The caller already checked that \p I calls the appropriate LibFunc with a 8347 /// correct prototype. 8348 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 8349 unsigned Opcode) { 8350 // We already checked this call's prototype; verify it doesn't modify errno. 8351 if (!I.onlyReadsMemory()) 8352 return false; 8353 8354 SDNodeFlags Flags; 8355 Flags.copyFMF(cast<FPMathOperator>(I)); 8356 8357 SDValue Tmp0 = getValue(I.getArgOperand(0)); 8358 SDValue Tmp1 = getValue(I.getArgOperand(1)); 8359 EVT VT = Tmp0.getValueType(); 8360 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 8361 return true; 8362 } 8363 8364 void SelectionDAGBuilder::visitCall(const CallInst &I) { 8365 // Handle inline assembly differently. 8366 if (I.isInlineAsm()) { 8367 visitInlineAsm(I); 8368 return; 8369 } 8370 8371 if (Function *F = I.getCalledFunction()) { 8372 diagnoseDontCall(I); 8373 8374 if (F->isDeclaration()) { 8375 // Is this an LLVM intrinsic or a target-specific intrinsic? 8376 unsigned IID = F->getIntrinsicID(); 8377 if (!IID) 8378 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 8379 IID = II->getIntrinsicID(F); 8380 8381 if (IID) { 8382 visitIntrinsicCall(I, IID); 8383 return; 8384 } 8385 } 8386 8387 // Check for well-known libc/libm calls. If the function is internal, it 8388 // can't be a library call. Don't do the check if marked as nobuiltin for 8389 // some reason or the call site requires strict floating point semantics. 8390 LibFunc Func; 8391 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 8392 F->hasName() && LibInfo->getLibFunc(*F, Func) && 8393 LibInfo->hasOptimizedCodeGen(Func)) { 8394 switch (Func) { 8395 default: break; 8396 case LibFunc_bcmp: 8397 if (visitMemCmpBCmpCall(I)) 8398 return; 8399 break; 8400 case LibFunc_copysign: 8401 case LibFunc_copysignf: 8402 case LibFunc_copysignl: 8403 // We already checked this call's prototype; verify it doesn't modify 8404 // errno. 8405 if (I.onlyReadsMemory()) { 8406 SDValue LHS = getValue(I.getArgOperand(0)); 8407 SDValue RHS = getValue(I.getArgOperand(1)); 8408 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 8409 LHS.getValueType(), LHS, RHS)); 8410 return; 8411 } 8412 break; 8413 case LibFunc_fabs: 8414 case LibFunc_fabsf: 8415 case LibFunc_fabsl: 8416 if (visitUnaryFloatCall(I, ISD::FABS)) 8417 return; 8418 break; 8419 case LibFunc_fmin: 8420 case LibFunc_fminf: 8421 case LibFunc_fminl: 8422 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 8423 return; 8424 break; 8425 case LibFunc_fmax: 8426 case LibFunc_fmaxf: 8427 case LibFunc_fmaxl: 8428 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 8429 return; 8430 break; 8431 case LibFunc_sin: 8432 case LibFunc_sinf: 8433 case LibFunc_sinl: 8434 if (visitUnaryFloatCall(I, ISD::FSIN)) 8435 return; 8436 break; 8437 case LibFunc_cos: 8438 case LibFunc_cosf: 8439 case LibFunc_cosl: 8440 if (visitUnaryFloatCall(I, ISD::FCOS)) 8441 return; 8442 break; 8443 case LibFunc_sqrt: 8444 case LibFunc_sqrtf: 8445 case LibFunc_sqrtl: 8446 case LibFunc_sqrt_finite: 8447 case LibFunc_sqrtf_finite: 8448 case LibFunc_sqrtl_finite: 8449 if (visitUnaryFloatCall(I, ISD::FSQRT)) 8450 return; 8451 break; 8452 case LibFunc_floor: 8453 case LibFunc_floorf: 8454 case LibFunc_floorl: 8455 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 8456 return; 8457 break; 8458 case LibFunc_nearbyint: 8459 case LibFunc_nearbyintf: 8460 case LibFunc_nearbyintl: 8461 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 8462 return; 8463 break; 8464 case LibFunc_ceil: 8465 case LibFunc_ceilf: 8466 case LibFunc_ceill: 8467 if (visitUnaryFloatCall(I, ISD::FCEIL)) 8468 return; 8469 break; 8470 case LibFunc_rint: 8471 case LibFunc_rintf: 8472 case LibFunc_rintl: 8473 if (visitUnaryFloatCall(I, ISD::FRINT)) 8474 return; 8475 break; 8476 case LibFunc_round: 8477 case LibFunc_roundf: 8478 case LibFunc_roundl: 8479 if (visitUnaryFloatCall(I, ISD::FROUND)) 8480 return; 8481 break; 8482 case LibFunc_trunc: 8483 case LibFunc_truncf: 8484 case LibFunc_truncl: 8485 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 8486 return; 8487 break; 8488 case LibFunc_log2: 8489 case LibFunc_log2f: 8490 case LibFunc_log2l: 8491 if (visitUnaryFloatCall(I, ISD::FLOG2)) 8492 return; 8493 break; 8494 case LibFunc_exp2: 8495 case LibFunc_exp2f: 8496 case LibFunc_exp2l: 8497 if (visitUnaryFloatCall(I, ISD::FEXP2)) 8498 return; 8499 break; 8500 case LibFunc_memcmp: 8501 if (visitMemCmpBCmpCall(I)) 8502 return; 8503 break; 8504 case LibFunc_mempcpy: 8505 if (visitMemPCpyCall(I)) 8506 return; 8507 break; 8508 case LibFunc_memchr: 8509 if (visitMemChrCall(I)) 8510 return; 8511 break; 8512 case LibFunc_strcpy: 8513 if (visitStrCpyCall(I, false)) 8514 return; 8515 break; 8516 case LibFunc_stpcpy: 8517 if (visitStrCpyCall(I, true)) 8518 return; 8519 break; 8520 case LibFunc_strcmp: 8521 if (visitStrCmpCall(I)) 8522 return; 8523 break; 8524 case LibFunc_strlen: 8525 if (visitStrLenCall(I)) 8526 return; 8527 break; 8528 case LibFunc_strnlen: 8529 if (visitStrNLenCall(I)) 8530 return; 8531 break; 8532 } 8533 } 8534 } 8535 8536 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 8537 // have to do anything here to lower funclet bundles. 8538 // CFGuardTarget bundles are lowered in LowerCallTo. 8539 assert(!I.hasOperandBundlesOtherThan( 8540 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 8541 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 8542 LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) && 8543 "Cannot lower calls with arbitrary operand bundles!"); 8544 8545 SDValue Callee = getValue(I.getCalledOperand()); 8546 8547 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 8548 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 8549 else 8550 // Check if we can potentially perform a tail call. More detailed checking 8551 // is be done within LowerCallTo, after more information about the call is 8552 // known. 8553 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 8554 } 8555 8556 namespace { 8557 8558 /// AsmOperandInfo - This contains information for each constraint that we are 8559 /// lowering. 8560 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 8561 public: 8562 /// CallOperand - If this is the result output operand or a clobber 8563 /// this is null, otherwise it is the incoming operand to the CallInst. 8564 /// This gets modified as the asm is processed. 8565 SDValue CallOperand; 8566 8567 /// AssignedRegs - If this is a register or register class operand, this 8568 /// contains the set of register corresponding to the operand. 8569 RegsForValue AssignedRegs; 8570 8571 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 8572 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 8573 } 8574 8575 /// Whether or not this operand accesses memory 8576 bool hasMemory(const TargetLowering &TLI) const { 8577 // Indirect operand accesses access memory. 8578 if (isIndirect) 8579 return true; 8580 8581 for (const auto &Code : Codes) 8582 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 8583 return true; 8584 8585 return false; 8586 } 8587 }; 8588 8589 8590 } // end anonymous namespace 8591 8592 /// Make sure that the output operand \p OpInfo and its corresponding input 8593 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 8594 /// out). 8595 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 8596 SDISelAsmOperandInfo &MatchingOpInfo, 8597 SelectionDAG &DAG) { 8598 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 8599 return; 8600 8601 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 8602 const auto &TLI = DAG.getTargetLoweringInfo(); 8603 8604 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 8605 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 8606 OpInfo.ConstraintVT); 8607 std::pair<unsigned, const TargetRegisterClass *> InputRC = 8608 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 8609 MatchingOpInfo.ConstraintVT); 8610 if ((OpInfo.ConstraintVT.isInteger() != 8611 MatchingOpInfo.ConstraintVT.isInteger()) || 8612 (MatchRC.second != InputRC.second)) { 8613 // FIXME: error out in a more elegant fashion 8614 report_fatal_error("Unsupported asm: input constraint" 8615 " with a matching output constraint of" 8616 " incompatible type!"); 8617 } 8618 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 8619 } 8620 8621 /// Get a direct memory input to behave well as an indirect operand. 8622 /// This may introduce stores, hence the need for a \p Chain. 8623 /// \return The (possibly updated) chain. 8624 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 8625 SDISelAsmOperandInfo &OpInfo, 8626 SelectionDAG &DAG) { 8627 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8628 8629 // If we don't have an indirect input, put it in the constpool if we can, 8630 // otherwise spill it to a stack slot. 8631 // TODO: This isn't quite right. We need to handle these according to 8632 // the addressing mode that the constraint wants. Also, this may take 8633 // an additional register for the computation and we don't want that 8634 // either. 8635 8636 // If the operand is a float, integer, or vector constant, spill to a 8637 // constant pool entry to get its address. 8638 const Value *OpVal = OpInfo.CallOperandVal; 8639 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 8640 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 8641 OpInfo.CallOperand = DAG.getConstantPool( 8642 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 8643 return Chain; 8644 } 8645 8646 // Otherwise, create a stack slot and emit a store to it before the asm. 8647 Type *Ty = OpVal->getType(); 8648 auto &DL = DAG.getDataLayout(); 8649 uint64_t TySize = DL.getTypeAllocSize(Ty); 8650 MachineFunction &MF = DAG.getMachineFunction(); 8651 int SSFI = MF.getFrameInfo().CreateStackObject( 8652 TySize, DL.getPrefTypeAlign(Ty), false); 8653 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 8654 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 8655 MachinePointerInfo::getFixedStack(MF, SSFI), 8656 TLI.getMemValueType(DL, Ty)); 8657 OpInfo.CallOperand = StackSlot; 8658 8659 return Chain; 8660 } 8661 8662 /// GetRegistersForValue - Assign registers (virtual or physical) for the 8663 /// specified operand. We prefer to assign virtual registers, to allow the 8664 /// register allocator to handle the assignment process. However, if the asm 8665 /// uses features that we can't model on machineinstrs, we have SDISel do the 8666 /// allocation. This produces generally horrible, but correct, code. 8667 /// 8668 /// OpInfo describes the operand 8669 /// RefOpInfo describes the matching operand if any, the operand otherwise 8670 static std::optional<unsigned> 8671 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 8672 SDISelAsmOperandInfo &OpInfo, 8673 SDISelAsmOperandInfo &RefOpInfo) { 8674 LLVMContext &Context = *DAG.getContext(); 8675 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8676 8677 MachineFunction &MF = DAG.getMachineFunction(); 8678 SmallVector<unsigned, 4> Regs; 8679 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8680 8681 // No work to do for memory/address operands. 8682 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8683 OpInfo.ConstraintType == TargetLowering::C_Address) 8684 return std::nullopt; 8685 8686 // If this is a constraint for a single physreg, or a constraint for a 8687 // register class, find it. 8688 unsigned AssignedReg; 8689 const TargetRegisterClass *RC; 8690 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 8691 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 8692 // RC is unset only on failure. Return immediately. 8693 if (!RC) 8694 return std::nullopt; 8695 8696 // Get the actual register value type. This is important, because the user 8697 // may have asked for (e.g.) the AX register in i32 type. We need to 8698 // remember that AX is actually i16 to get the right extension. 8699 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 8700 8701 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) { 8702 // If this is an FP operand in an integer register (or visa versa), or more 8703 // generally if the operand value disagrees with the register class we plan 8704 // to stick it in, fix the operand type. 8705 // 8706 // If this is an input value, the bitcast to the new type is done now. 8707 // Bitcast for output value is done at the end of visitInlineAsm(). 8708 if ((OpInfo.Type == InlineAsm::isOutput || 8709 OpInfo.Type == InlineAsm::isInput) && 8710 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 8711 // Try to convert to the first EVT that the reg class contains. If the 8712 // types are identical size, use a bitcast to convert (e.g. two differing 8713 // vector types). Note: output bitcast is done at the end of 8714 // visitInlineAsm(). 8715 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 8716 // Exclude indirect inputs while they are unsupported because the code 8717 // to perform the load is missing and thus OpInfo.CallOperand still 8718 // refers to the input address rather than the pointed-to value. 8719 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 8720 OpInfo.CallOperand = 8721 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 8722 OpInfo.ConstraintVT = RegVT; 8723 // If the operand is an FP value and we want it in integer registers, 8724 // use the corresponding integer type. This turns an f64 value into 8725 // i64, which can be passed with two i32 values on a 32-bit machine. 8726 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 8727 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 8728 if (OpInfo.Type == InlineAsm::isInput) 8729 OpInfo.CallOperand = 8730 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 8731 OpInfo.ConstraintVT = VT; 8732 } 8733 } 8734 } 8735 8736 // No need to allocate a matching input constraint since the constraint it's 8737 // matching to has already been allocated. 8738 if (OpInfo.isMatchingInputConstraint()) 8739 return std::nullopt; 8740 8741 EVT ValueVT = OpInfo.ConstraintVT; 8742 if (OpInfo.ConstraintVT == MVT::Other) 8743 ValueVT = RegVT; 8744 8745 // Initialize NumRegs. 8746 unsigned NumRegs = 1; 8747 if (OpInfo.ConstraintVT != MVT::Other) 8748 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT); 8749 8750 // If this is a constraint for a specific physical register, like {r17}, 8751 // assign it now. 8752 8753 // If this associated to a specific register, initialize iterator to correct 8754 // place. If virtual, make sure we have enough registers 8755 8756 // Initialize iterator if necessary 8757 TargetRegisterClass::iterator I = RC->begin(); 8758 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8759 8760 // Do not check for single registers. 8761 if (AssignedReg) { 8762 I = std::find(I, RC->end(), AssignedReg); 8763 if (I == RC->end()) { 8764 // RC does not contain the selected register, which indicates a 8765 // mismatch between the register and the required type/bitwidth. 8766 return {AssignedReg}; 8767 } 8768 } 8769 8770 for (; NumRegs; --NumRegs, ++I) { 8771 assert(I != RC->end() && "Ran out of registers to allocate!"); 8772 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8773 Regs.push_back(R); 8774 } 8775 8776 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8777 return std::nullopt; 8778 } 8779 8780 static unsigned 8781 findMatchingInlineAsmOperand(unsigned OperandNo, 8782 const std::vector<SDValue> &AsmNodeOperands) { 8783 // Scan until we find the definition we already emitted of this operand. 8784 unsigned CurOp = InlineAsm::Op_FirstOperand; 8785 for (; OperandNo; --OperandNo) { 8786 // Advance to the next operand. 8787 unsigned OpFlag = 8788 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8789 assert((InlineAsm::isRegDefKind(OpFlag) || 8790 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8791 InlineAsm::isMemKind(OpFlag)) && 8792 "Skipped past definitions?"); 8793 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8794 } 8795 return CurOp; 8796 } 8797 8798 namespace { 8799 8800 class ExtraFlags { 8801 unsigned Flags = 0; 8802 8803 public: 8804 explicit ExtraFlags(const CallBase &Call) { 8805 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8806 if (IA->hasSideEffects()) 8807 Flags |= InlineAsm::Extra_HasSideEffects; 8808 if (IA->isAlignStack()) 8809 Flags |= InlineAsm::Extra_IsAlignStack; 8810 if (Call.isConvergent()) 8811 Flags |= InlineAsm::Extra_IsConvergent; 8812 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8813 } 8814 8815 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8816 // Ideally, we would only check against memory constraints. However, the 8817 // meaning of an Other constraint can be target-specific and we can't easily 8818 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8819 // for Other constraints as well. 8820 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8821 OpInfo.ConstraintType == TargetLowering::C_Other) { 8822 if (OpInfo.Type == InlineAsm::isInput) 8823 Flags |= InlineAsm::Extra_MayLoad; 8824 else if (OpInfo.Type == InlineAsm::isOutput) 8825 Flags |= InlineAsm::Extra_MayStore; 8826 else if (OpInfo.Type == InlineAsm::isClobber) 8827 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8828 } 8829 } 8830 8831 unsigned get() const { return Flags; } 8832 }; 8833 8834 } // end anonymous namespace 8835 8836 static bool isFunction(SDValue Op) { 8837 if (Op && Op.getOpcode() == ISD::GlobalAddress) { 8838 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 8839 auto Fn = dyn_cast_or_null<Function>(GA->getGlobal()); 8840 8841 // In normal "call dllimport func" instruction (non-inlineasm) it force 8842 // indirect access by specifing call opcode. And usually specially print 8843 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can 8844 // not do in this way now. (In fact, this is similar with "Data Access" 8845 // action). So here we ignore dllimport function. 8846 if (Fn && !Fn->hasDLLImportStorageClass()) 8847 return true; 8848 } 8849 } 8850 return false; 8851 } 8852 8853 /// visitInlineAsm - Handle a call to an InlineAsm object. 8854 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 8855 const BasicBlock *EHPadBB) { 8856 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8857 8858 /// ConstraintOperands - Information about all of the constraints. 8859 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 8860 8861 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8862 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8863 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 8864 8865 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8866 // AsmDialect, MayLoad, MayStore). 8867 bool HasSideEffect = IA->hasSideEffects(); 8868 ExtraFlags ExtraInfo(Call); 8869 8870 for (auto &T : TargetConstraints) { 8871 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8872 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8873 8874 if (OpInfo.CallOperandVal) 8875 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8876 8877 if (!HasSideEffect) 8878 HasSideEffect = OpInfo.hasMemory(TLI); 8879 8880 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8881 // FIXME: Could we compute this on OpInfo rather than T? 8882 8883 // Compute the constraint code and ConstraintType to use. 8884 TLI.ComputeConstraintToUse(T, SDValue()); 8885 8886 if (T.ConstraintType == TargetLowering::C_Immediate && 8887 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8888 // We've delayed emitting a diagnostic like the "n" constraint because 8889 // inlining could cause an integer showing up. 8890 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 8891 "' expects an integer constant " 8892 "expression"); 8893 8894 ExtraInfo.update(T); 8895 } 8896 8897 // We won't need to flush pending loads if this asm doesn't touch 8898 // memory and is nonvolatile. 8899 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8900 8901 bool EmitEHLabels = isa<InvokeInst>(Call); 8902 if (EmitEHLabels) { 8903 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 8904 } 8905 bool IsCallBr = isa<CallBrInst>(Call); 8906 8907 if (IsCallBr || EmitEHLabels) { 8908 // If this is a callbr or invoke we need to flush pending exports since 8909 // inlineasm_br and invoke are terminators. 8910 // We need to do this before nodes are glued to the inlineasm_br node. 8911 Chain = getControlRoot(); 8912 } 8913 8914 MCSymbol *BeginLabel = nullptr; 8915 if (EmitEHLabels) { 8916 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 8917 } 8918 8919 int OpNo = -1; 8920 SmallVector<StringRef> AsmStrs; 8921 IA->collectAsmStrs(AsmStrs); 8922 8923 // Second pass over the constraints: compute which constraint option to use. 8924 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8925 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput) 8926 OpNo++; 8927 8928 // If this is an output operand with a matching input operand, look up the 8929 // matching input. If their types mismatch, e.g. one is an integer, the 8930 // other is floating point, or their sizes are different, flag it as an 8931 // error. 8932 if (OpInfo.hasMatchingInput()) { 8933 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8934 patchMatchingInput(OpInfo, Input, DAG); 8935 } 8936 8937 // Compute the constraint code and ConstraintType to use. 8938 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8939 8940 if ((OpInfo.ConstraintType == TargetLowering::C_Memory && 8941 OpInfo.Type == InlineAsm::isClobber) || 8942 OpInfo.ConstraintType == TargetLowering::C_Address) 8943 continue; 8944 8945 // In Linux PIC model, there are 4 cases about value/label addressing: 8946 // 8947 // 1: Function call or Label jmp inside the module. 8948 // 2: Data access (such as global variable, static variable) inside module. 8949 // 3: Function call or Label jmp outside the module. 8950 // 4: Data access (such as global variable) outside the module. 8951 // 8952 // Due to current llvm inline asm architecture designed to not "recognize" 8953 // the asm code, there are quite troubles for us to treat mem addressing 8954 // differently for same value/adress used in different instuctions. 8955 // For example, in pic model, call a func may in plt way or direclty 8956 // pc-related, but lea/mov a function adress may use got. 8957 // 8958 // Here we try to "recognize" function call for the case 1 and case 3 in 8959 // inline asm. And try to adjust the constraint for them. 8960 // 8961 // TODO: Due to current inline asm didn't encourage to jmp to the outsider 8962 // label, so here we don't handle jmp function label now, but we need to 8963 // enhance it (especilly in PIC model) if we meet meaningful requirements. 8964 if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) && 8965 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) && 8966 TM.getCodeModel() != CodeModel::Large) { 8967 OpInfo.isIndirect = false; 8968 OpInfo.ConstraintType = TargetLowering::C_Address; 8969 } 8970 8971 // If this is a memory input, and if the operand is not indirect, do what we 8972 // need to provide an address for the memory input. 8973 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8974 !OpInfo.isIndirect) { 8975 assert((OpInfo.isMultipleAlternative || 8976 (OpInfo.Type == InlineAsm::isInput)) && 8977 "Can only indirectify direct input operands!"); 8978 8979 // Memory operands really want the address of the value. 8980 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8981 8982 // There is no longer a Value* corresponding to this operand. 8983 OpInfo.CallOperandVal = nullptr; 8984 8985 // It is now an indirect operand. 8986 OpInfo.isIndirect = true; 8987 } 8988 8989 } 8990 8991 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8992 std::vector<SDValue> AsmNodeOperands; 8993 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8994 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8995 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 8996 8997 // If we have a !srcloc metadata node associated with it, we want to attach 8998 // this to the ultimately generated inline asm machineinstr. To do this, we 8999 // pass in the third operand as this (potentially null) inline asm MDNode. 9000 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 9001 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 9002 9003 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 9004 // bits as operand 3. 9005 AsmNodeOperands.push_back(DAG.getTargetConstant( 9006 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9007 9008 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 9009 // this, assign virtual and physical registers for inputs and otput. 9010 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9011 // Assign Registers. 9012 SDISelAsmOperandInfo &RefOpInfo = 9013 OpInfo.isMatchingInputConstraint() 9014 ? ConstraintOperands[OpInfo.getMatchedOperand()] 9015 : OpInfo; 9016 const auto RegError = 9017 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 9018 if (RegError) { 9019 const MachineFunction &MF = DAG.getMachineFunction(); 9020 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9021 const char *RegName = TRI.getName(*RegError); 9022 emitInlineAsmError(Call, "register '" + Twine(RegName) + 9023 "' allocated for constraint '" + 9024 Twine(OpInfo.ConstraintCode) + 9025 "' does not match required type"); 9026 return; 9027 } 9028 9029 auto DetectWriteToReservedRegister = [&]() { 9030 const MachineFunction &MF = DAG.getMachineFunction(); 9031 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9032 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 9033 if (Register::isPhysicalRegister(Reg) && 9034 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 9035 const char *RegName = TRI.getName(Reg); 9036 emitInlineAsmError(Call, "write to reserved register '" + 9037 Twine(RegName) + "'"); 9038 return true; 9039 } 9040 } 9041 return false; 9042 }; 9043 assert((OpInfo.ConstraintType != TargetLowering::C_Address || 9044 (OpInfo.Type == InlineAsm::isInput && 9045 !OpInfo.isMatchingInputConstraint())) && 9046 "Only address as input operand is allowed."); 9047 9048 switch (OpInfo.Type) { 9049 case InlineAsm::isOutput: 9050 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9051 unsigned ConstraintID = 9052 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9053 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9054 "Failed to convert memory constraint code to constraint id."); 9055 9056 // Add information to the INLINEASM node to know about this output. 9057 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9058 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 9059 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 9060 MVT::i32)); 9061 AsmNodeOperands.push_back(OpInfo.CallOperand); 9062 } else { 9063 // Otherwise, this outputs to a register (directly for C_Register / 9064 // C_RegisterClass, and a target-defined fashion for 9065 // C_Immediate/C_Other). Find a register that we can use. 9066 if (OpInfo.AssignedRegs.Regs.empty()) { 9067 emitInlineAsmError( 9068 Call, "couldn't allocate output register for constraint '" + 9069 Twine(OpInfo.ConstraintCode) + "'"); 9070 return; 9071 } 9072 9073 if (DetectWriteToReservedRegister()) 9074 return; 9075 9076 // Add information to the INLINEASM node to know that this register is 9077 // set. 9078 OpInfo.AssignedRegs.AddInlineAsmOperands( 9079 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 9080 : InlineAsm::Kind_RegDef, 9081 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 9082 } 9083 break; 9084 9085 case InlineAsm::isInput: 9086 case InlineAsm::isLabel: { 9087 SDValue InOperandVal = OpInfo.CallOperand; 9088 9089 if (OpInfo.isMatchingInputConstraint()) { 9090 // If this is required to match an output register we have already set, 9091 // just use its register. 9092 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 9093 AsmNodeOperands); 9094 unsigned OpFlag = 9095 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 9096 if (InlineAsm::isRegDefKind(OpFlag) || 9097 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 9098 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 9099 if (OpInfo.isIndirect) { 9100 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 9101 emitInlineAsmError(Call, "inline asm not supported yet: " 9102 "don't know how to handle tied " 9103 "indirect register inputs"); 9104 return; 9105 } 9106 9107 SmallVector<unsigned, 4> Regs; 9108 MachineFunction &MF = DAG.getMachineFunction(); 9109 MachineRegisterInfo &MRI = MF.getRegInfo(); 9110 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9111 auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]); 9112 Register TiedReg = R->getReg(); 9113 MVT RegVT = R->getSimpleValueType(0); 9114 const TargetRegisterClass *RC = 9115 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg) 9116 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT) 9117 : TRI.getMinimalPhysRegClass(TiedReg); 9118 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 9119 for (unsigned i = 0; i != NumRegs; ++i) 9120 Regs.push_back(MRI.createVirtualRegister(RC)); 9121 9122 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 9123 9124 SDLoc dl = getCurSDLoc(); 9125 // Use the produced MatchedRegs object to 9126 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call); 9127 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 9128 true, OpInfo.getMatchedOperand(), dl, 9129 DAG, AsmNodeOperands); 9130 break; 9131 } 9132 9133 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 9134 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 9135 "Unexpected number of operands"); 9136 // Add information to the INLINEASM node to know about this input. 9137 // See InlineAsm.h isUseOperandTiedToDef. 9138 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 9139 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 9140 OpInfo.getMatchedOperand()); 9141 AsmNodeOperands.push_back(DAG.getTargetConstant( 9142 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9143 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 9144 break; 9145 } 9146 9147 // Treat indirect 'X' constraint as memory. 9148 if (OpInfo.ConstraintType == TargetLowering::C_Other && 9149 OpInfo.isIndirect) 9150 OpInfo.ConstraintType = TargetLowering::C_Memory; 9151 9152 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 9153 OpInfo.ConstraintType == TargetLowering::C_Other) { 9154 std::vector<SDValue> Ops; 9155 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 9156 Ops, DAG); 9157 if (Ops.empty()) { 9158 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 9159 if (isa<ConstantSDNode>(InOperandVal)) { 9160 emitInlineAsmError(Call, "value out of range for constraint '" + 9161 Twine(OpInfo.ConstraintCode) + "'"); 9162 return; 9163 } 9164 9165 emitInlineAsmError(Call, 9166 "invalid operand for inline asm constraint '" + 9167 Twine(OpInfo.ConstraintCode) + "'"); 9168 return; 9169 } 9170 9171 // Add information to the INLINEASM node to know about this input. 9172 unsigned ResOpType = 9173 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 9174 AsmNodeOperands.push_back(DAG.getTargetConstant( 9175 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9176 llvm::append_range(AsmNodeOperands, Ops); 9177 break; 9178 } 9179 9180 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9181 assert((OpInfo.isIndirect || 9182 OpInfo.ConstraintType != TargetLowering::C_Memory) && 9183 "Operand must be indirect to be a mem!"); 9184 assert(InOperandVal.getValueType() == 9185 TLI.getPointerTy(DAG.getDataLayout()) && 9186 "Memory operands expect pointer values"); 9187 9188 unsigned ConstraintID = 9189 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9190 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9191 "Failed to convert memory constraint code to constraint id."); 9192 9193 // Add information to the INLINEASM node to know about this input. 9194 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9195 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 9196 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 9197 getCurSDLoc(), 9198 MVT::i32)); 9199 AsmNodeOperands.push_back(InOperandVal); 9200 break; 9201 } 9202 9203 if (OpInfo.ConstraintType == TargetLowering::C_Address) { 9204 assert(InOperandVal.getValueType() == 9205 TLI.getPointerTy(DAG.getDataLayout()) && 9206 "Address operands expect pointer values"); 9207 9208 unsigned ConstraintID = 9209 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9210 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9211 "Failed to convert memory constraint code to constraint id."); 9212 9213 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9214 9215 SDValue AsmOp = InOperandVal; 9216 if (isFunction(InOperandVal)) { 9217 auto *GA = cast<GlobalAddressSDNode>(InOperandVal); 9218 ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Func, 1); 9219 AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(), 9220 InOperandVal.getValueType(), 9221 GA->getOffset()); 9222 } 9223 9224 // Add information to the INLINEASM node to know about this input. 9225 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 9226 9227 AsmNodeOperands.push_back( 9228 DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32)); 9229 9230 AsmNodeOperands.push_back(AsmOp); 9231 break; 9232 } 9233 9234 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 9235 OpInfo.ConstraintType == TargetLowering::C_Register) && 9236 "Unknown constraint type!"); 9237 9238 // TODO: Support this. 9239 if (OpInfo.isIndirect) { 9240 emitInlineAsmError( 9241 Call, "Don't know how to handle indirect register inputs yet " 9242 "for constraint '" + 9243 Twine(OpInfo.ConstraintCode) + "'"); 9244 return; 9245 } 9246 9247 // Copy the input into the appropriate registers. 9248 if (OpInfo.AssignedRegs.Regs.empty()) { 9249 emitInlineAsmError(Call, 9250 "couldn't allocate input reg for constraint '" + 9251 Twine(OpInfo.ConstraintCode) + "'"); 9252 return; 9253 } 9254 9255 if (DetectWriteToReservedRegister()) 9256 return; 9257 9258 SDLoc dl = getCurSDLoc(); 9259 9260 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 9261 &Call); 9262 9263 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 9264 dl, DAG, AsmNodeOperands); 9265 break; 9266 } 9267 case InlineAsm::isClobber: 9268 // Add the clobbered value to the operand list, so that the register 9269 // allocator is aware that the physreg got clobbered. 9270 if (!OpInfo.AssignedRegs.Regs.empty()) 9271 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 9272 false, 0, getCurSDLoc(), DAG, 9273 AsmNodeOperands); 9274 break; 9275 } 9276 } 9277 9278 // Finish up input operands. Set the input chain and add the flag last. 9279 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 9280 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 9281 9282 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 9283 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 9284 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 9285 Flag = Chain.getValue(1); 9286 9287 // Do additional work to generate outputs. 9288 9289 SmallVector<EVT, 1> ResultVTs; 9290 SmallVector<SDValue, 1> ResultValues; 9291 SmallVector<SDValue, 8> OutChains; 9292 9293 llvm::Type *CallResultType = Call.getType(); 9294 ArrayRef<Type *> ResultTypes; 9295 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 9296 ResultTypes = StructResult->elements(); 9297 else if (!CallResultType->isVoidTy()) 9298 ResultTypes = ArrayRef(CallResultType); 9299 9300 auto CurResultType = ResultTypes.begin(); 9301 auto handleRegAssign = [&](SDValue V) { 9302 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 9303 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 9304 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 9305 ++CurResultType; 9306 // If the type of the inline asm call site return value is different but has 9307 // same size as the type of the asm output bitcast it. One example of this 9308 // is for vectors with different width / number of elements. This can 9309 // happen for register classes that can contain multiple different value 9310 // types. The preg or vreg allocated may not have the same VT as was 9311 // expected. 9312 // 9313 // This can also happen for a return value that disagrees with the register 9314 // class it is put in, eg. a double in a general-purpose register on a 9315 // 32-bit machine. 9316 if (ResultVT != V.getValueType() && 9317 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 9318 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 9319 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 9320 V.getValueType().isInteger()) { 9321 // If a result value was tied to an input value, the computed result 9322 // may have a wider width than the expected result. Extract the 9323 // relevant portion. 9324 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 9325 } 9326 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 9327 ResultVTs.push_back(ResultVT); 9328 ResultValues.push_back(V); 9329 }; 9330 9331 // Deal with output operands. 9332 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9333 if (OpInfo.Type == InlineAsm::isOutput) { 9334 SDValue Val; 9335 // Skip trivial output operands. 9336 if (OpInfo.AssignedRegs.Regs.empty()) 9337 continue; 9338 9339 switch (OpInfo.ConstraintType) { 9340 case TargetLowering::C_Register: 9341 case TargetLowering::C_RegisterClass: 9342 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 9343 Chain, &Flag, &Call); 9344 break; 9345 case TargetLowering::C_Immediate: 9346 case TargetLowering::C_Other: 9347 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 9348 OpInfo, DAG); 9349 break; 9350 case TargetLowering::C_Memory: 9351 break; // Already handled. 9352 case TargetLowering::C_Address: 9353 break; // Silence warning. 9354 case TargetLowering::C_Unknown: 9355 assert(false && "Unexpected unknown constraint"); 9356 } 9357 9358 // Indirect output manifest as stores. Record output chains. 9359 if (OpInfo.isIndirect) { 9360 const Value *Ptr = OpInfo.CallOperandVal; 9361 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 9362 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 9363 MachinePointerInfo(Ptr)); 9364 OutChains.push_back(Store); 9365 } else { 9366 // generate CopyFromRegs to associated registers. 9367 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 9368 if (Val.getOpcode() == ISD::MERGE_VALUES) { 9369 for (const SDValue &V : Val->op_values()) 9370 handleRegAssign(V); 9371 } else 9372 handleRegAssign(Val); 9373 } 9374 } 9375 } 9376 9377 // Set results. 9378 if (!ResultValues.empty()) { 9379 assert(CurResultType == ResultTypes.end() && 9380 "Mismatch in number of ResultTypes"); 9381 assert(ResultValues.size() == ResultTypes.size() && 9382 "Mismatch in number of output operands in asm result"); 9383 9384 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 9385 DAG.getVTList(ResultVTs), ResultValues); 9386 setValue(&Call, V); 9387 } 9388 9389 // Collect store chains. 9390 if (!OutChains.empty()) 9391 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 9392 9393 if (EmitEHLabels) { 9394 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 9395 } 9396 9397 // Only Update Root if inline assembly has a memory effect. 9398 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 9399 EmitEHLabels) 9400 DAG.setRoot(Chain); 9401 } 9402 9403 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 9404 const Twine &Message) { 9405 LLVMContext &Ctx = *DAG.getContext(); 9406 Ctx.emitError(&Call, Message); 9407 9408 // Make sure we leave the DAG in a valid state 9409 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9410 SmallVector<EVT, 1> ValueVTs; 9411 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 9412 9413 if (ValueVTs.empty()) 9414 return; 9415 9416 SmallVector<SDValue, 1> Ops; 9417 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 9418 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 9419 9420 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 9421 } 9422 9423 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 9424 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 9425 MVT::Other, getRoot(), 9426 getValue(I.getArgOperand(0)), 9427 DAG.getSrcValue(I.getArgOperand(0)))); 9428 } 9429 9430 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 9431 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9432 const DataLayout &DL = DAG.getDataLayout(); 9433 SDValue V = DAG.getVAArg( 9434 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 9435 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 9436 DL.getABITypeAlign(I.getType()).value()); 9437 DAG.setRoot(V.getValue(1)); 9438 9439 if (I.getType()->isPointerTy()) 9440 V = DAG.getPtrExtOrTrunc( 9441 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 9442 setValue(&I, V); 9443 } 9444 9445 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 9446 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 9447 MVT::Other, getRoot(), 9448 getValue(I.getArgOperand(0)), 9449 DAG.getSrcValue(I.getArgOperand(0)))); 9450 } 9451 9452 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 9453 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 9454 MVT::Other, getRoot(), 9455 getValue(I.getArgOperand(0)), 9456 getValue(I.getArgOperand(1)), 9457 DAG.getSrcValue(I.getArgOperand(0)), 9458 DAG.getSrcValue(I.getArgOperand(1)))); 9459 } 9460 9461 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 9462 const Instruction &I, 9463 SDValue Op) { 9464 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 9465 if (!Range) 9466 return Op; 9467 9468 ConstantRange CR = getConstantRangeFromMetadata(*Range); 9469 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 9470 return Op; 9471 9472 APInt Lo = CR.getUnsignedMin(); 9473 if (!Lo.isMinValue()) 9474 return Op; 9475 9476 APInt Hi = CR.getUnsignedMax(); 9477 unsigned Bits = std::max(Hi.getActiveBits(), 9478 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 9479 9480 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9481 9482 SDLoc SL = getCurSDLoc(); 9483 9484 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 9485 DAG.getValueType(SmallVT)); 9486 unsigned NumVals = Op.getNode()->getNumValues(); 9487 if (NumVals == 1) 9488 return ZExt; 9489 9490 SmallVector<SDValue, 4> Ops; 9491 9492 Ops.push_back(ZExt); 9493 for (unsigned I = 1; I != NumVals; ++I) 9494 Ops.push_back(Op.getValue(I)); 9495 9496 return DAG.getMergeValues(Ops, SL); 9497 } 9498 9499 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 9500 /// the call being lowered. 9501 /// 9502 /// This is a helper for lowering intrinsics that follow a target calling 9503 /// convention or require stack pointer adjustment. Only a subset of the 9504 /// intrinsic's operands need to participate in the calling convention. 9505 void SelectionDAGBuilder::populateCallLoweringInfo( 9506 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 9507 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 9508 bool IsPatchPoint) { 9509 TargetLowering::ArgListTy Args; 9510 Args.reserve(NumArgs); 9511 9512 // Populate the argument list. 9513 // Attributes for args start at offset 1, after the return attribute. 9514 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 9515 ArgI != ArgE; ++ArgI) { 9516 const Value *V = Call->getOperand(ArgI); 9517 9518 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 9519 9520 TargetLowering::ArgListEntry Entry; 9521 Entry.Node = getValue(V); 9522 Entry.Ty = V->getType(); 9523 Entry.setAttributes(Call, ArgI); 9524 Args.push_back(Entry); 9525 } 9526 9527 CLI.setDebugLoc(getCurSDLoc()) 9528 .setChain(getRoot()) 9529 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 9530 .setDiscardResult(Call->use_empty()) 9531 .setIsPatchPoint(IsPatchPoint) 9532 .setIsPreallocated( 9533 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 9534 } 9535 9536 /// Add a stack map intrinsic call's live variable operands to a stackmap 9537 /// or patchpoint target node's operand list. 9538 /// 9539 /// Constants are converted to TargetConstants purely as an optimization to 9540 /// avoid constant materialization and register allocation. 9541 /// 9542 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 9543 /// generate addess computation nodes, and so FinalizeISel can convert the 9544 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 9545 /// address materialization and register allocation, but may also be required 9546 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 9547 /// alloca in the entry block, then the runtime may assume that the alloca's 9548 /// StackMap location can be read immediately after compilation and that the 9549 /// location is valid at any point during execution (this is similar to the 9550 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 9551 /// only available in a register, then the runtime would need to trap when 9552 /// execution reaches the StackMap in order to read the alloca's location. 9553 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 9554 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 9555 SelectionDAGBuilder &Builder) { 9556 SelectionDAG &DAG = Builder.DAG; 9557 for (unsigned I = StartIdx; I < Call.arg_size(); I++) { 9558 SDValue Op = Builder.getValue(Call.getArgOperand(I)); 9559 9560 // Things on the stack are pointer-typed, meaning that they are already 9561 // legal and can be emitted directly to target nodes. 9562 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) { 9563 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType())); 9564 } else { 9565 // Otherwise emit a target independent node to be legalised. 9566 Ops.push_back(Builder.getValue(Call.getArgOperand(I))); 9567 } 9568 } 9569 } 9570 9571 /// Lower llvm.experimental.stackmap. 9572 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 9573 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>, 9574 // [live variables...]) 9575 9576 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 9577 9578 SDValue Chain, InFlag, Callee; 9579 SmallVector<SDValue, 32> Ops; 9580 9581 SDLoc DL = getCurSDLoc(); 9582 Callee = getValue(CI.getCalledOperand()); 9583 9584 // The stackmap intrinsic only records the live variables (the arguments 9585 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 9586 // intrinsic, this won't be lowered to a function call. This means we don't 9587 // have to worry about calling conventions and target specific lowering code. 9588 // Instead we perform the call lowering right here. 9589 // 9590 // chain, flag = CALLSEQ_START(chain, 0, 0) 9591 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 9592 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 9593 // 9594 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 9595 InFlag = Chain.getValue(1); 9596 9597 // Add the STACKMAP operands, starting with DAG house-keeping. 9598 Ops.push_back(Chain); 9599 Ops.push_back(InFlag); 9600 9601 // Add the <id>, <numShadowBytes> operands. 9602 // 9603 // These do not require legalisation, and can be emitted directly to target 9604 // constant nodes. 9605 SDValue ID = getValue(CI.getArgOperand(0)); 9606 assert(ID.getValueType() == MVT::i64); 9607 SDValue IDConst = DAG.getTargetConstant( 9608 cast<ConstantSDNode>(ID)->getZExtValue(), DL, ID.getValueType()); 9609 Ops.push_back(IDConst); 9610 9611 SDValue Shad = getValue(CI.getArgOperand(1)); 9612 assert(Shad.getValueType() == MVT::i32); 9613 SDValue ShadConst = DAG.getTargetConstant( 9614 cast<ConstantSDNode>(Shad)->getZExtValue(), DL, Shad.getValueType()); 9615 Ops.push_back(ShadConst); 9616 9617 // Add the live variables. 9618 addStackMapLiveVars(CI, 2, DL, Ops, *this); 9619 9620 // Create the STACKMAP node. 9621 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9622 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops); 9623 InFlag = Chain.getValue(1); 9624 9625 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InFlag, DL); 9626 9627 // Stackmaps don't generate values, so nothing goes into the NodeMap. 9628 9629 // Set the root to the target-lowered call chain. 9630 DAG.setRoot(Chain); 9631 9632 // Inform the Frame Information that we have a stackmap in this function. 9633 FuncInfo.MF->getFrameInfo().setHasStackMap(); 9634 } 9635 9636 /// Lower llvm.experimental.patchpoint directly to its target opcode. 9637 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 9638 const BasicBlock *EHPadBB) { 9639 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 9640 // i32 <numBytes>, 9641 // i8* <target>, 9642 // i32 <numArgs>, 9643 // [Args...], 9644 // [live variables...]) 9645 9646 CallingConv::ID CC = CB.getCallingConv(); 9647 bool IsAnyRegCC = CC == CallingConv::AnyReg; 9648 bool HasDef = !CB.getType()->isVoidTy(); 9649 SDLoc dl = getCurSDLoc(); 9650 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 9651 9652 // Handle immediate and symbolic callees. 9653 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 9654 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 9655 /*isTarget=*/true); 9656 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 9657 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 9658 SDLoc(SymbolicCallee), 9659 SymbolicCallee->getValueType(0)); 9660 9661 // Get the real number of arguments participating in the call <numArgs> 9662 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 9663 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 9664 9665 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 9666 // Intrinsics include all meta-operands up to but not including CC. 9667 unsigned NumMetaOpers = PatchPointOpers::CCPos; 9668 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 9669 "Not enough arguments provided to the patchpoint intrinsic"); 9670 9671 // For AnyRegCC the arguments are lowered later on manually. 9672 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 9673 Type *ReturnTy = 9674 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 9675 9676 TargetLowering::CallLoweringInfo CLI(DAG); 9677 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 9678 ReturnTy, true); 9679 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 9680 9681 SDNode *CallEnd = Result.second.getNode(); 9682 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 9683 CallEnd = CallEnd->getOperand(0).getNode(); 9684 9685 /// Get a call instruction from the call sequence chain. 9686 /// Tail calls are not allowed. 9687 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 9688 "Expected a callseq node."); 9689 SDNode *Call = CallEnd->getOperand(0).getNode(); 9690 bool HasGlue = Call->getGluedNode(); 9691 9692 // Replace the target specific call node with the patchable intrinsic. 9693 SmallVector<SDValue, 8> Ops; 9694 9695 // Push the chain. 9696 Ops.push_back(*(Call->op_begin())); 9697 9698 // Optionally, push the glue (if any). 9699 if (HasGlue) 9700 Ops.push_back(*(Call->op_end() - 1)); 9701 9702 // Push the register mask info. 9703 if (HasGlue) 9704 Ops.push_back(*(Call->op_end() - 2)); 9705 else 9706 Ops.push_back(*(Call->op_end() - 1)); 9707 9708 // Add the <id> and <numBytes> constants. 9709 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 9710 Ops.push_back(DAG.getTargetConstant( 9711 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 9712 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 9713 Ops.push_back(DAG.getTargetConstant( 9714 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 9715 MVT::i32)); 9716 9717 // Add the callee. 9718 Ops.push_back(Callee); 9719 9720 // Adjust <numArgs> to account for any arguments that have been passed on the 9721 // stack instead. 9722 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 9723 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 9724 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 9725 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 9726 9727 // Add the calling convention 9728 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 9729 9730 // Add the arguments we omitted previously. The register allocator should 9731 // place these in any free register. 9732 if (IsAnyRegCC) 9733 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 9734 Ops.push_back(getValue(CB.getArgOperand(i))); 9735 9736 // Push the arguments from the call instruction. 9737 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 9738 Ops.append(Call->op_begin() + 2, e); 9739 9740 // Push live variables for the stack map. 9741 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 9742 9743 SDVTList NodeTys; 9744 if (IsAnyRegCC && HasDef) { 9745 // Create the return types based on the intrinsic definition 9746 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9747 SmallVector<EVT, 3> ValueVTs; 9748 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 9749 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 9750 9751 // There is always a chain and a glue type at the end 9752 ValueVTs.push_back(MVT::Other); 9753 ValueVTs.push_back(MVT::Glue); 9754 NodeTys = DAG.getVTList(ValueVTs); 9755 } else 9756 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9757 9758 // Replace the target specific call node with a PATCHPOINT node. 9759 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops); 9760 9761 // Update the NodeMap. 9762 if (HasDef) { 9763 if (IsAnyRegCC) 9764 setValue(&CB, SDValue(PPV.getNode(), 0)); 9765 else 9766 setValue(&CB, Result.first); 9767 } 9768 9769 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 9770 // call sequence. Furthermore the location of the chain and glue can change 9771 // when the AnyReg calling convention is used and the intrinsic returns a 9772 // value. 9773 if (IsAnyRegCC && HasDef) { 9774 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 9775 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)}; 9776 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 9777 } else 9778 DAG.ReplaceAllUsesWith(Call, PPV.getNode()); 9779 DAG.DeleteNode(Call); 9780 9781 // Inform the Frame Information that we have a patchpoint in this function. 9782 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 9783 } 9784 9785 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 9786 unsigned Intrinsic) { 9787 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9788 SDValue Op1 = getValue(I.getArgOperand(0)); 9789 SDValue Op2; 9790 if (I.arg_size() > 1) 9791 Op2 = getValue(I.getArgOperand(1)); 9792 SDLoc dl = getCurSDLoc(); 9793 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 9794 SDValue Res; 9795 SDNodeFlags SDFlags; 9796 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 9797 SDFlags.copyFMF(*FPMO); 9798 9799 switch (Intrinsic) { 9800 case Intrinsic::vector_reduce_fadd: 9801 if (SDFlags.hasAllowReassociation()) 9802 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 9803 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 9804 SDFlags); 9805 else 9806 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 9807 break; 9808 case Intrinsic::vector_reduce_fmul: 9809 if (SDFlags.hasAllowReassociation()) 9810 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 9811 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 9812 SDFlags); 9813 else 9814 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 9815 break; 9816 case Intrinsic::vector_reduce_add: 9817 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 9818 break; 9819 case Intrinsic::vector_reduce_mul: 9820 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 9821 break; 9822 case Intrinsic::vector_reduce_and: 9823 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 9824 break; 9825 case Intrinsic::vector_reduce_or: 9826 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 9827 break; 9828 case Intrinsic::vector_reduce_xor: 9829 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 9830 break; 9831 case Intrinsic::vector_reduce_smax: 9832 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 9833 break; 9834 case Intrinsic::vector_reduce_smin: 9835 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 9836 break; 9837 case Intrinsic::vector_reduce_umax: 9838 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 9839 break; 9840 case Intrinsic::vector_reduce_umin: 9841 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 9842 break; 9843 case Intrinsic::vector_reduce_fmax: 9844 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 9845 break; 9846 case Intrinsic::vector_reduce_fmin: 9847 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 9848 break; 9849 default: 9850 llvm_unreachable("Unhandled vector reduce intrinsic"); 9851 } 9852 setValue(&I, Res); 9853 } 9854 9855 /// Returns an AttributeList representing the attributes applied to the return 9856 /// value of the given call. 9857 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9858 SmallVector<Attribute::AttrKind, 2> Attrs; 9859 if (CLI.RetSExt) 9860 Attrs.push_back(Attribute::SExt); 9861 if (CLI.RetZExt) 9862 Attrs.push_back(Attribute::ZExt); 9863 if (CLI.IsInReg) 9864 Attrs.push_back(Attribute::InReg); 9865 9866 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9867 Attrs); 9868 } 9869 9870 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9871 /// implementation, which just calls LowerCall. 9872 /// FIXME: When all targets are 9873 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9874 std::pair<SDValue, SDValue> 9875 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9876 // Handle the incoming return values from the call. 9877 CLI.Ins.clear(); 9878 Type *OrigRetTy = CLI.RetTy; 9879 SmallVector<EVT, 4> RetTys; 9880 SmallVector<uint64_t, 4> Offsets; 9881 auto &DL = CLI.DAG.getDataLayout(); 9882 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 9883 9884 if (CLI.IsPostTypeLegalization) { 9885 // If we are lowering a libcall after legalization, split the return type. 9886 SmallVector<EVT, 4> OldRetTys; 9887 SmallVector<uint64_t, 4> OldOffsets; 9888 RetTys.swap(OldRetTys); 9889 Offsets.swap(OldOffsets); 9890 9891 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9892 EVT RetVT = OldRetTys[i]; 9893 uint64_t Offset = OldOffsets[i]; 9894 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9895 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9896 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9897 RetTys.append(NumRegs, RegisterVT); 9898 for (unsigned j = 0; j != NumRegs; ++j) 9899 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9900 } 9901 } 9902 9903 SmallVector<ISD::OutputArg, 4> Outs; 9904 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9905 9906 bool CanLowerReturn = 9907 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9908 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9909 9910 SDValue DemoteStackSlot; 9911 int DemoteStackIdx = -100; 9912 if (!CanLowerReturn) { 9913 // FIXME: equivalent assert? 9914 // assert(!CS.hasInAllocaArgument() && 9915 // "sret demotion is incompatible with inalloca"); 9916 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9917 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 9918 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9919 DemoteStackIdx = 9920 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 9921 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9922 DL.getAllocaAddrSpace()); 9923 9924 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9925 ArgListEntry Entry; 9926 Entry.Node = DemoteStackSlot; 9927 Entry.Ty = StackSlotPtrType; 9928 Entry.IsSExt = false; 9929 Entry.IsZExt = false; 9930 Entry.IsInReg = false; 9931 Entry.IsSRet = true; 9932 Entry.IsNest = false; 9933 Entry.IsByVal = false; 9934 Entry.IsByRef = false; 9935 Entry.IsReturned = false; 9936 Entry.IsSwiftSelf = false; 9937 Entry.IsSwiftAsync = false; 9938 Entry.IsSwiftError = false; 9939 Entry.IsCFGuardTarget = false; 9940 Entry.Alignment = Alignment; 9941 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9942 CLI.NumFixedArgs += 1; 9943 CLI.getArgs()[0].IndirectType = CLI.RetTy; 9944 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9945 9946 // sret demotion isn't compatible with tail-calls, since the sret argument 9947 // points into the callers stack frame. 9948 CLI.IsTailCall = false; 9949 } else { 9950 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9951 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL); 9952 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9953 ISD::ArgFlagsTy Flags; 9954 if (NeedsRegBlock) { 9955 Flags.setInConsecutiveRegs(); 9956 if (I == RetTys.size() - 1) 9957 Flags.setInConsecutiveRegsLast(); 9958 } 9959 EVT VT = RetTys[I]; 9960 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9961 CLI.CallConv, VT); 9962 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9963 CLI.CallConv, VT); 9964 for (unsigned i = 0; i != NumRegs; ++i) { 9965 ISD::InputArg MyFlags; 9966 MyFlags.Flags = Flags; 9967 MyFlags.VT = RegisterVT; 9968 MyFlags.ArgVT = VT; 9969 MyFlags.Used = CLI.IsReturnValueUsed; 9970 if (CLI.RetTy->isPointerTy()) { 9971 MyFlags.Flags.setPointer(); 9972 MyFlags.Flags.setPointerAddrSpace( 9973 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9974 } 9975 if (CLI.RetSExt) 9976 MyFlags.Flags.setSExt(); 9977 if (CLI.RetZExt) 9978 MyFlags.Flags.setZExt(); 9979 if (CLI.IsInReg) 9980 MyFlags.Flags.setInReg(); 9981 CLI.Ins.push_back(MyFlags); 9982 } 9983 } 9984 } 9985 9986 // We push in swifterror return as the last element of CLI.Ins. 9987 ArgListTy &Args = CLI.getArgs(); 9988 if (supportSwiftError()) { 9989 for (const ArgListEntry &Arg : Args) { 9990 if (Arg.IsSwiftError) { 9991 ISD::InputArg MyFlags; 9992 MyFlags.VT = getPointerTy(DL); 9993 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9994 MyFlags.Flags.setSwiftError(); 9995 CLI.Ins.push_back(MyFlags); 9996 } 9997 } 9998 } 9999 10000 // Handle all of the outgoing arguments. 10001 CLI.Outs.clear(); 10002 CLI.OutVals.clear(); 10003 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 10004 SmallVector<EVT, 4> ValueVTs; 10005 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 10006 // FIXME: Split arguments if CLI.IsPostTypeLegalization 10007 Type *FinalType = Args[i].Ty; 10008 if (Args[i].IsByVal) 10009 FinalType = Args[i].IndirectType; 10010 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10011 FinalType, CLI.CallConv, CLI.IsVarArg, DL); 10012 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 10013 ++Value) { 10014 EVT VT = ValueVTs[Value]; 10015 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 10016 SDValue Op = SDValue(Args[i].Node.getNode(), 10017 Args[i].Node.getResNo() + Value); 10018 ISD::ArgFlagsTy Flags; 10019 10020 // Certain targets (such as MIPS), may have a different ABI alignment 10021 // for a type depending on the context. Give the target a chance to 10022 // specify the alignment it wants. 10023 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 10024 Flags.setOrigAlign(OriginalAlignment); 10025 10026 if (Args[i].Ty->isPointerTy()) { 10027 Flags.setPointer(); 10028 Flags.setPointerAddrSpace( 10029 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 10030 } 10031 if (Args[i].IsZExt) 10032 Flags.setZExt(); 10033 if (Args[i].IsSExt) 10034 Flags.setSExt(); 10035 if (Args[i].IsInReg) { 10036 // If we are using vectorcall calling convention, a structure that is 10037 // passed InReg - is surely an HVA 10038 if (CLI.CallConv == CallingConv::X86_VectorCall && 10039 isa<StructType>(FinalType)) { 10040 // The first value of a structure is marked 10041 if (0 == Value) 10042 Flags.setHvaStart(); 10043 Flags.setHva(); 10044 } 10045 // Set InReg Flag 10046 Flags.setInReg(); 10047 } 10048 if (Args[i].IsSRet) 10049 Flags.setSRet(); 10050 if (Args[i].IsSwiftSelf) 10051 Flags.setSwiftSelf(); 10052 if (Args[i].IsSwiftAsync) 10053 Flags.setSwiftAsync(); 10054 if (Args[i].IsSwiftError) 10055 Flags.setSwiftError(); 10056 if (Args[i].IsCFGuardTarget) 10057 Flags.setCFGuardTarget(); 10058 if (Args[i].IsByVal) 10059 Flags.setByVal(); 10060 if (Args[i].IsByRef) 10061 Flags.setByRef(); 10062 if (Args[i].IsPreallocated) { 10063 Flags.setPreallocated(); 10064 // Set the byval flag for CCAssignFn callbacks that don't know about 10065 // preallocated. This way we can know how many bytes we should've 10066 // allocated and how many bytes a callee cleanup function will pop. If 10067 // we port preallocated to more targets, we'll have to add custom 10068 // preallocated handling in the various CC lowering callbacks. 10069 Flags.setByVal(); 10070 } 10071 if (Args[i].IsInAlloca) { 10072 Flags.setInAlloca(); 10073 // Set the byval flag for CCAssignFn callbacks that don't know about 10074 // inalloca. This way we can know how many bytes we should've allocated 10075 // and how many bytes a callee cleanup function will pop. If we port 10076 // inalloca to more targets, we'll have to add custom inalloca handling 10077 // in the various CC lowering callbacks. 10078 Flags.setByVal(); 10079 } 10080 Align MemAlign; 10081 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 10082 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType); 10083 Flags.setByValSize(FrameSize); 10084 10085 // info is not there but there are cases it cannot get right. 10086 if (auto MA = Args[i].Alignment) 10087 MemAlign = *MA; 10088 else 10089 MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL)); 10090 } else if (auto MA = Args[i].Alignment) { 10091 MemAlign = *MA; 10092 } else { 10093 MemAlign = OriginalAlignment; 10094 } 10095 Flags.setMemAlign(MemAlign); 10096 if (Args[i].IsNest) 10097 Flags.setNest(); 10098 if (NeedsRegBlock) 10099 Flags.setInConsecutiveRegs(); 10100 10101 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10102 CLI.CallConv, VT); 10103 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10104 CLI.CallConv, VT); 10105 SmallVector<SDValue, 4> Parts(NumParts); 10106 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 10107 10108 if (Args[i].IsSExt) 10109 ExtendKind = ISD::SIGN_EXTEND; 10110 else if (Args[i].IsZExt) 10111 ExtendKind = ISD::ZERO_EXTEND; 10112 10113 // Conservatively only handle 'returned' on non-vectors that can be lowered, 10114 // for now. 10115 if (Args[i].IsReturned && !Op.getValueType().isVector() && 10116 CanLowerReturn) { 10117 assert((CLI.RetTy == Args[i].Ty || 10118 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 10119 CLI.RetTy->getPointerAddressSpace() == 10120 Args[i].Ty->getPointerAddressSpace())) && 10121 RetTys.size() == NumValues && "unexpected use of 'returned'"); 10122 // Before passing 'returned' to the target lowering code, ensure that 10123 // either the register MVT and the actual EVT are the same size or that 10124 // the return value and argument are extended in the same way; in these 10125 // cases it's safe to pass the argument register value unchanged as the 10126 // return register value (although it's at the target's option whether 10127 // to do so) 10128 // TODO: allow code generation to take advantage of partially preserved 10129 // registers rather than clobbering the entire register when the 10130 // parameter extension method is not compatible with the return 10131 // extension method 10132 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 10133 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 10134 CLI.RetZExt == Args[i].IsZExt)) 10135 Flags.setReturned(); 10136 } 10137 10138 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 10139 CLI.CallConv, ExtendKind); 10140 10141 for (unsigned j = 0; j != NumParts; ++j) { 10142 // if it isn't first piece, alignment must be 1 10143 // For scalable vectors the scalable part is currently handled 10144 // by individual targets, so we just use the known minimum size here. 10145 ISD::OutputArg MyFlags( 10146 Flags, Parts[j].getValueType().getSimpleVT(), VT, 10147 i < CLI.NumFixedArgs, i, 10148 j * Parts[j].getValueType().getStoreSize().getKnownMinValue()); 10149 if (NumParts > 1 && j == 0) 10150 MyFlags.Flags.setSplit(); 10151 else if (j != 0) { 10152 MyFlags.Flags.setOrigAlign(Align(1)); 10153 if (j == NumParts - 1) 10154 MyFlags.Flags.setSplitEnd(); 10155 } 10156 10157 CLI.Outs.push_back(MyFlags); 10158 CLI.OutVals.push_back(Parts[j]); 10159 } 10160 10161 if (NeedsRegBlock && Value == NumValues - 1) 10162 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 10163 } 10164 } 10165 10166 SmallVector<SDValue, 4> InVals; 10167 CLI.Chain = LowerCall(CLI, InVals); 10168 10169 // Update CLI.InVals to use outside of this function. 10170 CLI.InVals = InVals; 10171 10172 // Verify that the target's LowerCall behaved as expected. 10173 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 10174 "LowerCall didn't return a valid chain!"); 10175 assert((!CLI.IsTailCall || InVals.empty()) && 10176 "LowerCall emitted a return value for a tail call!"); 10177 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 10178 "LowerCall didn't emit the correct number of values!"); 10179 10180 // For a tail call, the return value is merely live-out and there aren't 10181 // any nodes in the DAG representing it. Return a special value to 10182 // indicate that a tail call has been emitted and no more Instructions 10183 // should be processed in the current block. 10184 if (CLI.IsTailCall) { 10185 CLI.DAG.setRoot(CLI.Chain); 10186 return std::make_pair(SDValue(), SDValue()); 10187 } 10188 10189 #ifndef NDEBUG 10190 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 10191 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 10192 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 10193 "LowerCall emitted a value with the wrong type!"); 10194 } 10195 #endif 10196 10197 SmallVector<SDValue, 4> ReturnValues; 10198 if (!CanLowerReturn) { 10199 // The instruction result is the result of loading from the 10200 // hidden sret parameter. 10201 SmallVector<EVT, 1> PVTs; 10202 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 10203 10204 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 10205 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 10206 EVT PtrVT = PVTs[0]; 10207 10208 unsigned NumValues = RetTys.size(); 10209 ReturnValues.resize(NumValues); 10210 SmallVector<SDValue, 4> Chains(NumValues); 10211 10212 // An aggregate return value cannot wrap around the address space, so 10213 // offsets to its parts don't wrap either. 10214 SDNodeFlags Flags; 10215 Flags.setNoUnsignedWrap(true); 10216 10217 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10218 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 10219 for (unsigned i = 0; i < NumValues; ++i) { 10220 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 10221 CLI.DAG.getConstant(Offsets[i], CLI.DL, 10222 PtrVT), Flags); 10223 SDValue L = CLI.DAG.getLoad( 10224 RetTys[i], CLI.DL, CLI.Chain, Add, 10225 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 10226 DemoteStackIdx, Offsets[i]), 10227 HiddenSRetAlign); 10228 ReturnValues[i] = L; 10229 Chains[i] = L.getValue(1); 10230 } 10231 10232 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 10233 } else { 10234 // Collect the legal value parts into potentially illegal values 10235 // that correspond to the original function's return values. 10236 std::optional<ISD::NodeType> AssertOp; 10237 if (CLI.RetSExt) 10238 AssertOp = ISD::AssertSext; 10239 else if (CLI.RetZExt) 10240 AssertOp = ISD::AssertZext; 10241 unsigned CurReg = 0; 10242 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 10243 EVT VT = RetTys[I]; 10244 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10245 CLI.CallConv, VT); 10246 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10247 CLI.CallConv, VT); 10248 10249 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 10250 NumRegs, RegisterVT, VT, nullptr, 10251 CLI.CallConv, AssertOp)); 10252 CurReg += NumRegs; 10253 } 10254 10255 // For a function returning void, there is no return value. We can't create 10256 // such a node, so we just return a null return value in that case. In 10257 // that case, nothing will actually look at the value. 10258 if (ReturnValues.empty()) 10259 return std::make_pair(SDValue(), CLI.Chain); 10260 } 10261 10262 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 10263 CLI.DAG.getVTList(RetTys), ReturnValues); 10264 return std::make_pair(Res, CLI.Chain); 10265 } 10266 10267 /// Places new result values for the node in Results (their number 10268 /// and types must exactly match those of the original return values of 10269 /// the node), or leaves Results empty, which indicates that the node is not 10270 /// to be custom lowered after all. 10271 void TargetLowering::LowerOperationWrapper(SDNode *N, 10272 SmallVectorImpl<SDValue> &Results, 10273 SelectionDAG &DAG) const { 10274 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 10275 10276 if (!Res.getNode()) 10277 return; 10278 10279 // If the original node has one result, take the return value from 10280 // LowerOperation as is. It might not be result number 0. 10281 if (N->getNumValues() == 1) { 10282 Results.push_back(Res); 10283 return; 10284 } 10285 10286 // If the original node has multiple results, then the return node should 10287 // have the same number of results. 10288 assert((N->getNumValues() == Res->getNumValues()) && 10289 "Lowering returned the wrong number of results!"); 10290 10291 // Places new result values base on N result number. 10292 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 10293 Results.push_back(Res.getValue(I)); 10294 } 10295 10296 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10297 llvm_unreachable("LowerOperation not implemented for this target!"); 10298 } 10299 10300 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, 10301 unsigned Reg, 10302 ISD::NodeType ExtendType) { 10303 SDValue Op = getNonRegisterValue(V); 10304 assert((Op.getOpcode() != ISD::CopyFromReg || 10305 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 10306 "Copy from a reg to the same reg!"); 10307 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 10308 10309 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10310 // If this is an InlineAsm we have to match the registers required, not the 10311 // notional registers required by the type. 10312 10313 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 10314 std::nullopt); // This is not an ABI copy. 10315 SDValue Chain = DAG.getEntryNode(); 10316 10317 if (ExtendType == ISD::ANY_EXTEND) { 10318 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V); 10319 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end()) 10320 ExtendType = PreferredExtendIt->second; 10321 } 10322 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 10323 PendingExports.push_back(Chain); 10324 } 10325 10326 #include "llvm/CodeGen/SelectionDAGISel.h" 10327 10328 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 10329 /// entry block, return true. This includes arguments used by switches, since 10330 /// the switch may expand into multiple basic blocks. 10331 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 10332 // With FastISel active, we may be splitting blocks, so force creation 10333 // of virtual registers for all non-dead arguments. 10334 if (FastISel) 10335 return A->use_empty(); 10336 10337 const BasicBlock &Entry = A->getParent()->front(); 10338 for (const User *U : A->users()) 10339 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 10340 return false; // Use not in entry block. 10341 10342 return true; 10343 } 10344 10345 using ArgCopyElisionMapTy = 10346 DenseMap<const Argument *, 10347 std::pair<const AllocaInst *, const StoreInst *>>; 10348 10349 /// Scan the entry block of the function in FuncInfo for arguments that look 10350 /// like copies into a local alloca. Record any copied arguments in 10351 /// ArgCopyElisionCandidates. 10352 static void 10353 findArgumentCopyElisionCandidates(const DataLayout &DL, 10354 FunctionLoweringInfo *FuncInfo, 10355 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 10356 // Record the state of every static alloca used in the entry block. Argument 10357 // allocas are all used in the entry block, so we need approximately as many 10358 // entries as we have arguments. 10359 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 10360 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 10361 unsigned NumArgs = FuncInfo->Fn->arg_size(); 10362 StaticAllocas.reserve(NumArgs * 2); 10363 10364 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 10365 if (!V) 10366 return nullptr; 10367 V = V->stripPointerCasts(); 10368 const auto *AI = dyn_cast<AllocaInst>(V); 10369 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 10370 return nullptr; 10371 auto Iter = StaticAllocas.insert({AI, Unknown}); 10372 return &Iter.first->second; 10373 }; 10374 10375 // Look for stores of arguments to static allocas. Look through bitcasts and 10376 // GEPs to handle type coercions, as long as the alloca is fully initialized 10377 // by the store. Any non-store use of an alloca escapes it and any subsequent 10378 // unanalyzed store might write it. 10379 // FIXME: Handle structs initialized with multiple stores. 10380 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 10381 // Look for stores, and handle non-store uses conservatively. 10382 const auto *SI = dyn_cast<StoreInst>(&I); 10383 if (!SI) { 10384 // We will look through cast uses, so ignore them completely. 10385 if (I.isCast()) 10386 continue; 10387 // Ignore debug info and pseudo op intrinsics, they don't escape or store 10388 // to allocas. 10389 if (I.isDebugOrPseudoInst()) 10390 continue; 10391 // This is an unknown instruction. Assume it escapes or writes to all 10392 // static alloca operands. 10393 for (const Use &U : I.operands()) { 10394 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 10395 *Info = StaticAllocaInfo::Clobbered; 10396 } 10397 continue; 10398 } 10399 10400 // If the stored value is a static alloca, mark it as escaped. 10401 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 10402 *Info = StaticAllocaInfo::Clobbered; 10403 10404 // Check if the destination is a static alloca. 10405 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 10406 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 10407 if (!Info) 10408 continue; 10409 const AllocaInst *AI = cast<AllocaInst>(Dst); 10410 10411 // Skip allocas that have been initialized or clobbered. 10412 if (*Info != StaticAllocaInfo::Unknown) 10413 continue; 10414 10415 // Check if the stored value is an argument, and that this store fully 10416 // initializes the alloca. 10417 // If the argument type has padding bits we can't directly forward a pointer 10418 // as the upper bits may contain garbage. 10419 // Don't elide copies from the same argument twice. 10420 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 10421 const auto *Arg = dyn_cast<Argument>(Val); 10422 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 10423 Arg->getType()->isEmptyTy() || 10424 DL.getTypeStoreSize(Arg->getType()) != 10425 DL.getTypeAllocSize(AI->getAllocatedType()) || 10426 !DL.typeSizeEqualsStoreSize(Arg->getType()) || 10427 ArgCopyElisionCandidates.count(Arg)) { 10428 *Info = StaticAllocaInfo::Clobbered; 10429 continue; 10430 } 10431 10432 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 10433 << '\n'); 10434 10435 // Mark this alloca and store for argument copy elision. 10436 *Info = StaticAllocaInfo::Elidable; 10437 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 10438 10439 // Stop scanning if we've seen all arguments. This will happen early in -O0 10440 // builds, which is useful, because -O0 builds have large entry blocks and 10441 // many allocas. 10442 if (ArgCopyElisionCandidates.size() == NumArgs) 10443 break; 10444 } 10445 } 10446 10447 /// Try to elide argument copies from memory into a local alloca. Succeeds if 10448 /// ArgVal is a load from a suitable fixed stack object. 10449 static void tryToElideArgumentCopy( 10450 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 10451 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 10452 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 10453 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 10454 SDValue ArgVal, bool &ArgHasUses) { 10455 // Check if this is a load from a fixed stack object. 10456 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 10457 if (!LNode) 10458 return; 10459 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 10460 if (!FINode) 10461 return; 10462 10463 // Check that the fixed stack object is the right size and alignment. 10464 // Look at the alignment that the user wrote on the alloca instead of looking 10465 // at the stack object. 10466 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 10467 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 10468 const AllocaInst *AI = ArgCopyIter->second.first; 10469 int FixedIndex = FINode->getIndex(); 10470 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 10471 int OldIndex = AllocaIndex; 10472 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 10473 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 10474 LLVM_DEBUG( 10475 dbgs() << " argument copy elision failed due to bad fixed stack " 10476 "object size\n"); 10477 return; 10478 } 10479 Align RequiredAlignment = AI->getAlign(); 10480 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 10481 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 10482 "greater than stack argument alignment (" 10483 << DebugStr(RequiredAlignment) << " vs " 10484 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 10485 return; 10486 } 10487 10488 // Perform the elision. Delete the old stack object and replace its only use 10489 // in the variable info map. Mark the stack object as mutable. 10490 LLVM_DEBUG({ 10491 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 10492 << " Replacing frame index " << OldIndex << " with " << FixedIndex 10493 << '\n'; 10494 }); 10495 MFI.RemoveStackObject(OldIndex); 10496 MFI.setIsImmutableObjectIndex(FixedIndex, false); 10497 AllocaIndex = FixedIndex; 10498 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 10499 Chains.push_back(ArgVal.getValue(1)); 10500 10501 // Avoid emitting code for the store implementing the copy. 10502 const StoreInst *SI = ArgCopyIter->second.second; 10503 ElidedArgCopyInstrs.insert(SI); 10504 10505 // Check for uses of the argument again so that we can avoid exporting ArgVal 10506 // if it is't used by anything other than the store. 10507 for (const Value *U : Arg.users()) { 10508 if (U != SI) { 10509 ArgHasUses = true; 10510 break; 10511 } 10512 } 10513 } 10514 10515 void SelectionDAGISel::LowerArguments(const Function &F) { 10516 SelectionDAG &DAG = SDB->DAG; 10517 SDLoc dl = SDB->getCurSDLoc(); 10518 const DataLayout &DL = DAG.getDataLayout(); 10519 SmallVector<ISD::InputArg, 16> Ins; 10520 10521 // In Naked functions we aren't going to save any registers. 10522 if (F.hasFnAttribute(Attribute::Naked)) 10523 return; 10524 10525 if (!FuncInfo->CanLowerReturn) { 10526 // Put in an sret pointer parameter before all the other parameters. 10527 SmallVector<EVT, 1> ValueVTs; 10528 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10529 F.getReturnType()->getPointerTo( 10530 DAG.getDataLayout().getAllocaAddrSpace()), 10531 ValueVTs); 10532 10533 // NOTE: Assuming that a pointer will never break down to more than one VT 10534 // or one register. 10535 ISD::ArgFlagsTy Flags; 10536 Flags.setSRet(); 10537 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 10538 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 10539 ISD::InputArg::NoArgIndex, 0); 10540 Ins.push_back(RetArg); 10541 } 10542 10543 // Look for stores of arguments to static allocas. Mark such arguments with a 10544 // flag to ask the target to give us the memory location of that argument if 10545 // available. 10546 ArgCopyElisionMapTy ArgCopyElisionCandidates; 10547 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 10548 ArgCopyElisionCandidates); 10549 10550 // Set up the incoming argument description vector. 10551 for (const Argument &Arg : F.args()) { 10552 unsigned ArgNo = Arg.getArgNo(); 10553 SmallVector<EVT, 4> ValueVTs; 10554 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10555 bool isArgValueUsed = !Arg.use_empty(); 10556 unsigned PartBase = 0; 10557 Type *FinalType = Arg.getType(); 10558 if (Arg.hasAttribute(Attribute::ByVal)) 10559 FinalType = Arg.getParamByValType(); 10560 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 10561 FinalType, F.getCallingConv(), F.isVarArg(), DL); 10562 for (unsigned Value = 0, NumValues = ValueVTs.size(); 10563 Value != NumValues; ++Value) { 10564 EVT VT = ValueVTs[Value]; 10565 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 10566 ISD::ArgFlagsTy Flags; 10567 10568 10569 if (Arg.getType()->isPointerTy()) { 10570 Flags.setPointer(); 10571 Flags.setPointerAddrSpace( 10572 cast<PointerType>(Arg.getType())->getAddressSpace()); 10573 } 10574 if (Arg.hasAttribute(Attribute::ZExt)) 10575 Flags.setZExt(); 10576 if (Arg.hasAttribute(Attribute::SExt)) 10577 Flags.setSExt(); 10578 if (Arg.hasAttribute(Attribute::InReg)) { 10579 // If we are using vectorcall calling convention, a structure that is 10580 // passed InReg - is surely an HVA 10581 if (F.getCallingConv() == CallingConv::X86_VectorCall && 10582 isa<StructType>(Arg.getType())) { 10583 // The first value of a structure is marked 10584 if (0 == Value) 10585 Flags.setHvaStart(); 10586 Flags.setHva(); 10587 } 10588 // Set InReg Flag 10589 Flags.setInReg(); 10590 } 10591 if (Arg.hasAttribute(Attribute::StructRet)) 10592 Flags.setSRet(); 10593 if (Arg.hasAttribute(Attribute::SwiftSelf)) 10594 Flags.setSwiftSelf(); 10595 if (Arg.hasAttribute(Attribute::SwiftAsync)) 10596 Flags.setSwiftAsync(); 10597 if (Arg.hasAttribute(Attribute::SwiftError)) 10598 Flags.setSwiftError(); 10599 if (Arg.hasAttribute(Attribute::ByVal)) 10600 Flags.setByVal(); 10601 if (Arg.hasAttribute(Attribute::ByRef)) 10602 Flags.setByRef(); 10603 if (Arg.hasAttribute(Attribute::InAlloca)) { 10604 Flags.setInAlloca(); 10605 // Set the byval flag for CCAssignFn callbacks that don't know about 10606 // inalloca. This way we can know how many bytes we should've allocated 10607 // and how many bytes a callee cleanup function will pop. If we port 10608 // inalloca to more targets, we'll have to add custom inalloca handling 10609 // in the various CC lowering callbacks. 10610 Flags.setByVal(); 10611 } 10612 if (Arg.hasAttribute(Attribute::Preallocated)) { 10613 Flags.setPreallocated(); 10614 // Set the byval flag for CCAssignFn callbacks that don't know about 10615 // preallocated. This way we can know how many bytes we should've 10616 // allocated and how many bytes a callee cleanup function will pop. If 10617 // we port preallocated to more targets, we'll have to add custom 10618 // preallocated handling in the various CC lowering callbacks. 10619 Flags.setByVal(); 10620 } 10621 10622 // Certain targets (such as MIPS), may have a different ABI alignment 10623 // for a type depending on the context. Give the target a chance to 10624 // specify the alignment it wants. 10625 const Align OriginalAlignment( 10626 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 10627 Flags.setOrigAlign(OriginalAlignment); 10628 10629 Align MemAlign; 10630 Type *ArgMemTy = nullptr; 10631 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 10632 Flags.isByRef()) { 10633 if (!ArgMemTy) 10634 ArgMemTy = Arg.getPointeeInMemoryValueType(); 10635 10636 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 10637 10638 // For in-memory arguments, size and alignment should be passed from FE. 10639 // BE will guess if this info is not there but there are cases it cannot 10640 // get right. 10641 if (auto ParamAlign = Arg.getParamStackAlign()) 10642 MemAlign = *ParamAlign; 10643 else if ((ParamAlign = Arg.getParamAlign())) 10644 MemAlign = *ParamAlign; 10645 else 10646 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 10647 if (Flags.isByRef()) 10648 Flags.setByRefSize(MemSize); 10649 else 10650 Flags.setByValSize(MemSize); 10651 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 10652 MemAlign = *ParamAlign; 10653 } else { 10654 MemAlign = OriginalAlignment; 10655 } 10656 Flags.setMemAlign(MemAlign); 10657 10658 if (Arg.hasAttribute(Attribute::Nest)) 10659 Flags.setNest(); 10660 if (NeedsRegBlock) 10661 Flags.setInConsecutiveRegs(); 10662 if (ArgCopyElisionCandidates.count(&Arg)) 10663 Flags.setCopyElisionCandidate(); 10664 if (Arg.hasAttribute(Attribute::Returned)) 10665 Flags.setReturned(); 10666 10667 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 10668 *CurDAG->getContext(), F.getCallingConv(), VT); 10669 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 10670 *CurDAG->getContext(), F.getCallingConv(), VT); 10671 for (unsigned i = 0; i != NumRegs; ++i) { 10672 // For scalable vectors, use the minimum size; individual targets 10673 // are responsible for handling scalable vector arguments and 10674 // return values. 10675 ISD::InputArg MyFlags( 10676 Flags, RegisterVT, VT, isArgValueUsed, ArgNo, 10677 PartBase + i * RegisterVT.getStoreSize().getKnownMinValue()); 10678 if (NumRegs > 1 && i == 0) 10679 MyFlags.Flags.setSplit(); 10680 // if it isn't first piece, alignment must be 1 10681 else if (i > 0) { 10682 MyFlags.Flags.setOrigAlign(Align(1)); 10683 if (i == NumRegs - 1) 10684 MyFlags.Flags.setSplitEnd(); 10685 } 10686 Ins.push_back(MyFlags); 10687 } 10688 if (NeedsRegBlock && Value == NumValues - 1) 10689 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 10690 PartBase += VT.getStoreSize().getKnownMinValue(); 10691 } 10692 } 10693 10694 // Call the target to set up the argument values. 10695 SmallVector<SDValue, 8> InVals; 10696 SDValue NewRoot = TLI->LowerFormalArguments( 10697 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 10698 10699 // Verify that the target's LowerFormalArguments behaved as expected. 10700 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 10701 "LowerFormalArguments didn't return a valid chain!"); 10702 assert(InVals.size() == Ins.size() && 10703 "LowerFormalArguments didn't emit the correct number of values!"); 10704 LLVM_DEBUG({ 10705 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 10706 assert(InVals[i].getNode() && 10707 "LowerFormalArguments emitted a null value!"); 10708 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 10709 "LowerFormalArguments emitted a value with the wrong type!"); 10710 } 10711 }); 10712 10713 // Update the DAG with the new chain value resulting from argument lowering. 10714 DAG.setRoot(NewRoot); 10715 10716 // Set up the argument values. 10717 unsigned i = 0; 10718 if (!FuncInfo->CanLowerReturn) { 10719 // Create a virtual register for the sret pointer, and put in a copy 10720 // from the sret argument into it. 10721 SmallVector<EVT, 1> ValueVTs; 10722 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10723 F.getReturnType()->getPointerTo( 10724 DAG.getDataLayout().getAllocaAddrSpace()), 10725 ValueVTs); 10726 MVT VT = ValueVTs[0].getSimpleVT(); 10727 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 10728 std::optional<ISD::NodeType> AssertOp; 10729 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 10730 nullptr, F.getCallingConv(), AssertOp); 10731 10732 MachineFunction& MF = SDB->DAG.getMachineFunction(); 10733 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 10734 Register SRetReg = 10735 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 10736 FuncInfo->DemoteRegister = SRetReg; 10737 NewRoot = 10738 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 10739 DAG.setRoot(NewRoot); 10740 10741 // i indexes lowered arguments. Bump it past the hidden sret argument. 10742 ++i; 10743 } 10744 10745 SmallVector<SDValue, 4> Chains; 10746 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 10747 for (const Argument &Arg : F.args()) { 10748 SmallVector<SDValue, 4> ArgValues; 10749 SmallVector<EVT, 4> ValueVTs; 10750 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10751 unsigned NumValues = ValueVTs.size(); 10752 if (NumValues == 0) 10753 continue; 10754 10755 bool ArgHasUses = !Arg.use_empty(); 10756 10757 // Elide the copying store if the target loaded this argument from a 10758 // suitable fixed stack object. 10759 if (Ins[i].Flags.isCopyElisionCandidate()) { 10760 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 10761 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 10762 InVals[i], ArgHasUses); 10763 } 10764 10765 // If this argument is unused then remember its value. It is used to generate 10766 // debugging information. 10767 bool isSwiftErrorArg = 10768 TLI->supportSwiftError() && 10769 Arg.hasAttribute(Attribute::SwiftError); 10770 if (!ArgHasUses && !isSwiftErrorArg) { 10771 SDB->setUnusedArgValue(&Arg, InVals[i]); 10772 10773 // Also remember any frame index for use in FastISel. 10774 if (FrameIndexSDNode *FI = 10775 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 10776 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10777 } 10778 10779 for (unsigned Val = 0; Val != NumValues; ++Val) { 10780 EVT VT = ValueVTs[Val]; 10781 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 10782 F.getCallingConv(), VT); 10783 unsigned NumParts = TLI->getNumRegistersForCallingConv( 10784 *CurDAG->getContext(), F.getCallingConv(), VT); 10785 10786 // Even an apparent 'unused' swifterror argument needs to be returned. So 10787 // we do generate a copy for it that can be used on return from the 10788 // function. 10789 if (ArgHasUses || isSwiftErrorArg) { 10790 std::optional<ISD::NodeType> AssertOp; 10791 if (Arg.hasAttribute(Attribute::SExt)) 10792 AssertOp = ISD::AssertSext; 10793 else if (Arg.hasAttribute(Attribute::ZExt)) 10794 AssertOp = ISD::AssertZext; 10795 10796 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 10797 PartVT, VT, nullptr, 10798 F.getCallingConv(), AssertOp)); 10799 } 10800 10801 i += NumParts; 10802 } 10803 10804 // We don't need to do anything else for unused arguments. 10805 if (ArgValues.empty()) 10806 continue; 10807 10808 // Note down frame index. 10809 if (FrameIndexSDNode *FI = 10810 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 10811 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10812 10813 SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues), 10814 SDB->getCurSDLoc()); 10815 10816 SDB->setValue(&Arg, Res); 10817 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 10818 // We want to associate the argument with the frame index, among 10819 // involved operands, that correspond to the lowest address. The 10820 // getCopyFromParts function, called earlier, is swapping the order of 10821 // the operands to BUILD_PAIR depending on endianness. The result of 10822 // that swapping is that the least significant bits of the argument will 10823 // be in the first operand of the BUILD_PAIR node, and the most 10824 // significant bits will be in the second operand. 10825 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 10826 if (LoadSDNode *LNode = 10827 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 10828 if (FrameIndexSDNode *FI = 10829 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 10830 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10831 } 10832 10833 // Analyses past this point are naive and don't expect an assertion. 10834 if (Res.getOpcode() == ISD::AssertZext) 10835 Res = Res.getOperand(0); 10836 10837 // Update the SwiftErrorVRegDefMap. 10838 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 10839 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10840 if (Register::isVirtualRegister(Reg)) 10841 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 10842 Reg); 10843 } 10844 10845 // If this argument is live outside of the entry block, insert a copy from 10846 // wherever we got it to the vreg that other BB's will reference it as. 10847 if (Res.getOpcode() == ISD::CopyFromReg) { 10848 // If we can, though, try to skip creating an unnecessary vreg. 10849 // FIXME: This isn't very clean... it would be nice to make this more 10850 // general. 10851 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10852 if (Register::isVirtualRegister(Reg)) { 10853 FuncInfo->ValueMap[&Arg] = Reg; 10854 continue; 10855 } 10856 } 10857 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 10858 FuncInfo->InitializeRegForValue(&Arg); 10859 SDB->CopyToExportRegsIfNeeded(&Arg); 10860 } 10861 } 10862 10863 if (!Chains.empty()) { 10864 Chains.push_back(NewRoot); 10865 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 10866 } 10867 10868 DAG.setRoot(NewRoot); 10869 10870 assert(i == InVals.size() && "Argument register count mismatch!"); 10871 10872 // If any argument copy elisions occurred and we have debug info, update the 10873 // stale frame indices used in the dbg.declare variable info table. 10874 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 10875 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 10876 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 10877 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 10878 if (I != ArgCopyElisionFrameIndexMap.end()) 10879 VI.Slot = I->second; 10880 } 10881 } 10882 10883 // Finally, if the target has anything special to do, allow it to do so. 10884 emitFunctionEntryCode(); 10885 } 10886 10887 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 10888 /// ensure constants are generated when needed. Remember the virtual registers 10889 /// that need to be added to the Machine PHI nodes as input. We cannot just 10890 /// directly add them, because expansion might result in multiple MBB's for one 10891 /// BB. As such, the start of the BB might correspond to a different MBB than 10892 /// the end. 10893 void 10894 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 10895 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10896 10897 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 10898 10899 // Check PHI nodes in successors that expect a value to be available from this 10900 // block. 10901 for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) { 10902 if (!isa<PHINode>(SuccBB->begin())) continue; 10903 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 10904 10905 // If this terminator has multiple identical successors (common for 10906 // switches), only handle each succ once. 10907 if (!SuccsHandled.insert(SuccMBB).second) 10908 continue; 10909 10910 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 10911 10912 // At this point we know that there is a 1-1 correspondence between LLVM PHI 10913 // nodes and Machine PHI nodes, but the incoming operands have not been 10914 // emitted yet. 10915 for (const PHINode &PN : SuccBB->phis()) { 10916 // Ignore dead phi's. 10917 if (PN.use_empty()) 10918 continue; 10919 10920 // Skip empty types 10921 if (PN.getType()->isEmptyTy()) 10922 continue; 10923 10924 unsigned Reg; 10925 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 10926 10927 if (const auto *C = dyn_cast<Constant>(PHIOp)) { 10928 unsigned &RegOut = ConstantsOut[C]; 10929 if (RegOut == 0) { 10930 RegOut = FuncInfo.CreateRegs(C); 10931 // We need to zero/sign extend ConstantInt phi operands to match 10932 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo. 10933 ISD::NodeType ExtendType = ISD::ANY_EXTEND; 10934 if (auto *CI = dyn_cast<ConstantInt>(C)) 10935 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND 10936 : ISD::ZERO_EXTEND; 10937 CopyValueToVirtualRegister(C, RegOut, ExtendType); 10938 } 10939 Reg = RegOut; 10940 } else { 10941 DenseMap<const Value *, Register>::iterator I = 10942 FuncInfo.ValueMap.find(PHIOp); 10943 if (I != FuncInfo.ValueMap.end()) 10944 Reg = I->second; 10945 else { 10946 assert(isa<AllocaInst>(PHIOp) && 10947 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 10948 "Didn't codegen value into a register!??"); 10949 Reg = FuncInfo.CreateRegs(PHIOp); 10950 CopyValueToVirtualRegister(PHIOp, Reg); 10951 } 10952 } 10953 10954 // Remember that this register needs to added to the machine PHI node as 10955 // the input for this MBB. 10956 SmallVector<EVT, 4> ValueVTs; 10957 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 10958 for (EVT VT : ValueVTs) { 10959 const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 10960 for (unsigned i = 0; i != NumRegisters; ++i) 10961 FuncInfo.PHINodesToUpdate.push_back( 10962 std::make_pair(&*MBBI++, Reg + i)); 10963 Reg += NumRegisters; 10964 } 10965 } 10966 } 10967 10968 ConstantsOut.clear(); 10969 } 10970 10971 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 10972 MachineFunction::iterator I(MBB); 10973 if (++I == FuncInfo.MF->end()) 10974 return nullptr; 10975 return &*I; 10976 } 10977 10978 /// During lowering new call nodes can be created (such as memset, etc.). 10979 /// Those will become new roots of the current DAG, but complications arise 10980 /// when they are tail calls. In such cases, the call lowering will update 10981 /// the root, but the builder still needs to know that a tail call has been 10982 /// lowered in order to avoid generating an additional return. 10983 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 10984 // If the node is null, we do have a tail call. 10985 if (MaybeTC.getNode() != nullptr) 10986 DAG.setRoot(MaybeTC); 10987 else 10988 HasTailCall = true; 10989 } 10990 10991 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10992 MachineBasicBlock *SwitchMBB, 10993 MachineBasicBlock *DefaultMBB) { 10994 MachineFunction *CurMF = FuncInfo.MF; 10995 MachineBasicBlock *NextMBB = nullptr; 10996 MachineFunction::iterator BBI(W.MBB); 10997 if (++BBI != FuncInfo.MF->end()) 10998 NextMBB = &*BBI; 10999 11000 unsigned Size = W.LastCluster - W.FirstCluster + 1; 11001 11002 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11003 11004 if (Size == 2 && W.MBB == SwitchMBB) { 11005 // If any two of the cases has the same destination, and if one value 11006 // is the same as the other, but has one bit unset that the other has set, 11007 // use bit manipulation to do two compares at once. For example: 11008 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 11009 // TODO: This could be extended to merge any 2 cases in switches with 3 11010 // cases. 11011 // TODO: Handle cases where W.CaseBB != SwitchBB. 11012 CaseCluster &Small = *W.FirstCluster; 11013 CaseCluster &Big = *W.LastCluster; 11014 11015 if (Small.Low == Small.High && Big.Low == Big.High && 11016 Small.MBB == Big.MBB) { 11017 const APInt &SmallValue = Small.Low->getValue(); 11018 const APInt &BigValue = Big.Low->getValue(); 11019 11020 // Check that there is only one bit different. 11021 APInt CommonBit = BigValue ^ SmallValue; 11022 if (CommonBit.isPowerOf2()) { 11023 SDValue CondLHS = getValue(Cond); 11024 EVT VT = CondLHS.getValueType(); 11025 SDLoc DL = getCurSDLoc(); 11026 11027 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 11028 DAG.getConstant(CommonBit, DL, VT)); 11029 SDValue Cond = DAG.getSetCC( 11030 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 11031 ISD::SETEQ); 11032 11033 // Update successor info. 11034 // Both Small and Big will jump to Small.BB, so we sum up the 11035 // probabilities. 11036 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 11037 if (BPI) 11038 addSuccessorWithProb( 11039 SwitchMBB, DefaultMBB, 11040 // The default destination is the first successor in IR. 11041 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 11042 else 11043 addSuccessorWithProb(SwitchMBB, DefaultMBB); 11044 11045 // Insert the true branch. 11046 SDValue BrCond = 11047 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 11048 DAG.getBasicBlock(Small.MBB)); 11049 // Insert the false branch. 11050 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 11051 DAG.getBasicBlock(DefaultMBB)); 11052 11053 DAG.setRoot(BrCond); 11054 return; 11055 } 11056 } 11057 } 11058 11059 if (TM.getOptLevel() != CodeGenOpt::None) { 11060 // Here, we order cases by probability so the most likely case will be 11061 // checked first. However, two clusters can have the same probability in 11062 // which case their relative ordering is non-deterministic. So we use Low 11063 // as a tie-breaker as clusters are guaranteed to never overlap. 11064 llvm::sort(W.FirstCluster, W.LastCluster + 1, 11065 [](const CaseCluster &a, const CaseCluster &b) { 11066 return a.Prob != b.Prob ? 11067 a.Prob > b.Prob : 11068 a.Low->getValue().slt(b.Low->getValue()); 11069 }); 11070 11071 // Rearrange the case blocks so that the last one falls through if possible 11072 // without changing the order of probabilities. 11073 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 11074 --I; 11075 if (I->Prob > W.LastCluster->Prob) 11076 break; 11077 if (I->Kind == CC_Range && I->MBB == NextMBB) { 11078 std::swap(*I, *W.LastCluster); 11079 break; 11080 } 11081 } 11082 } 11083 11084 // Compute total probability. 11085 BranchProbability DefaultProb = W.DefaultProb; 11086 BranchProbability UnhandledProbs = DefaultProb; 11087 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 11088 UnhandledProbs += I->Prob; 11089 11090 MachineBasicBlock *CurMBB = W.MBB; 11091 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 11092 bool FallthroughUnreachable = false; 11093 MachineBasicBlock *Fallthrough; 11094 if (I == W.LastCluster) { 11095 // For the last cluster, fall through to the default destination. 11096 Fallthrough = DefaultMBB; 11097 FallthroughUnreachable = isa<UnreachableInst>( 11098 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 11099 } else { 11100 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 11101 CurMF->insert(BBI, Fallthrough); 11102 // Put Cond in a virtual register to make it available from the new blocks. 11103 ExportFromCurrentBlock(Cond); 11104 } 11105 UnhandledProbs -= I->Prob; 11106 11107 switch (I->Kind) { 11108 case CC_JumpTable: { 11109 // FIXME: Optimize away range check based on pivot comparisons. 11110 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 11111 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 11112 11113 // The jump block hasn't been inserted yet; insert it here. 11114 MachineBasicBlock *JumpMBB = JT->MBB; 11115 CurMF->insert(BBI, JumpMBB); 11116 11117 auto JumpProb = I->Prob; 11118 auto FallthroughProb = UnhandledProbs; 11119 11120 // If the default statement is a target of the jump table, we evenly 11121 // distribute the default probability to successors of CurMBB. Also 11122 // update the probability on the edge from JumpMBB to Fallthrough. 11123 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 11124 SE = JumpMBB->succ_end(); 11125 SI != SE; ++SI) { 11126 if (*SI == DefaultMBB) { 11127 JumpProb += DefaultProb / 2; 11128 FallthroughProb -= DefaultProb / 2; 11129 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 11130 JumpMBB->normalizeSuccProbs(); 11131 break; 11132 } 11133 } 11134 11135 if (FallthroughUnreachable) 11136 JTH->FallthroughUnreachable = true; 11137 11138 if (!JTH->FallthroughUnreachable) 11139 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 11140 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 11141 CurMBB->normalizeSuccProbs(); 11142 11143 // The jump table header will be inserted in our current block, do the 11144 // range check, and fall through to our fallthrough block. 11145 JTH->HeaderBB = CurMBB; 11146 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 11147 11148 // If we're in the right place, emit the jump table header right now. 11149 if (CurMBB == SwitchMBB) { 11150 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 11151 JTH->Emitted = true; 11152 } 11153 break; 11154 } 11155 case CC_BitTests: { 11156 // FIXME: Optimize away range check based on pivot comparisons. 11157 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 11158 11159 // The bit test blocks haven't been inserted yet; insert them here. 11160 for (BitTestCase &BTC : BTB->Cases) 11161 CurMF->insert(BBI, BTC.ThisBB); 11162 11163 // Fill in fields of the BitTestBlock. 11164 BTB->Parent = CurMBB; 11165 BTB->Default = Fallthrough; 11166 11167 BTB->DefaultProb = UnhandledProbs; 11168 // If the cases in bit test don't form a contiguous range, we evenly 11169 // distribute the probability on the edge to Fallthrough to two 11170 // successors of CurMBB. 11171 if (!BTB->ContiguousRange) { 11172 BTB->Prob += DefaultProb / 2; 11173 BTB->DefaultProb -= DefaultProb / 2; 11174 } 11175 11176 if (FallthroughUnreachable) 11177 BTB->FallthroughUnreachable = true; 11178 11179 // If we're in the right place, emit the bit test header right now. 11180 if (CurMBB == SwitchMBB) { 11181 visitBitTestHeader(*BTB, SwitchMBB); 11182 BTB->Emitted = true; 11183 } 11184 break; 11185 } 11186 case CC_Range: { 11187 const Value *RHS, *LHS, *MHS; 11188 ISD::CondCode CC; 11189 if (I->Low == I->High) { 11190 // Check Cond == I->Low. 11191 CC = ISD::SETEQ; 11192 LHS = Cond; 11193 RHS=I->Low; 11194 MHS = nullptr; 11195 } else { 11196 // Check I->Low <= Cond <= I->High. 11197 CC = ISD::SETLE; 11198 LHS = I->Low; 11199 MHS = Cond; 11200 RHS = I->High; 11201 } 11202 11203 // If Fallthrough is unreachable, fold away the comparison. 11204 if (FallthroughUnreachable) 11205 CC = ISD::SETTRUE; 11206 11207 // The false probability is the sum of all unhandled cases. 11208 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 11209 getCurSDLoc(), I->Prob, UnhandledProbs); 11210 11211 if (CurMBB == SwitchMBB) 11212 visitSwitchCase(CB, SwitchMBB); 11213 else 11214 SL->SwitchCases.push_back(CB); 11215 11216 break; 11217 } 11218 } 11219 CurMBB = Fallthrough; 11220 } 11221 } 11222 11223 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 11224 CaseClusterIt First, 11225 CaseClusterIt Last) { 11226 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 11227 if (X.Prob != CC.Prob) 11228 return X.Prob > CC.Prob; 11229 11230 // Ties are broken by comparing the case value. 11231 return X.Low->getValue().slt(CC.Low->getValue()); 11232 }); 11233 } 11234 11235 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 11236 const SwitchWorkListItem &W, 11237 Value *Cond, 11238 MachineBasicBlock *SwitchMBB) { 11239 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 11240 "Clusters not sorted?"); 11241 11242 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 11243 11244 // Balance the tree based on branch probabilities to create a near-optimal (in 11245 // terms of search time given key frequency) binary search tree. See e.g. Kurt 11246 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 11247 CaseClusterIt LastLeft = W.FirstCluster; 11248 CaseClusterIt FirstRight = W.LastCluster; 11249 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 11250 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 11251 11252 // Move LastLeft and FirstRight towards each other from opposite directions to 11253 // find a partitioning of the clusters which balances the probability on both 11254 // sides. If LeftProb and RightProb are equal, alternate which side is 11255 // taken to ensure 0-probability nodes are distributed evenly. 11256 unsigned I = 0; 11257 while (LastLeft + 1 < FirstRight) { 11258 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 11259 LeftProb += (++LastLeft)->Prob; 11260 else 11261 RightProb += (--FirstRight)->Prob; 11262 I++; 11263 } 11264 11265 while (true) { 11266 // Our binary search tree differs from a typical BST in that ours can have up 11267 // to three values in each leaf. The pivot selection above doesn't take that 11268 // into account, which means the tree might require more nodes and be less 11269 // efficient. We compensate for this here. 11270 11271 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 11272 unsigned NumRight = W.LastCluster - FirstRight + 1; 11273 11274 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 11275 // If one side has less than 3 clusters, and the other has more than 3, 11276 // consider taking a cluster from the other side. 11277 11278 if (NumLeft < NumRight) { 11279 // Consider moving the first cluster on the right to the left side. 11280 CaseCluster &CC = *FirstRight; 11281 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11282 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11283 if (LeftSideRank <= RightSideRank) { 11284 // Moving the cluster to the left does not demote it. 11285 ++LastLeft; 11286 ++FirstRight; 11287 continue; 11288 } 11289 } else { 11290 assert(NumRight < NumLeft); 11291 // Consider moving the last element on the left to the right side. 11292 CaseCluster &CC = *LastLeft; 11293 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11294 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11295 if (RightSideRank <= LeftSideRank) { 11296 // Moving the cluster to the right does not demot it. 11297 --LastLeft; 11298 --FirstRight; 11299 continue; 11300 } 11301 } 11302 } 11303 break; 11304 } 11305 11306 assert(LastLeft + 1 == FirstRight); 11307 assert(LastLeft >= W.FirstCluster); 11308 assert(FirstRight <= W.LastCluster); 11309 11310 // Use the first element on the right as pivot since we will make less-than 11311 // comparisons against it. 11312 CaseClusterIt PivotCluster = FirstRight; 11313 assert(PivotCluster > W.FirstCluster); 11314 assert(PivotCluster <= W.LastCluster); 11315 11316 CaseClusterIt FirstLeft = W.FirstCluster; 11317 CaseClusterIt LastRight = W.LastCluster; 11318 11319 const ConstantInt *Pivot = PivotCluster->Low; 11320 11321 // New blocks will be inserted immediately after the current one. 11322 MachineFunction::iterator BBI(W.MBB); 11323 ++BBI; 11324 11325 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 11326 // we can branch to its destination directly if it's squeezed exactly in 11327 // between the known lower bound and Pivot - 1. 11328 MachineBasicBlock *LeftMBB; 11329 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 11330 FirstLeft->Low == W.GE && 11331 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 11332 LeftMBB = FirstLeft->MBB; 11333 } else { 11334 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11335 FuncInfo.MF->insert(BBI, LeftMBB); 11336 WorkList.push_back( 11337 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 11338 // Put Cond in a virtual register to make it available from the new blocks. 11339 ExportFromCurrentBlock(Cond); 11340 } 11341 11342 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 11343 // single cluster, RHS.Low == Pivot, and we can branch to its destination 11344 // directly if RHS.High equals the current upper bound. 11345 MachineBasicBlock *RightMBB; 11346 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 11347 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 11348 RightMBB = FirstRight->MBB; 11349 } else { 11350 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11351 FuncInfo.MF->insert(BBI, RightMBB); 11352 WorkList.push_back( 11353 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 11354 // Put Cond in a virtual register to make it available from the new blocks. 11355 ExportFromCurrentBlock(Cond); 11356 } 11357 11358 // Create the CaseBlock record that will be used to lower the branch. 11359 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 11360 getCurSDLoc(), LeftProb, RightProb); 11361 11362 if (W.MBB == SwitchMBB) 11363 visitSwitchCase(CB, SwitchMBB); 11364 else 11365 SL->SwitchCases.push_back(CB); 11366 } 11367 11368 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 11369 // from the swith statement. 11370 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 11371 BranchProbability PeeledCaseProb) { 11372 if (PeeledCaseProb == BranchProbability::getOne()) 11373 return BranchProbability::getZero(); 11374 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 11375 11376 uint32_t Numerator = CaseProb.getNumerator(); 11377 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 11378 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 11379 } 11380 11381 // Try to peel the top probability case if it exceeds the threshold. 11382 // Return current MachineBasicBlock for the switch statement if the peeling 11383 // does not occur. 11384 // If the peeling is performed, return the newly created MachineBasicBlock 11385 // for the peeled switch statement. Also update Clusters to remove the peeled 11386 // case. PeeledCaseProb is the BranchProbability for the peeled case. 11387 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 11388 const SwitchInst &SI, CaseClusterVector &Clusters, 11389 BranchProbability &PeeledCaseProb) { 11390 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11391 // Don't perform if there is only one cluster or optimizing for size. 11392 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 11393 TM.getOptLevel() == CodeGenOpt::None || 11394 SwitchMBB->getParent()->getFunction().hasMinSize()) 11395 return SwitchMBB; 11396 11397 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 11398 unsigned PeeledCaseIndex = 0; 11399 bool SwitchPeeled = false; 11400 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 11401 CaseCluster &CC = Clusters[Index]; 11402 if (CC.Prob < TopCaseProb) 11403 continue; 11404 TopCaseProb = CC.Prob; 11405 PeeledCaseIndex = Index; 11406 SwitchPeeled = true; 11407 } 11408 if (!SwitchPeeled) 11409 return SwitchMBB; 11410 11411 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 11412 << TopCaseProb << "\n"); 11413 11414 // Record the MBB for the peeled switch statement. 11415 MachineFunction::iterator BBI(SwitchMBB); 11416 ++BBI; 11417 MachineBasicBlock *PeeledSwitchMBB = 11418 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 11419 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 11420 11421 ExportFromCurrentBlock(SI.getCondition()); 11422 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 11423 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 11424 nullptr, nullptr, TopCaseProb.getCompl()}; 11425 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 11426 11427 Clusters.erase(PeeledCaseIt); 11428 for (CaseCluster &CC : Clusters) { 11429 LLVM_DEBUG( 11430 dbgs() << "Scale the probablity for one cluster, before scaling: " 11431 << CC.Prob << "\n"); 11432 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 11433 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 11434 } 11435 PeeledCaseProb = TopCaseProb; 11436 return PeeledSwitchMBB; 11437 } 11438 11439 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 11440 // Extract cases from the switch. 11441 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11442 CaseClusterVector Clusters; 11443 Clusters.reserve(SI.getNumCases()); 11444 for (auto I : SI.cases()) { 11445 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 11446 const ConstantInt *CaseVal = I.getCaseValue(); 11447 BranchProbability Prob = 11448 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 11449 : BranchProbability(1, SI.getNumCases() + 1); 11450 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 11451 } 11452 11453 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 11454 11455 // Cluster adjacent cases with the same destination. We do this at all 11456 // optimization levels because it's cheap to do and will make codegen faster 11457 // if there are many clusters. 11458 sortAndRangeify(Clusters); 11459 11460 // The branch probablity of the peeled case. 11461 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 11462 MachineBasicBlock *PeeledSwitchMBB = 11463 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 11464 11465 // If there is only the default destination, jump there directly. 11466 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11467 if (Clusters.empty()) { 11468 assert(PeeledSwitchMBB == SwitchMBB); 11469 SwitchMBB->addSuccessor(DefaultMBB); 11470 if (DefaultMBB != NextBlock(SwitchMBB)) { 11471 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 11472 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 11473 } 11474 return; 11475 } 11476 11477 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 11478 SL->findBitTestClusters(Clusters, &SI); 11479 11480 LLVM_DEBUG({ 11481 dbgs() << "Case clusters: "; 11482 for (const CaseCluster &C : Clusters) { 11483 if (C.Kind == CC_JumpTable) 11484 dbgs() << "JT:"; 11485 if (C.Kind == CC_BitTests) 11486 dbgs() << "BT:"; 11487 11488 C.Low->getValue().print(dbgs(), true); 11489 if (C.Low != C.High) { 11490 dbgs() << '-'; 11491 C.High->getValue().print(dbgs(), true); 11492 } 11493 dbgs() << ' '; 11494 } 11495 dbgs() << '\n'; 11496 }); 11497 11498 assert(!Clusters.empty()); 11499 SwitchWorkList WorkList; 11500 CaseClusterIt First = Clusters.begin(); 11501 CaseClusterIt Last = Clusters.end() - 1; 11502 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 11503 // Scale the branchprobability for DefaultMBB if the peel occurs and 11504 // DefaultMBB is not replaced. 11505 if (PeeledCaseProb != BranchProbability::getZero() && 11506 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 11507 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 11508 WorkList.push_back( 11509 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 11510 11511 while (!WorkList.empty()) { 11512 SwitchWorkListItem W = WorkList.pop_back_val(); 11513 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 11514 11515 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 11516 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 11517 // For optimized builds, lower large range as a balanced binary tree. 11518 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 11519 continue; 11520 } 11521 11522 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 11523 } 11524 } 11525 11526 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 11527 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11528 auto DL = getCurSDLoc(); 11529 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11530 setValue(&I, DAG.getStepVector(DL, ResultVT)); 11531 } 11532 11533 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 11534 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11535 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11536 11537 SDLoc DL = getCurSDLoc(); 11538 SDValue V = getValue(I.getOperand(0)); 11539 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 11540 11541 if (VT.isScalableVector()) { 11542 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 11543 return; 11544 } 11545 11546 // Use VECTOR_SHUFFLE for the fixed-length vector 11547 // to maintain existing behavior. 11548 SmallVector<int, 8> Mask; 11549 unsigned NumElts = VT.getVectorMinNumElements(); 11550 for (unsigned i = 0; i != NumElts; ++i) 11551 Mask.push_back(NumElts - 1 - i); 11552 11553 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 11554 } 11555 11556 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 11557 SmallVector<EVT, 4> ValueVTs; 11558 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 11559 ValueVTs); 11560 unsigned NumValues = ValueVTs.size(); 11561 if (NumValues == 0) return; 11562 11563 SmallVector<SDValue, 4> Values(NumValues); 11564 SDValue Op = getValue(I.getOperand(0)); 11565 11566 for (unsigned i = 0; i != NumValues; ++i) 11567 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 11568 SDValue(Op.getNode(), Op.getResNo() + i)); 11569 11570 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 11571 DAG.getVTList(ValueVTs), Values)); 11572 } 11573 11574 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 11575 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11576 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11577 11578 SDLoc DL = getCurSDLoc(); 11579 SDValue V1 = getValue(I.getOperand(0)); 11580 SDValue V2 = getValue(I.getOperand(1)); 11581 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 11582 11583 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 11584 if (VT.isScalableVector()) { 11585 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 11586 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 11587 DAG.getConstant(Imm, DL, IdxVT))); 11588 return; 11589 } 11590 11591 unsigned NumElts = VT.getVectorNumElements(); 11592 11593 uint64_t Idx = (NumElts + Imm) % NumElts; 11594 11595 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 11596 SmallVector<int, 8> Mask; 11597 for (unsigned i = 0; i < NumElts; ++i) 11598 Mask.push_back(Idx + i); 11599 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 11600 } 11601