1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This implements routines for translating from LLVM IR into SelectionDAG IR. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "SelectionDAGBuilder.h" 14 #include "SDNodeDbgValue.h" 15 #include "llvm/ADT/APFloat.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/BitVector.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/ADT/SmallPtrSet.h" 20 #include "llvm/ADT/SmallSet.h" 21 #include "llvm/ADT/StringRef.h" 22 #include "llvm/ADT/Twine.h" 23 #include "llvm/Analysis/AliasAnalysis.h" 24 #include "llvm/Analysis/BranchProbabilityInfo.h" 25 #include "llvm/Analysis/ConstantFolding.h" 26 #include "llvm/Analysis/Loads.h" 27 #include "llvm/Analysis/MemoryLocation.h" 28 #include "llvm/Analysis/TargetLibraryInfo.h" 29 #include "llvm/Analysis/ValueTracking.h" 30 #include "llvm/Analysis/VectorUtils.h" 31 #include "llvm/CodeGen/Analysis.h" 32 #include "llvm/CodeGen/AssignmentTrackingAnalysis.h" 33 #include "llvm/CodeGen/CodeGenCommonISel.h" 34 #include "llvm/CodeGen/FunctionLoweringInfo.h" 35 #include "llvm/CodeGen/GCMetadata.h" 36 #include "llvm/CodeGen/ISDOpcodes.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/EHPersonalities.h" 71 #include "llvm/IR/Function.h" 72 #include "llvm/IR/GetElementPtrTypeIterator.h" 73 #include "llvm/IR/InlineAsm.h" 74 #include "llvm/IR/InstrTypes.h" 75 #include "llvm/IR/Instructions.h" 76 #include "llvm/IR/IntrinsicInst.h" 77 #include "llvm/IR/Intrinsics.h" 78 #include "llvm/IR/IntrinsicsAArch64.h" 79 #include "llvm/IR/IntrinsicsAMDGPU.h" 80 #include "llvm/IR/IntrinsicsWebAssembly.h" 81 #include "llvm/IR/LLVMContext.h" 82 #include "llvm/IR/Metadata.h" 83 #include "llvm/IR/Module.h" 84 #include "llvm/IR/Operator.h" 85 #include "llvm/IR/PatternMatch.h" 86 #include "llvm/IR/Statepoint.h" 87 #include "llvm/IR/Type.h" 88 #include "llvm/IR/User.h" 89 #include "llvm/IR/Value.h" 90 #include "llvm/MC/MCContext.h" 91 #include "llvm/Support/AtomicOrdering.h" 92 #include "llvm/Support/Casting.h" 93 #include "llvm/Support/CommandLine.h" 94 #include "llvm/Support/Compiler.h" 95 #include "llvm/Support/Debug.h" 96 #include "llvm/Support/MathExtras.h" 97 #include "llvm/Support/raw_ostream.h" 98 #include "llvm/Target/TargetIntrinsicInfo.h" 99 #include "llvm/Target/TargetMachine.h" 100 #include "llvm/Target/TargetOptions.h" 101 #include "llvm/TargetParser/Triple.h" 102 #include "llvm/Transforms/Utils/Local.h" 103 #include <cstddef> 104 #include <iterator> 105 #include <limits> 106 #include <optional> 107 #include <tuple> 108 109 using namespace llvm; 110 using namespace PatternMatch; 111 using namespace SwitchCG; 112 113 #define DEBUG_TYPE "isel" 114 115 /// LimitFloatPrecision - Generate low-precision inline sequences for 116 /// some float libcalls (6, 8 or 12 bits). 117 static unsigned LimitFloatPrecision; 118 119 static cl::opt<bool> 120 InsertAssertAlign("insert-assert-align", cl::init(true), 121 cl::desc("Insert the experimental `assertalign` node."), 122 cl::ReallyHidden); 123 124 static cl::opt<unsigned, true> 125 LimitFPPrecision("limit-float-precision", 126 cl::desc("Generate low-precision inline sequences " 127 "for some float libcalls"), 128 cl::location(LimitFloatPrecision), cl::Hidden, 129 cl::init(0)); 130 131 static cl::opt<unsigned> SwitchPeelThreshold( 132 "switch-peel-threshold", cl::Hidden, cl::init(66), 133 cl::desc("Set the case probability threshold for peeling the case from a " 134 "switch statement. A value greater than 100 will void this " 135 "optimization")); 136 137 // Limit the width of DAG chains. This is important in general to prevent 138 // DAG-based analysis from blowing up. For example, alias analysis and 139 // load clustering may not complete in reasonable time. It is difficult to 140 // recognize and avoid this situation within each individual analysis, and 141 // future analyses are likely to have the same behavior. Limiting DAG width is 142 // the safe approach and will be especially important with global DAGs. 143 // 144 // MaxParallelChains default is arbitrarily high to avoid affecting 145 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 146 // sequence over this should have been converted to llvm.memcpy by the 147 // frontend. It is easy to induce this behavior with .ll code such as: 148 // %buffer = alloca [4096 x i8] 149 // %data = load [4096 x i8]* %argPtr 150 // store [4096 x i8] %data, [4096 x i8]* %buffer 151 static const unsigned MaxParallelChains = 64; 152 153 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 154 const SDValue *Parts, unsigned NumParts, 155 MVT PartVT, EVT ValueVT, const Value *V, 156 std::optional<CallingConv::ID> CC); 157 158 /// getCopyFromParts - Create a value that contains the specified legal parts 159 /// combined into the value they represent. If the parts combine to a type 160 /// larger than ValueVT then AssertOp can be used to specify whether the extra 161 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 162 /// (ISD::AssertSext). 163 static SDValue 164 getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, 165 unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V, 166 std::optional<CallingConv::ID> CC = std::nullopt, 167 std::optional<ISD::NodeType> AssertOp = std::nullopt) { 168 // Let the target assemble the parts if it wants to 169 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 170 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts, 171 PartVT, ValueVT, CC)) 172 return Val; 173 174 if (ValueVT.isVector()) 175 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 176 CC); 177 178 assert(NumParts > 0 && "No parts to assemble!"); 179 SDValue Val = Parts[0]; 180 181 if (NumParts > 1) { 182 // Assemble the value from multiple parts. 183 if (ValueVT.isInteger()) { 184 unsigned PartBits = PartVT.getSizeInBits(); 185 unsigned ValueBits = ValueVT.getSizeInBits(); 186 187 // Assemble the power of 2 part. 188 unsigned RoundParts = llvm::bit_floor(NumParts); 189 unsigned RoundBits = PartBits * RoundParts; 190 EVT RoundVT = RoundBits == ValueBits ? 191 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 192 SDValue Lo, Hi; 193 194 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 195 196 if (RoundParts > 2) { 197 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 198 PartVT, HalfVT, V); 199 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 200 RoundParts / 2, PartVT, HalfVT, V); 201 } else { 202 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 203 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 204 } 205 206 if (DAG.getDataLayout().isBigEndian()) 207 std::swap(Lo, Hi); 208 209 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 210 211 if (RoundParts < NumParts) { 212 // Assemble the trailing non-power-of-2 part. 213 unsigned OddParts = NumParts - RoundParts; 214 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 215 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 216 OddVT, V, CC); 217 218 // Combine the round and odd parts. 219 Lo = Val; 220 if (DAG.getDataLayout().isBigEndian()) 221 std::swap(Lo, Hi); 222 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 223 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 224 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 225 DAG.getConstant(Lo.getValueSizeInBits(), DL, 226 TLI.getShiftAmountTy( 227 TotalVT, DAG.getDataLayout()))); 228 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 229 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 230 } 231 } else if (PartVT.isFloatingPoint()) { 232 // FP split into multiple FP parts (for ppcf128) 233 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 234 "Unexpected split"); 235 SDValue Lo, Hi; 236 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 237 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 238 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 239 std::swap(Lo, Hi); 240 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 241 } else { 242 // FP split into integer parts (soft fp) 243 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 244 !PartVT.isVector() && "Unexpected split"); 245 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 246 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 247 } 248 } 249 250 // There is now one part, held in Val. Correct it to match ValueVT. 251 // PartEVT is the type of the register class that holds the value. 252 // ValueVT is the type of the inline asm operation. 253 EVT PartEVT = Val.getValueType(); 254 255 if (PartEVT == ValueVT) 256 return Val; 257 258 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 259 ValueVT.bitsLT(PartEVT)) { 260 // For an FP value in an integer part, we need to truncate to the right 261 // width first. 262 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 263 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 264 } 265 266 // Handle types that have the same size. 267 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 268 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 269 270 // Handle types with different sizes. 271 if (PartEVT.isInteger() && ValueVT.isInteger()) { 272 if (ValueVT.bitsLT(PartEVT)) { 273 // For a truncate, see if we have any information to 274 // indicate whether the truncated bits will always be 275 // zero or sign-extension. 276 if (AssertOp) 277 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 278 DAG.getValueType(ValueVT)); 279 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 280 } 281 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 282 } 283 284 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 285 // FP_ROUND's are always exact here. 286 if (ValueVT.bitsLT(Val.getValueType())) 287 return DAG.getNode( 288 ISD::FP_ROUND, DL, ValueVT, Val, 289 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 290 291 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 292 } 293 294 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 295 // then truncating. 296 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 297 ValueVT.bitsLT(PartEVT)) { 298 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 299 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 300 } 301 302 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 303 } 304 305 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 306 const Twine &ErrMsg) { 307 const Instruction *I = dyn_cast_or_null<Instruction>(V); 308 if (!V) 309 return Ctx.emitError(ErrMsg); 310 311 const char *AsmError = ", possible invalid constraint for vector type"; 312 if (const CallInst *CI = dyn_cast<CallInst>(I)) 313 if (CI->isInlineAsm()) 314 return Ctx.emitError(I, ErrMsg + AsmError); 315 316 return Ctx.emitError(I, ErrMsg); 317 } 318 319 /// getCopyFromPartsVector - Create a value that contains the specified legal 320 /// parts combined into the value they represent. If the parts combine to a 321 /// type larger than ValueVT then AssertOp can be used to specify whether the 322 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 323 /// ValueVT (ISD::AssertSext). 324 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 325 const SDValue *Parts, unsigned NumParts, 326 MVT PartVT, EVT ValueVT, const Value *V, 327 std::optional<CallingConv::ID> CallConv) { 328 assert(ValueVT.isVector() && "Not a vector value"); 329 assert(NumParts > 0 && "No parts to assemble!"); 330 const bool IsABIRegCopy = CallConv.has_value(); 331 332 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 333 SDValue Val = Parts[0]; 334 335 // Handle a multi-element vector. 336 if (NumParts > 1) { 337 EVT IntermediateVT; 338 MVT RegisterVT; 339 unsigned NumIntermediates; 340 unsigned NumRegs; 341 342 if (IsABIRegCopy) { 343 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 344 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, 345 NumIntermediates, RegisterVT); 346 } else { 347 NumRegs = 348 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 349 NumIntermediates, RegisterVT); 350 } 351 352 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 353 NumParts = NumRegs; // Silence a compiler warning. 354 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 355 assert(RegisterVT.getSizeInBits() == 356 Parts[0].getSimpleValueType().getSizeInBits() && 357 "Part type sizes don't match!"); 358 359 // Assemble the parts into intermediate operands. 360 SmallVector<SDValue, 8> Ops(NumIntermediates); 361 if (NumIntermediates == NumParts) { 362 // If the register was not expanded, truncate or copy the value, 363 // as appropriate. 364 for (unsigned i = 0; i != NumParts; ++i) 365 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 366 PartVT, IntermediateVT, V, CallConv); 367 } else if (NumParts > 0) { 368 // If the intermediate type was expanded, build the intermediate 369 // operands from the parts. 370 assert(NumParts % NumIntermediates == 0 && 371 "Must expand into a divisible number of parts!"); 372 unsigned Factor = NumParts / NumIntermediates; 373 for (unsigned i = 0; i != NumIntermediates; ++i) 374 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 375 PartVT, IntermediateVT, V, CallConv); 376 } 377 378 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 379 // intermediate operands. 380 EVT BuiltVectorTy = 381 IntermediateVT.isVector() 382 ? EVT::getVectorVT( 383 *DAG.getContext(), IntermediateVT.getScalarType(), 384 IntermediateVT.getVectorElementCount() * NumParts) 385 : EVT::getVectorVT(*DAG.getContext(), 386 IntermediateVT.getScalarType(), 387 NumIntermediates); 388 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 389 : ISD::BUILD_VECTOR, 390 DL, BuiltVectorTy, Ops); 391 } 392 393 // There is now one part, held in Val. Correct it to match ValueVT. 394 EVT PartEVT = Val.getValueType(); 395 396 if (PartEVT == ValueVT) 397 return Val; 398 399 if (PartEVT.isVector()) { 400 // Vector/Vector bitcast. 401 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 402 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 403 404 // If the parts vector has more elements than the value vector, then we 405 // have a vector widening case (e.g. <2 x float> -> <4 x float>). 406 // Extract the elements we want. 407 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) { 408 assert((PartEVT.getVectorElementCount().getKnownMinValue() > 409 ValueVT.getVectorElementCount().getKnownMinValue()) && 410 (PartEVT.getVectorElementCount().isScalable() == 411 ValueVT.getVectorElementCount().isScalable()) && 412 "Cannot narrow, it would be a lossy transformation"); 413 PartEVT = 414 EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(), 415 ValueVT.getVectorElementCount()); 416 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val, 417 DAG.getVectorIdxConstant(0, DL)); 418 if (PartEVT == ValueVT) 419 return Val; 420 if (PartEVT.isInteger() && ValueVT.isFloatingPoint()) 421 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 422 423 // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>). 424 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 425 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 426 } 427 428 // Promoted vector extract 429 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 430 } 431 432 // Trivial bitcast if the types are the same size and the destination 433 // vector type is legal. 434 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 435 TLI.isTypeLegal(ValueVT)) 436 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 437 438 if (ValueVT.getVectorNumElements() != 1) { 439 // Certain ABIs require that vectors are passed as integers. For vectors 440 // are the same size, this is an obvious bitcast. 441 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 442 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 443 } else if (ValueVT.bitsLT(PartEVT)) { 444 const uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 445 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 446 // Drop the extra bits. 447 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 448 return DAG.getBitcast(ValueVT, Val); 449 } 450 451 diagnosePossiblyInvalidConstraint( 452 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 453 return DAG.getUNDEF(ValueVT); 454 } 455 456 // Handle cases such as i8 -> <1 x i1> 457 EVT ValueSVT = ValueVT.getVectorElementType(); 458 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 459 unsigned ValueSize = ValueSVT.getSizeInBits(); 460 if (ValueSize == PartEVT.getSizeInBits()) { 461 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 462 } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) { 463 // It's possible a scalar floating point type gets softened to integer and 464 // then promoted to a larger integer. If PartEVT is the larger integer 465 // we need to truncate it and then bitcast to the FP type. 466 assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types"); 467 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 468 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 469 Val = DAG.getBitcast(ValueSVT, Val); 470 } else { 471 Val = ValueVT.isFloatingPoint() 472 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 473 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 474 } 475 } 476 477 return DAG.getBuildVector(ValueVT, DL, Val); 478 } 479 480 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 481 SDValue Val, SDValue *Parts, unsigned NumParts, 482 MVT PartVT, const Value *V, 483 std::optional<CallingConv::ID> CallConv); 484 485 /// getCopyToParts - Create a series of nodes that contain the specified value 486 /// split into legal parts. If the parts contain more bits than Val, then, for 487 /// integers, ExtendKind can be used to specify how to generate the extra bits. 488 static void 489 getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 490 unsigned NumParts, MVT PartVT, const Value *V, 491 std::optional<CallingConv::ID> CallConv = std::nullopt, 492 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 493 // Let the target split the parts if it wants to 494 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 495 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 496 CallConv)) 497 return; 498 EVT ValueVT = Val.getValueType(); 499 500 // Handle the vector case separately. 501 if (ValueVT.isVector()) 502 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 503 CallConv); 504 505 unsigned OrigNumParts = NumParts; 506 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 507 "Copying to an illegal type!"); 508 509 if (NumParts == 0) 510 return; 511 512 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 513 EVT PartEVT = PartVT; 514 if (PartEVT == ValueVT) { 515 assert(NumParts == 1 && "No-op copy with multiple parts!"); 516 Parts[0] = Val; 517 return; 518 } 519 520 unsigned PartBits = PartVT.getSizeInBits(); 521 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 522 // If the parts cover more bits than the value has, promote the value. 523 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 524 assert(NumParts == 1 && "Do not know what to promote to!"); 525 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 526 } else { 527 if (ValueVT.isFloatingPoint()) { 528 // FP values need to be bitcast, then extended if they are being put 529 // into a larger container. 530 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 531 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 532 } 533 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 534 ValueVT.isInteger() && 535 "Unknown mismatch!"); 536 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 537 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 538 if (PartVT == MVT::x86mmx) 539 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 540 } 541 } else if (PartBits == ValueVT.getSizeInBits()) { 542 // Different types of the same size. 543 assert(NumParts == 1 && PartEVT != ValueVT); 544 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 545 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 546 // If the parts cover less bits than value has, truncate the value. 547 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 548 ValueVT.isInteger() && 549 "Unknown mismatch!"); 550 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 551 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 552 if (PartVT == MVT::x86mmx) 553 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 554 } 555 556 // The value may have changed - recompute ValueVT. 557 ValueVT = Val.getValueType(); 558 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 559 "Failed to tile the value with PartVT!"); 560 561 if (NumParts == 1) { 562 if (PartEVT != ValueVT) { 563 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 564 "scalar-to-vector conversion failed"); 565 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 566 } 567 568 Parts[0] = Val; 569 return; 570 } 571 572 // Expand the value into multiple parts. 573 if (NumParts & (NumParts - 1)) { 574 // The number of parts is not a power of 2. Split off and copy the tail. 575 assert(PartVT.isInteger() && ValueVT.isInteger() && 576 "Do not know what to expand to!"); 577 unsigned RoundParts = llvm::bit_floor(NumParts); 578 unsigned RoundBits = RoundParts * PartBits; 579 unsigned OddParts = NumParts - RoundParts; 580 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 581 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL)); 582 583 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 584 CallConv); 585 586 if (DAG.getDataLayout().isBigEndian()) 587 // The odd parts were reversed by getCopyToParts - unreverse them. 588 std::reverse(Parts + RoundParts, Parts + NumParts); 589 590 NumParts = RoundParts; 591 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 592 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 593 } 594 595 // The number of parts is a power of 2. Repeatedly bisect the value using 596 // EXTRACT_ELEMENT. 597 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 598 EVT::getIntegerVT(*DAG.getContext(), 599 ValueVT.getSizeInBits()), 600 Val); 601 602 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 603 for (unsigned i = 0; i < NumParts; i += StepSize) { 604 unsigned ThisBits = StepSize * PartBits / 2; 605 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 606 SDValue &Part0 = Parts[i]; 607 SDValue &Part1 = Parts[i+StepSize/2]; 608 609 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 610 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 611 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 612 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 613 614 if (ThisBits == PartBits && ThisVT != PartVT) { 615 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 616 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 617 } 618 } 619 } 620 621 if (DAG.getDataLayout().isBigEndian()) 622 std::reverse(Parts, Parts + OrigNumParts); 623 } 624 625 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val, 626 const SDLoc &DL, EVT PartVT) { 627 if (!PartVT.isVector()) 628 return SDValue(); 629 630 EVT ValueVT = Val.getValueType(); 631 EVT PartEVT = PartVT.getVectorElementType(); 632 EVT ValueEVT = ValueVT.getVectorElementType(); 633 ElementCount PartNumElts = PartVT.getVectorElementCount(); 634 ElementCount ValueNumElts = ValueVT.getVectorElementCount(); 635 636 // We only support widening vectors with equivalent element types and 637 // fixed/scalable properties. If a target needs to widen a fixed-length type 638 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below. 639 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) || 640 PartNumElts.isScalable() != ValueNumElts.isScalable()) 641 return SDValue(); 642 643 // Have a try for bf16 because some targets share its ABI with fp16. 644 if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) { 645 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 646 "Cannot widen to illegal type"); 647 Val = DAG.getNode(ISD::BITCAST, DL, 648 ValueVT.changeVectorElementType(MVT::f16), Val); 649 } else if (PartEVT != ValueEVT) { 650 return SDValue(); 651 } 652 653 // Widening a scalable vector to another scalable vector is done by inserting 654 // the vector into a larger undef one. 655 if (PartNumElts.isScalable()) 656 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 657 Val, DAG.getVectorIdxConstant(0, DL)); 658 659 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 660 // undef elements. 661 SmallVector<SDValue, 16> Ops; 662 DAG.ExtractVectorElements(Val, Ops); 663 SDValue EltUndef = DAG.getUNDEF(PartEVT); 664 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef); 665 666 // FIXME: Use CONCAT for 2x -> 4x. 667 return DAG.getBuildVector(PartVT, DL, Ops); 668 } 669 670 /// getCopyToPartsVector - Create a series of nodes that contain the specified 671 /// value split into legal parts. 672 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 673 SDValue Val, SDValue *Parts, unsigned NumParts, 674 MVT PartVT, const Value *V, 675 std::optional<CallingConv::ID> CallConv) { 676 EVT ValueVT = Val.getValueType(); 677 assert(ValueVT.isVector() && "Not a vector"); 678 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 679 const bool IsABIRegCopy = CallConv.has_value(); 680 681 if (NumParts == 1) { 682 EVT PartEVT = PartVT; 683 if (PartEVT == ValueVT) { 684 // Nothing to do. 685 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 686 // Bitconvert vector->vector case. 687 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 688 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 689 Val = Widened; 690 } else if (PartVT.isVector() && 691 PartEVT.getVectorElementType().bitsGE( 692 ValueVT.getVectorElementType()) && 693 PartEVT.getVectorElementCount() == 694 ValueVT.getVectorElementCount()) { 695 696 // Promoted vector extract 697 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 698 } else if (PartEVT.isVector() && 699 PartEVT.getVectorElementType() != 700 ValueVT.getVectorElementType() && 701 TLI.getTypeAction(*DAG.getContext(), ValueVT) == 702 TargetLowering::TypeWidenVector) { 703 // Combination of widening and promotion. 704 EVT WidenVT = 705 EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(), 706 PartVT.getVectorElementCount()); 707 SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT); 708 Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT); 709 } else { 710 // Don't extract an integer from a float vector. This can happen if the 711 // FP type gets softened to integer and then promoted. The promotion 712 // prevents it from being picked up by the earlier bitcast case. 713 if (ValueVT.getVectorElementCount().isScalar() && 714 (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) { 715 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 716 DAG.getVectorIdxConstant(0, DL)); 717 } else { 718 uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 719 assert(PartVT.getFixedSizeInBits() > ValueSize && 720 "lossy conversion of vector to scalar type"); 721 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 722 Val = DAG.getBitcast(IntermediateType, Val); 723 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 724 } 725 } 726 727 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 728 Parts[0] = Val; 729 return; 730 } 731 732 // Handle a multi-element vector. 733 EVT IntermediateVT; 734 MVT RegisterVT; 735 unsigned NumIntermediates; 736 unsigned NumRegs; 737 if (IsABIRegCopy) { 738 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 739 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates, 740 RegisterVT); 741 } else { 742 NumRegs = 743 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 744 NumIntermediates, RegisterVT); 745 } 746 747 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 748 NumParts = NumRegs; // Silence a compiler warning. 749 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 750 751 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 752 "Mixing scalable and fixed vectors when copying in parts"); 753 754 std::optional<ElementCount> DestEltCnt; 755 756 if (IntermediateVT.isVector()) 757 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 758 else 759 DestEltCnt = ElementCount::getFixed(NumIntermediates); 760 761 EVT BuiltVectorTy = EVT::getVectorVT( 762 *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt); 763 764 if (ValueVT == BuiltVectorTy) { 765 // Nothing to do. 766 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) { 767 // Bitconvert vector->vector case. 768 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 769 } else { 770 if (BuiltVectorTy.getVectorElementType().bitsGT( 771 ValueVT.getVectorElementType())) { 772 // Integer promotion. 773 ValueVT = EVT::getVectorVT(*DAG.getContext(), 774 BuiltVectorTy.getVectorElementType(), 775 ValueVT.getVectorElementCount()); 776 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 777 } 778 779 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) { 780 Val = Widened; 781 } 782 } 783 784 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type"); 785 786 // Split the vector into intermediate operands. 787 SmallVector<SDValue, 8> Ops(NumIntermediates); 788 for (unsigned i = 0; i != NumIntermediates; ++i) { 789 if (IntermediateVT.isVector()) { 790 // This does something sensible for scalable vectors - see the 791 // definition of EXTRACT_SUBVECTOR for further details. 792 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 793 Ops[i] = 794 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 795 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 796 } else { 797 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 798 DAG.getVectorIdxConstant(i, DL)); 799 } 800 } 801 802 // Split the intermediate operands into legal parts. 803 if (NumParts == NumIntermediates) { 804 // If the register was not expanded, promote or copy the value, 805 // as appropriate. 806 for (unsigned i = 0; i != NumParts; ++i) 807 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 808 } else if (NumParts > 0) { 809 // If the intermediate type was expanded, split each the value into 810 // legal parts. 811 assert(NumIntermediates != 0 && "division by zero"); 812 assert(NumParts % NumIntermediates == 0 && 813 "Must expand into a divisible number of parts!"); 814 unsigned Factor = NumParts / NumIntermediates; 815 for (unsigned i = 0; i != NumIntermediates; ++i) 816 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 817 CallConv); 818 } 819 } 820 821 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 822 EVT valuevt, std::optional<CallingConv::ID> CC) 823 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 824 RegCount(1, regs.size()), CallConv(CC) {} 825 826 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 827 const DataLayout &DL, unsigned Reg, Type *Ty, 828 std::optional<CallingConv::ID> CC) { 829 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 830 831 CallConv = CC; 832 833 for (EVT ValueVT : ValueVTs) { 834 unsigned NumRegs = 835 isABIMangled() 836 ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT) 837 : TLI.getNumRegisters(Context, ValueVT); 838 MVT RegisterVT = 839 isABIMangled() 840 ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT) 841 : TLI.getRegisterType(Context, ValueVT); 842 for (unsigned i = 0; i != NumRegs; ++i) 843 Regs.push_back(Reg + i); 844 RegVTs.push_back(RegisterVT); 845 RegCount.push_back(NumRegs); 846 Reg += NumRegs; 847 } 848 } 849 850 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 851 FunctionLoweringInfo &FuncInfo, 852 const SDLoc &dl, SDValue &Chain, 853 SDValue *Glue, const Value *V) const { 854 // A Value with type {} or [0 x %t] needs no registers. 855 if (ValueVTs.empty()) 856 return SDValue(); 857 858 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 859 860 // Assemble the legal parts into the final values. 861 SmallVector<SDValue, 4> Values(ValueVTs.size()); 862 SmallVector<SDValue, 8> Parts; 863 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 864 // Copy the legal parts from the registers. 865 EVT ValueVT = ValueVTs[Value]; 866 unsigned NumRegs = RegCount[Value]; 867 MVT RegisterVT = isABIMangled() 868 ? TLI.getRegisterTypeForCallingConv( 869 *DAG.getContext(), *CallConv, RegVTs[Value]) 870 : RegVTs[Value]; 871 872 Parts.resize(NumRegs); 873 for (unsigned i = 0; i != NumRegs; ++i) { 874 SDValue P; 875 if (!Glue) { 876 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 877 } else { 878 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue); 879 *Glue = P.getValue(2); 880 } 881 882 Chain = P.getValue(1); 883 Parts[i] = P; 884 885 // If the source register was virtual and if we know something about it, 886 // add an assert node. 887 if (!Register::isVirtualRegister(Regs[Part + i]) || 888 !RegisterVT.isInteger()) 889 continue; 890 891 const FunctionLoweringInfo::LiveOutInfo *LOI = 892 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 893 if (!LOI) 894 continue; 895 896 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 897 unsigned NumSignBits = LOI->NumSignBits; 898 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 899 900 if (NumZeroBits == RegSize) { 901 // The current value is a zero. 902 // Explicitly express that as it would be easier for 903 // optimizations to kick in. 904 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 905 continue; 906 } 907 908 // FIXME: We capture more information than the dag can represent. For 909 // now, just use the tightest assertzext/assertsext possible. 910 bool isSExt; 911 EVT FromVT(MVT::Other); 912 if (NumZeroBits) { 913 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 914 isSExt = false; 915 } else if (NumSignBits > 1) { 916 FromVT = 917 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 918 isSExt = true; 919 } else { 920 continue; 921 } 922 // Add an assertion node. 923 assert(FromVT != MVT::Other); 924 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 925 RegisterVT, P, DAG.getValueType(FromVT)); 926 } 927 928 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 929 RegisterVT, ValueVT, V, CallConv); 930 Part += NumRegs; 931 Parts.clear(); 932 } 933 934 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 935 } 936 937 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 938 const SDLoc &dl, SDValue &Chain, SDValue *Glue, 939 const Value *V, 940 ISD::NodeType PreferredExtendType) const { 941 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 942 ISD::NodeType ExtendKind = PreferredExtendType; 943 944 // Get the list of the values's legal parts. 945 unsigned NumRegs = Regs.size(); 946 SmallVector<SDValue, 8> Parts(NumRegs); 947 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 948 unsigned NumParts = RegCount[Value]; 949 950 MVT RegisterVT = isABIMangled() 951 ? TLI.getRegisterTypeForCallingConv( 952 *DAG.getContext(), *CallConv, RegVTs[Value]) 953 : RegVTs[Value]; 954 955 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 956 ExtendKind = ISD::ZERO_EXTEND; 957 958 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 959 NumParts, RegisterVT, V, CallConv, ExtendKind); 960 Part += NumParts; 961 } 962 963 // Copy the parts into the registers. 964 SmallVector<SDValue, 8> Chains(NumRegs); 965 for (unsigned i = 0; i != NumRegs; ++i) { 966 SDValue Part; 967 if (!Glue) { 968 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 969 } else { 970 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue); 971 *Glue = Part.getValue(1); 972 } 973 974 Chains[i] = Part.getValue(0); 975 } 976 977 if (NumRegs == 1 || Glue) 978 // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is 979 // flagged to it. That is the CopyToReg nodes and the user are considered 980 // a single scheduling unit. If we create a TokenFactor and return it as 981 // chain, then the TokenFactor is both a predecessor (operand) of the 982 // user as well as a successor (the TF operands are flagged to the user). 983 // c1, f1 = CopyToReg 984 // c2, f2 = CopyToReg 985 // c3 = TokenFactor c1, c2 986 // ... 987 // = op c3, ..., f2 988 Chain = Chains[NumRegs-1]; 989 else 990 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 991 } 992 993 void RegsForValue::AddInlineAsmOperands(InlineAsm::Kind Code, bool HasMatching, 994 unsigned MatchingIdx, const SDLoc &dl, 995 SelectionDAG &DAG, 996 std::vector<SDValue> &Ops) const { 997 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 998 999 InlineAsm::Flag Flag(Code, Regs.size()); 1000 if (HasMatching) 1001 Flag.setMatchingOp(MatchingIdx); 1002 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 1003 // Put the register class of the virtual registers in the flag word. That 1004 // way, later passes can recompute register class constraints for inline 1005 // assembly as well as normal instructions. 1006 // Don't do this for tied operands that can use the regclass information 1007 // from the def. 1008 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1009 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 1010 Flag.setRegClass(RC->getID()); 1011 } 1012 1013 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 1014 Ops.push_back(Res); 1015 1016 if (Code == InlineAsm::Kind::Clobber) { 1017 // Clobbers should always have a 1:1 mapping with registers, and may 1018 // reference registers that have illegal (e.g. vector) types. Hence, we 1019 // shouldn't try to apply any sort of splitting logic to them. 1020 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 1021 "No 1:1 mapping from clobbers to regs?"); 1022 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 1023 (void)SP; 1024 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 1025 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 1026 assert( 1027 (Regs[I] != SP || 1028 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 1029 "If we clobbered the stack pointer, MFI should know about it."); 1030 } 1031 return; 1032 } 1033 1034 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 1035 MVT RegisterVT = RegVTs[Value]; 1036 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value], 1037 RegisterVT); 1038 for (unsigned i = 0; i != NumRegs; ++i) { 1039 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 1040 unsigned TheReg = Regs[Reg++]; 1041 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 1042 } 1043 } 1044 } 1045 1046 SmallVector<std::pair<unsigned, TypeSize>, 4> 1047 RegsForValue::getRegsAndSizes() const { 1048 SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec; 1049 unsigned I = 0; 1050 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1051 unsigned RegCount = std::get<0>(CountAndVT); 1052 MVT RegisterVT = std::get<1>(CountAndVT); 1053 TypeSize RegisterSize = RegisterVT.getSizeInBits(); 1054 for (unsigned E = I + RegCount; I != E; ++I) 1055 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1056 } 1057 return OutVec; 1058 } 1059 1060 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1061 AssumptionCache *ac, 1062 const TargetLibraryInfo *li) { 1063 AA = aa; 1064 AC = ac; 1065 GFI = gfi; 1066 LibInfo = li; 1067 Context = DAG.getContext(); 1068 LPadToCallSiteMap.clear(); 1069 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1070 AssignmentTrackingEnabled = isAssignmentTrackingEnabled( 1071 *DAG.getMachineFunction().getFunction().getParent()); 1072 } 1073 1074 void SelectionDAGBuilder::clear() { 1075 NodeMap.clear(); 1076 UnusedArgNodeMap.clear(); 1077 PendingLoads.clear(); 1078 PendingExports.clear(); 1079 PendingConstrainedFP.clear(); 1080 PendingConstrainedFPStrict.clear(); 1081 CurInst = nullptr; 1082 HasTailCall = false; 1083 SDNodeOrder = LowestSDNodeOrder; 1084 StatepointLowering.clear(); 1085 } 1086 1087 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1088 DanglingDebugInfoMap.clear(); 1089 } 1090 1091 // Update DAG root to include dependencies on Pending chains. 1092 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1093 SDValue Root = DAG.getRoot(); 1094 1095 if (Pending.empty()) 1096 return Root; 1097 1098 // Add current root to PendingChains, unless we already indirectly 1099 // depend on it. 1100 if (Root.getOpcode() != ISD::EntryToken) { 1101 unsigned i = 0, e = Pending.size(); 1102 for (; i != e; ++i) { 1103 assert(Pending[i].getNode()->getNumOperands() > 1); 1104 if (Pending[i].getNode()->getOperand(0) == Root) 1105 break; // Don't add the root if we already indirectly depend on it. 1106 } 1107 1108 if (i == e) 1109 Pending.push_back(Root); 1110 } 1111 1112 if (Pending.size() == 1) 1113 Root = Pending[0]; 1114 else 1115 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1116 1117 DAG.setRoot(Root); 1118 Pending.clear(); 1119 return Root; 1120 } 1121 1122 SDValue SelectionDAGBuilder::getMemoryRoot() { 1123 return updateRoot(PendingLoads); 1124 } 1125 1126 SDValue SelectionDAGBuilder::getRoot() { 1127 // Chain up all pending constrained intrinsics together with all 1128 // pending loads, by simply appending them to PendingLoads and 1129 // then calling getMemoryRoot(). 1130 PendingLoads.reserve(PendingLoads.size() + 1131 PendingConstrainedFP.size() + 1132 PendingConstrainedFPStrict.size()); 1133 PendingLoads.append(PendingConstrainedFP.begin(), 1134 PendingConstrainedFP.end()); 1135 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1136 PendingConstrainedFPStrict.end()); 1137 PendingConstrainedFP.clear(); 1138 PendingConstrainedFPStrict.clear(); 1139 return getMemoryRoot(); 1140 } 1141 1142 SDValue SelectionDAGBuilder::getControlRoot() { 1143 // We need to emit pending fpexcept.strict constrained intrinsics, 1144 // so append them to the PendingExports list. 1145 PendingExports.append(PendingConstrainedFPStrict.begin(), 1146 PendingConstrainedFPStrict.end()); 1147 PendingConstrainedFPStrict.clear(); 1148 return updateRoot(PendingExports); 1149 } 1150 1151 void SelectionDAGBuilder::handleDebugDeclare(Value *Address, 1152 DILocalVariable *Variable, 1153 DIExpression *Expression, 1154 DebugLoc DL) { 1155 assert(Variable && "Missing variable"); 1156 1157 // Check if address has undef value. 1158 if (!Address || isa<UndefValue>(Address) || 1159 (Address->use_empty() && !isa<Argument>(Address))) { 1160 LLVM_DEBUG( 1161 dbgs() 1162 << "dbg_declare: Dropping debug info (bad/undef/unused-arg address)\n"); 1163 return; 1164 } 1165 1166 bool IsParameter = Variable->isParameter() || isa<Argument>(Address); 1167 1168 SDValue &N = NodeMap[Address]; 1169 if (!N.getNode() && isa<Argument>(Address)) 1170 // Check unused arguments map. 1171 N = UnusedArgNodeMap[Address]; 1172 SDDbgValue *SDV; 1173 if (N.getNode()) { 1174 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 1175 Address = BCI->getOperand(0); 1176 // Parameters are handled specially. 1177 auto *FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 1178 if (IsParameter && FINode) { 1179 // Byval parameter. We have a frame index at this point. 1180 SDV = DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 1181 /*IsIndirect*/ true, DL, SDNodeOrder); 1182 } else if (isa<Argument>(Address)) { 1183 // Address is an argument, so try to emit its dbg value using 1184 // virtual register info from the FuncInfo.ValueMap. 1185 EmitFuncArgumentDbgValue(Address, Variable, Expression, DL, 1186 FuncArgumentDbgValueKind::Declare, N); 1187 return; 1188 } else { 1189 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 1190 true, DL, SDNodeOrder); 1191 } 1192 DAG.AddDbgValue(SDV, IsParameter); 1193 } else { 1194 // If Address is an argument then try to emit its dbg value using 1195 // virtual register info from the FuncInfo.ValueMap. 1196 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, DL, 1197 FuncArgumentDbgValueKind::Declare, N)) { 1198 LLVM_DEBUG(dbgs() << "dbg_declare: Dropping debug info" 1199 << " (could not emit func-arg dbg_value)\n"); 1200 } 1201 } 1202 return; 1203 } 1204 1205 void SelectionDAGBuilder::visitDbgInfo(const Instruction &I) { 1206 // Add SDDbgValue nodes for any var locs here. Do so before updating 1207 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1208 if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) { 1209 // Add SDDbgValue nodes for any var locs here. Do so before updating 1210 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1211 for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I); 1212 It != End; ++It) { 1213 auto *Var = FnVarLocs->getDILocalVariable(It->VariableID); 1214 dropDanglingDebugInfo(Var, It->Expr); 1215 if (It->Values.isKillLocation(It->Expr)) { 1216 handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder); 1217 continue; 1218 } 1219 SmallVector<Value *> Values(It->Values.location_ops()); 1220 if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder, 1221 It->Values.hasArgList())) { 1222 SmallVector<Value *, 4> Vals; 1223 for (Value *V : It->Values.location_ops()) 1224 Vals.push_back(V); 1225 addDanglingDebugInfo(Vals, 1226 FnVarLocs->getDILocalVariable(It->VariableID), 1227 It->Expr, Vals.size() > 1, It->DL, SDNodeOrder); 1228 } 1229 } 1230 } 1231 1232 // Is there is any debug-info attached to this instruction, in the form of 1233 // DPValue non-instruction debug-info records. 1234 for (DPValue &DPV : I.getDbgValueRange()) { 1235 DILocalVariable *Variable = DPV.getVariable(); 1236 DIExpression *Expression = DPV.getExpression(); 1237 dropDanglingDebugInfo(Variable, Expression); 1238 1239 if (DPV.getType() == DPValue::LocationType::Declare) { 1240 if (FuncInfo.PreprocessedDPVDeclares.contains(&DPV)) 1241 continue; 1242 LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DPV 1243 << "\n"); 1244 handleDebugDeclare(DPV.getVariableLocationOp(0), Variable, Expression, 1245 DPV.getDebugLoc()); 1246 continue; 1247 } 1248 1249 // A DPValue with no locations is a kill location. 1250 SmallVector<Value *, 4> Values(DPV.location_ops()); 1251 if (Values.empty()) { 1252 handleKillDebugValue(Variable, Expression, DPV.getDebugLoc(), 1253 SDNodeOrder); 1254 continue; 1255 } 1256 1257 // A DPValue with an undef or absent location is also a kill location. 1258 if (llvm::any_of(Values, 1259 [](Value *V) { return !V || isa<UndefValue>(V); })) { 1260 handleKillDebugValue(Variable, Expression, DPV.getDebugLoc(), 1261 SDNodeOrder); 1262 continue; 1263 } 1264 1265 bool IsVariadic = DPV.hasArgList(); 1266 if (!handleDebugValue(Values, Variable, Expression, DPV.getDebugLoc(), 1267 SDNodeOrder, IsVariadic)) { 1268 addDanglingDebugInfo(Values, Variable, Expression, IsVariadic, 1269 DPV.getDebugLoc(), SDNodeOrder); 1270 } 1271 } 1272 } 1273 1274 void SelectionDAGBuilder::visit(const Instruction &I) { 1275 visitDbgInfo(I); 1276 1277 // Set up outgoing PHI node register values before emitting the terminator. 1278 if (I.isTerminator()) { 1279 HandlePHINodesInSuccessorBlocks(I.getParent()); 1280 } 1281 1282 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1283 if (!isa<DbgInfoIntrinsic>(I)) 1284 ++SDNodeOrder; 1285 1286 CurInst = &I; 1287 1288 // Set inserted listener only if required. 1289 bool NodeInserted = false; 1290 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener; 1291 MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections); 1292 if (PCSectionsMD) { 1293 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>( 1294 DAG, [&](SDNode *) { NodeInserted = true; }); 1295 } 1296 1297 visit(I.getOpcode(), I); 1298 1299 if (!I.isTerminator() && !HasTailCall && 1300 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1301 CopyToExportRegsIfNeeded(&I); 1302 1303 // Handle metadata. 1304 if (PCSectionsMD) { 1305 auto It = NodeMap.find(&I); 1306 if (It != NodeMap.end()) { 1307 DAG.addPCSections(It->second.getNode(), PCSectionsMD); 1308 } else if (NodeInserted) { 1309 // This should not happen; if it does, don't let it go unnoticed so we can 1310 // fix it. Relevant visit*() function is probably missing a setValue(). 1311 errs() << "warning: loosing !pcsections metadata [" 1312 << I.getModule()->getName() << "]\n"; 1313 LLVM_DEBUG(I.dump()); 1314 assert(false); 1315 } 1316 } 1317 1318 CurInst = nullptr; 1319 } 1320 1321 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1322 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1323 } 1324 1325 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1326 // Note: this doesn't use InstVisitor, because it has to work with 1327 // ConstantExpr's in addition to instructions. 1328 switch (Opcode) { 1329 default: llvm_unreachable("Unknown instruction type encountered!"); 1330 // Build the switch statement using the Instruction.def file. 1331 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1332 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1333 #include "llvm/IR/Instruction.def" 1334 } 1335 } 1336 1337 static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG, 1338 DILocalVariable *Variable, 1339 DebugLoc DL, unsigned Order, 1340 SmallVectorImpl<Value *> &Values, 1341 DIExpression *Expression) { 1342 // For variadic dbg_values we will now insert an undef. 1343 // FIXME: We can potentially recover these! 1344 SmallVector<SDDbgOperand, 2> Locs; 1345 for (const Value *V : Values) { 1346 auto *Undef = UndefValue::get(V->getType()); 1347 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1348 } 1349 SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {}, 1350 /*IsIndirect=*/false, DL, Order, 1351 /*IsVariadic=*/true); 1352 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1353 return true; 1354 } 1355 1356 void SelectionDAGBuilder::addDanglingDebugInfo(SmallVectorImpl<Value *> &Values, 1357 DILocalVariable *Var, 1358 DIExpression *Expr, 1359 bool IsVariadic, DebugLoc DL, 1360 unsigned Order) { 1361 if (IsVariadic) { 1362 handleDanglingVariadicDebugInfo(DAG, Var, DL, Order, Values, Expr); 1363 return; 1364 } 1365 // TODO: Dangling debug info will eventually either be resolved or produce 1366 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1367 // between the original dbg.value location and its resolved DBG_VALUE, 1368 // which we should ideally fill with an extra Undef DBG_VALUE. 1369 assert(Values.size() == 1); 1370 DanglingDebugInfoMap[Values[0]].emplace_back(Var, Expr, DL, Order); 1371 } 1372 1373 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1374 const DIExpression *Expr) { 1375 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1376 DIVariable *DanglingVariable = DDI.getVariable(); 1377 DIExpression *DanglingExpr = DDI.getExpression(); 1378 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1379 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " 1380 << printDDI(nullptr, DDI) << "\n"); 1381 return true; 1382 } 1383 return false; 1384 }; 1385 1386 for (auto &DDIMI : DanglingDebugInfoMap) { 1387 DanglingDebugInfoVector &DDIV = DDIMI.second; 1388 1389 // If debug info is to be dropped, run it through final checks to see 1390 // whether it can be salvaged. 1391 for (auto &DDI : DDIV) 1392 if (isMatchingDbgValue(DDI)) 1393 salvageUnresolvedDbgValue(DDIMI.first, DDI); 1394 1395 erase_if(DDIV, isMatchingDbgValue); 1396 } 1397 } 1398 1399 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1400 // generate the debug data structures now that we've seen its definition. 1401 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1402 SDValue Val) { 1403 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1404 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1405 return; 1406 1407 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1408 for (auto &DDI : DDIV) { 1409 DebugLoc DL = DDI.getDebugLoc(); 1410 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1411 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1412 DILocalVariable *Variable = DDI.getVariable(); 1413 DIExpression *Expr = DDI.getExpression(); 1414 assert(Variable->isValidLocationForIntrinsic(DL) && 1415 "Expected inlined-at fields to agree"); 1416 SDDbgValue *SDV; 1417 if (Val.getNode()) { 1418 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1419 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1420 // we couldn't resolve it directly when examining the DbgValue intrinsic 1421 // in the first place we should not be more successful here). Unless we 1422 // have some test case that prove this to be correct we should avoid 1423 // calling EmitFuncArgumentDbgValue here. 1424 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL, 1425 FuncArgumentDbgValueKind::Value, Val)) { 1426 LLVM_DEBUG(dbgs() << "Resolve dangling debug info for " 1427 << printDDI(V, DDI) << "\n"); 1428 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1429 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1430 // inserted after the definition of Val when emitting the instructions 1431 // after ISel. An alternative could be to teach 1432 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1433 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1434 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1435 << ValSDNodeOrder << "\n"); 1436 SDV = getDbgValue(Val, Variable, Expr, DL, 1437 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1438 DAG.AddDbgValue(SDV, false); 1439 } else 1440 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " 1441 << printDDI(V, DDI) 1442 << " in EmitFuncArgumentDbgValue\n"); 1443 } else { 1444 LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(V, DDI) 1445 << "\n"); 1446 auto Undef = UndefValue::get(V->getType()); 1447 auto SDV = 1448 DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder); 1449 DAG.AddDbgValue(SDV, false); 1450 } 1451 } 1452 DDIV.clear(); 1453 } 1454 1455 void SelectionDAGBuilder::salvageUnresolvedDbgValue(const Value *V, 1456 DanglingDebugInfo &DDI) { 1457 // TODO: For the variadic implementation, instead of only checking the fail 1458 // state of `handleDebugValue`, we need know specifically which values were 1459 // invalid, so that we attempt to salvage only those values when processing 1460 // a DIArgList. 1461 const Value *OrigV = V; 1462 DILocalVariable *Var = DDI.getVariable(); 1463 DIExpression *Expr = DDI.getExpression(); 1464 DebugLoc DL = DDI.getDebugLoc(); 1465 unsigned SDOrder = DDI.getSDNodeOrder(); 1466 1467 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1468 // that DW_OP_stack_value is desired. 1469 bool StackValue = true; 1470 1471 // Can this Value can be encoded without any further work? 1472 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) 1473 return; 1474 1475 // Attempt to salvage back through as many instructions as possible. Bail if 1476 // a non-instruction is seen, such as a constant expression or global 1477 // variable. FIXME: Further work could recover those too. 1478 while (isa<Instruction>(V)) { 1479 const Instruction &VAsInst = *cast<const Instruction>(V); 1480 // Temporary "0", awaiting real implementation. 1481 SmallVector<uint64_t, 16> Ops; 1482 SmallVector<Value *, 4> AdditionalValues; 1483 V = salvageDebugInfoImpl(const_cast<Instruction &>(VAsInst), 1484 Expr->getNumLocationOperands(), Ops, 1485 AdditionalValues); 1486 // If we cannot salvage any further, and haven't yet found a suitable debug 1487 // expression, bail out. 1488 if (!V) 1489 break; 1490 1491 // TODO: If AdditionalValues isn't empty, then the salvage can only be 1492 // represented with a DBG_VALUE_LIST, so we give up. When we have support 1493 // here for variadic dbg_values, remove that condition. 1494 if (!AdditionalValues.empty()) 1495 break; 1496 1497 // New value and expr now represent this debuginfo. 1498 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue); 1499 1500 // Some kind of simplification occurred: check whether the operand of the 1501 // salvaged debug expression can be encoded in this DAG. 1502 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) { 1503 LLVM_DEBUG( 1504 dbgs() << "Salvaged debug location info for:\n " << *Var << "\n" 1505 << *OrigV << "\nBy stripping back to:\n " << *V << "\n"); 1506 return; 1507 } 1508 } 1509 1510 // This was the final opportunity to salvage this debug information, and it 1511 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1512 // any earlier variable location. 1513 assert(OrigV && "V shouldn't be null"); 1514 auto *Undef = UndefValue::get(OrigV->getType()); 1515 auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1516 DAG.AddDbgValue(SDV, false); 1517 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " 1518 << printDDI(OrigV, DDI) << "\n"); 1519 } 1520 1521 void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var, 1522 DIExpression *Expr, 1523 DebugLoc DbgLoc, 1524 unsigned Order) { 1525 Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context)); 1526 DIExpression *NewExpr = 1527 const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr)); 1528 handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order, 1529 /*IsVariadic*/ false); 1530 } 1531 1532 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1533 DILocalVariable *Var, 1534 DIExpression *Expr, DebugLoc DbgLoc, 1535 unsigned Order, bool IsVariadic) { 1536 if (Values.empty()) 1537 return true; 1538 SmallVector<SDDbgOperand> LocationOps; 1539 SmallVector<SDNode *> Dependencies; 1540 for (const Value *V : Values) { 1541 // Constant value. 1542 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1543 isa<ConstantPointerNull>(V)) { 1544 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1545 continue; 1546 } 1547 1548 // Look through IntToPtr constants. 1549 if (auto *CE = dyn_cast<ConstantExpr>(V)) 1550 if (CE->getOpcode() == Instruction::IntToPtr) { 1551 LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0))); 1552 continue; 1553 } 1554 1555 // If the Value is a frame index, we can create a FrameIndex debug value 1556 // without relying on the DAG at all. 1557 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1558 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1559 if (SI != FuncInfo.StaticAllocaMap.end()) { 1560 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1561 continue; 1562 } 1563 } 1564 1565 // Do not use getValue() in here; we don't want to generate code at 1566 // this point if it hasn't been done yet. 1567 SDValue N = NodeMap[V]; 1568 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1569 N = UnusedArgNodeMap[V]; 1570 if (N.getNode()) { 1571 // Only emit func arg dbg value for non-variadic dbg.values for now. 1572 if (!IsVariadic && 1573 EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc, 1574 FuncArgumentDbgValueKind::Value, N)) 1575 return true; 1576 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1577 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1578 // describe stack slot locations. 1579 // 1580 // Consider "int x = 0; int *px = &x;". There are two kinds of 1581 // interesting debug values here after optimization: 1582 // 1583 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1584 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1585 // 1586 // Both describe the direct values of their associated variables. 1587 Dependencies.push_back(N.getNode()); 1588 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1589 continue; 1590 } 1591 LocationOps.emplace_back( 1592 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1593 continue; 1594 } 1595 1596 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1597 // Special rules apply for the first dbg.values of parameter variables in a 1598 // function. Identify them by the fact they reference Argument Values, that 1599 // they're parameters, and they are parameters of the current function. We 1600 // need to let them dangle until they get an SDNode. 1601 bool IsParamOfFunc = 1602 isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt(); 1603 if (IsParamOfFunc) 1604 return false; 1605 1606 // The value is not used in this block yet (or it would have an SDNode). 1607 // We still want the value to appear for the user if possible -- if it has 1608 // an associated VReg, we can refer to that instead. 1609 auto VMI = FuncInfo.ValueMap.find(V); 1610 if (VMI != FuncInfo.ValueMap.end()) { 1611 unsigned Reg = VMI->second; 1612 // If this is a PHI node, it may be split up into several MI PHI nodes 1613 // (in FunctionLoweringInfo::set). 1614 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1615 V->getType(), std::nullopt); 1616 if (RFV.occupiesMultipleRegs()) { 1617 // FIXME: We could potentially support variadic dbg_values here. 1618 if (IsVariadic) 1619 return false; 1620 unsigned Offset = 0; 1621 unsigned BitsToDescribe = 0; 1622 if (auto VarSize = Var->getSizeInBits()) 1623 BitsToDescribe = *VarSize; 1624 if (auto Fragment = Expr->getFragmentInfo()) 1625 BitsToDescribe = Fragment->SizeInBits; 1626 for (const auto &RegAndSize : RFV.getRegsAndSizes()) { 1627 // Bail out if all bits are described already. 1628 if (Offset >= BitsToDescribe) 1629 break; 1630 // TODO: handle scalable vectors. 1631 unsigned RegisterSize = RegAndSize.second; 1632 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1633 ? BitsToDescribe - Offset 1634 : RegisterSize; 1635 auto FragmentExpr = DIExpression::createFragmentExpression( 1636 Expr, Offset, FragmentSize); 1637 if (!FragmentExpr) 1638 continue; 1639 SDDbgValue *SDV = DAG.getVRegDbgValue( 1640 Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, SDNodeOrder); 1641 DAG.AddDbgValue(SDV, false); 1642 Offset += RegisterSize; 1643 } 1644 return true; 1645 } 1646 // We can use simple vreg locations for variadic dbg_values as well. 1647 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1648 continue; 1649 } 1650 // We failed to create a SDDbgOperand for V. 1651 return false; 1652 } 1653 1654 // We have created a SDDbgOperand for each Value in Values. 1655 // Should use Order instead of SDNodeOrder? 1656 assert(!LocationOps.empty()); 1657 SDDbgValue *SDV = DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1658 /*IsIndirect=*/false, DbgLoc, 1659 SDNodeOrder, IsVariadic); 1660 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1661 return true; 1662 } 1663 1664 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1665 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1666 for (auto &Pair : DanglingDebugInfoMap) 1667 for (auto &DDI : Pair.second) 1668 salvageUnresolvedDbgValue(const_cast<Value *>(Pair.first), DDI); 1669 clearDanglingDebugInfo(); 1670 } 1671 1672 /// getCopyFromRegs - If there was virtual register allocated for the value V 1673 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1674 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1675 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1676 SDValue Result; 1677 1678 if (It != FuncInfo.ValueMap.end()) { 1679 Register InReg = It->second; 1680 1681 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1682 DAG.getDataLayout(), InReg, Ty, 1683 std::nullopt); // This is not an ABI copy. 1684 SDValue Chain = DAG.getEntryNode(); 1685 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1686 V); 1687 resolveDanglingDebugInfo(V, Result); 1688 } 1689 1690 return Result; 1691 } 1692 1693 /// getValue - Return an SDValue for the given Value. 1694 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1695 // If we already have an SDValue for this value, use it. It's important 1696 // to do this first, so that we don't create a CopyFromReg if we already 1697 // have a regular SDValue. 1698 SDValue &N = NodeMap[V]; 1699 if (N.getNode()) return N; 1700 1701 // If there's a virtual register allocated and initialized for this 1702 // value, use it. 1703 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1704 return copyFromReg; 1705 1706 // Otherwise create a new SDValue and remember it. 1707 SDValue Val = getValueImpl(V); 1708 NodeMap[V] = Val; 1709 resolveDanglingDebugInfo(V, Val); 1710 return Val; 1711 } 1712 1713 /// getNonRegisterValue - Return an SDValue for the given Value, but 1714 /// don't look in FuncInfo.ValueMap for a virtual register. 1715 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1716 // If we already have an SDValue for this value, use it. 1717 SDValue &N = NodeMap[V]; 1718 if (N.getNode()) { 1719 if (isIntOrFPConstant(N)) { 1720 // Remove the debug location from the node as the node is about to be used 1721 // in a location which may differ from the original debug location. This 1722 // is relevant to Constant and ConstantFP nodes because they can appear 1723 // as constant expressions inside PHI nodes. 1724 N->setDebugLoc(DebugLoc()); 1725 } 1726 return N; 1727 } 1728 1729 // Otherwise create a new SDValue and remember it. 1730 SDValue Val = getValueImpl(V); 1731 NodeMap[V] = Val; 1732 resolveDanglingDebugInfo(V, Val); 1733 return Val; 1734 } 1735 1736 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1737 /// Create an SDValue for the given value. 1738 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1739 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1740 1741 if (const Constant *C = dyn_cast<Constant>(V)) { 1742 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1743 1744 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1745 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1746 1747 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1748 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1749 1750 if (isa<ConstantPointerNull>(C)) { 1751 unsigned AS = V->getType()->getPointerAddressSpace(); 1752 return DAG.getConstant(0, getCurSDLoc(), 1753 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1754 } 1755 1756 if (match(C, m_VScale())) 1757 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1758 1759 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1760 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1761 1762 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1763 return DAG.getUNDEF(VT); 1764 1765 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1766 visit(CE->getOpcode(), *CE); 1767 SDValue N1 = NodeMap[V]; 1768 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1769 return N1; 1770 } 1771 1772 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1773 SmallVector<SDValue, 4> Constants; 1774 for (const Use &U : C->operands()) { 1775 SDNode *Val = getValue(U).getNode(); 1776 // If the operand is an empty aggregate, there are no values. 1777 if (!Val) continue; 1778 // Add each leaf value from the operand to the Constants list 1779 // to form a flattened list of all the values. 1780 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1781 Constants.push_back(SDValue(Val, i)); 1782 } 1783 1784 return DAG.getMergeValues(Constants, getCurSDLoc()); 1785 } 1786 1787 if (const ConstantDataSequential *CDS = 1788 dyn_cast<ConstantDataSequential>(C)) { 1789 SmallVector<SDValue, 4> Ops; 1790 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1791 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1792 // Add each leaf value from the operand to the Constants list 1793 // to form a flattened list of all the values. 1794 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1795 Ops.push_back(SDValue(Val, i)); 1796 } 1797 1798 if (isa<ArrayType>(CDS->getType())) 1799 return DAG.getMergeValues(Ops, getCurSDLoc()); 1800 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1801 } 1802 1803 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1804 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1805 "Unknown struct or array constant!"); 1806 1807 SmallVector<EVT, 4> ValueVTs; 1808 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1809 unsigned NumElts = ValueVTs.size(); 1810 if (NumElts == 0) 1811 return SDValue(); // empty struct 1812 SmallVector<SDValue, 4> Constants(NumElts); 1813 for (unsigned i = 0; i != NumElts; ++i) { 1814 EVT EltVT = ValueVTs[i]; 1815 if (isa<UndefValue>(C)) 1816 Constants[i] = DAG.getUNDEF(EltVT); 1817 else if (EltVT.isFloatingPoint()) 1818 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1819 else 1820 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1821 } 1822 1823 return DAG.getMergeValues(Constants, getCurSDLoc()); 1824 } 1825 1826 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1827 return DAG.getBlockAddress(BA, VT); 1828 1829 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1830 return getValue(Equiv->getGlobalValue()); 1831 1832 if (const auto *NC = dyn_cast<NoCFIValue>(C)) 1833 return getValue(NC->getGlobalValue()); 1834 1835 if (VT == MVT::aarch64svcount) { 1836 assert(C->isNullValue() && "Can only zero this target type!"); 1837 return DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, 1838 DAG.getConstant(0, getCurSDLoc(), MVT::nxv16i1)); 1839 } 1840 1841 VectorType *VecTy = cast<VectorType>(V->getType()); 1842 1843 // Now that we know the number and type of the elements, get that number of 1844 // elements into the Ops array based on what kind of constant it is. 1845 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1846 SmallVector<SDValue, 16> Ops; 1847 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1848 for (unsigned i = 0; i != NumElements; ++i) 1849 Ops.push_back(getValue(CV->getOperand(i))); 1850 1851 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1852 } 1853 1854 if (isa<ConstantAggregateZero>(C)) { 1855 EVT EltVT = 1856 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1857 1858 SDValue Op; 1859 if (EltVT.isFloatingPoint()) 1860 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1861 else 1862 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1863 1864 return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op); 1865 } 1866 1867 llvm_unreachable("Unknown vector constant"); 1868 } 1869 1870 // If this is a static alloca, generate it as the frameindex instead of 1871 // computation. 1872 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1873 DenseMap<const AllocaInst*, int>::iterator SI = 1874 FuncInfo.StaticAllocaMap.find(AI); 1875 if (SI != FuncInfo.StaticAllocaMap.end()) 1876 return DAG.getFrameIndex( 1877 SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType())); 1878 } 1879 1880 // If this is an instruction which fast-isel has deferred, select it now. 1881 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1882 Register InReg = FuncInfo.InitializeRegForValue(Inst); 1883 1884 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1885 Inst->getType(), std::nullopt); 1886 SDValue Chain = DAG.getEntryNode(); 1887 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1888 } 1889 1890 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) 1891 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1892 1893 if (const auto *BB = dyn_cast<BasicBlock>(V)) 1894 return DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 1895 1896 llvm_unreachable("Can't get register for value!"); 1897 } 1898 1899 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1900 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1901 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1902 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1903 bool IsSEH = isAsynchronousEHPersonality(Pers); 1904 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1905 if (!IsSEH) 1906 CatchPadMBB->setIsEHScopeEntry(); 1907 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1908 if (IsMSVCCXX || IsCoreCLR) 1909 CatchPadMBB->setIsEHFuncletEntry(); 1910 } 1911 1912 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1913 // Update machine-CFG edge. 1914 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1915 FuncInfo.MBB->addSuccessor(TargetMBB); 1916 TargetMBB->setIsEHCatchretTarget(true); 1917 DAG.getMachineFunction().setHasEHCatchret(true); 1918 1919 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1920 bool IsSEH = isAsynchronousEHPersonality(Pers); 1921 if (IsSEH) { 1922 // If this is not a fall-through branch or optimizations are switched off, 1923 // emit the branch. 1924 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1925 TM.getOptLevel() == CodeGenOptLevel::None) 1926 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1927 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1928 return; 1929 } 1930 1931 // Figure out the funclet membership for the catchret's successor. 1932 // This will be used by the FuncletLayout pass to determine how to order the 1933 // BB's. 1934 // A 'catchret' returns to the outer scope's color. 1935 Value *ParentPad = I.getCatchSwitchParentPad(); 1936 const BasicBlock *SuccessorColor; 1937 if (isa<ConstantTokenNone>(ParentPad)) 1938 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1939 else 1940 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1941 assert(SuccessorColor && "No parent funclet for catchret!"); 1942 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1943 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1944 1945 // Create the terminator node. 1946 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1947 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1948 DAG.getBasicBlock(SuccessorColorMBB)); 1949 DAG.setRoot(Ret); 1950 } 1951 1952 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1953 // Don't emit any special code for the cleanuppad instruction. It just marks 1954 // the start of an EH scope/funclet. 1955 FuncInfo.MBB->setIsEHScopeEntry(); 1956 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1957 if (Pers != EHPersonality::Wasm_CXX) { 1958 FuncInfo.MBB->setIsEHFuncletEntry(); 1959 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1960 } 1961 } 1962 1963 // In wasm EH, even though a catchpad may not catch an exception if a tag does 1964 // not match, it is OK to add only the first unwind destination catchpad to the 1965 // successors, because there will be at least one invoke instruction within the 1966 // catch scope that points to the next unwind destination, if one exists, so 1967 // CFGSort cannot mess up with BB sorting order. 1968 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 1969 // call within them, and catchpads only consisting of 'catch (...)' have a 1970 // '__cxa_end_catch' call within them, both of which generate invokes in case 1971 // the next unwind destination exists, i.e., the next unwind destination is not 1972 // the caller.) 1973 // 1974 // Having at most one EH pad successor is also simpler and helps later 1975 // transformations. 1976 // 1977 // For example, 1978 // current: 1979 // invoke void @foo to ... unwind label %catch.dispatch 1980 // catch.dispatch: 1981 // %0 = catchswitch within ... [label %catch.start] unwind label %next 1982 // catch.start: 1983 // ... 1984 // ... in this BB or some other child BB dominated by this BB there will be an 1985 // invoke that points to 'next' BB as an unwind destination 1986 // 1987 // next: ; We don't need to add this to 'current' BB's successor 1988 // ... 1989 static void findWasmUnwindDestinations( 1990 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1991 BranchProbability Prob, 1992 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1993 &UnwindDests) { 1994 while (EHPadBB) { 1995 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1996 if (isa<CleanupPadInst>(Pad)) { 1997 // Stop on cleanup pads. 1998 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1999 UnwindDests.back().first->setIsEHScopeEntry(); 2000 break; 2001 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 2002 // Add the catchpad handlers to the possible destinations. We don't 2003 // continue to the unwind destination of the catchswitch for wasm. 2004 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 2005 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 2006 UnwindDests.back().first->setIsEHScopeEntry(); 2007 } 2008 break; 2009 } else { 2010 continue; 2011 } 2012 } 2013 } 2014 2015 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 2016 /// many places it could ultimately go. In the IR, we have a single unwind 2017 /// destination, but in the machine CFG, we enumerate all the possible blocks. 2018 /// This function skips over imaginary basic blocks that hold catchswitch 2019 /// instructions, and finds all the "real" machine 2020 /// basic block destinations. As those destinations may not be successors of 2021 /// EHPadBB, here we also calculate the edge probability to those destinations. 2022 /// The passed-in Prob is the edge probability to EHPadBB. 2023 static void findUnwindDestinations( 2024 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 2025 BranchProbability Prob, 2026 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 2027 &UnwindDests) { 2028 EHPersonality Personality = 2029 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 2030 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 2031 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 2032 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 2033 bool IsSEH = isAsynchronousEHPersonality(Personality); 2034 2035 if (IsWasmCXX) { 2036 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 2037 assert(UnwindDests.size() <= 1 && 2038 "There should be at most one unwind destination for wasm"); 2039 return; 2040 } 2041 2042 while (EHPadBB) { 2043 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 2044 BasicBlock *NewEHPadBB = nullptr; 2045 if (isa<LandingPadInst>(Pad)) { 2046 // Stop on landingpads. They are not funclets. 2047 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 2048 break; 2049 } else if (isa<CleanupPadInst>(Pad)) { 2050 // Stop on cleanup pads. Cleanups are always funclet entries for all known 2051 // personalities. 2052 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 2053 UnwindDests.back().first->setIsEHScopeEntry(); 2054 UnwindDests.back().first->setIsEHFuncletEntry(); 2055 break; 2056 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 2057 // Add the catchpad handlers to the possible destinations. 2058 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 2059 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 2060 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 2061 if (IsMSVCCXX || IsCoreCLR) 2062 UnwindDests.back().first->setIsEHFuncletEntry(); 2063 if (!IsSEH) 2064 UnwindDests.back().first->setIsEHScopeEntry(); 2065 } 2066 NewEHPadBB = CatchSwitch->getUnwindDest(); 2067 } else { 2068 continue; 2069 } 2070 2071 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2072 if (BPI && NewEHPadBB) 2073 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 2074 EHPadBB = NewEHPadBB; 2075 } 2076 } 2077 2078 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 2079 // Update successor info. 2080 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2081 auto UnwindDest = I.getUnwindDest(); 2082 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2083 BranchProbability UnwindDestProb = 2084 (BPI && UnwindDest) 2085 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 2086 : BranchProbability::getZero(); 2087 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 2088 for (auto &UnwindDest : UnwindDests) { 2089 UnwindDest.first->setIsEHPad(); 2090 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 2091 } 2092 FuncInfo.MBB->normalizeSuccProbs(); 2093 2094 // Create the terminator node. 2095 SDValue Ret = 2096 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 2097 DAG.setRoot(Ret); 2098 } 2099 2100 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 2101 report_fatal_error("visitCatchSwitch not yet implemented!"); 2102 } 2103 2104 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 2105 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2106 auto &DL = DAG.getDataLayout(); 2107 SDValue Chain = getControlRoot(); 2108 SmallVector<ISD::OutputArg, 8> Outs; 2109 SmallVector<SDValue, 8> OutVals; 2110 2111 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 2112 // lower 2113 // 2114 // %val = call <ty> @llvm.experimental.deoptimize() 2115 // ret <ty> %val 2116 // 2117 // differently. 2118 if (I.getParent()->getTerminatingDeoptimizeCall()) { 2119 LowerDeoptimizingReturn(); 2120 return; 2121 } 2122 2123 if (!FuncInfo.CanLowerReturn) { 2124 unsigned DemoteReg = FuncInfo.DemoteRegister; 2125 const Function *F = I.getParent()->getParent(); 2126 2127 // Emit a store of the return value through the virtual register. 2128 // Leave Outs empty so that LowerReturn won't try to load return 2129 // registers the usual way. 2130 SmallVector<EVT, 1> PtrValueVTs; 2131 ComputeValueVTs(TLI, DL, 2132 PointerType::get(F->getContext(), 2133 DAG.getDataLayout().getAllocaAddrSpace()), 2134 PtrValueVTs); 2135 2136 SDValue RetPtr = 2137 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]); 2138 SDValue RetOp = getValue(I.getOperand(0)); 2139 2140 SmallVector<EVT, 4> ValueVTs, MemVTs; 2141 SmallVector<uint64_t, 4> Offsets; 2142 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 2143 &Offsets, 0); 2144 unsigned NumValues = ValueVTs.size(); 2145 2146 SmallVector<SDValue, 4> Chains(NumValues); 2147 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 2148 for (unsigned i = 0; i != NumValues; ++i) { 2149 // An aggregate return value cannot wrap around the address space, so 2150 // offsets to its parts don't wrap either. 2151 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 2152 TypeSize::getFixed(Offsets[i])); 2153 2154 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 2155 if (MemVTs[i] != ValueVTs[i]) 2156 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 2157 Chains[i] = DAG.getStore( 2158 Chain, getCurSDLoc(), Val, 2159 // FIXME: better loc info would be nice. 2160 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 2161 commonAlignment(BaseAlign, Offsets[i])); 2162 } 2163 2164 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 2165 MVT::Other, Chains); 2166 } else if (I.getNumOperands() != 0) { 2167 SmallVector<EVT, 4> ValueVTs; 2168 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 2169 unsigned NumValues = ValueVTs.size(); 2170 if (NumValues) { 2171 SDValue RetOp = getValue(I.getOperand(0)); 2172 2173 const Function *F = I.getParent()->getParent(); 2174 2175 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 2176 I.getOperand(0)->getType(), F->getCallingConv(), 2177 /*IsVarArg*/ false, DL); 2178 2179 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 2180 if (F->getAttributes().hasRetAttr(Attribute::SExt)) 2181 ExtendKind = ISD::SIGN_EXTEND; 2182 else if (F->getAttributes().hasRetAttr(Attribute::ZExt)) 2183 ExtendKind = ISD::ZERO_EXTEND; 2184 2185 LLVMContext &Context = F->getContext(); 2186 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg); 2187 2188 for (unsigned j = 0; j != NumValues; ++j) { 2189 EVT VT = ValueVTs[j]; 2190 2191 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 2192 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 2193 2194 CallingConv::ID CC = F->getCallingConv(); 2195 2196 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 2197 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 2198 SmallVector<SDValue, 4> Parts(NumParts); 2199 getCopyToParts(DAG, getCurSDLoc(), 2200 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 2201 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 2202 2203 // 'inreg' on function refers to return value 2204 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2205 if (RetInReg) 2206 Flags.setInReg(); 2207 2208 if (I.getOperand(0)->getType()->isPointerTy()) { 2209 Flags.setPointer(); 2210 Flags.setPointerAddrSpace( 2211 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 2212 } 2213 2214 if (NeedsRegBlock) { 2215 Flags.setInConsecutiveRegs(); 2216 if (j == NumValues - 1) 2217 Flags.setInConsecutiveRegsLast(); 2218 } 2219 2220 // Propagate extension type if any 2221 if (ExtendKind == ISD::SIGN_EXTEND) 2222 Flags.setSExt(); 2223 else if (ExtendKind == ISD::ZERO_EXTEND) 2224 Flags.setZExt(); 2225 2226 for (unsigned i = 0; i < NumParts; ++i) { 2227 Outs.push_back(ISD::OutputArg(Flags, 2228 Parts[i].getValueType().getSimpleVT(), 2229 VT, /*isfixed=*/true, 0, 0)); 2230 OutVals.push_back(Parts[i]); 2231 } 2232 } 2233 } 2234 } 2235 2236 // Push in swifterror virtual register as the last element of Outs. This makes 2237 // sure swifterror virtual register will be returned in the swifterror 2238 // physical register. 2239 const Function *F = I.getParent()->getParent(); 2240 if (TLI.supportSwiftError() && 2241 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2242 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2243 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2244 Flags.setSwiftError(); 2245 Outs.push_back(ISD::OutputArg( 2246 Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)), 2247 /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0)); 2248 // Create SDNode for the swifterror virtual register. 2249 OutVals.push_back( 2250 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2251 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2252 EVT(TLI.getPointerTy(DL)))); 2253 } 2254 2255 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2256 CallingConv::ID CallConv = 2257 DAG.getMachineFunction().getFunction().getCallingConv(); 2258 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2259 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2260 2261 // Verify that the target's LowerReturn behaved as expected. 2262 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2263 "LowerReturn didn't return a valid chain!"); 2264 2265 // Update the DAG with the new chain value resulting from return lowering. 2266 DAG.setRoot(Chain); 2267 } 2268 2269 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2270 /// created for it, emit nodes to copy the value into the virtual 2271 /// registers. 2272 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2273 // Skip empty types 2274 if (V->getType()->isEmptyTy()) 2275 return; 2276 2277 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2278 if (VMI != FuncInfo.ValueMap.end()) { 2279 assert((!V->use_empty() || isa<CallBrInst>(V)) && 2280 "Unused value assigned virtual registers!"); 2281 CopyValueToVirtualRegister(V, VMI->second); 2282 } 2283 } 2284 2285 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2286 /// the current basic block, add it to ValueMap now so that we'll get a 2287 /// CopyTo/FromReg. 2288 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2289 // No need to export constants. 2290 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2291 2292 // Already exported? 2293 if (FuncInfo.isExportedInst(V)) return; 2294 2295 Register Reg = FuncInfo.InitializeRegForValue(V); 2296 CopyValueToVirtualRegister(V, Reg); 2297 } 2298 2299 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2300 const BasicBlock *FromBB) { 2301 // The operands of the setcc have to be in this block. We don't know 2302 // how to export them from some other block. 2303 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2304 // Can export from current BB. 2305 if (VI->getParent() == FromBB) 2306 return true; 2307 2308 // Is already exported, noop. 2309 return FuncInfo.isExportedInst(V); 2310 } 2311 2312 // If this is an argument, we can export it if the BB is the entry block or 2313 // if it is already exported. 2314 if (isa<Argument>(V)) { 2315 if (FromBB->isEntryBlock()) 2316 return true; 2317 2318 // Otherwise, can only export this if it is already exported. 2319 return FuncInfo.isExportedInst(V); 2320 } 2321 2322 // Otherwise, constants can always be exported. 2323 return true; 2324 } 2325 2326 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2327 BranchProbability 2328 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2329 const MachineBasicBlock *Dst) const { 2330 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2331 const BasicBlock *SrcBB = Src->getBasicBlock(); 2332 const BasicBlock *DstBB = Dst->getBasicBlock(); 2333 if (!BPI) { 2334 // If BPI is not available, set the default probability as 1 / N, where N is 2335 // the number of successors. 2336 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2337 return BranchProbability(1, SuccSize); 2338 } 2339 return BPI->getEdgeProbability(SrcBB, DstBB); 2340 } 2341 2342 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2343 MachineBasicBlock *Dst, 2344 BranchProbability Prob) { 2345 if (!FuncInfo.BPI) 2346 Src->addSuccessorWithoutProb(Dst); 2347 else { 2348 if (Prob.isUnknown()) 2349 Prob = getEdgeProbability(Src, Dst); 2350 Src->addSuccessor(Dst, Prob); 2351 } 2352 } 2353 2354 static bool InBlock(const Value *V, const BasicBlock *BB) { 2355 if (const Instruction *I = dyn_cast<Instruction>(V)) 2356 return I->getParent() == BB; 2357 return true; 2358 } 2359 2360 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2361 /// This function emits a branch and is used at the leaves of an OR or an 2362 /// AND operator tree. 2363 void 2364 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2365 MachineBasicBlock *TBB, 2366 MachineBasicBlock *FBB, 2367 MachineBasicBlock *CurBB, 2368 MachineBasicBlock *SwitchBB, 2369 BranchProbability TProb, 2370 BranchProbability FProb, 2371 bool InvertCond) { 2372 const BasicBlock *BB = CurBB->getBasicBlock(); 2373 2374 // If the leaf of the tree is a comparison, merge the condition into 2375 // the caseblock. 2376 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2377 // The operands of the cmp have to be in this block. We don't know 2378 // how to export them from some other block. If this is the first block 2379 // of the sequence, no exporting is needed. 2380 if (CurBB == SwitchBB || 2381 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2382 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2383 ISD::CondCode Condition; 2384 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2385 ICmpInst::Predicate Pred = 2386 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2387 Condition = getICmpCondCode(Pred); 2388 } else { 2389 const FCmpInst *FC = cast<FCmpInst>(Cond); 2390 FCmpInst::Predicate Pred = 2391 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2392 Condition = getFCmpCondCode(Pred); 2393 if (TM.Options.NoNaNsFPMath) 2394 Condition = getFCmpCodeWithoutNaN(Condition); 2395 } 2396 2397 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2398 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2399 SL->SwitchCases.push_back(CB); 2400 return; 2401 } 2402 } 2403 2404 // Create a CaseBlock record representing this branch. 2405 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2406 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2407 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2408 SL->SwitchCases.push_back(CB); 2409 } 2410 2411 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2412 MachineBasicBlock *TBB, 2413 MachineBasicBlock *FBB, 2414 MachineBasicBlock *CurBB, 2415 MachineBasicBlock *SwitchBB, 2416 Instruction::BinaryOps Opc, 2417 BranchProbability TProb, 2418 BranchProbability FProb, 2419 bool InvertCond) { 2420 // Skip over not part of the tree and remember to invert op and operands at 2421 // next level. 2422 Value *NotCond; 2423 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2424 InBlock(NotCond, CurBB->getBasicBlock())) { 2425 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2426 !InvertCond); 2427 return; 2428 } 2429 2430 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2431 const Value *BOpOp0, *BOpOp1; 2432 // Compute the effective opcode for Cond, taking into account whether it needs 2433 // to be inverted, e.g. 2434 // and (not (or A, B)), C 2435 // gets lowered as 2436 // and (and (not A, not B), C) 2437 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2438 if (BOp) { 2439 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2440 ? Instruction::And 2441 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2442 ? Instruction::Or 2443 : (Instruction::BinaryOps)0); 2444 if (InvertCond) { 2445 if (BOpc == Instruction::And) 2446 BOpc = Instruction::Or; 2447 else if (BOpc == Instruction::Or) 2448 BOpc = Instruction::And; 2449 } 2450 } 2451 2452 // If this node is not part of the or/and tree, emit it as a branch. 2453 // Note that all nodes in the tree should have same opcode. 2454 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2455 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2456 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2457 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2458 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2459 TProb, FProb, InvertCond); 2460 return; 2461 } 2462 2463 // Create TmpBB after CurBB. 2464 MachineFunction::iterator BBI(CurBB); 2465 MachineFunction &MF = DAG.getMachineFunction(); 2466 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2467 CurBB->getParent()->insert(++BBI, TmpBB); 2468 2469 if (Opc == Instruction::Or) { 2470 // Codegen X | Y as: 2471 // BB1: 2472 // jmp_if_X TBB 2473 // jmp TmpBB 2474 // TmpBB: 2475 // jmp_if_Y TBB 2476 // jmp FBB 2477 // 2478 2479 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2480 // The requirement is that 2481 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2482 // = TrueProb for original BB. 2483 // Assuming the original probabilities are A and B, one choice is to set 2484 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2485 // A/(1+B) and 2B/(1+B). This choice assumes that 2486 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2487 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2488 // TmpBB, but the math is more complicated. 2489 2490 auto NewTrueProb = TProb / 2; 2491 auto NewFalseProb = TProb / 2 + FProb; 2492 // Emit the LHS condition. 2493 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2494 NewFalseProb, InvertCond); 2495 2496 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2497 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2498 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2499 // Emit the RHS condition into TmpBB. 2500 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2501 Probs[1], InvertCond); 2502 } else { 2503 assert(Opc == Instruction::And && "Unknown merge op!"); 2504 // Codegen X & Y as: 2505 // BB1: 2506 // jmp_if_X TmpBB 2507 // jmp FBB 2508 // TmpBB: 2509 // jmp_if_Y TBB 2510 // jmp FBB 2511 // 2512 // This requires creation of TmpBB after CurBB. 2513 2514 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2515 // The requirement is that 2516 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2517 // = FalseProb for original BB. 2518 // Assuming the original probabilities are A and B, one choice is to set 2519 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2520 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2521 // TrueProb for BB1 * FalseProb for TmpBB. 2522 2523 auto NewTrueProb = TProb + FProb / 2; 2524 auto NewFalseProb = FProb / 2; 2525 // Emit the LHS condition. 2526 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2527 NewFalseProb, InvertCond); 2528 2529 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2530 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2531 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2532 // Emit the RHS condition into TmpBB. 2533 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2534 Probs[1], InvertCond); 2535 } 2536 } 2537 2538 /// If the set of cases should be emitted as a series of branches, return true. 2539 /// If we should emit this as a bunch of and/or'd together conditions, return 2540 /// false. 2541 bool 2542 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2543 if (Cases.size() != 2) return true; 2544 2545 // If this is two comparisons of the same values or'd or and'd together, they 2546 // will get folded into a single comparison, so don't emit two blocks. 2547 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2548 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2549 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2550 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2551 return false; 2552 } 2553 2554 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2555 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2556 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2557 Cases[0].CC == Cases[1].CC && 2558 isa<Constant>(Cases[0].CmpRHS) && 2559 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2560 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2561 return false; 2562 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2563 return false; 2564 } 2565 2566 return true; 2567 } 2568 2569 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2570 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2571 2572 // Update machine-CFG edges. 2573 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2574 2575 if (I.isUnconditional()) { 2576 // Update machine-CFG edges. 2577 BrMBB->addSuccessor(Succ0MBB); 2578 2579 // If this is not a fall-through branch or optimizations are switched off, 2580 // emit the branch. 2581 if (Succ0MBB != NextBlock(BrMBB) || 2582 TM.getOptLevel() == CodeGenOptLevel::None) { 2583 auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 2584 getControlRoot(), DAG.getBasicBlock(Succ0MBB)); 2585 setValue(&I, Br); 2586 DAG.setRoot(Br); 2587 } 2588 2589 return; 2590 } 2591 2592 // If this condition is one of the special cases we handle, do special stuff 2593 // now. 2594 const Value *CondVal = I.getCondition(); 2595 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2596 2597 // If this is a series of conditions that are or'd or and'd together, emit 2598 // this as a sequence of branches instead of setcc's with and/or operations. 2599 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2600 // unpredictable branches, and vector extracts because those jumps are likely 2601 // expensive for any target), this should improve performance. 2602 // For example, instead of something like: 2603 // cmp A, B 2604 // C = seteq 2605 // cmp D, E 2606 // F = setle 2607 // or C, F 2608 // jnz foo 2609 // Emit: 2610 // cmp A, B 2611 // je foo 2612 // cmp D, E 2613 // jle foo 2614 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2615 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2616 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2617 Value *Vec; 2618 const Value *BOp0, *BOp1; 2619 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2620 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2621 Opcode = Instruction::And; 2622 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2623 Opcode = Instruction::Or; 2624 2625 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2626 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2627 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2628 getEdgeProbability(BrMBB, Succ0MBB), 2629 getEdgeProbability(BrMBB, Succ1MBB), 2630 /*InvertCond=*/false); 2631 // If the compares in later blocks need to use values not currently 2632 // exported from this block, export them now. This block should always 2633 // be the first entry. 2634 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2635 2636 // Allow some cases to be rejected. 2637 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2638 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2639 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2640 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2641 } 2642 2643 // Emit the branch for this block. 2644 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2645 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2646 return; 2647 } 2648 2649 // Okay, we decided not to do this, remove any inserted MBB's and clear 2650 // SwitchCases. 2651 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2652 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2653 2654 SL->SwitchCases.clear(); 2655 } 2656 } 2657 2658 // Create a CaseBlock record representing this branch. 2659 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2660 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2661 2662 // Use visitSwitchCase to actually insert the fast branch sequence for this 2663 // cond branch. 2664 visitSwitchCase(CB, BrMBB); 2665 } 2666 2667 /// visitSwitchCase - Emits the necessary code to represent a single node in 2668 /// the binary search tree resulting from lowering a switch instruction. 2669 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2670 MachineBasicBlock *SwitchBB) { 2671 SDValue Cond; 2672 SDValue CondLHS = getValue(CB.CmpLHS); 2673 SDLoc dl = CB.DL; 2674 2675 if (CB.CC == ISD::SETTRUE) { 2676 // Branch or fall through to TrueBB. 2677 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2678 SwitchBB->normalizeSuccProbs(); 2679 if (CB.TrueBB != NextBlock(SwitchBB)) { 2680 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2681 DAG.getBasicBlock(CB.TrueBB))); 2682 } 2683 return; 2684 } 2685 2686 auto &TLI = DAG.getTargetLoweringInfo(); 2687 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2688 2689 // Build the setcc now. 2690 if (!CB.CmpMHS) { 2691 // Fold "(X == true)" to X and "(X == false)" to !X to 2692 // handle common cases produced by branch lowering. 2693 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2694 CB.CC == ISD::SETEQ) 2695 Cond = CondLHS; 2696 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2697 CB.CC == ISD::SETEQ) { 2698 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2699 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2700 } else { 2701 SDValue CondRHS = getValue(CB.CmpRHS); 2702 2703 // If a pointer's DAG type is larger than its memory type then the DAG 2704 // values are zero-extended. This breaks signed comparisons so truncate 2705 // back to the underlying type before doing the compare. 2706 if (CondLHS.getValueType() != MemVT) { 2707 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2708 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2709 } 2710 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2711 } 2712 } else { 2713 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2714 2715 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2716 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2717 2718 SDValue CmpOp = getValue(CB.CmpMHS); 2719 EVT VT = CmpOp.getValueType(); 2720 2721 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2722 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2723 ISD::SETLE); 2724 } else { 2725 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2726 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2727 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2728 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2729 } 2730 } 2731 2732 // Update successor info 2733 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2734 // TrueBB and FalseBB are always different unless the incoming IR is 2735 // degenerate. This only happens when running llc on weird IR. 2736 if (CB.TrueBB != CB.FalseBB) 2737 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2738 SwitchBB->normalizeSuccProbs(); 2739 2740 // If the lhs block is the next block, invert the condition so that we can 2741 // fall through to the lhs instead of the rhs block. 2742 if (CB.TrueBB == NextBlock(SwitchBB)) { 2743 std::swap(CB.TrueBB, CB.FalseBB); 2744 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2745 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2746 } 2747 2748 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2749 MVT::Other, getControlRoot(), Cond, 2750 DAG.getBasicBlock(CB.TrueBB)); 2751 2752 setValue(CurInst, BrCond); 2753 2754 // Insert the false branch. Do this even if it's a fall through branch, 2755 // this makes it easier to do DAG optimizations which require inverting 2756 // the branch condition. 2757 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2758 DAG.getBasicBlock(CB.FalseBB)); 2759 2760 DAG.setRoot(BrCond); 2761 } 2762 2763 /// visitJumpTable - Emit JumpTable node in the current MBB 2764 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2765 // Emit the code for the jump table 2766 assert(JT.SL && "Should set SDLoc for SelectionDAG!"); 2767 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2768 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2769 SDValue Index = DAG.getCopyFromReg(getControlRoot(), *JT.SL, JT.Reg, PTy); 2770 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2771 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, *JT.SL, MVT::Other, 2772 Index.getValue(1), Table, Index); 2773 DAG.setRoot(BrJumpTable); 2774 } 2775 2776 /// visitJumpTableHeader - This function emits necessary code to produce index 2777 /// in the JumpTable from switch case. 2778 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2779 JumpTableHeader &JTH, 2780 MachineBasicBlock *SwitchBB) { 2781 assert(JT.SL && "Should set SDLoc for SelectionDAG!"); 2782 const SDLoc &dl = *JT.SL; 2783 2784 // Subtract the lowest switch case value from the value being switched on. 2785 SDValue SwitchOp = getValue(JTH.SValue); 2786 EVT VT = SwitchOp.getValueType(); 2787 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2788 DAG.getConstant(JTH.First, dl, VT)); 2789 2790 // The SDNode we just created, which holds the value being switched on minus 2791 // the smallest case value, needs to be copied to a virtual register so it 2792 // can be used as an index into the jump table in a subsequent basic block. 2793 // This value may be smaller or larger than the target's pointer type, and 2794 // therefore require extension or truncating. 2795 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2796 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2797 2798 unsigned JumpTableReg = 2799 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2800 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2801 JumpTableReg, SwitchOp); 2802 JT.Reg = JumpTableReg; 2803 2804 if (!JTH.FallthroughUnreachable) { 2805 // Emit the range check for the jump table, and branch to the default block 2806 // for the switch statement if the value being switched on exceeds the 2807 // largest case in the switch. 2808 SDValue CMP = DAG.getSetCC( 2809 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2810 Sub.getValueType()), 2811 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2812 2813 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2814 MVT::Other, CopyTo, CMP, 2815 DAG.getBasicBlock(JT.Default)); 2816 2817 // Avoid emitting unnecessary branches to the next block. 2818 if (JT.MBB != NextBlock(SwitchBB)) 2819 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2820 DAG.getBasicBlock(JT.MBB)); 2821 2822 DAG.setRoot(BrCond); 2823 } else { 2824 // Avoid emitting unnecessary branches to the next block. 2825 if (JT.MBB != NextBlock(SwitchBB)) 2826 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2827 DAG.getBasicBlock(JT.MBB))); 2828 else 2829 DAG.setRoot(CopyTo); 2830 } 2831 } 2832 2833 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2834 /// variable if there exists one. 2835 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2836 SDValue &Chain) { 2837 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2838 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2839 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2840 MachineFunction &MF = DAG.getMachineFunction(); 2841 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2842 MachineSDNode *Node = 2843 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2844 if (Global) { 2845 MachinePointerInfo MPInfo(Global); 2846 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2847 MachineMemOperand::MODereferenceable; 2848 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2849 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2850 DAG.setNodeMemRefs(Node, {MemRef}); 2851 } 2852 if (PtrTy != PtrMemTy) 2853 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2854 return SDValue(Node, 0); 2855 } 2856 2857 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2858 /// tail spliced into a stack protector check success bb. 2859 /// 2860 /// For a high level explanation of how this fits into the stack protector 2861 /// generation see the comment on the declaration of class 2862 /// StackProtectorDescriptor. 2863 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2864 MachineBasicBlock *ParentBB) { 2865 2866 // First create the loads to the guard/stack slot for the comparison. 2867 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2868 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2869 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2870 2871 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2872 int FI = MFI.getStackProtectorIndex(); 2873 2874 SDValue Guard; 2875 SDLoc dl = getCurSDLoc(); 2876 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2877 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2878 Align Align = 2879 DAG.getDataLayout().getPrefTypeAlign(PointerType::get(M.getContext(), 0)); 2880 2881 // Generate code to load the content of the guard slot. 2882 SDValue GuardVal = DAG.getLoad( 2883 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2884 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2885 MachineMemOperand::MOVolatile); 2886 2887 if (TLI.useStackGuardXorFP()) 2888 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2889 2890 // Retrieve guard check function, nullptr if instrumentation is inlined. 2891 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2892 // The target provides a guard check function to validate the guard value. 2893 // Generate a call to that function with the content of the guard slot as 2894 // argument. 2895 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2896 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2897 2898 TargetLowering::ArgListTy Args; 2899 TargetLowering::ArgListEntry Entry; 2900 Entry.Node = GuardVal; 2901 Entry.Ty = FnTy->getParamType(0); 2902 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg)) 2903 Entry.IsInReg = true; 2904 Args.push_back(Entry); 2905 2906 TargetLowering::CallLoweringInfo CLI(DAG); 2907 CLI.setDebugLoc(getCurSDLoc()) 2908 .setChain(DAG.getEntryNode()) 2909 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2910 getValue(GuardCheckFn), std::move(Args)); 2911 2912 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2913 DAG.setRoot(Result.second); 2914 return; 2915 } 2916 2917 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2918 // Otherwise, emit a volatile load to retrieve the stack guard value. 2919 SDValue Chain = DAG.getEntryNode(); 2920 if (TLI.useLoadStackGuardNode()) { 2921 Guard = getLoadStackGuard(DAG, dl, Chain); 2922 } else { 2923 const Value *IRGuard = TLI.getSDagStackGuard(M); 2924 SDValue GuardPtr = getValue(IRGuard); 2925 2926 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2927 MachinePointerInfo(IRGuard, 0), Align, 2928 MachineMemOperand::MOVolatile); 2929 } 2930 2931 // Perform the comparison via a getsetcc. 2932 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2933 *DAG.getContext(), 2934 Guard.getValueType()), 2935 Guard, GuardVal, ISD::SETNE); 2936 2937 // If the guard/stackslot do not equal, branch to failure MBB. 2938 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2939 MVT::Other, GuardVal.getOperand(0), 2940 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2941 // Otherwise branch to success MBB. 2942 SDValue Br = DAG.getNode(ISD::BR, dl, 2943 MVT::Other, BrCond, 2944 DAG.getBasicBlock(SPD.getSuccessMBB())); 2945 2946 DAG.setRoot(Br); 2947 } 2948 2949 /// Codegen the failure basic block for a stack protector check. 2950 /// 2951 /// A failure stack protector machine basic block consists simply of a call to 2952 /// __stack_chk_fail(). 2953 /// 2954 /// For a high level explanation of how this fits into the stack protector 2955 /// generation see the comment on the declaration of class 2956 /// StackProtectorDescriptor. 2957 void 2958 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2959 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2960 TargetLowering::MakeLibCallOptions CallOptions; 2961 CallOptions.setDiscardResult(true); 2962 SDValue Chain = 2963 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2964 std::nullopt, CallOptions, getCurSDLoc()) 2965 .second; 2966 // On PS4/PS5, the "return address" must still be within the calling 2967 // function, even if it's at the very end, so emit an explicit TRAP here. 2968 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2969 if (TM.getTargetTriple().isPS()) 2970 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2971 // WebAssembly needs an unreachable instruction after a non-returning call, 2972 // because the function return type can be different from __stack_chk_fail's 2973 // return type (void). 2974 if (TM.getTargetTriple().isWasm()) 2975 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2976 2977 DAG.setRoot(Chain); 2978 } 2979 2980 /// visitBitTestHeader - This function emits necessary code to produce value 2981 /// suitable for "bit tests" 2982 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2983 MachineBasicBlock *SwitchBB) { 2984 SDLoc dl = getCurSDLoc(); 2985 2986 // Subtract the minimum value. 2987 SDValue SwitchOp = getValue(B.SValue); 2988 EVT VT = SwitchOp.getValueType(); 2989 SDValue RangeSub = 2990 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2991 2992 // Determine the type of the test operands. 2993 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2994 bool UsePtrType = false; 2995 if (!TLI.isTypeLegal(VT)) { 2996 UsePtrType = true; 2997 } else { 2998 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2999 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 3000 // Switch table case range are encoded into series of masks. 3001 // Just use pointer type, it's guaranteed to fit. 3002 UsePtrType = true; 3003 break; 3004 } 3005 } 3006 SDValue Sub = RangeSub; 3007 if (UsePtrType) { 3008 VT = TLI.getPointerTy(DAG.getDataLayout()); 3009 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 3010 } 3011 3012 B.RegVT = VT.getSimpleVT(); 3013 B.Reg = FuncInfo.CreateReg(B.RegVT); 3014 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 3015 3016 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 3017 3018 if (!B.FallthroughUnreachable) 3019 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 3020 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 3021 SwitchBB->normalizeSuccProbs(); 3022 3023 SDValue Root = CopyTo; 3024 if (!B.FallthroughUnreachable) { 3025 // Conditional branch to the default block. 3026 SDValue RangeCmp = DAG.getSetCC(dl, 3027 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 3028 RangeSub.getValueType()), 3029 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 3030 ISD::SETUGT); 3031 3032 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 3033 DAG.getBasicBlock(B.Default)); 3034 } 3035 3036 // Avoid emitting unnecessary branches to the next block. 3037 if (MBB != NextBlock(SwitchBB)) 3038 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 3039 3040 DAG.setRoot(Root); 3041 } 3042 3043 /// visitBitTestCase - this function produces one "bit test" 3044 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 3045 MachineBasicBlock* NextMBB, 3046 BranchProbability BranchProbToNext, 3047 unsigned Reg, 3048 BitTestCase &B, 3049 MachineBasicBlock *SwitchBB) { 3050 SDLoc dl = getCurSDLoc(); 3051 MVT VT = BB.RegVT; 3052 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 3053 SDValue Cmp; 3054 unsigned PopCount = llvm::popcount(B.Mask); 3055 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3056 if (PopCount == 1) { 3057 // Testing for a single bit; just compare the shift count with what it 3058 // would need to be to shift a 1 bit in that position. 3059 Cmp = DAG.getSetCC( 3060 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 3061 ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT), 3062 ISD::SETEQ); 3063 } else if (PopCount == BB.Range) { 3064 // There is only one zero bit in the range, test for it directly. 3065 Cmp = DAG.getSetCC( 3066 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 3067 ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE); 3068 } else { 3069 // Make desired shift 3070 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 3071 DAG.getConstant(1, dl, VT), ShiftOp); 3072 3073 // Emit bit tests and jumps 3074 SDValue AndOp = DAG.getNode(ISD::AND, dl, 3075 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 3076 Cmp = DAG.getSetCC( 3077 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 3078 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 3079 } 3080 3081 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 3082 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 3083 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 3084 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 3085 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 3086 // one as they are relative probabilities (and thus work more like weights), 3087 // and hence we need to normalize them to let the sum of them become one. 3088 SwitchBB->normalizeSuccProbs(); 3089 3090 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 3091 MVT::Other, getControlRoot(), 3092 Cmp, DAG.getBasicBlock(B.TargetBB)); 3093 3094 // Avoid emitting unnecessary branches to the next block. 3095 if (NextMBB != NextBlock(SwitchBB)) 3096 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 3097 DAG.getBasicBlock(NextMBB)); 3098 3099 DAG.setRoot(BrAnd); 3100 } 3101 3102 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 3103 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 3104 3105 // Retrieve successors. Look through artificial IR level blocks like 3106 // catchswitch for successors. 3107 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 3108 const BasicBlock *EHPadBB = I.getSuccessor(1); 3109 MachineBasicBlock *EHPadMBB = FuncInfo.MBBMap[EHPadBB]; 3110 3111 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3112 // have to do anything here to lower funclet bundles. 3113 assert(!I.hasOperandBundlesOtherThan( 3114 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 3115 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 3116 LLVMContext::OB_cfguardtarget, 3117 LLVMContext::OB_clang_arc_attachedcall}) && 3118 "Cannot lower invokes with arbitrary operand bundles yet!"); 3119 3120 const Value *Callee(I.getCalledOperand()); 3121 const Function *Fn = dyn_cast<Function>(Callee); 3122 if (isa<InlineAsm>(Callee)) 3123 visitInlineAsm(I, EHPadBB); 3124 else if (Fn && Fn->isIntrinsic()) { 3125 switch (Fn->getIntrinsicID()) { 3126 default: 3127 llvm_unreachable("Cannot invoke this intrinsic"); 3128 case Intrinsic::donothing: 3129 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 3130 case Intrinsic::seh_try_begin: 3131 case Intrinsic::seh_scope_begin: 3132 case Intrinsic::seh_try_end: 3133 case Intrinsic::seh_scope_end: 3134 if (EHPadMBB) 3135 // a block referenced by EH table 3136 // so dtor-funclet not removed by opts 3137 EHPadMBB->setMachineBlockAddressTaken(); 3138 break; 3139 case Intrinsic::experimental_patchpoint_void: 3140 case Intrinsic::experimental_patchpoint_i64: 3141 visitPatchpoint(I, EHPadBB); 3142 break; 3143 case Intrinsic::experimental_gc_statepoint: 3144 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 3145 break; 3146 case Intrinsic::wasm_rethrow: { 3147 // This is usually done in visitTargetIntrinsic, but this intrinsic is 3148 // special because it can be invoked, so we manually lower it to a DAG 3149 // node here. 3150 SmallVector<SDValue, 8> Ops; 3151 Ops.push_back(getRoot()); // inchain 3152 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3153 Ops.push_back( 3154 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 3155 TLI.getPointerTy(DAG.getDataLayout()))); 3156 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 3157 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 3158 break; 3159 } 3160 } 3161 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 3162 // Currently we do not lower any intrinsic calls with deopt operand bundles. 3163 // Eventually we will support lowering the @llvm.experimental.deoptimize 3164 // intrinsic, and right now there are no plans to support other intrinsics 3165 // with deopt state. 3166 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 3167 } else { 3168 LowerCallTo(I, getValue(Callee), false, false, EHPadBB); 3169 } 3170 3171 // If the value of the invoke is used outside of its defining block, make it 3172 // available as a virtual register. 3173 // We already took care of the exported value for the statepoint instruction 3174 // during call to the LowerStatepoint. 3175 if (!isa<GCStatepointInst>(I)) { 3176 CopyToExportRegsIfNeeded(&I); 3177 } 3178 3179 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 3180 BranchProbabilityInfo *BPI = FuncInfo.BPI; 3181 BranchProbability EHPadBBProb = 3182 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 3183 : BranchProbability::getZero(); 3184 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 3185 3186 // Update successor info. 3187 addSuccessorWithProb(InvokeMBB, Return); 3188 for (auto &UnwindDest : UnwindDests) { 3189 UnwindDest.first->setIsEHPad(); 3190 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 3191 } 3192 InvokeMBB->normalizeSuccProbs(); 3193 3194 // Drop into normal successor. 3195 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 3196 DAG.getBasicBlock(Return))); 3197 } 3198 3199 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 3200 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 3201 3202 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3203 // have to do anything here to lower funclet bundles. 3204 assert(!I.hasOperandBundlesOtherThan( 3205 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 3206 "Cannot lower callbrs with arbitrary operand bundles yet!"); 3207 3208 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 3209 visitInlineAsm(I); 3210 CopyToExportRegsIfNeeded(&I); 3211 3212 // Retrieve successors. 3213 SmallPtrSet<BasicBlock *, 8> Dests; 3214 Dests.insert(I.getDefaultDest()); 3215 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 3216 3217 // Update successor info. 3218 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 3219 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 3220 BasicBlock *Dest = I.getIndirectDest(i); 3221 MachineBasicBlock *Target = FuncInfo.MBBMap[Dest]; 3222 Target->setIsInlineAsmBrIndirectTarget(); 3223 Target->setMachineBlockAddressTaken(); 3224 Target->setLabelMustBeEmitted(); 3225 // Don't add duplicate machine successors. 3226 if (Dests.insert(Dest).second) 3227 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 3228 } 3229 CallBrMBB->normalizeSuccProbs(); 3230 3231 // Drop into default successor. 3232 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 3233 MVT::Other, getControlRoot(), 3234 DAG.getBasicBlock(Return))); 3235 } 3236 3237 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 3238 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 3239 } 3240 3241 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 3242 assert(FuncInfo.MBB->isEHPad() && 3243 "Call to landingpad not in landing pad!"); 3244 3245 // If there aren't registers to copy the values into (e.g., during SjLj 3246 // exceptions), then don't bother to create these DAG nodes. 3247 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3248 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 3249 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 3250 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 3251 return; 3252 3253 // If landingpad's return type is token type, we don't create DAG nodes 3254 // for its exception pointer and selector value. The extraction of exception 3255 // pointer or selector value from token type landingpads is not currently 3256 // supported. 3257 if (LP.getType()->isTokenTy()) 3258 return; 3259 3260 SmallVector<EVT, 2> ValueVTs; 3261 SDLoc dl = getCurSDLoc(); 3262 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3263 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3264 3265 // Get the two live-in registers as SDValues. The physregs have already been 3266 // copied into virtual registers. 3267 SDValue Ops[2]; 3268 if (FuncInfo.ExceptionPointerVirtReg) { 3269 Ops[0] = DAG.getZExtOrTrunc( 3270 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3271 FuncInfo.ExceptionPointerVirtReg, 3272 TLI.getPointerTy(DAG.getDataLayout())), 3273 dl, ValueVTs[0]); 3274 } else { 3275 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3276 } 3277 Ops[1] = DAG.getZExtOrTrunc( 3278 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3279 FuncInfo.ExceptionSelectorVirtReg, 3280 TLI.getPointerTy(DAG.getDataLayout())), 3281 dl, ValueVTs[1]); 3282 3283 // Merge into one. 3284 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3285 DAG.getVTList(ValueVTs), Ops); 3286 setValue(&LP, Res); 3287 } 3288 3289 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3290 MachineBasicBlock *Last) { 3291 // Update JTCases. 3292 for (JumpTableBlock &JTB : SL->JTCases) 3293 if (JTB.first.HeaderBB == First) 3294 JTB.first.HeaderBB = Last; 3295 3296 // Update BitTestCases. 3297 for (BitTestBlock &BTB : SL->BitTestCases) 3298 if (BTB.Parent == First) 3299 BTB.Parent = Last; 3300 } 3301 3302 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3303 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3304 3305 // Update machine-CFG edges with unique successors. 3306 SmallSet<BasicBlock*, 32> Done; 3307 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3308 BasicBlock *BB = I.getSuccessor(i); 3309 bool Inserted = Done.insert(BB).second; 3310 if (!Inserted) 3311 continue; 3312 3313 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3314 addSuccessorWithProb(IndirectBrMBB, Succ); 3315 } 3316 IndirectBrMBB->normalizeSuccProbs(); 3317 3318 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3319 MVT::Other, getControlRoot(), 3320 getValue(I.getAddress()))); 3321 } 3322 3323 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3324 if (!DAG.getTarget().Options.TrapUnreachable) 3325 return; 3326 3327 // We may be able to ignore unreachable behind a noreturn call. 3328 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3329 if (const CallInst *Call = dyn_cast_or_null<CallInst>(I.getPrevNode())) { 3330 if (Call->doesNotReturn()) 3331 return; 3332 } 3333 } 3334 3335 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3336 } 3337 3338 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3339 SDNodeFlags Flags; 3340 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3341 Flags.copyFMF(*FPOp); 3342 3343 SDValue Op = getValue(I.getOperand(0)); 3344 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3345 Op, Flags); 3346 setValue(&I, UnNodeValue); 3347 } 3348 3349 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3350 SDNodeFlags Flags; 3351 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3352 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3353 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3354 } 3355 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3356 Flags.setExact(ExactOp->isExact()); 3357 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3358 Flags.copyFMF(*FPOp); 3359 3360 SDValue Op1 = getValue(I.getOperand(0)); 3361 SDValue Op2 = getValue(I.getOperand(1)); 3362 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3363 Op1, Op2, Flags); 3364 setValue(&I, BinNodeValue); 3365 } 3366 3367 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3368 SDValue Op1 = getValue(I.getOperand(0)); 3369 SDValue Op2 = getValue(I.getOperand(1)); 3370 3371 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3372 Op1.getValueType(), DAG.getDataLayout()); 3373 3374 // Coerce the shift amount to the right type if we can. This exposes the 3375 // truncate or zext to optimization early. 3376 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3377 assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) && 3378 "Unexpected shift type"); 3379 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy); 3380 } 3381 3382 bool nuw = false; 3383 bool nsw = false; 3384 bool exact = false; 3385 3386 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3387 3388 if (const OverflowingBinaryOperator *OFBinOp = 3389 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3390 nuw = OFBinOp->hasNoUnsignedWrap(); 3391 nsw = OFBinOp->hasNoSignedWrap(); 3392 } 3393 if (const PossiblyExactOperator *ExactOp = 3394 dyn_cast<const PossiblyExactOperator>(&I)) 3395 exact = ExactOp->isExact(); 3396 } 3397 SDNodeFlags Flags; 3398 Flags.setExact(exact); 3399 Flags.setNoSignedWrap(nsw); 3400 Flags.setNoUnsignedWrap(nuw); 3401 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3402 Flags); 3403 setValue(&I, Res); 3404 } 3405 3406 void SelectionDAGBuilder::visitSDiv(const User &I) { 3407 SDValue Op1 = getValue(I.getOperand(0)); 3408 SDValue Op2 = getValue(I.getOperand(1)); 3409 3410 SDNodeFlags Flags; 3411 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3412 cast<PossiblyExactOperator>(&I)->isExact()); 3413 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3414 Op2, Flags)); 3415 } 3416 3417 void SelectionDAGBuilder::visitICmp(const User &I) { 3418 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3419 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3420 predicate = IC->getPredicate(); 3421 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3422 predicate = ICmpInst::Predicate(IC->getPredicate()); 3423 SDValue Op1 = getValue(I.getOperand(0)); 3424 SDValue Op2 = getValue(I.getOperand(1)); 3425 ISD::CondCode Opcode = getICmpCondCode(predicate); 3426 3427 auto &TLI = DAG.getTargetLoweringInfo(); 3428 EVT MemVT = 3429 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3430 3431 // If a pointer's DAG type is larger than its memory type then the DAG values 3432 // are zero-extended. This breaks signed comparisons so truncate back to the 3433 // underlying type before doing the compare. 3434 if (Op1.getValueType() != MemVT) { 3435 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3436 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3437 } 3438 3439 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3440 I.getType()); 3441 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3442 } 3443 3444 void SelectionDAGBuilder::visitFCmp(const User &I) { 3445 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3446 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3447 predicate = FC->getPredicate(); 3448 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3449 predicate = FCmpInst::Predicate(FC->getPredicate()); 3450 SDValue Op1 = getValue(I.getOperand(0)); 3451 SDValue Op2 = getValue(I.getOperand(1)); 3452 3453 ISD::CondCode Condition = getFCmpCondCode(predicate); 3454 auto *FPMO = cast<FPMathOperator>(&I); 3455 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3456 Condition = getFCmpCodeWithoutNaN(Condition); 3457 3458 SDNodeFlags Flags; 3459 Flags.copyFMF(*FPMO); 3460 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3461 3462 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3463 I.getType()); 3464 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3465 } 3466 3467 // Check if the condition of the select has one use or two users that are both 3468 // selects with the same condition. 3469 static bool hasOnlySelectUsers(const Value *Cond) { 3470 return llvm::all_of(Cond->users(), [](const Value *V) { 3471 return isa<SelectInst>(V); 3472 }); 3473 } 3474 3475 void SelectionDAGBuilder::visitSelect(const User &I) { 3476 SmallVector<EVT, 4> ValueVTs; 3477 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3478 ValueVTs); 3479 unsigned NumValues = ValueVTs.size(); 3480 if (NumValues == 0) return; 3481 3482 SmallVector<SDValue, 4> Values(NumValues); 3483 SDValue Cond = getValue(I.getOperand(0)); 3484 SDValue LHSVal = getValue(I.getOperand(1)); 3485 SDValue RHSVal = getValue(I.getOperand(2)); 3486 SmallVector<SDValue, 1> BaseOps(1, Cond); 3487 ISD::NodeType OpCode = 3488 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3489 3490 bool IsUnaryAbs = false; 3491 bool Negate = false; 3492 3493 SDNodeFlags Flags; 3494 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3495 Flags.copyFMF(*FPOp); 3496 3497 Flags.setUnpredictable( 3498 cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable)); 3499 3500 // Min/max matching is only viable if all output VTs are the same. 3501 if (all_equal(ValueVTs)) { 3502 EVT VT = ValueVTs[0]; 3503 LLVMContext &Ctx = *DAG.getContext(); 3504 auto &TLI = DAG.getTargetLoweringInfo(); 3505 3506 // We care about the legality of the operation after it has been type 3507 // legalized. 3508 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3509 VT = TLI.getTypeToTransformTo(Ctx, VT); 3510 3511 // If the vselect is legal, assume we want to leave this as a vector setcc + 3512 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3513 // min/max is legal on the scalar type. 3514 bool UseScalarMinMax = VT.isVector() && 3515 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3516 3517 // ValueTracking's select pattern matching does not account for -0.0, 3518 // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that 3519 // -0.0 is less than +0.0. 3520 Value *LHS, *RHS; 3521 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3522 ISD::NodeType Opc = ISD::DELETED_NODE; 3523 switch (SPR.Flavor) { 3524 case SPF_UMAX: Opc = ISD::UMAX; break; 3525 case SPF_UMIN: Opc = ISD::UMIN; break; 3526 case SPF_SMAX: Opc = ISD::SMAX; break; 3527 case SPF_SMIN: Opc = ISD::SMIN; break; 3528 case SPF_FMINNUM: 3529 switch (SPR.NaNBehavior) { 3530 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3531 case SPNB_RETURNS_NAN: break; 3532 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3533 case SPNB_RETURNS_ANY: 3534 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) || 3535 (UseScalarMinMax && 3536 TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()))) 3537 Opc = ISD::FMINNUM; 3538 break; 3539 } 3540 break; 3541 case SPF_FMAXNUM: 3542 switch (SPR.NaNBehavior) { 3543 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3544 case SPNB_RETURNS_NAN: break; 3545 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3546 case SPNB_RETURNS_ANY: 3547 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) || 3548 (UseScalarMinMax && 3549 TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()))) 3550 Opc = ISD::FMAXNUM; 3551 break; 3552 } 3553 break; 3554 case SPF_NABS: 3555 Negate = true; 3556 [[fallthrough]]; 3557 case SPF_ABS: 3558 IsUnaryAbs = true; 3559 Opc = ISD::ABS; 3560 break; 3561 default: break; 3562 } 3563 3564 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3565 (TLI.isOperationLegalOrCustomOrPromote(Opc, VT) || 3566 (UseScalarMinMax && 3567 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3568 // If the underlying comparison instruction is used by any other 3569 // instruction, the consumed instructions won't be destroyed, so it is 3570 // not profitable to convert to a min/max. 3571 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3572 OpCode = Opc; 3573 LHSVal = getValue(LHS); 3574 RHSVal = getValue(RHS); 3575 BaseOps.clear(); 3576 } 3577 3578 if (IsUnaryAbs) { 3579 OpCode = Opc; 3580 LHSVal = getValue(LHS); 3581 BaseOps.clear(); 3582 } 3583 } 3584 3585 if (IsUnaryAbs) { 3586 for (unsigned i = 0; i != NumValues; ++i) { 3587 SDLoc dl = getCurSDLoc(); 3588 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3589 Values[i] = 3590 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3591 if (Negate) 3592 Values[i] = DAG.getNegative(Values[i], dl, VT); 3593 } 3594 } else { 3595 for (unsigned i = 0; i != NumValues; ++i) { 3596 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3597 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3598 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3599 Values[i] = DAG.getNode( 3600 OpCode, getCurSDLoc(), 3601 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3602 } 3603 } 3604 3605 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3606 DAG.getVTList(ValueVTs), Values)); 3607 } 3608 3609 void SelectionDAGBuilder::visitTrunc(const User &I) { 3610 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3611 SDValue N = getValue(I.getOperand(0)); 3612 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3613 I.getType()); 3614 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3615 } 3616 3617 void SelectionDAGBuilder::visitZExt(const User &I) { 3618 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3619 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3620 SDValue N = getValue(I.getOperand(0)); 3621 auto &TLI = DAG.getTargetLoweringInfo(); 3622 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3623 3624 SDNodeFlags Flags; 3625 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I)) 3626 Flags.setNonNeg(PNI->hasNonNeg()); 3627 3628 // Eagerly use nonneg information to canonicalize towards sign_extend if 3629 // that is the target's preference. 3630 // TODO: Let the target do this later. 3631 if (Flags.hasNonNeg() && 3632 TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) { 3633 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3634 return; 3635 } 3636 3637 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags)); 3638 } 3639 3640 void SelectionDAGBuilder::visitSExt(const User &I) { 3641 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3642 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3643 SDValue N = getValue(I.getOperand(0)); 3644 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3645 I.getType()); 3646 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3647 } 3648 3649 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3650 // FPTrunc is never a no-op cast, no need to check 3651 SDValue N = getValue(I.getOperand(0)); 3652 SDLoc dl = getCurSDLoc(); 3653 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3654 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3655 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3656 DAG.getTargetConstant( 3657 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3658 } 3659 3660 void SelectionDAGBuilder::visitFPExt(const User &I) { 3661 // FPExt is never a no-op cast, no need to check 3662 SDValue N = getValue(I.getOperand(0)); 3663 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3664 I.getType()); 3665 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3666 } 3667 3668 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3669 // FPToUI is never a no-op cast, no need to check 3670 SDValue N = getValue(I.getOperand(0)); 3671 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3672 I.getType()); 3673 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3674 } 3675 3676 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3677 // FPToSI is never a no-op cast, no need to check 3678 SDValue N = getValue(I.getOperand(0)); 3679 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3680 I.getType()); 3681 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3682 } 3683 3684 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3685 // UIToFP is never a no-op cast, no need to check 3686 SDValue N = getValue(I.getOperand(0)); 3687 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3688 I.getType()); 3689 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3690 } 3691 3692 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3693 // SIToFP is never a no-op cast, no need to check 3694 SDValue N = getValue(I.getOperand(0)); 3695 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3696 I.getType()); 3697 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3698 } 3699 3700 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3701 // What to do depends on the size of the integer and the size of the pointer. 3702 // We can either truncate, zero extend, or no-op, accordingly. 3703 SDValue N = getValue(I.getOperand(0)); 3704 auto &TLI = DAG.getTargetLoweringInfo(); 3705 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3706 I.getType()); 3707 EVT PtrMemVT = 3708 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3709 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3710 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3711 setValue(&I, N); 3712 } 3713 3714 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3715 // What to do depends on the size of the integer and the size of the pointer. 3716 // We can either truncate, zero extend, or no-op, accordingly. 3717 SDValue N = getValue(I.getOperand(0)); 3718 auto &TLI = DAG.getTargetLoweringInfo(); 3719 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3720 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3721 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3722 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3723 setValue(&I, N); 3724 } 3725 3726 void SelectionDAGBuilder::visitBitCast(const User &I) { 3727 SDValue N = getValue(I.getOperand(0)); 3728 SDLoc dl = getCurSDLoc(); 3729 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3730 I.getType()); 3731 3732 // BitCast assures us that source and destination are the same size so this is 3733 // either a BITCAST or a no-op. 3734 if (DestVT != N.getValueType()) 3735 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3736 DestVT, N)); // convert types. 3737 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3738 // might fold any kind of constant expression to an integer constant and that 3739 // is not what we are looking for. Only recognize a bitcast of a genuine 3740 // constant integer as an opaque constant. 3741 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3742 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3743 /*isOpaque*/true)); 3744 else 3745 setValue(&I, N); // noop cast. 3746 } 3747 3748 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3749 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3750 const Value *SV = I.getOperand(0); 3751 SDValue N = getValue(SV); 3752 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3753 3754 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3755 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3756 3757 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3758 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3759 3760 setValue(&I, N); 3761 } 3762 3763 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3764 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3765 SDValue InVec = getValue(I.getOperand(0)); 3766 SDValue InVal = getValue(I.getOperand(1)); 3767 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3768 TLI.getVectorIdxTy(DAG.getDataLayout())); 3769 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3770 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3771 InVec, InVal, InIdx)); 3772 } 3773 3774 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3775 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3776 SDValue InVec = getValue(I.getOperand(0)); 3777 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3778 TLI.getVectorIdxTy(DAG.getDataLayout())); 3779 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3780 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3781 InVec, InIdx)); 3782 } 3783 3784 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3785 SDValue Src1 = getValue(I.getOperand(0)); 3786 SDValue Src2 = getValue(I.getOperand(1)); 3787 ArrayRef<int> Mask; 3788 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3789 Mask = SVI->getShuffleMask(); 3790 else 3791 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3792 SDLoc DL = getCurSDLoc(); 3793 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3794 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3795 EVT SrcVT = Src1.getValueType(); 3796 3797 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3798 VT.isScalableVector()) { 3799 // Canonical splat form of first element of first input vector. 3800 SDValue FirstElt = 3801 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3802 DAG.getVectorIdxConstant(0, DL)); 3803 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3804 return; 3805 } 3806 3807 // For now, we only handle splats for scalable vectors. 3808 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3809 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3810 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3811 3812 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3813 unsigned MaskNumElts = Mask.size(); 3814 3815 if (SrcNumElts == MaskNumElts) { 3816 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3817 return; 3818 } 3819 3820 // Normalize the shuffle vector since mask and vector length don't match. 3821 if (SrcNumElts < MaskNumElts) { 3822 // Mask is longer than the source vectors. We can use concatenate vector to 3823 // make the mask and vectors lengths match. 3824 3825 if (MaskNumElts % SrcNumElts == 0) { 3826 // Mask length is a multiple of the source vector length. 3827 // Check if the shuffle is some kind of concatenation of the input 3828 // vectors. 3829 unsigned NumConcat = MaskNumElts / SrcNumElts; 3830 bool IsConcat = true; 3831 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3832 for (unsigned i = 0; i != MaskNumElts; ++i) { 3833 int Idx = Mask[i]; 3834 if (Idx < 0) 3835 continue; 3836 // Ensure the indices in each SrcVT sized piece are sequential and that 3837 // the same source is used for the whole piece. 3838 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3839 (ConcatSrcs[i / SrcNumElts] >= 0 && 3840 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3841 IsConcat = false; 3842 break; 3843 } 3844 // Remember which source this index came from. 3845 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3846 } 3847 3848 // The shuffle is concatenating multiple vectors together. Just emit 3849 // a CONCAT_VECTORS operation. 3850 if (IsConcat) { 3851 SmallVector<SDValue, 8> ConcatOps; 3852 for (auto Src : ConcatSrcs) { 3853 if (Src < 0) 3854 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3855 else if (Src == 0) 3856 ConcatOps.push_back(Src1); 3857 else 3858 ConcatOps.push_back(Src2); 3859 } 3860 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3861 return; 3862 } 3863 } 3864 3865 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3866 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3867 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3868 PaddedMaskNumElts); 3869 3870 // Pad both vectors with undefs to make them the same length as the mask. 3871 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3872 3873 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3874 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3875 MOps1[0] = Src1; 3876 MOps2[0] = Src2; 3877 3878 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3879 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3880 3881 // Readjust mask for new input vector length. 3882 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3883 for (unsigned i = 0; i != MaskNumElts; ++i) { 3884 int Idx = Mask[i]; 3885 if (Idx >= (int)SrcNumElts) 3886 Idx -= SrcNumElts - PaddedMaskNumElts; 3887 MappedOps[i] = Idx; 3888 } 3889 3890 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3891 3892 // If the concatenated vector was padded, extract a subvector with the 3893 // correct number of elements. 3894 if (MaskNumElts != PaddedMaskNumElts) 3895 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3896 DAG.getVectorIdxConstant(0, DL)); 3897 3898 setValue(&I, Result); 3899 return; 3900 } 3901 3902 if (SrcNumElts > MaskNumElts) { 3903 // Analyze the access pattern of the vector to see if we can extract 3904 // two subvectors and do the shuffle. 3905 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3906 bool CanExtract = true; 3907 for (int Idx : Mask) { 3908 unsigned Input = 0; 3909 if (Idx < 0) 3910 continue; 3911 3912 if (Idx >= (int)SrcNumElts) { 3913 Input = 1; 3914 Idx -= SrcNumElts; 3915 } 3916 3917 // If all the indices come from the same MaskNumElts sized portion of 3918 // the sources we can use extract. Also make sure the extract wouldn't 3919 // extract past the end of the source. 3920 int NewStartIdx = alignDown(Idx, MaskNumElts); 3921 if (NewStartIdx + MaskNumElts > SrcNumElts || 3922 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3923 CanExtract = false; 3924 // Make sure we always update StartIdx as we use it to track if all 3925 // elements are undef. 3926 StartIdx[Input] = NewStartIdx; 3927 } 3928 3929 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3930 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3931 return; 3932 } 3933 if (CanExtract) { 3934 // Extract appropriate subvector and generate a vector shuffle 3935 for (unsigned Input = 0; Input < 2; ++Input) { 3936 SDValue &Src = Input == 0 ? Src1 : Src2; 3937 if (StartIdx[Input] < 0) 3938 Src = DAG.getUNDEF(VT); 3939 else { 3940 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3941 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3942 } 3943 } 3944 3945 // Calculate new mask. 3946 SmallVector<int, 8> MappedOps(Mask); 3947 for (int &Idx : MappedOps) { 3948 if (Idx >= (int)SrcNumElts) 3949 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3950 else if (Idx >= 0) 3951 Idx -= StartIdx[0]; 3952 } 3953 3954 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3955 return; 3956 } 3957 } 3958 3959 // We can't use either concat vectors or extract subvectors so fall back to 3960 // replacing the shuffle with extract and build vector. 3961 // to insert and build vector. 3962 EVT EltVT = VT.getVectorElementType(); 3963 SmallVector<SDValue,8> Ops; 3964 for (int Idx : Mask) { 3965 SDValue Res; 3966 3967 if (Idx < 0) { 3968 Res = DAG.getUNDEF(EltVT); 3969 } else { 3970 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3971 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3972 3973 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3974 DAG.getVectorIdxConstant(Idx, DL)); 3975 } 3976 3977 Ops.push_back(Res); 3978 } 3979 3980 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3981 } 3982 3983 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) { 3984 ArrayRef<unsigned> Indices = I.getIndices(); 3985 const Value *Op0 = I.getOperand(0); 3986 const Value *Op1 = I.getOperand(1); 3987 Type *AggTy = I.getType(); 3988 Type *ValTy = Op1->getType(); 3989 bool IntoUndef = isa<UndefValue>(Op0); 3990 bool FromUndef = isa<UndefValue>(Op1); 3991 3992 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3993 3994 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3995 SmallVector<EVT, 4> AggValueVTs; 3996 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3997 SmallVector<EVT, 4> ValValueVTs; 3998 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3999 4000 unsigned NumAggValues = AggValueVTs.size(); 4001 unsigned NumValValues = ValValueVTs.size(); 4002 SmallVector<SDValue, 4> Values(NumAggValues); 4003 4004 // Ignore an insertvalue that produces an empty object 4005 if (!NumAggValues) { 4006 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 4007 return; 4008 } 4009 4010 SDValue Agg = getValue(Op0); 4011 unsigned i = 0; 4012 // Copy the beginning value(s) from the original aggregate. 4013 for (; i != LinearIndex; ++i) 4014 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 4015 SDValue(Agg.getNode(), Agg.getResNo() + i); 4016 // Copy values from the inserted value(s). 4017 if (NumValValues) { 4018 SDValue Val = getValue(Op1); 4019 for (; i != LinearIndex + NumValValues; ++i) 4020 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 4021 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 4022 } 4023 // Copy remaining value(s) from the original aggregate. 4024 for (; i != NumAggValues; ++i) 4025 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 4026 SDValue(Agg.getNode(), Agg.getResNo() + i); 4027 4028 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 4029 DAG.getVTList(AggValueVTs), Values)); 4030 } 4031 4032 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) { 4033 ArrayRef<unsigned> Indices = I.getIndices(); 4034 const Value *Op0 = I.getOperand(0); 4035 Type *AggTy = Op0->getType(); 4036 Type *ValTy = I.getType(); 4037 bool OutOfUndef = isa<UndefValue>(Op0); 4038 4039 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 4040 4041 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4042 SmallVector<EVT, 4> ValValueVTs; 4043 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 4044 4045 unsigned NumValValues = ValValueVTs.size(); 4046 4047 // Ignore a extractvalue that produces an empty object 4048 if (!NumValValues) { 4049 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 4050 return; 4051 } 4052 4053 SmallVector<SDValue, 4> Values(NumValValues); 4054 4055 SDValue Agg = getValue(Op0); 4056 // Copy out the selected value(s). 4057 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 4058 Values[i - LinearIndex] = 4059 OutOfUndef ? 4060 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 4061 SDValue(Agg.getNode(), Agg.getResNo() + i); 4062 4063 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 4064 DAG.getVTList(ValValueVTs), Values)); 4065 } 4066 4067 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 4068 Value *Op0 = I.getOperand(0); 4069 // Note that the pointer operand may be a vector of pointers. Take the scalar 4070 // element which holds a pointer. 4071 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 4072 SDValue N = getValue(Op0); 4073 SDLoc dl = getCurSDLoc(); 4074 auto &TLI = DAG.getTargetLoweringInfo(); 4075 4076 // Normalize Vector GEP - all scalar operands should be converted to the 4077 // splat vector. 4078 bool IsVectorGEP = I.getType()->isVectorTy(); 4079 ElementCount VectorElementCount = 4080 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 4081 : ElementCount::getFixed(0); 4082 4083 if (IsVectorGEP && !N.getValueType().isVector()) { 4084 LLVMContext &Context = *DAG.getContext(); 4085 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 4086 N = DAG.getSplat(VT, dl, N); 4087 } 4088 4089 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 4090 GTI != E; ++GTI) { 4091 const Value *Idx = GTI.getOperand(); 4092 if (StructType *StTy = GTI.getStructTypeOrNull()) { 4093 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 4094 if (Field) { 4095 // N = N + Offset 4096 uint64_t Offset = 4097 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field); 4098 4099 // In an inbounds GEP with an offset that is nonnegative even when 4100 // interpreted as signed, assume there is no unsigned overflow. 4101 SDNodeFlags Flags; 4102 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 4103 Flags.setNoUnsignedWrap(true); 4104 4105 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 4106 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 4107 } 4108 } else { 4109 // IdxSize is the width of the arithmetic according to IR semantics. 4110 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 4111 // (and fix up the result later). 4112 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 4113 MVT IdxTy = MVT::getIntegerVT(IdxSize); 4114 TypeSize ElementSize = 4115 DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType()); 4116 // We intentionally mask away the high bits here; ElementSize may not 4117 // fit in IdxTy. 4118 APInt ElementMul(IdxSize, ElementSize.getKnownMinValue()); 4119 bool ElementScalable = ElementSize.isScalable(); 4120 4121 // If this is a scalar constant or a splat vector of constants, 4122 // handle it quickly. 4123 const auto *C = dyn_cast<Constant>(Idx); 4124 if (C && isa<VectorType>(C->getType())) 4125 C = C->getSplatValue(); 4126 4127 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 4128 if (CI && CI->isZero()) 4129 continue; 4130 if (CI && !ElementScalable) { 4131 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 4132 LLVMContext &Context = *DAG.getContext(); 4133 SDValue OffsVal; 4134 if (IsVectorGEP) 4135 OffsVal = DAG.getConstant( 4136 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 4137 else 4138 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 4139 4140 // In an inbounds GEP with an offset that is nonnegative even when 4141 // interpreted as signed, assume there is no unsigned overflow. 4142 SDNodeFlags Flags; 4143 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 4144 Flags.setNoUnsignedWrap(true); 4145 4146 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 4147 4148 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 4149 continue; 4150 } 4151 4152 // N = N + Idx * ElementMul; 4153 SDValue IdxN = getValue(Idx); 4154 4155 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 4156 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 4157 VectorElementCount); 4158 IdxN = DAG.getSplat(VT, dl, IdxN); 4159 } 4160 4161 // If the index is smaller or larger than intptr_t, truncate or extend 4162 // it. 4163 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 4164 4165 if (ElementScalable) { 4166 EVT VScaleTy = N.getValueType().getScalarType(); 4167 SDValue VScale = DAG.getNode( 4168 ISD::VSCALE, dl, VScaleTy, 4169 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 4170 if (IsVectorGEP) 4171 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 4172 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 4173 } else { 4174 // If this is a multiply by a power of two, turn it into a shl 4175 // immediately. This is a very common case. 4176 if (ElementMul != 1) { 4177 if (ElementMul.isPowerOf2()) { 4178 unsigned Amt = ElementMul.logBase2(); 4179 IdxN = DAG.getNode(ISD::SHL, dl, 4180 N.getValueType(), IdxN, 4181 DAG.getConstant(Amt, dl, IdxN.getValueType())); 4182 } else { 4183 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 4184 IdxN.getValueType()); 4185 IdxN = DAG.getNode(ISD::MUL, dl, 4186 N.getValueType(), IdxN, Scale); 4187 } 4188 } 4189 } 4190 4191 N = DAG.getNode(ISD::ADD, dl, 4192 N.getValueType(), N, IdxN); 4193 } 4194 } 4195 4196 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 4197 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 4198 if (IsVectorGEP) { 4199 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 4200 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 4201 } 4202 4203 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 4204 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 4205 4206 setValue(&I, N); 4207 } 4208 4209 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 4210 // If this is a fixed sized alloca in the entry block of the function, 4211 // allocate it statically on the stack. 4212 if (FuncInfo.StaticAllocaMap.count(&I)) 4213 return; // getValue will auto-populate this. 4214 4215 SDLoc dl = getCurSDLoc(); 4216 Type *Ty = I.getAllocatedType(); 4217 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4218 auto &DL = DAG.getDataLayout(); 4219 TypeSize TySize = DL.getTypeAllocSize(Ty); 4220 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 4221 4222 SDValue AllocSize = getValue(I.getArraySize()); 4223 4224 EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace()); 4225 if (AllocSize.getValueType() != IntPtr) 4226 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 4227 4228 if (TySize.isScalable()) 4229 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4230 DAG.getVScale(dl, IntPtr, 4231 APInt(IntPtr.getScalarSizeInBits(), 4232 TySize.getKnownMinValue()))); 4233 else { 4234 SDValue TySizeValue = 4235 DAG.getConstant(TySize.getFixedValue(), dl, MVT::getIntegerVT(64)); 4236 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4237 DAG.getZExtOrTrunc(TySizeValue, dl, IntPtr)); 4238 } 4239 4240 // Handle alignment. If the requested alignment is less than or equal to 4241 // the stack alignment, ignore it. If the size is greater than or equal to 4242 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4243 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 4244 if (*Alignment <= StackAlign) 4245 Alignment = std::nullopt; 4246 4247 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4248 // Round the size of the allocation up to the stack alignment size 4249 // by add SA-1 to the size. This doesn't overflow because we're computing 4250 // an address inside an alloca. 4251 SDNodeFlags Flags; 4252 Flags.setNoUnsignedWrap(true); 4253 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4254 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4255 4256 // Mask out the low bits for alignment purposes. 4257 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4258 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 4259 4260 SDValue Ops[] = { 4261 getRoot(), AllocSize, 4262 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4263 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4264 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4265 setValue(&I, DSA); 4266 DAG.setRoot(DSA.getValue(1)); 4267 4268 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4269 } 4270 4271 static const MDNode *getRangeMetadata(const Instruction &I) { 4272 // If !noundef is not present, then !range violation results in a poison 4273 // value rather than immediate undefined behavior. In theory, transferring 4274 // these annotations to SDAG is fine, but in practice there are key SDAG 4275 // transforms that are known not to be poison-safe, such as folding logical 4276 // and/or to bitwise and/or. For now, only transfer !range if !noundef is 4277 // also present. 4278 if (!I.hasMetadata(LLVMContext::MD_noundef)) 4279 return nullptr; 4280 return I.getMetadata(LLVMContext::MD_range); 4281 } 4282 4283 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4284 if (I.isAtomic()) 4285 return visitAtomicLoad(I); 4286 4287 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4288 const Value *SV = I.getOperand(0); 4289 if (TLI.supportSwiftError()) { 4290 // Swifterror values can come from either a function parameter with 4291 // swifterror attribute or an alloca with swifterror attribute. 4292 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4293 if (Arg->hasSwiftErrorAttr()) 4294 return visitLoadFromSwiftError(I); 4295 } 4296 4297 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4298 if (Alloca->isSwiftError()) 4299 return visitLoadFromSwiftError(I); 4300 } 4301 } 4302 4303 SDValue Ptr = getValue(SV); 4304 4305 Type *Ty = I.getType(); 4306 SmallVector<EVT, 4> ValueVTs, MemVTs; 4307 SmallVector<TypeSize, 4> Offsets; 4308 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets, 0); 4309 unsigned NumValues = ValueVTs.size(); 4310 if (NumValues == 0) 4311 return; 4312 4313 Align Alignment = I.getAlign(); 4314 AAMDNodes AAInfo = I.getAAMetadata(); 4315 const MDNode *Ranges = getRangeMetadata(I); 4316 bool isVolatile = I.isVolatile(); 4317 MachineMemOperand::Flags MMOFlags = 4318 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 4319 4320 SDValue Root; 4321 bool ConstantMemory = false; 4322 if (isVolatile) 4323 // Serialize volatile loads with other side effects. 4324 Root = getRoot(); 4325 else if (NumValues > MaxParallelChains) 4326 Root = getMemoryRoot(); 4327 else if (AA && 4328 AA->pointsToConstantMemory(MemoryLocation( 4329 SV, 4330 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4331 AAInfo))) { 4332 // Do not serialize (non-volatile) loads of constant memory with anything. 4333 Root = DAG.getEntryNode(); 4334 ConstantMemory = true; 4335 MMOFlags |= MachineMemOperand::MOInvariant; 4336 } else { 4337 // Do not serialize non-volatile loads against each other. 4338 Root = DAG.getRoot(); 4339 } 4340 4341 SDLoc dl = getCurSDLoc(); 4342 4343 if (isVolatile) 4344 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4345 4346 SmallVector<SDValue, 4> Values(NumValues); 4347 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4348 4349 unsigned ChainI = 0; 4350 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4351 // Serializing loads here may result in excessive register pressure, and 4352 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4353 // could recover a bit by hoisting nodes upward in the chain by recognizing 4354 // they are side-effect free or do not alias. The optimizer should really 4355 // avoid this case by converting large object/array copies to llvm.memcpy 4356 // (MaxParallelChains should always remain as failsafe). 4357 if (ChainI == MaxParallelChains) { 4358 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4359 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4360 ArrayRef(Chains.data(), ChainI)); 4361 Root = Chain; 4362 ChainI = 0; 4363 } 4364 4365 // TODO: MachinePointerInfo only supports a fixed length offset. 4366 MachinePointerInfo PtrInfo = 4367 !Offsets[i].isScalable() || Offsets[i].isZero() 4368 ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue()) 4369 : MachinePointerInfo(); 4370 4371 SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]); 4372 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment, 4373 MMOFlags, AAInfo, Ranges); 4374 Chains[ChainI] = L.getValue(1); 4375 4376 if (MemVTs[i] != ValueVTs[i]) 4377 L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]); 4378 4379 Values[i] = L; 4380 } 4381 4382 if (!ConstantMemory) { 4383 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4384 ArrayRef(Chains.data(), ChainI)); 4385 if (isVolatile) 4386 DAG.setRoot(Chain); 4387 else 4388 PendingLoads.push_back(Chain); 4389 } 4390 4391 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4392 DAG.getVTList(ValueVTs), Values)); 4393 } 4394 4395 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4396 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4397 "call visitStoreToSwiftError when backend supports swifterror"); 4398 4399 SmallVector<EVT, 4> ValueVTs; 4400 SmallVector<uint64_t, 4> Offsets; 4401 const Value *SrcV = I.getOperand(0); 4402 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4403 SrcV->getType(), ValueVTs, &Offsets, 0); 4404 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4405 "expect a single EVT for swifterror"); 4406 4407 SDValue Src = getValue(SrcV); 4408 // Create a virtual register, then update the virtual register. 4409 Register VReg = 4410 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4411 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4412 // Chain can be getRoot or getControlRoot. 4413 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4414 SDValue(Src.getNode(), Src.getResNo())); 4415 DAG.setRoot(CopyNode); 4416 } 4417 4418 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4419 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4420 "call visitLoadFromSwiftError when backend supports swifterror"); 4421 4422 assert(!I.isVolatile() && 4423 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4424 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4425 "Support volatile, non temporal, invariant for load_from_swift_error"); 4426 4427 const Value *SV = I.getOperand(0); 4428 Type *Ty = I.getType(); 4429 assert( 4430 (!AA || 4431 !AA->pointsToConstantMemory(MemoryLocation( 4432 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4433 I.getAAMetadata()))) && 4434 "load_from_swift_error should not be constant memory"); 4435 4436 SmallVector<EVT, 4> ValueVTs; 4437 SmallVector<uint64_t, 4> Offsets; 4438 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4439 ValueVTs, &Offsets, 0); 4440 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4441 "expect a single EVT for swifterror"); 4442 4443 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4444 SDValue L = DAG.getCopyFromReg( 4445 getRoot(), getCurSDLoc(), 4446 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4447 4448 setValue(&I, L); 4449 } 4450 4451 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4452 if (I.isAtomic()) 4453 return visitAtomicStore(I); 4454 4455 const Value *SrcV = I.getOperand(0); 4456 const Value *PtrV = I.getOperand(1); 4457 4458 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4459 if (TLI.supportSwiftError()) { 4460 // Swifterror values can come from either a function parameter with 4461 // swifterror attribute or an alloca with swifterror attribute. 4462 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4463 if (Arg->hasSwiftErrorAttr()) 4464 return visitStoreToSwiftError(I); 4465 } 4466 4467 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4468 if (Alloca->isSwiftError()) 4469 return visitStoreToSwiftError(I); 4470 } 4471 } 4472 4473 SmallVector<EVT, 4> ValueVTs, MemVTs; 4474 SmallVector<TypeSize, 4> Offsets; 4475 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4476 SrcV->getType(), ValueVTs, &MemVTs, &Offsets, 0); 4477 unsigned NumValues = ValueVTs.size(); 4478 if (NumValues == 0) 4479 return; 4480 4481 // Get the lowered operands. Note that we do this after 4482 // checking if NumResults is zero, because with zero results 4483 // the operands won't have values in the map. 4484 SDValue Src = getValue(SrcV); 4485 SDValue Ptr = getValue(PtrV); 4486 4487 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4488 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4489 SDLoc dl = getCurSDLoc(); 4490 Align Alignment = I.getAlign(); 4491 AAMDNodes AAInfo = I.getAAMetadata(); 4492 4493 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4494 4495 unsigned ChainI = 0; 4496 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4497 // See visitLoad comments. 4498 if (ChainI == MaxParallelChains) { 4499 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4500 ArrayRef(Chains.data(), ChainI)); 4501 Root = Chain; 4502 ChainI = 0; 4503 } 4504 4505 // TODO: MachinePointerInfo only supports a fixed length offset. 4506 MachinePointerInfo PtrInfo = 4507 !Offsets[i].isScalable() || Offsets[i].isZero() 4508 ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue()) 4509 : MachinePointerInfo(); 4510 4511 SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]); 4512 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4513 if (MemVTs[i] != ValueVTs[i]) 4514 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4515 SDValue St = 4516 DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags, AAInfo); 4517 Chains[ChainI] = St; 4518 } 4519 4520 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4521 ArrayRef(Chains.data(), ChainI)); 4522 setValue(&I, StoreNode); 4523 DAG.setRoot(StoreNode); 4524 } 4525 4526 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4527 bool IsCompressing) { 4528 SDLoc sdl = getCurSDLoc(); 4529 4530 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4531 MaybeAlign &Alignment) { 4532 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4533 Src0 = I.getArgOperand(0); 4534 Ptr = I.getArgOperand(1); 4535 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4536 Mask = I.getArgOperand(3); 4537 }; 4538 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4539 MaybeAlign &Alignment) { 4540 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4541 Src0 = I.getArgOperand(0); 4542 Ptr = I.getArgOperand(1); 4543 Mask = I.getArgOperand(2); 4544 Alignment = std::nullopt; 4545 }; 4546 4547 Value *PtrOperand, *MaskOperand, *Src0Operand; 4548 MaybeAlign Alignment; 4549 if (IsCompressing) 4550 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4551 else 4552 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4553 4554 SDValue Ptr = getValue(PtrOperand); 4555 SDValue Src0 = getValue(Src0Operand); 4556 SDValue Mask = getValue(MaskOperand); 4557 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4558 4559 EVT VT = Src0.getValueType(); 4560 if (!Alignment) 4561 Alignment = DAG.getEVTAlign(VT); 4562 4563 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4564 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4565 MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata()); 4566 SDValue StoreNode = 4567 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4568 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4569 DAG.setRoot(StoreNode); 4570 setValue(&I, StoreNode); 4571 } 4572 4573 // Get a uniform base for the Gather/Scatter intrinsic. 4574 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4575 // We try to represent it as a base pointer + vector of indices. 4576 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4577 // The first operand of the GEP may be a single pointer or a vector of pointers 4578 // Example: 4579 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4580 // or 4581 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4582 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4583 // 4584 // When the first GEP operand is a single pointer - it is the uniform base we 4585 // are looking for. If first operand of the GEP is a splat vector - we 4586 // extract the splat value and use it as a uniform base. 4587 // In all other cases the function returns 'false'. 4588 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4589 ISD::MemIndexType &IndexType, SDValue &Scale, 4590 SelectionDAGBuilder *SDB, const BasicBlock *CurBB, 4591 uint64_t ElemSize) { 4592 SelectionDAG& DAG = SDB->DAG; 4593 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4594 const DataLayout &DL = DAG.getDataLayout(); 4595 4596 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type"); 4597 4598 // Handle splat constant pointer. 4599 if (auto *C = dyn_cast<Constant>(Ptr)) { 4600 C = C->getSplatValue(); 4601 if (!C) 4602 return false; 4603 4604 Base = SDB->getValue(C); 4605 4606 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); 4607 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4608 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4609 IndexType = ISD::SIGNED_SCALED; 4610 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4611 return true; 4612 } 4613 4614 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4615 if (!GEP || GEP->getParent() != CurBB) 4616 return false; 4617 4618 if (GEP->getNumOperands() != 2) 4619 return false; 4620 4621 const Value *BasePtr = GEP->getPointerOperand(); 4622 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4623 4624 // Make sure the base is scalar and the index is a vector. 4625 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4626 return false; 4627 4628 TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType()); 4629 if (ScaleVal.isScalable()) 4630 return false; 4631 4632 // Target may not support the required addressing mode. 4633 if (ScaleVal != 1 && 4634 !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize)) 4635 return false; 4636 4637 Base = SDB->getValue(BasePtr); 4638 Index = SDB->getValue(IndexVal); 4639 IndexType = ISD::SIGNED_SCALED; 4640 4641 Scale = 4642 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4643 return true; 4644 } 4645 4646 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4647 SDLoc sdl = getCurSDLoc(); 4648 4649 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4650 const Value *Ptr = I.getArgOperand(1); 4651 SDValue Src0 = getValue(I.getArgOperand(0)); 4652 SDValue Mask = getValue(I.getArgOperand(3)); 4653 EVT VT = Src0.getValueType(); 4654 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4655 ->getMaybeAlignValue() 4656 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4657 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4658 4659 SDValue Base; 4660 SDValue Index; 4661 ISD::MemIndexType IndexType; 4662 SDValue Scale; 4663 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4664 I.getParent(), VT.getScalarStoreSize()); 4665 4666 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4667 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4668 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4669 // TODO: Make MachineMemOperands aware of scalable 4670 // vectors. 4671 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata()); 4672 if (!UniformBase) { 4673 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4674 Index = getValue(Ptr); 4675 IndexType = ISD::SIGNED_SCALED; 4676 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4677 } 4678 4679 EVT IdxVT = Index.getValueType(); 4680 EVT EltTy = IdxVT.getVectorElementType(); 4681 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4682 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4683 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4684 } 4685 4686 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4687 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4688 Ops, MMO, IndexType, false); 4689 DAG.setRoot(Scatter); 4690 setValue(&I, Scatter); 4691 } 4692 4693 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4694 SDLoc sdl = getCurSDLoc(); 4695 4696 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4697 MaybeAlign &Alignment) { 4698 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4699 Ptr = I.getArgOperand(0); 4700 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4701 Mask = I.getArgOperand(2); 4702 Src0 = I.getArgOperand(3); 4703 }; 4704 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4705 MaybeAlign &Alignment) { 4706 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4707 Ptr = I.getArgOperand(0); 4708 Alignment = std::nullopt; 4709 Mask = I.getArgOperand(1); 4710 Src0 = I.getArgOperand(2); 4711 }; 4712 4713 Value *PtrOperand, *MaskOperand, *Src0Operand; 4714 MaybeAlign Alignment; 4715 if (IsExpanding) 4716 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4717 else 4718 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4719 4720 SDValue Ptr = getValue(PtrOperand); 4721 SDValue Src0 = getValue(Src0Operand); 4722 SDValue Mask = getValue(MaskOperand); 4723 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4724 4725 EVT VT = Src0.getValueType(); 4726 if (!Alignment) 4727 Alignment = DAG.getEVTAlign(VT); 4728 4729 AAMDNodes AAInfo = I.getAAMetadata(); 4730 const MDNode *Ranges = getRangeMetadata(I); 4731 4732 // Do not serialize masked loads of constant memory with anything. 4733 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 4734 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4735 4736 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4737 4738 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4739 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4740 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 4741 4742 SDValue Load = 4743 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4744 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4745 if (AddToChain) 4746 PendingLoads.push_back(Load.getValue(1)); 4747 setValue(&I, Load); 4748 } 4749 4750 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4751 SDLoc sdl = getCurSDLoc(); 4752 4753 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4754 const Value *Ptr = I.getArgOperand(0); 4755 SDValue Src0 = getValue(I.getArgOperand(3)); 4756 SDValue Mask = getValue(I.getArgOperand(2)); 4757 4758 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4759 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4760 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4761 ->getMaybeAlignValue() 4762 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4763 4764 const MDNode *Ranges = getRangeMetadata(I); 4765 4766 SDValue Root = DAG.getRoot(); 4767 SDValue Base; 4768 SDValue Index; 4769 ISD::MemIndexType IndexType; 4770 SDValue Scale; 4771 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4772 I.getParent(), VT.getScalarStoreSize()); 4773 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4774 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4775 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4776 // TODO: Make MachineMemOperands aware of scalable 4777 // vectors. 4778 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges); 4779 4780 if (!UniformBase) { 4781 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4782 Index = getValue(Ptr); 4783 IndexType = ISD::SIGNED_SCALED; 4784 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4785 } 4786 4787 EVT IdxVT = Index.getValueType(); 4788 EVT EltTy = IdxVT.getVectorElementType(); 4789 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4790 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4791 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4792 } 4793 4794 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4795 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4796 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4797 4798 PendingLoads.push_back(Gather.getValue(1)); 4799 setValue(&I, Gather); 4800 } 4801 4802 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4803 SDLoc dl = getCurSDLoc(); 4804 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4805 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4806 SyncScope::ID SSID = I.getSyncScopeID(); 4807 4808 SDValue InChain = getRoot(); 4809 4810 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4811 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4812 4813 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4814 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4815 4816 MachineFunction &MF = DAG.getMachineFunction(); 4817 MachineMemOperand *MMO = MF.getMachineMemOperand( 4818 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4819 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4820 FailureOrdering); 4821 4822 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4823 dl, MemVT, VTs, InChain, 4824 getValue(I.getPointerOperand()), 4825 getValue(I.getCompareOperand()), 4826 getValue(I.getNewValOperand()), MMO); 4827 4828 SDValue OutChain = L.getValue(2); 4829 4830 setValue(&I, L); 4831 DAG.setRoot(OutChain); 4832 } 4833 4834 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4835 SDLoc dl = getCurSDLoc(); 4836 ISD::NodeType NT; 4837 switch (I.getOperation()) { 4838 default: llvm_unreachable("Unknown atomicrmw operation"); 4839 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4840 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4841 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4842 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4843 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4844 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4845 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4846 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4847 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4848 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4849 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4850 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4851 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4852 case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break; 4853 case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break; 4854 case AtomicRMWInst::UIncWrap: 4855 NT = ISD::ATOMIC_LOAD_UINC_WRAP; 4856 break; 4857 case AtomicRMWInst::UDecWrap: 4858 NT = ISD::ATOMIC_LOAD_UDEC_WRAP; 4859 break; 4860 } 4861 AtomicOrdering Ordering = I.getOrdering(); 4862 SyncScope::ID SSID = I.getSyncScopeID(); 4863 4864 SDValue InChain = getRoot(); 4865 4866 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4867 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4868 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4869 4870 MachineFunction &MF = DAG.getMachineFunction(); 4871 MachineMemOperand *MMO = MF.getMachineMemOperand( 4872 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4873 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4874 4875 SDValue L = 4876 DAG.getAtomic(NT, dl, MemVT, InChain, 4877 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4878 MMO); 4879 4880 SDValue OutChain = L.getValue(1); 4881 4882 setValue(&I, L); 4883 DAG.setRoot(OutChain); 4884 } 4885 4886 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4887 SDLoc dl = getCurSDLoc(); 4888 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4889 SDValue Ops[3]; 4890 Ops[0] = getRoot(); 4891 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4892 TLI.getFenceOperandTy(DAG.getDataLayout())); 4893 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4894 TLI.getFenceOperandTy(DAG.getDataLayout())); 4895 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops); 4896 setValue(&I, N); 4897 DAG.setRoot(N); 4898 } 4899 4900 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4901 SDLoc dl = getCurSDLoc(); 4902 AtomicOrdering Order = I.getOrdering(); 4903 SyncScope::ID SSID = I.getSyncScopeID(); 4904 4905 SDValue InChain = getRoot(); 4906 4907 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4908 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4909 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4910 4911 if (!TLI.supportsUnalignedAtomics() && 4912 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4913 report_fatal_error("Cannot generate unaligned atomic load"); 4914 4915 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 4916 4917 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4918 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4919 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4920 4921 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4922 4923 SDValue Ptr = getValue(I.getPointerOperand()); 4924 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4925 Ptr, MMO); 4926 4927 SDValue OutChain = L.getValue(1); 4928 if (MemVT != VT) 4929 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4930 4931 setValue(&I, L); 4932 DAG.setRoot(OutChain); 4933 } 4934 4935 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4936 SDLoc dl = getCurSDLoc(); 4937 4938 AtomicOrdering Ordering = I.getOrdering(); 4939 SyncScope::ID SSID = I.getSyncScopeID(); 4940 4941 SDValue InChain = getRoot(); 4942 4943 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4944 EVT MemVT = 4945 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4946 4947 if (!TLI.supportsUnalignedAtomics() && 4948 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4949 report_fatal_error("Cannot generate unaligned atomic store"); 4950 4951 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4952 4953 MachineFunction &MF = DAG.getMachineFunction(); 4954 MachineMemOperand *MMO = MF.getMachineMemOperand( 4955 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4956 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4957 4958 SDValue Val = getValue(I.getValueOperand()); 4959 if (Val.getValueType() != MemVT) 4960 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4961 SDValue Ptr = getValue(I.getPointerOperand()); 4962 4963 SDValue OutChain = 4964 DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO); 4965 4966 setValue(&I, OutChain); 4967 DAG.setRoot(OutChain); 4968 } 4969 4970 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4971 /// node. 4972 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4973 unsigned Intrinsic) { 4974 // Ignore the callsite's attributes. A specific call site may be marked with 4975 // readnone, but the lowering code will expect the chain based on the 4976 // definition. 4977 const Function *F = I.getCalledFunction(); 4978 bool HasChain = !F->doesNotAccessMemory(); 4979 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4980 4981 // Build the operand list. 4982 SmallVector<SDValue, 8> Ops; 4983 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4984 if (OnlyLoad) { 4985 // We don't need to serialize loads against other loads. 4986 Ops.push_back(DAG.getRoot()); 4987 } else { 4988 Ops.push_back(getRoot()); 4989 } 4990 } 4991 4992 // Info is set by getTgtMemIntrinsic 4993 TargetLowering::IntrinsicInfo Info; 4994 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4995 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4996 DAG.getMachineFunction(), 4997 Intrinsic); 4998 4999 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 5000 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 5001 Info.opc == ISD::INTRINSIC_W_CHAIN) 5002 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 5003 TLI.getPointerTy(DAG.getDataLayout()))); 5004 5005 // Add all operands of the call to the operand list. 5006 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) { 5007 const Value *Arg = I.getArgOperand(i); 5008 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 5009 Ops.push_back(getValue(Arg)); 5010 continue; 5011 } 5012 5013 // Use TargetConstant instead of a regular constant for immarg. 5014 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true); 5015 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 5016 assert(CI->getBitWidth() <= 64 && 5017 "large intrinsic immediates not handled"); 5018 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 5019 } else { 5020 Ops.push_back( 5021 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 5022 } 5023 } 5024 5025 SmallVector<EVT, 4> ValueVTs; 5026 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 5027 5028 if (HasChain) 5029 ValueVTs.push_back(MVT::Other); 5030 5031 SDVTList VTs = DAG.getVTList(ValueVTs); 5032 5033 // Propagate fast-math-flags from IR to node(s). 5034 SDNodeFlags Flags; 5035 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 5036 Flags.copyFMF(*FPMO); 5037 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 5038 5039 // Create the node. 5040 SDValue Result; 5041 // In some cases, custom collection of operands from CallInst I may be needed. 5042 TLI.CollectTargetIntrinsicOperands(I, Ops, DAG); 5043 if (IsTgtIntrinsic) { 5044 // This is target intrinsic that touches memory 5045 // 5046 // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic 5047 // didn't yield anything useful. 5048 MachinePointerInfo MPI; 5049 if (Info.ptrVal) 5050 MPI = MachinePointerInfo(Info.ptrVal, Info.offset); 5051 else if (Info.fallbackAddressSpace) 5052 MPI = MachinePointerInfo(*Info.fallbackAddressSpace); 5053 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, 5054 Info.memVT, MPI, Info.align, Info.flags, 5055 Info.size, I.getAAMetadata()); 5056 } else if (!HasChain) { 5057 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 5058 } else if (!I.getType()->isVoidTy()) { 5059 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 5060 } else { 5061 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 5062 } 5063 5064 if (HasChain) { 5065 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 5066 if (OnlyLoad) 5067 PendingLoads.push_back(Chain); 5068 else 5069 DAG.setRoot(Chain); 5070 } 5071 5072 if (!I.getType()->isVoidTy()) { 5073 if (!isa<VectorType>(I.getType())) 5074 Result = lowerRangeToAssertZExt(DAG, I, Result); 5075 5076 MaybeAlign Alignment = I.getRetAlign(); 5077 5078 // Insert `assertalign` node if there's an alignment. 5079 if (InsertAssertAlign && Alignment) { 5080 Result = 5081 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 5082 } 5083 5084 setValue(&I, Result); 5085 } 5086 } 5087 5088 /// GetSignificand - Get the significand and build it into a floating-point 5089 /// number with exponent of 1: 5090 /// 5091 /// Op = (Op & 0x007fffff) | 0x3f800000; 5092 /// 5093 /// where Op is the hexadecimal representation of floating point value. 5094 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 5095 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 5096 DAG.getConstant(0x007fffff, dl, MVT::i32)); 5097 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 5098 DAG.getConstant(0x3f800000, dl, MVT::i32)); 5099 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 5100 } 5101 5102 /// GetExponent - Get the exponent: 5103 /// 5104 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 5105 /// 5106 /// where Op is the hexadecimal representation of floating point value. 5107 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 5108 const TargetLowering &TLI, const SDLoc &dl) { 5109 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 5110 DAG.getConstant(0x7f800000, dl, MVT::i32)); 5111 SDValue t1 = DAG.getNode( 5112 ISD::SRL, dl, MVT::i32, t0, 5113 DAG.getConstant(23, dl, 5114 TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout()))); 5115 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 5116 DAG.getConstant(127, dl, MVT::i32)); 5117 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 5118 } 5119 5120 /// getF32Constant - Get 32-bit floating point constant. 5121 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 5122 const SDLoc &dl) { 5123 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 5124 MVT::f32); 5125 } 5126 5127 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 5128 SelectionDAG &DAG) { 5129 // TODO: What fast-math-flags should be set on the floating-point nodes? 5130 5131 // IntegerPartOfX = ((int32_t)(t0); 5132 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 5133 5134 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 5135 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 5136 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 5137 5138 // IntegerPartOfX <<= 23; 5139 IntegerPartOfX = 5140 DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 5141 DAG.getConstant(23, dl, 5142 DAG.getTargetLoweringInfo().getShiftAmountTy( 5143 MVT::i32, DAG.getDataLayout()))); 5144 5145 SDValue TwoToFractionalPartOfX; 5146 if (LimitFloatPrecision <= 6) { 5147 // For floating-point precision of 6: 5148 // 5149 // TwoToFractionalPartOfX = 5150 // 0.997535578f + 5151 // (0.735607626f + 0.252464424f * x) * x; 5152 // 5153 // error 0.0144103317, which is 6 bits 5154 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5155 getF32Constant(DAG, 0x3e814304, dl)); 5156 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5157 getF32Constant(DAG, 0x3f3c50c8, dl)); 5158 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5159 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5160 getF32Constant(DAG, 0x3f7f5e7e, dl)); 5161 } else if (LimitFloatPrecision <= 12) { 5162 // For floating-point precision of 12: 5163 // 5164 // TwoToFractionalPartOfX = 5165 // 0.999892986f + 5166 // (0.696457318f + 5167 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 5168 // 5169 // error 0.000107046256, which is 13 to 14 bits 5170 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5171 getF32Constant(DAG, 0x3da235e3, dl)); 5172 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5173 getF32Constant(DAG, 0x3e65b8f3, dl)); 5174 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5175 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5176 getF32Constant(DAG, 0x3f324b07, dl)); 5177 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5178 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5179 getF32Constant(DAG, 0x3f7ff8fd, dl)); 5180 } else { // LimitFloatPrecision <= 18 5181 // For floating-point precision of 18: 5182 // 5183 // TwoToFractionalPartOfX = 5184 // 0.999999982f + 5185 // (0.693148872f + 5186 // (0.240227044f + 5187 // (0.554906021e-1f + 5188 // (0.961591928e-2f + 5189 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 5190 // error 2.47208000*10^(-7), which is better than 18 bits 5191 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5192 getF32Constant(DAG, 0x3924b03e, dl)); 5193 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5194 getF32Constant(DAG, 0x3ab24b87, dl)); 5195 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5196 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5197 getF32Constant(DAG, 0x3c1d8c17, dl)); 5198 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5199 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5200 getF32Constant(DAG, 0x3d634a1d, dl)); 5201 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5202 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5203 getF32Constant(DAG, 0x3e75fe14, dl)); 5204 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5205 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 5206 getF32Constant(DAG, 0x3f317234, dl)); 5207 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 5208 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 5209 getF32Constant(DAG, 0x3f800000, dl)); 5210 } 5211 5212 // Add the exponent into the result in integer domain. 5213 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 5214 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5215 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 5216 } 5217 5218 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5219 /// limited-precision mode. 5220 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5221 const TargetLowering &TLI, SDNodeFlags Flags) { 5222 if (Op.getValueType() == MVT::f32 && 5223 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5224 5225 // Put the exponent in the right bit position for later addition to the 5226 // final result: 5227 // 5228 // t0 = Op * log2(e) 5229 5230 // TODO: What fast-math-flags should be set here? 5231 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5232 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5233 return getLimitedPrecisionExp2(t0, dl, DAG); 5234 } 5235 5236 // No special expansion. 5237 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5238 } 5239 5240 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5241 /// limited-precision mode. 5242 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5243 const TargetLowering &TLI, SDNodeFlags Flags) { 5244 // TODO: What fast-math-flags should be set on the floating-point nodes? 5245 5246 if (Op.getValueType() == MVT::f32 && 5247 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5248 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5249 5250 // Scale the exponent by log(2). 5251 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5252 SDValue LogOfExponent = 5253 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5254 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5255 5256 // Get the significand and build it into a floating-point number with 5257 // exponent of 1. 5258 SDValue X = GetSignificand(DAG, Op1, dl); 5259 5260 SDValue LogOfMantissa; 5261 if (LimitFloatPrecision <= 6) { 5262 // For floating-point precision of 6: 5263 // 5264 // LogofMantissa = 5265 // -1.1609546f + 5266 // (1.4034025f - 0.23903021f * x) * x; 5267 // 5268 // error 0.0034276066, which is better than 8 bits 5269 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5270 getF32Constant(DAG, 0xbe74c456, dl)); 5271 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5272 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5273 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5274 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5275 getF32Constant(DAG, 0x3f949a29, dl)); 5276 } else if (LimitFloatPrecision <= 12) { 5277 // For floating-point precision of 12: 5278 // 5279 // LogOfMantissa = 5280 // -1.7417939f + 5281 // (2.8212026f + 5282 // (-1.4699568f + 5283 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5284 // 5285 // error 0.000061011436, which is 14 bits 5286 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5287 getF32Constant(DAG, 0xbd67b6d6, dl)); 5288 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5289 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5290 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5291 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5292 getF32Constant(DAG, 0x3fbc278b, dl)); 5293 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5294 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5295 getF32Constant(DAG, 0x40348e95, dl)); 5296 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5297 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5298 getF32Constant(DAG, 0x3fdef31a, dl)); 5299 } else { // LimitFloatPrecision <= 18 5300 // For floating-point precision of 18: 5301 // 5302 // LogOfMantissa = 5303 // -2.1072184f + 5304 // (4.2372794f + 5305 // (-3.7029485f + 5306 // (2.2781945f + 5307 // (-0.87823314f + 5308 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5309 // 5310 // error 0.0000023660568, which is better than 18 bits 5311 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5312 getF32Constant(DAG, 0xbc91e5ac, dl)); 5313 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5314 getF32Constant(DAG, 0x3e4350aa, dl)); 5315 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5316 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5317 getF32Constant(DAG, 0x3f60d3e3, dl)); 5318 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5319 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5320 getF32Constant(DAG, 0x4011cdf0, dl)); 5321 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5322 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5323 getF32Constant(DAG, 0x406cfd1c, dl)); 5324 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5325 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5326 getF32Constant(DAG, 0x408797cb, dl)); 5327 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5328 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5329 getF32Constant(DAG, 0x4006dcab, dl)); 5330 } 5331 5332 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5333 } 5334 5335 // No special expansion. 5336 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5337 } 5338 5339 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5340 /// limited-precision mode. 5341 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5342 const TargetLowering &TLI, SDNodeFlags Flags) { 5343 // TODO: What fast-math-flags should be set on the floating-point nodes? 5344 5345 if (Op.getValueType() == MVT::f32 && 5346 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5347 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5348 5349 // Get the exponent. 5350 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5351 5352 // Get the significand and build it into a floating-point number with 5353 // exponent of 1. 5354 SDValue X = GetSignificand(DAG, Op1, dl); 5355 5356 // Different possible minimax approximations of significand in 5357 // floating-point for various degrees of accuracy over [1,2]. 5358 SDValue Log2ofMantissa; 5359 if (LimitFloatPrecision <= 6) { 5360 // For floating-point precision of 6: 5361 // 5362 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5363 // 5364 // error 0.0049451742, which is more than 7 bits 5365 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5366 getF32Constant(DAG, 0xbeb08fe0, dl)); 5367 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5368 getF32Constant(DAG, 0x40019463, dl)); 5369 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5370 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5371 getF32Constant(DAG, 0x3fd6633d, dl)); 5372 } else if (LimitFloatPrecision <= 12) { 5373 // For floating-point precision of 12: 5374 // 5375 // Log2ofMantissa = 5376 // -2.51285454f + 5377 // (4.07009056f + 5378 // (-2.12067489f + 5379 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5380 // 5381 // error 0.0000876136000, which is better than 13 bits 5382 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5383 getF32Constant(DAG, 0xbda7262e, dl)); 5384 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5385 getF32Constant(DAG, 0x3f25280b, dl)); 5386 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5387 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5388 getF32Constant(DAG, 0x4007b923, dl)); 5389 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5390 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5391 getF32Constant(DAG, 0x40823e2f, dl)); 5392 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5393 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5394 getF32Constant(DAG, 0x4020d29c, dl)); 5395 } else { // LimitFloatPrecision <= 18 5396 // For floating-point precision of 18: 5397 // 5398 // Log2ofMantissa = 5399 // -3.0400495f + 5400 // (6.1129976f + 5401 // (-5.3420409f + 5402 // (3.2865683f + 5403 // (-1.2669343f + 5404 // (0.27515199f - 5405 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5406 // 5407 // error 0.0000018516, which is better than 18 bits 5408 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5409 getF32Constant(DAG, 0xbcd2769e, dl)); 5410 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5411 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5412 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5413 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5414 getF32Constant(DAG, 0x3fa22ae7, dl)); 5415 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5416 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5417 getF32Constant(DAG, 0x40525723, dl)); 5418 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5419 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5420 getF32Constant(DAG, 0x40aaf200, dl)); 5421 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5422 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5423 getF32Constant(DAG, 0x40c39dad, dl)); 5424 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5425 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5426 getF32Constant(DAG, 0x4042902c, dl)); 5427 } 5428 5429 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5430 } 5431 5432 // No special expansion. 5433 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5434 } 5435 5436 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5437 /// limited-precision mode. 5438 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5439 const TargetLowering &TLI, SDNodeFlags Flags) { 5440 // TODO: What fast-math-flags should be set on the floating-point nodes? 5441 5442 if (Op.getValueType() == MVT::f32 && 5443 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5444 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5445 5446 // Scale the exponent by log10(2) [0.30102999f]. 5447 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5448 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5449 getF32Constant(DAG, 0x3e9a209a, dl)); 5450 5451 // Get the significand and build it into a floating-point number with 5452 // exponent of 1. 5453 SDValue X = GetSignificand(DAG, Op1, dl); 5454 5455 SDValue Log10ofMantissa; 5456 if (LimitFloatPrecision <= 6) { 5457 // For floating-point precision of 6: 5458 // 5459 // Log10ofMantissa = 5460 // -0.50419619f + 5461 // (0.60948995f - 0.10380950f * x) * x; 5462 // 5463 // error 0.0014886165, which is 6 bits 5464 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5465 getF32Constant(DAG, 0xbdd49a13, dl)); 5466 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5467 getF32Constant(DAG, 0x3f1c0789, dl)); 5468 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5469 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5470 getF32Constant(DAG, 0x3f011300, dl)); 5471 } else if (LimitFloatPrecision <= 12) { 5472 // For floating-point precision of 12: 5473 // 5474 // Log10ofMantissa = 5475 // -0.64831180f + 5476 // (0.91751397f + 5477 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5478 // 5479 // error 0.00019228036, which is better than 12 bits 5480 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5481 getF32Constant(DAG, 0x3d431f31, dl)); 5482 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5483 getF32Constant(DAG, 0x3ea21fb2, dl)); 5484 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5485 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5486 getF32Constant(DAG, 0x3f6ae232, dl)); 5487 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5488 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5489 getF32Constant(DAG, 0x3f25f7c3, dl)); 5490 } else { // LimitFloatPrecision <= 18 5491 // For floating-point precision of 18: 5492 // 5493 // Log10ofMantissa = 5494 // -0.84299375f + 5495 // (1.5327582f + 5496 // (-1.0688956f + 5497 // (0.49102474f + 5498 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5499 // 5500 // error 0.0000037995730, which is better than 18 bits 5501 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5502 getF32Constant(DAG, 0x3c5d51ce, dl)); 5503 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5504 getF32Constant(DAG, 0x3e00685a, dl)); 5505 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5506 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5507 getF32Constant(DAG, 0x3efb6798, dl)); 5508 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5509 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5510 getF32Constant(DAG, 0x3f88d192, dl)); 5511 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5512 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5513 getF32Constant(DAG, 0x3fc4316c, dl)); 5514 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5515 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5516 getF32Constant(DAG, 0x3f57ce70, dl)); 5517 } 5518 5519 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5520 } 5521 5522 // No special expansion. 5523 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5524 } 5525 5526 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5527 /// limited-precision mode. 5528 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5529 const TargetLowering &TLI, SDNodeFlags Flags) { 5530 if (Op.getValueType() == MVT::f32 && 5531 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5532 return getLimitedPrecisionExp2(Op, dl, DAG); 5533 5534 // No special expansion. 5535 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5536 } 5537 5538 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5539 /// limited-precision mode with x == 10.0f. 5540 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5541 SelectionDAG &DAG, const TargetLowering &TLI, 5542 SDNodeFlags Flags) { 5543 bool IsExp10 = false; 5544 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5545 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5546 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5547 APFloat Ten(10.0f); 5548 IsExp10 = LHSC->isExactlyValue(Ten); 5549 } 5550 } 5551 5552 // TODO: What fast-math-flags should be set on the FMUL node? 5553 if (IsExp10) { 5554 // Put the exponent in the right bit position for later addition to the 5555 // final result: 5556 // 5557 // #define LOG2OF10 3.3219281f 5558 // t0 = Op * LOG2OF10; 5559 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5560 getF32Constant(DAG, 0x40549a78, dl)); 5561 return getLimitedPrecisionExp2(t0, dl, DAG); 5562 } 5563 5564 // No special expansion. 5565 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5566 } 5567 5568 /// ExpandPowI - Expand a llvm.powi intrinsic. 5569 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5570 SelectionDAG &DAG) { 5571 // If RHS is a constant, we can expand this out to a multiplication tree if 5572 // it's beneficial on the target, otherwise we end up lowering to a call to 5573 // __powidf2 (for example). 5574 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5575 unsigned Val = RHSC->getSExtValue(); 5576 5577 // powi(x, 0) -> 1.0 5578 if (Val == 0) 5579 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5580 5581 if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI( 5582 Val, DAG.shouldOptForSize())) { 5583 // Get the exponent as a positive value. 5584 if ((int)Val < 0) 5585 Val = -Val; 5586 // We use the simple binary decomposition method to generate the multiply 5587 // sequence. There are more optimal ways to do this (for example, 5588 // powi(x,15) generates one more multiply than it should), but this has 5589 // the benefit of being both really simple and much better than a libcall. 5590 SDValue Res; // Logically starts equal to 1.0 5591 SDValue CurSquare = LHS; 5592 // TODO: Intrinsics should have fast-math-flags that propagate to these 5593 // nodes. 5594 while (Val) { 5595 if (Val & 1) { 5596 if (Res.getNode()) 5597 Res = 5598 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare); 5599 else 5600 Res = CurSquare; // 1.0*CurSquare. 5601 } 5602 5603 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5604 CurSquare, CurSquare); 5605 Val >>= 1; 5606 } 5607 5608 // If the original was negative, invert the result, producing 1/(x*x*x). 5609 if (RHSC->getSExtValue() < 0) 5610 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5611 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5612 return Res; 5613 } 5614 } 5615 5616 // Otherwise, expand to a libcall. 5617 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5618 } 5619 5620 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5621 SDValue LHS, SDValue RHS, SDValue Scale, 5622 SelectionDAG &DAG, const TargetLowering &TLI) { 5623 EVT VT = LHS.getValueType(); 5624 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5625 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5626 LLVMContext &Ctx = *DAG.getContext(); 5627 5628 // If the type is legal but the operation isn't, this node might survive all 5629 // the way to operation legalization. If we end up there and we do not have 5630 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5631 // node. 5632 5633 // Coax the legalizer into expanding the node during type legalization instead 5634 // by bumping the size by one bit. This will force it to Promote, enabling the 5635 // early expansion and avoiding the need to expand later. 5636 5637 // We don't have to do this if Scale is 0; that can always be expanded, unless 5638 // it's a saturating signed operation. Those can experience true integer 5639 // division overflow, a case which we must avoid. 5640 5641 // FIXME: We wouldn't have to do this (or any of the early 5642 // expansion/promotion) if it was possible to expand a libcall of an 5643 // illegal type during operation legalization. But it's not, so things 5644 // get a bit hacky. 5645 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5646 if ((ScaleInt > 0 || (Saturating && Signed)) && 5647 (TLI.isTypeLegal(VT) || 5648 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5649 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5650 Opcode, VT, ScaleInt); 5651 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5652 EVT PromVT; 5653 if (VT.isScalarInteger()) 5654 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5655 else if (VT.isVector()) { 5656 PromVT = VT.getVectorElementType(); 5657 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5658 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5659 } else 5660 llvm_unreachable("Wrong VT for DIVFIX?"); 5661 LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT); 5662 RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT); 5663 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5664 // For saturating operations, we need to shift up the LHS to get the 5665 // proper saturation width, and then shift down again afterwards. 5666 if (Saturating) 5667 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5668 DAG.getConstant(1, DL, ShiftTy)); 5669 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5670 if (Saturating) 5671 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5672 DAG.getConstant(1, DL, ShiftTy)); 5673 return DAG.getZExtOrTrunc(Res, DL, VT); 5674 } 5675 } 5676 5677 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5678 } 5679 5680 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5681 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5682 static void 5683 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5684 const SDValue &N) { 5685 switch (N.getOpcode()) { 5686 case ISD::CopyFromReg: { 5687 SDValue Op = N.getOperand(1); 5688 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5689 Op.getValueType().getSizeInBits()); 5690 return; 5691 } 5692 case ISD::BITCAST: 5693 case ISD::AssertZext: 5694 case ISD::AssertSext: 5695 case ISD::TRUNCATE: 5696 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5697 return; 5698 case ISD::BUILD_PAIR: 5699 case ISD::BUILD_VECTOR: 5700 case ISD::CONCAT_VECTORS: 5701 for (SDValue Op : N->op_values()) 5702 getUnderlyingArgRegs(Regs, Op); 5703 return; 5704 default: 5705 return; 5706 } 5707 } 5708 5709 /// If the DbgValueInst is a dbg_value of a function argument, create the 5710 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5711 /// instruction selection, they will be inserted to the entry BB. 5712 /// We don't currently support this for variadic dbg_values, as they shouldn't 5713 /// appear for function arguments or in the prologue. 5714 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5715 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5716 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) { 5717 const Argument *Arg = dyn_cast<Argument>(V); 5718 if (!Arg) 5719 return false; 5720 5721 MachineFunction &MF = DAG.getMachineFunction(); 5722 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5723 5724 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind 5725 // we've been asked to pursue. 5726 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr, 5727 bool Indirect) { 5728 if (Reg.isVirtual() && MF.useDebugInstrRef()) { 5729 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF 5730 // pointing at the VReg, which will be patched up later. 5731 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF); 5732 SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg( 5733 /* Reg */ Reg, /* isDef */ false, /* isImp */ false, 5734 /* isKill */ false, /* isDead */ false, 5735 /* isUndef */ false, /* isEarlyClobber */ false, 5736 /* SubReg */ 0, /* isDebug */ true)}); 5737 5738 auto *NewDIExpr = FragExpr; 5739 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into 5740 // the DIExpression. 5741 if (Indirect) 5742 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore); 5743 SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0}); 5744 NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops); 5745 return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr); 5746 } else { 5747 // Create a completely standard DBG_VALUE. 5748 auto &Inst = TII->get(TargetOpcode::DBG_VALUE); 5749 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr); 5750 } 5751 }; 5752 5753 if (Kind == FuncArgumentDbgValueKind::Value) { 5754 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5755 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5756 // the entry block. 5757 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5758 if (!IsInEntryBlock) 5759 return false; 5760 5761 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5762 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5763 // variable that also is a param. 5764 // 5765 // Although, if we are at the top of the entry block already, we can still 5766 // emit using ArgDbgValue. This might catch some situations when the 5767 // dbg.value refers to an argument that isn't used in the entry block, so 5768 // any CopyToReg node would be optimized out and the only way to express 5769 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5770 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5771 // we should only emit as ArgDbgValue if the Variable is an argument to the 5772 // current function, and the dbg.value intrinsic is found in the entry 5773 // block. 5774 bool VariableIsFunctionInputArg = Variable->isParameter() && 5775 !DL->getInlinedAt(); 5776 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5777 if (!IsInPrologue && !VariableIsFunctionInputArg) 5778 return false; 5779 5780 // Here we assume that a function argument on IR level only can be used to 5781 // describe one input parameter on source level. If we for example have 5782 // source code like this 5783 // 5784 // struct A { long x, y; }; 5785 // void foo(struct A a, long b) { 5786 // ... 5787 // b = a.x; 5788 // ... 5789 // } 5790 // 5791 // and IR like this 5792 // 5793 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5794 // entry: 5795 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5796 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5797 // call void @llvm.dbg.value(metadata i32 %b, "b", 5798 // ... 5799 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5800 // ... 5801 // 5802 // then the last dbg.value is describing a parameter "b" using a value that 5803 // is an argument. But since we already has used %a1 to describe a parameter 5804 // we should not handle that last dbg.value here (that would result in an 5805 // incorrect hoisting of the DBG_VALUE to the function entry). 5806 // Notice that we allow one dbg.value per IR level argument, to accommodate 5807 // for the situation with fragments above. 5808 if (VariableIsFunctionInputArg) { 5809 unsigned ArgNo = Arg->getArgNo(); 5810 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5811 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5812 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5813 return false; 5814 FuncInfo.DescribedArgs.set(ArgNo); 5815 } 5816 } 5817 5818 bool IsIndirect = false; 5819 std::optional<MachineOperand> Op; 5820 // Some arguments' frame index is recorded during argument lowering. 5821 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5822 if (FI != std::numeric_limits<int>::max()) 5823 Op = MachineOperand::CreateFI(FI); 5824 5825 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 5826 if (!Op && N.getNode()) { 5827 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5828 Register Reg; 5829 if (ArgRegsAndSizes.size() == 1) 5830 Reg = ArgRegsAndSizes.front().first; 5831 5832 if (Reg && Reg.isVirtual()) { 5833 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5834 Register PR = RegInfo.getLiveInPhysReg(Reg); 5835 if (PR) 5836 Reg = PR; 5837 } 5838 if (Reg) { 5839 Op = MachineOperand::CreateReg(Reg, false); 5840 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5841 } 5842 } 5843 5844 if (!Op && N.getNode()) { 5845 // Check if frame index is available. 5846 SDValue LCandidate = peekThroughBitcasts(N); 5847 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5848 if (FrameIndexSDNode *FINode = 5849 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5850 Op = MachineOperand::CreateFI(FINode->getIndex()); 5851 } 5852 5853 if (!Op) { 5854 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5855 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 5856 SplitRegs) { 5857 unsigned Offset = 0; 5858 for (const auto &RegAndSize : SplitRegs) { 5859 // If the expression is already a fragment, the current register 5860 // offset+size might extend beyond the fragment. In this case, only 5861 // the register bits that are inside the fragment are relevant. 5862 int RegFragmentSizeInBits = RegAndSize.second; 5863 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5864 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5865 // The register is entirely outside the expression fragment, 5866 // so is irrelevant for debug info. 5867 if (Offset >= ExprFragmentSizeInBits) 5868 break; 5869 // The register is partially outside the expression fragment, only 5870 // the low bits within the fragment are relevant for debug info. 5871 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5872 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5873 } 5874 } 5875 5876 auto FragmentExpr = DIExpression::createFragmentExpression( 5877 Expr, Offset, RegFragmentSizeInBits); 5878 Offset += RegAndSize.second; 5879 // If a valid fragment expression cannot be created, the variable's 5880 // correct value cannot be determined and so it is set as Undef. 5881 if (!FragmentExpr) { 5882 SDDbgValue *SDV = DAG.getConstantDbgValue( 5883 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5884 DAG.AddDbgValue(SDV, false); 5885 continue; 5886 } 5887 MachineInstr *NewMI = 5888 MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, 5889 Kind != FuncArgumentDbgValueKind::Value); 5890 FuncInfo.ArgDbgValues.push_back(NewMI); 5891 } 5892 }; 5893 5894 // Check if ValueMap has reg number. 5895 DenseMap<const Value *, Register>::const_iterator 5896 VMI = FuncInfo.ValueMap.find(V); 5897 if (VMI != FuncInfo.ValueMap.end()) { 5898 const auto &TLI = DAG.getTargetLoweringInfo(); 5899 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5900 V->getType(), std::nullopt); 5901 if (RFV.occupiesMultipleRegs()) { 5902 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5903 return true; 5904 } 5905 5906 Op = MachineOperand::CreateReg(VMI->second, false); 5907 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5908 } else if (ArgRegsAndSizes.size() > 1) { 5909 // This was split due to the calling convention, and no virtual register 5910 // mapping exists for the value. 5911 splitMultiRegDbgValue(ArgRegsAndSizes); 5912 return true; 5913 } 5914 } 5915 5916 if (!Op) 5917 return false; 5918 5919 assert(Variable->isValidLocationForIntrinsic(DL) && 5920 "Expected inlined-at fields to agree"); 5921 MachineInstr *NewMI = nullptr; 5922 5923 if (Op->isReg()) 5924 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect); 5925 else 5926 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op, 5927 Variable, Expr); 5928 5929 // Otherwise, use ArgDbgValues. 5930 FuncInfo.ArgDbgValues.push_back(NewMI); 5931 return true; 5932 } 5933 5934 /// Return the appropriate SDDbgValue based on N. 5935 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5936 DILocalVariable *Variable, 5937 DIExpression *Expr, 5938 const DebugLoc &dl, 5939 unsigned DbgSDNodeOrder) { 5940 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5941 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5942 // stack slot locations. 5943 // 5944 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5945 // debug values here after optimization: 5946 // 5947 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5948 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5949 // 5950 // Both describe the direct values of their associated variables. 5951 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5952 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5953 } 5954 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5955 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5956 } 5957 5958 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5959 switch (Intrinsic) { 5960 case Intrinsic::smul_fix: 5961 return ISD::SMULFIX; 5962 case Intrinsic::umul_fix: 5963 return ISD::UMULFIX; 5964 case Intrinsic::smul_fix_sat: 5965 return ISD::SMULFIXSAT; 5966 case Intrinsic::umul_fix_sat: 5967 return ISD::UMULFIXSAT; 5968 case Intrinsic::sdiv_fix: 5969 return ISD::SDIVFIX; 5970 case Intrinsic::udiv_fix: 5971 return ISD::UDIVFIX; 5972 case Intrinsic::sdiv_fix_sat: 5973 return ISD::SDIVFIXSAT; 5974 case Intrinsic::udiv_fix_sat: 5975 return ISD::UDIVFIXSAT; 5976 default: 5977 llvm_unreachable("Unhandled fixed point intrinsic"); 5978 } 5979 } 5980 5981 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5982 const char *FunctionName) { 5983 assert(FunctionName && "FunctionName must not be nullptr"); 5984 SDValue Callee = DAG.getExternalSymbol( 5985 FunctionName, 5986 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5987 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 5988 } 5989 5990 /// Given a @llvm.call.preallocated.setup, return the corresponding 5991 /// preallocated call. 5992 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5993 assert(cast<CallBase>(PreallocatedSetup) 5994 ->getCalledFunction() 5995 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5996 "expected call_preallocated_setup Value"); 5997 for (const auto *U : PreallocatedSetup->users()) { 5998 auto *UseCall = cast<CallBase>(U); 5999 const Function *Fn = UseCall->getCalledFunction(); 6000 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 6001 return UseCall; 6002 } 6003 } 6004 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 6005 } 6006 6007 /// If DI is a debug value with an EntryValue expression, lower it using the 6008 /// corresponding physical register of the associated Argument value 6009 /// (guaranteed to exist by the verifier). 6010 bool SelectionDAGBuilder::visitEntryValueDbgValue(const DbgValueInst &DI) { 6011 DILocalVariable *Variable = DI.getVariable(); 6012 DIExpression *Expr = DI.getExpression(); 6013 if (!Expr->isEntryValue() || !hasSingleElement(DI.getValues())) 6014 return false; 6015 6016 // These properties are guaranteed by the verifier. 6017 Argument *Arg = cast<Argument>(DI.getValue(0)); 6018 assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync)); 6019 6020 auto ArgIt = FuncInfo.ValueMap.find(Arg); 6021 if (ArgIt == FuncInfo.ValueMap.end()) { 6022 LLVM_DEBUG( 6023 dbgs() << "Dropping dbg.value: expression is entry_value but " 6024 "couldn't find an associated register for the Argument\n"); 6025 return true; 6026 } 6027 Register ArgVReg = ArgIt->getSecond(); 6028 6029 for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins()) 6030 if (ArgVReg == VirtReg || ArgVReg == PhysReg) { 6031 SDDbgValue *SDV = 6032 DAG.getVRegDbgValue(Variable, Expr, PhysReg, false /*IsIndidrect*/, 6033 DI.getDebugLoc(), SDNodeOrder); 6034 DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/); 6035 return true; 6036 } 6037 LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but " 6038 "couldn't find a physical register\n"); 6039 return true; 6040 } 6041 6042 /// Lower the call to the specified intrinsic function. 6043 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 6044 unsigned Intrinsic) { 6045 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6046 SDLoc sdl = getCurSDLoc(); 6047 DebugLoc dl = getCurDebugLoc(); 6048 SDValue Res; 6049 6050 SDNodeFlags Flags; 6051 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 6052 Flags.copyFMF(*FPOp); 6053 6054 switch (Intrinsic) { 6055 default: 6056 // By default, turn this into a target intrinsic node. 6057 visitTargetIntrinsic(I, Intrinsic); 6058 return; 6059 case Intrinsic::vscale: { 6060 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6061 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1))); 6062 return; 6063 } 6064 case Intrinsic::vastart: visitVAStart(I); return; 6065 case Intrinsic::vaend: visitVAEnd(I); return; 6066 case Intrinsic::vacopy: visitVACopy(I); return; 6067 case Intrinsic::returnaddress: 6068 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 6069 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6070 getValue(I.getArgOperand(0)))); 6071 return; 6072 case Intrinsic::addressofreturnaddress: 6073 setValue(&I, 6074 DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 6075 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 6076 return; 6077 case Intrinsic::sponentry: 6078 setValue(&I, 6079 DAG.getNode(ISD::SPONENTRY, sdl, 6080 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 6081 return; 6082 case Intrinsic::frameaddress: 6083 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 6084 TLI.getFrameIndexTy(DAG.getDataLayout()), 6085 getValue(I.getArgOperand(0)))); 6086 return; 6087 case Intrinsic::read_volatile_register: 6088 case Intrinsic::read_register: { 6089 Value *Reg = I.getArgOperand(0); 6090 SDValue Chain = getRoot(); 6091 SDValue RegName = 6092 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 6093 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6094 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 6095 DAG.getVTList(VT, MVT::Other), Chain, RegName); 6096 setValue(&I, Res); 6097 DAG.setRoot(Res.getValue(1)); 6098 return; 6099 } 6100 case Intrinsic::write_register: { 6101 Value *Reg = I.getArgOperand(0); 6102 Value *RegValue = I.getArgOperand(1); 6103 SDValue Chain = getRoot(); 6104 SDValue RegName = 6105 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 6106 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 6107 RegName, getValue(RegValue))); 6108 return; 6109 } 6110 case Intrinsic::memcpy: { 6111 const auto &MCI = cast<MemCpyInst>(I); 6112 SDValue Op1 = getValue(I.getArgOperand(0)); 6113 SDValue Op2 = getValue(I.getArgOperand(1)); 6114 SDValue Op3 = getValue(I.getArgOperand(2)); 6115 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 6116 Align DstAlign = MCI.getDestAlign().valueOrOne(); 6117 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 6118 Align Alignment = std::min(DstAlign, SrcAlign); 6119 bool isVol = MCI.isVolatile(); 6120 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6121 // FIXME: Support passing different dest/src alignments to the memcpy DAG 6122 // node. 6123 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6124 SDValue MC = DAG.getMemcpy( 6125 Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6126 /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)), 6127 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 6128 updateDAGForMaybeTailCall(MC); 6129 return; 6130 } 6131 case Intrinsic::memcpy_inline: { 6132 const auto &MCI = cast<MemCpyInlineInst>(I); 6133 SDValue Dst = getValue(I.getArgOperand(0)); 6134 SDValue Src = getValue(I.getArgOperand(1)); 6135 SDValue Size = getValue(I.getArgOperand(2)); 6136 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 6137 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 6138 Align DstAlign = MCI.getDestAlign().valueOrOne(); 6139 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 6140 Align Alignment = std::min(DstAlign, SrcAlign); 6141 bool isVol = MCI.isVolatile(); 6142 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6143 // FIXME: Support passing different dest/src alignments to the memcpy DAG 6144 // node. 6145 SDValue MC = DAG.getMemcpy( 6146 getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 6147 /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)), 6148 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 6149 updateDAGForMaybeTailCall(MC); 6150 return; 6151 } 6152 case Intrinsic::memset: { 6153 const auto &MSI = cast<MemSetInst>(I); 6154 SDValue Op1 = getValue(I.getArgOperand(0)); 6155 SDValue Op2 = getValue(I.getArgOperand(1)); 6156 SDValue Op3 = getValue(I.getArgOperand(2)); 6157 // @llvm.memset defines 0 and 1 to both mean no alignment. 6158 Align Alignment = MSI.getDestAlign().valueOrOne(); 6159 bool isVol = MSI.isVolatile(); 6160 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6161 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6162 SDValue MS = DAG.getMemset( 6163 Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false, 6164 isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata()); 6165 updateDAGForMaybeTailCall(MS); 6166 return; 6167 } 6168 case Intrinsic::memset_inline: { 6169 const auto &MSII = cast<MemSetInlineInst>(I); 6170 SDValue Dst = getValue(I.getArgOperand(0)); 6171 SDValue Value = getValue(I.getArgOperand(1)); 6172 SDValue Size = getValue(I.getArgOperand(2)); 6173 assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size"); 6174 // @llvm.memset defines 0 and 1 to both mean no alignment. 6175 Align DstAlign = MSII.getDestAlign().valueOrOne(); 6176 bool isVol = MSII.isVolatile(); 6177 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6178 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6179 SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol, 6180 /* AlwaysInline */ true, isTC, 6181 MachinePointerInfo(I.getArgOperand(0)), 6182 I.getAAMetadata()); 6183 updateDAGForMaybeTailCall(MC); 6184 return; 6185 } 6186 case Intrinsic::memmove: { 6187 const auto &MMI = cast<MemMoveInst>(I); 6188 SDValue Op1 = getValue(I.getArgOperand(0)); 6189 SDValue Op2 = getValue(I.getArgOperand(1)); 6190 SDValue Op3 = getValue(I.getArgOperand(2)); 6191 // @llvm.memmove defines 0 and 1 to both mean no alignment. 6192 Align DstAlign = MMI.getDestAlign().valueOrOne(); 6193 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 6194 Align Alignment = std::min(DstAlign, SrcAlign); 6195 bool isVol = MMI.isVolatile(); 6196 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6197 // FIXME: Support passing different dest/src alignments to the memmove DAG 6198 // node. 6199 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6200 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6201 isTC, MachinePointerInfo(I.getArgOperand(0)), 6202 MachinePointerInfo(I.getArgOperand(1)), 6203 I.getAAMetadata(), AA); 6204 updateDAGForMaybeTailCall(MM); 6205 return; 6206 } 6207 case Intrinsic::memcpy_element_unordered_atomic: { 6208 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 6209 SDValue Dst = getValue(MI.getRawDest()); 6210 SDValue Src = getValue(MI.getRawSource()); 6211 SDValue Length = getValue(MI.getLength()); 6212 6213 Type *LengthTy = MI.getLength()->getType(); 6214 unsigned ElemSz = MI.getElementSizeInBytes(); 6215 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6216 SDValue MC = 6217 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6218 isTC, MachinePointerInfo(MI.getRawDest()), 6219 MachinePointerInfo(MI.getRawSource())); 6220 updateDAGForMaybeTailCall(MC); 6221 return; 6222 } 6223 case Intrinsic::memmove_element_unordered_atomic: { 6224 auto &MI = cast<AtomicMemMoveInst>(I); 6225 SDValue Dst = getValue(MI.getRawDest()); 6226 SDValue Src = getValue(MI.getRawSource()); 6227 SDValue Length = getValue(MI.getLength()); 6228 6229 Type *LengthTy = MI.getLength()->getType(); 6230 unsigned ElemSz = MI.getElementSizeInBytes(); 6231 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6232 SDValue MC = 6233 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6234 isTC, MachinePointerInfo(MI.getRawDest()), 6235 MachinePointerInfo(MI.getRawSource())); 6236 updateDAGForMaybeTailCall(MC); 6237 return; 6238 } 6239 case Intrinsic::memset_element_unordered_atomic: { 6240 auto &MI = cast<AtomicMemSetInst>(I); 6241 SDValue Dst = getValue(MI.getRawDest()); 6242 SDValue Val = getValue(MI.getValue()); 6243 SDValue Length = getValue(MI.getLength()); 6244 6245 Type *LengthTy = MI.getLength()->getType(); 6246 unsigned ElemSz = MI.getElementSizeInBytes(); 6247 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6248 SDValue MC = 6249 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz, 6250 isTC, MachinePointerInfo(MI.getRawDest())); 6251 updateDAGForMaybeTailCall(MC); 6252 return; 6253 } 6254 case Intrinsic::call_preallocated_setup: { 6255 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 6256 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6257 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 6258 getRoot(), SrcValue); 6259 setValue(&I, Res); 6260 DAG.setRoot(Res); 6261 return; 6262 } 6263 case Intrinsic::call_preallocated_arg: { 6264 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 6265 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6266 SDValue Ops[3]; 6267 Ops[0] = getRoot(); 6268 Ops[1] = SrcValue; 6269 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 6270 MVT::i32); // arg index 6271 SDValue Res = DAG.getNode( 6272 ISD::PREALLOCATED_ARG, sdl, 6273 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 6274 setValue(&I, Res); 6275 DAG.setRoot(Res.getValue(1)); 6276 return; 6277 } 6278 case Intrinsic::dbg_declare: { 6279 const auto &DI = cast<DbgDeclareInst>(I); 6280 // Debug intrinsics are handled separately in assignment tracking mode. 6281 // Some intrinsics are handled right after Argument lowering. 6282 if (AssignmentTrackingEnabled || 6283 FuncInfo.PreprocessedDbgDeclares.count(&DI)) 6284 return; 6285 LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DI << "\n"); 6286 DILocalVariable *Variable = DI.getVariable(); 6287 DIExpression *Expression = DI.getExpression(); 6288 dropDanglingDebugInfo(Variable, Expression); 6289 // Assume dbg.declare can not currently use DIArgList, i.e. 6290 // it is non-variadic. 6291 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 6292 handleDebugDeclare(DI.getVariableLocationOp(0), Variable, Expression, 6293 DI.getDebugLoc()); 6294 return; 6295 } 6296 case Intrinsic::dbg_label: { 6297 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6298 DILabel *Label = DI.getLabel(); 6299 assert(Label && "Missing label"); 6300 6301 SDDbgLabel *SDV; 6302 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6303 DAG.AddDbgLabel(SDV); 6304 return; 6305 } 6306 case Intrinsic::dbg_assign: { 6307 // Debug intrinsics are handled seperately in assignment tracking mode. 6308 if (AssignmentTrackingEnabled) 6309 return; 6310 // If assignment tracking hasn't been enabled then fall through and treat 6311 // the dbg.assign as a dbg.value. 6312 [[fallthrough]]; 6313 } 6314 case Intrinsic::dbg_value: { 6315 // Debug intrinsics are handled seperately in assignment tracking mode. 6316 if (AssignmentTrackingEnabled) 6317 return; 6318 const DbgValueInst &DI = cast<DbgValueInst>(I); 6319 assert(DI.getVariable() && "Missing variable"); 6320 6321 DILocalVariable *Variable = DI.getVariable(); 6322 DIExpression *Expression = DI.getExpression(); 6323 dropDanglingDebugInfo(Variable, Expression); 6324 6325 if (visitEntryValueDbgValue(DI)) 6326 return; 6327 6328 if (DI.isKillLocation()) { 6329 handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder); 6330 return; 6331 } 6332 6333 SmallVector<Value *, 4> Values(DI.getValues()); 6334 if (Values.empty()) 6335 return; 6336 6337 bool IsVariadic = DI.hasArgList(); 6338 if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(), 6339 SDNodeOrder, IsVariadic)) 6340 addDanglingDebugInfo(Values, Variable, Expression, IsVariadic, 6341 DI.getDebugLoc(), SDNodeOrder); 6342 return; 6343 } 6344 6345 case Intrinsic::eh_typeid_for: { 6346 // Find the type id for the given typeinfo. 6347 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6348 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6349 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6350 setValue(&I, Res); 6351 return; 6352 } 6353 6354 case Intrinsic::eh_return_i32: 6355 case Intrinsic::eh_return_i64: 6356 DAG.getMachineFunction().setCallsEHReturn(true); 6357 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6358 MVT::Other, 6359 getControlRoot(), 6360 getValue(I.getArgOperand(0)), 6361 getValue(I.getArgOperand(1)))); 6362 return; 6363 case Intrinsic::eh_unwind_init: 6364 DAG.getMachineFunction().setCallsUnwindInit(true); 6365 return; 6366 case Intrinsic::eh_dwarf_cfa: 6367 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6368 TLI.getPointerTy(DAG.getDataLayout()), 6369 getValue(I.getArgOperand(0)))); 6370 return; 6371 case Intrinsic::eh_sjlj_callsite: { 6372 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6373 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0)); 6374 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6375 6376 MMI.setCurrentCallSite(CI->getZExtValue()); 6377 return; 6378 } 6379 case Intrinsic::eh_sjlj_functioncontext: { 6380 // Get and store the index of the function context. 6381 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6382 AllocaInst *FnCtx = 6383 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6384 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6385 MFI.setFunctionContextIndex(FI); 6386 return; 6387 } 6388 case Intrinsic::eh_sjlj_setjmp: { 6389 SDValue Ops[2]; 6390 Ops[0] = getRoot(); 6391 Ops[1] = getValue(I.getArgOperand(0)); 6392 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6393 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6394 setValue(&I, Op.getValue(0)); 6395 DAG.setRoot(Op.getValue(1)); 6396 return; 6397 } 6398 case Intrinsic::eh_sjlj_longjmp: 6399 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6400 getRoot(), getValue(I.getArgOperand(0)))); 6401 return; 6402 case Intrinsic::eh_sjlj_setup_dispatch: 6403 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6404 getRoot())); 6405 return; 6406 case Intrinsic::masked_gather: 6407 visitMaskedGather(I); 6408 return; 6409 case Intrinsic::masked_load: 6410 visitMaskedLoad(I); 6411 return; 6412 case Intrinsic::masked_scatter: 6413 visitMaskedScatter(I); 6414 return; 6415 case Intrinsic::masked_store: 6416 visitMaskedStore(I); 6417 return; 6418 case Intrinsic::masked_expandload: 6419 visitMaskedLoad(I, true /* IsExpanding */); 6420 return; 6421 case Intrinsic::masked_compressstore: 6422 visitMaskedStore(I, true /* IsCompressing */); 6423 return; 6424 case Intrinsic::powi: 6425 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6426 getValue(I.getArgOperand(1)), DAG)); 6427 return; 6428 case Intrinsic::log: 6429 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6430 return; 6431 case Intrinsic::log2: 6432 setValue(&I, 6433 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6434 return; 6435 case Intrinsic::log10: 6436 setValue(&I, 6437 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6438 return; 6439 case Intrinsic::exp: 6440 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6441 return; 6442 case Intrinsic::exp2: 6443 setValue(&I, 6444 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6445 return; 6446 case Intrinsic::pow: 6447 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6448 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6449 return; 6450 case Intrinsic::sqrt: 6451 case Intrinsic::fabs: 6452 case Intrinsic::sin: 6453 case Intrinsic::cos: 6454 case Intrinsic::exp10: 6455 case Intrinsic::floor: 6456 case Intrinsic::ceil: 6457 case Intrinsic::trunc: 6458 case Intrinsic::rint: 6459 case Intrinsic::nearbyint: 6460 case Intrinsic::round: 6461 case Intrinsic::roundeven: 6462 case Intrinsic::canonicalize: { 6463 unsigned Opcode; 6464 switch (Intrinsic) { 6465 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6466 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6467 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6468 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6469 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6470 case Intrinsic::exp10: Opcode = ISD::FEXP10; break; 6471 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6472 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6473 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6474 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6475 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6476 case Intrinsic::round: Opcode = ISD::FROUND; break; 6477 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6478 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6479 } 6480 6481 setValue(&I, DAG.getNode(Opcode, sdl, 6482 getValue(I.getArgOperand(0)).getValueType(), 6483 getValue(I.getArgOperand(0)), Flags)); 6484 return; 6485 } 6486 case Intrinsic::lround: 6487 case Intrinsic::llround: 6488 case Intrinsic::lrint: 6489 case Intrinsic::llrint: { 6490 unsigned Opcode; 6491 switch (Intrinsic) { 6492 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6493 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6494 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6495 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6496 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6497 } 6498 6499 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6500 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6501 getValue(I.getArgOperand(0)))); 6502 return; 6503 } 6504 case Intrinsic::minnum: 6505 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6506 getValue(I.getArgOperand(0)).getValueType(), 6507 getValue(I.getArgOperand(0)), 6508 getValue(I.getArgOperand(1)), Flags)); 6509 return; 6510 case Intrinsic::maxnum: 6511 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6512 getValue(I.getArgOperand(0)).getValueType(), 6513 getValue(I.getArgOperand(0)), 6514 getValue(I.getArgOperand(1)), Flags)); 6515 return; 6516 case Intrinsic::minimum: 6517 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6518 getValue(I.getArgOperand(0)).getValueType(), 6519 getValue(I.getArgOperand(0)), 6520 getValue(I.getArgOperand(1)), Flags)); 6521 return; 6522 case Intrinsic::maximum: 6523 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6524 getValue(I.getArgOperand(0)).getValueType(), 6525 getValue(I.getArgOperand(0)), 6526 getValue(I.getArgOperand(1)), Flags)); 6527 return; 6528 case Intrinsic::copysign: 6529 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6530 getValue(I.getArgOperand(0)).getValueType(), 6531 getValue(I.getArgOperand(0)), 6532 getValue(I.getArgOperand(1)), Flags)); 6533 return; 6534 case Intrinsic::ldexp: 6535 setValue(&I, DAG.getNode(ISD::FLDEXP, sdl, 6536 getValue(I.getArgOperand(0)).getValueType(), 6537 getValue(I.getArgOperand(0)), 6538 getValue(I.getArgOperand(1)), Flags)); 6539 return; 6540 case Intrinsic::frexp: { 6541 SmallVector<EVT, 2> ValueVTs; 6542 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 6543 SDVTList VTs = DAG.getVTList(ValueVTs); 6544 setValue(&I, 6545 DAG.getNode(ISD::FFREXP, sdl, VTs, getValue(I.getArgOperand(0)))); 6546 return; 6547 } 6548 case Intrinsic::arithmetic_fence: { 6549 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl, 6550 getValue(I.getArgOperand(0)).getValueType(), 6551 getValue(I.getArgOperand(0)), Flags)); 6552 return; 6553 } 6554 case Intrinsic::fma: 6555 setValue(&I, DAG.getNode( 6556 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6557 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6558 getValue(I.getArgOperand(2)), Flags)); 6559 return; 6560 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6561 case Intrinsic::INTRINSIC: 6562 #include "llvm/IR/ConstrainedOps.def" 6563 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6564 return; 6565 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6566 #include "llvm/IR/VPIntrinsics.def" 6567 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6568 return; 6569 case Intrinsic::fptrunc_round: { 6570 // Get the last argument, the metadata and convert it to an integer in the 6571 // call 6572 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata(); 6573 std::optional<RoundingMode> RoundMode = 6574 convertStrToRoundingMode(cast<MDString>(MD)->getString()); 6575 6576 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6577 6578 // Propagate fast-math-flags from IR to node(s). 6579 SDNodeFlags Flags; 6580 Flags.copyFMF(*cast<FPMathOperator>(&I)); 6581 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 6582 6583 SDValue Result; 6584 Result = DAG.getNode( 6585 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)), 6586 DAG.getTargetConstant((int)*RoundMode, sdl, 6587 TLI.getPointerTy(DAG.getDataLayout()))); 6588 setValue(&I, Result); 6589 6590 return; 6591 } 6592 case Intrinsic::fmuladd: { 6593 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6594 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6595 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6596 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6597 getValue(I.getArgOperand(0)).getValueType(), 6598 getValue(I.getArgOperand(0)), 6599 getValue(I.getArgOperand(1)), 6600 getValue(I.getArgOperand(2)), Flags)); 6601 } else { 6602 // TODO: Intrinsic calls should have fast-math-flags. 6603 SDValue Mul = DAG.getNode( 6604 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6605 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6606 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6607 getValue(I.getArgOperand(0)).getValueType(), 6608 Mul, getValue(I.getArgOperand(2)), Flags); 6609 setValue(&I, Add); 6610 } 6611 return; 6612 } 6613 case Intrinsic::convert_to_fp16: 6614 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6615 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6616 getValue(I.getArgOperand(0)), 6617 DAG.getTargetConstant(0, sdl, 6618 MVT::i32)))); 6619 return; 6620 case Intrinsic::convert_from_fp16: 6621 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6622 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6623 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6624 getValue(I.getArgOperand(0))))); 6625 return; 6626 case Intrinsic::fptosi_sat: { 6627 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6628 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 6629 getValue(I.getArgOperand(0)), 6630 DAG.getValueType(VT.getScalarType()))); 6631 return; 6632 } 6633 case Intrinsic::fptoui_sat: { 6634 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6635 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 6636 getValue(I.getArgOperand(0)), 6637 DAG.getValueType(VT.getScalarType()))); 6638 return; 6639 } 6640 case Intrinsic::set_rounding: 6641 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6642 {getRoot(), getValue(I.getArgOperand(0))}); 6643 setValue(&I, Res); 6644 DAG.setRoot(Res.getValue(0)); 6645 return; 6646 case Intrinsic::is_fpclass: { 6647 const DataLayout DLayout = DAG.getDataLayout(); 6648 EVT DestVT = TLI.getValueType(DLayout, I.getType()); 6649 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType()); 6650 FPClassTest Test = static_cast<FPClassTest>( 6651 cast<ConstantInt>(I.getArgOperand(1))->getZExtValue()); 6652 MachineFunction &MF = DAG.getMachineFunction(); 6653 const Function &F = MF.getFunction(); 6654 SDValue Op = getValue(I.getArgOperand(0)); 6655 SDNodeFlags Flags; 6656 Flags.setNoFPExcept( 6657 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP)); 6658 // If ISD::IS_FPCLASS should be expanded, do it right now, because the 6659 // expansion can use illegal types. Making expansion early allows 6660 // legalizing these types prior to selection. 6661 if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) { 6662 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG); 6663 setValue(&I, Result); 6664 return; 6665 } 6666 6667 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32); 6668 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags); 6669 setValue(&I, V); 6670 return; 6671 } 6672 case Intrinsic::get_fpenv: { 6673 const DataLayout DLayout = DAG.getDataLayout(); 6674 EVT EnvVT = TLI.getValueType(DLayout, I.getType()); 6675 Align TempAlign = DAG.getEVTAlign(EnvVT); 6676 SDValue Chain = getRoot(); 6677 // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node 6678 // and temporary storage in stack. 6679 if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) { 6680 Res = DAG.getNode( 6681 ISD::GET_FPENV, sdl, 6682 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()), 6683 MVT::Other), 6684 Chain); 6685 } else { 6686 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value()); 6687 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex(); 6688 auto MPI = 6689 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI); 6690 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 6691 MPI, MachineMemOperand::MOStore, MemoryLocation::UnknownSize, 6692 TempAlign); 6693 Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO); 6694 Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI); 6695 } 6696 setValue(&I, Res); 6697 DAG.setRoot(Res.getValue(1)); 6698 return; 6699 } 6700 case Intrinsic::set_fpenv: { 6701 const DataLayout DLayout = DAG.getDataLayout(); 6702 SDValue Env = getValue(I.getArgOperand(0)); 6703 EVT EnvVT = Env.getValueType(); 6704 Align TempAlign = DAG.getEVTAlign(EnvVT); 6705 SDValue Chain = getRoot(); 6706 // If SET_FPENV is custom or legal, use it. Otherwise use loading 6707 // environment from memory. 6708 if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) { 6709 Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env); 6710 } else { 6711 // Allocate space in stack, copy environment bits into it and use this 6712 // memory in SET_FPENV_MEM. 6713 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value()); 6714 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex(); 6715 auto MPI = 6716 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI); 6717 Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign, 6718 MachineMemOperand::MOStore); 6719 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 6720 MPI, MachineMemOperand::MOLoad, MemoryLocation::UnknownSize, 6721 TempAlign); 6722 Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO); 6723 } 6724 DAG.setRoot(Chain); 6725 return; 6726 } 6727 case Intrinsic::reset_fpenv: 6728 DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot())); 6729 return; 6730 case Intrinsic::get_fpmode: 6731 Res = DAG.getNode( 6732 ISD::GET_FPMODE, sdl, 6733 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()), 6734 MVT::Other), 6735 DAG.getRoot()); 6736 setValue(&I, Res); 6737 DAG.setRoot(Res.getValue(1)); 6738 return; 6739 case Intrinsic::set_fpmode: 6740 Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()}, 6741 getValue(I.getArgOperand(0))); 6742 DAG.setRoot(Res); 6743 return; 6744 case Intrinsic::reset_fpmode: { 6745 Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot()); 6746 DAG.setRoot(Res); 6747 return; 6748 } 6749 case Intrinsic::pcmarker: { 6750 SDValue Tmp = getValue(I.getArgOperand(0)); 6751 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6752 return; 6753 } 6754 case Intrinsic::readcyclecounter: { 6755 SDValue Op = getRoot(); 6756 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6757 DAG.getVTList(MVT::i64, MVT::Other), Op); 6758 setValue(&I, Res); 6759 DAG.setRoot(Res.getValue(1)); 6760 return; 6761 } 6762 case Intrinsic::bitreverse: 6763 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6764 getValue(I.getArgOperand(0)).getValueType(), 6765 getValue(I.getArgOperand(0)))); 6766 return; 6767 case Intrinsic::bswap: 6768 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6769 getValue(I.getArgOperand(0)).getValueType(), 6770 getValue(I.getArgOperand(0)))); 6771 return; 6772 case Intrinsic::cttz: { 6773 SDValue Arg = getValue(I.getArgOperand(0)); 6774 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6775 EVT Ty = Arg.getValueType(); 6776 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6777 sdl, Ty, Arg)); 6778 return; 6779 } 6780 case Intrinsic::ctlz: { 6781 SDValue Arg = getValue(I.getArgOperand(0)); 6782 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6783 EVT Ty = Arg.getValueType(); 6784 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6785 sdl, Ty, Arg)); 6786 return; 6787 } 6788 case Intrinsic::ctpop: { 6789 SDValue Arg = getValue(I.getArgOperand(0)); 6790 EVT Ty = Arg.getValueType(); 6791 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6792 return; 6793 } 6794 case Intrinsic::fshl: 6795 case Intrinsic::fshr: { 6796 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6797 SDValue X = getValue(I.getArgOperand(0)); 6798 SDValue Y = getValue(I.getArgOperand(1)); 6799 SDValue Z = getValue(I.getArgOperand(2)); 6800 EVT VT = X.getValueType(); 6801 6802 if (X == Y) { 6803 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6804 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6805 } else { 6806 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6807 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6808 } 6809 return; 6810 } 6811 case Intrinsic::sadd_sat: { 6812 SDValue Op1 = getValue(I.getArgOperand(0)); 6813 SDValue Op2 = getValue(I.getArgOperand(1)); 6814 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6815 return; 6816 } 6817 case Intrinsic::uadd_sat: { 6818 SDValue Op1 = getValue(I.getArgOperand(0)); 6819 SDValue Op2 = getValue(I.getArgOperand(1)); 6820 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6821 return; 6822 } 6823 case Intrinsic::ssub_sat: { 6824 SDValue Op1 = getValue(I.getArgOperand(0)); 6825 SDValue Op2 = getValue(I.getArgOperand(1)); 6826 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6827 return; 6828 } 6829 case Intrinsic::usub_sat: { 6830 SDValue Op1 = getValue(I.getArgOperand(0)); 6831 SDValue Op2 = getValue(I.getArgOperand(1)); 6832 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6833 return; 6834 } 6835 case Intrinsic::sshl_sat: { 6836 SDValue Op1 = getValue(I.getArgOperand(0)); 6837 SDValue Op2 = getValue(I.getArgOperand(1)); 6838 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6839 return; 6840 } 6841 case Intrinsic::ushl_sat: { 6842 SDValue Op1 = getValue(I.getArgOperand(0)); 6843 SDValue Op2 = getValue(I.getArgOperand(1)); 6844 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6845 return; 6846 } 6847 case Intrinsic::smul_fix: 6848 case Intrinsic::umul_fix: 6849 case Intrinsic::smul_fix_sat: 6850 case Intrinsic::umul_fix_sat: { 6851 SDValue Op1 = getValue(I.getArgOperand(0)); 6852 SDValue Op2 = getValue(I.getArgOperand(1)); 6853 SDValue Op3 = getValue(I.getArgOperand(2)); 6854 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6855 Op1.getValueType(), Op1, Op2, Op3)); 6856 return; 6857 } 6858 case Intrinsic::sdiv_fix: 6859 case Intrinsic::udiv_fix: 6860 case Intrinsic::sdiv_fix_sat: 6861 case Intrinsic::udiv_fix_sat: { 6862 SDValue Op1 = getValue(I.getArgOperand(0)); 6863 SDValue Op2 = getValue(I.getArgOperand(1)); 6864 SDValue Op3 = getValue(I.getArgOperand(2)); 6865 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6866 Op1, Op2, Op3, DAG, TLI)); 6867 return; 6868 } 6869 case Intrinsic::smax: { 6870 SDValue Op1 = getValue(I.getArgOperand(0)); 6871 SDValue Op2 = getValue(I.getArgOperand(1)); 6872 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6873 return; 6874 } 6875 case Intrinsic::smin: { 6876 SDValue Op1 = getValue(I.getArgOperand(0)); 6877 SDValue Op2 = getValue(I.getArgOperand(1)); 6878 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6879 return; 6880 } 6881 case Intrinsic::umax: { 6882 SDValue Op1 = getValue(I.getArgOperand(0)); 6883 SDValue Op2 = getValue(I.getArgOperand(1)); 6884 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6885 return; 6886 } 6887 case Intrinsic::umin: { 6888 SDValue Op1 = getValue(I.getArgOperand(0)); 6889 SDValue Op2 = getValue(I.getArgOperand(1)); 6890 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6891 return; 6892 } 6893 case Intrinsic::abs: { 6894 // TODO: Preserve "int min is poison" arg in SDAG? 6895 SDValue Op1 = getValue(I.getArgOperand(0)); 6896 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6897 return; 6898 } 6899 case Intrinsic::stacksave: { 6900 SDValue Op = getRoot(); 6901 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6902 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6903 setValue(&I, Res); 6904 DAG.setRoot(Res.getValue(1)); 6905 return; 6906 } 6907 case Intrinsic::stackrestore: 6908 Res = getValue(I.getArgOperand(0)); 6909 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6910 return; 6911 case Intrinsic::get_dynamic_area_offset: { 6912 SDValue Op = getRoot(); 6913 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6914 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6915 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6916 // target. 6917 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 6918 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6919 " intrinsic!"); 6920 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6921 Op); 6922 DAG.setRoot(Op); 6923 setValue(&I, Res); 6924 return; 6925 } 6926 case Intrinsic::stackguard: { 6927 MachineFunction &MF = DAG.getMachineFunction(); 6928 const Module &M = *MF.getFunction().getParent(); 6929 SDValue Chain = getRoot(); 6930 if (TLI.useLoadStackGuardNode()) { 6931 Res = getLoadStackGuard(DAG, sdl, Chain); 6932 } else { 6933 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6934 const Value *Global = TLI.getSDagStackGuard(M); 6935 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType()); 6936 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6937 MachinePointerInfo(Global, 0), Align, 6938 MachineMemOperand::MOVolatile); 6939 } 6940 if (TLI.useStackGuardXorFP()) 6941 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6942 DAG.setRoot(Chain); 6943 setValue(&I, Res); 6944 return; 6945 } 6946 case Intrinsic::stackprotector: { 6947 // Emit code into the DAG to store the stack guard onto the stack. 6948 MachineFunction &MF = DAG.getMachineFunction(); 6949 MachineFrameInfo &MFI = MF.getFrameInfo(); 6950 SDValue Src, Chain = getRoot(); 6951 6952 if (TLI.useLoadStackGuardNode()) 6953 Src = getLoadStackGuard(DAG, sdl, Chain); 6954 else 6955 Src = getValue(I.getArgOperand(0)); // The guard's value. 6956 6957 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6958 6959 int FI = FuncInfo.StaticAllocaMap[Slot]; 6960 MFI.setStackProtectorIndex(FI); 6961 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6962 6963 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6964 6965 // Store the stack protector onto the stack. 6966 Res = DAG.getStore( 6967 Chain, sdl, Src, FIN, 6968 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 6969 MaybeAlign(), MachineMemOperand::MOVolatile); 6970 setValue(&I, Res); 6971 DAG.setRoot(Res); 6972 return; 6973 } 6974 case Intrinsic::objectsize: 6975 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6976 6977 case Intrinsic::is_constant: 6978 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6979 6980 case Intrinsic::annotation: 6981 case Intrinsic::ptr_annotation: 6982 case Intrinsic::launder_invariant_group: 6983 case Intrinsic::strip_invariant_group: 6984 // Drop the intrinsic, but forward the value 6985 setValue(&I, getValue(I.getOperand(0))); 6986 return; 6987 6988 case Intrinsic::assume: 6989 case Intrinsic::experimental_noalias_scope_decl: 6990 case Intrinsic::var_annotation: 6991 case Intrinsic::sideeffect: 6992 // Discard annotate attributes, noalias scope declarations, assumptions, and 6993 // artificial side-effects. 6994 return; 6995 6996 case Intrinsic::codeview_annotation: { 6997 // Emit a label associated with this metadata. 6998 MachineFunction &MF = DAG.getMachineFunction(); 6999 MCSymbol *Label = 7000 MF.getMMI().getContext().createTempSymbol("annotation", true); 7001 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 7002 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 7003 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 7004 DAG.setRoot(Res); 7005 return; 7006 } 7007 7008 case Intrinsic::init_trampoline: { 7009 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 7010 7011 SDValue Ops[6]; 7012 Ops[0] = getRoot(); 7013 Ops[1] = getValue(I.getArgOperand(0)); 7014 Ops[2] = getValue(I.getArgOperand(1)); 7015 Ops[3] = getValue(I.getArgOperand(2)); 7016 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 7017 Ops[5] = DAG.getSrcValue(F); 7018 7019 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 7020 7021 DAG.setRoot(Res); 7022 return; 7023 } 7024 case Intrinsic::adjust_trampoline: 7025 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 7026 TLI.getPointerTy(DAG.getDataLayout()), 7027 getValue(I.getArgOperand(0)))); 7028 return; 7029 case Intrinsic::gcroot: { 7030 assert(DAG.getMachineFunction().getFunction().hasGC() && 7031 "only valid in functions with gc specified, enforced by Verifier"); 7032 assert(GFI && "implied by previous"); 7033 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 7034 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 7035 7036 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 7037 GFI->addStackRoot(FI->getIndex(), TypeMap); 7038 return; 7039 } 7040 case Intrinsic::gcread: 7041 case Intrinsic::gcwrite: 7042 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 7043 case Intrinsic::get_rounding: 7044 Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot()); 7045 setValue(&I, Res); 7046 DAG.setRoot(Res.getValue(1)); 7047 return; 7048 7049 case Intrinsic::expect: 7050 // Just replace __builtin_expect(exp, c) with EXP. 7051 setValue(&I, getValue(I.getArgOperand(0))); 7052 return; 7053 7054 case Intrinsic::ubsantrap: 7055 case Intrinsic::debugtrap: 7056 case Intrinsic::trap: { 7057 StringRef TrapFuncName = 7058 I.getAttributes().getFnAttr("trap-func-name").getValueAsString(); 7059 if (TrapFuncName.empty()) { 7060 switch (Intrinsic) { 7061 case Intrinsic::trap: 7062 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 7063 break; 7064 case Intrinsic::debugtrap: 7065 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 7066 break; 7067 case Intrinsic::ubsantrap: 7068 DAG.setRoot(DAG.getNode( 7069 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 7070 DAG.getTargetConstant( 7071 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 7072 MVT::i32))); 7073 break; 7074 default: llvm_unreachable("unknown trap intrinsic"); 7075 } 7076 return; 7077 } 7078 TargetLowering::ArgListTy Args; 7079 if (Intrinsic == Intrinsic::ubsantrap) { 7080 Args.push_back(TargetLoweringBase::ArgListEntry()); 7081 Args[0].Val = I.getArgOperand(0); 7082 Args[0].Node = getValue(Args[0].Val); 7083 Args[0].Ty = Args[0].Val->getType(); 7084 } 7085 7086 TargetLowering::CallLoweringInfo CLI(DAG); 7087 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 7088 CallingConv::C, I.getType(), 7089 DAG.getExternalSymbol(TrapFuncName.data(), 7090 TLI.getPointerTy(DAG.getDataLayout())), 7091 std::move(Args)); 7092 7093 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7094 DAG.setRoot(Result.second); 7095 return; 7096 } 7097 7098 case Intrinsic::uadd_with_overflow: 7099 case Intrinsic::sadd_with_overflow: 7100 case Intrinsic::usub_with_overflow: 7101 case Intrinsic::ssub_with_overflow: 7102 case Intrinsic::umul_with_overflow: 7103 case Intrinsic::smul_with_overflow: { 7104 ISD::NodeType Op; 7105 switch (Intrinsic) { 7106 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7107 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 7108 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 7109 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 7110 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 7111 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 7112 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 7113 } 7114 SDValue Op1 = getValue(I.getArgOperand(0)); 7115 SDValue Op2 = getValue(I.getArgOperand(1)); 7116 7117 EVT ResultVT = Op1.getValueType(); 7118 EVT OverflowVT = MVT::i1; 7119 if (ResultVT.isVector()) 7120 OverflowVT = EVT::getVectorVT( 7121 *Context, OverflowVT, ResultVT.getVectorElementCount()); 7122 7123 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 7124 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 7125 return; 7126 } 7127 case Intrinsic::prefetch: { 7128 SDValue Ops[5]; 7129 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 7130 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 7131 Ops[0] = DAG.getRoot(); 7132 Ops[1] = getValue(I.getArgOperand(0)); 7133 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 7134 MVT::i32); 7135 Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl, 7136 MVT::i32); 7137 Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl, 7138 MVT::i32); 7139 SDValue Result = DAG.getMemIntrinsicNode( 7140 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 7141 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 7142 /* align */ std::nullopt, Flags); 7143 7144 // Chain the prefetch in parallel with any pending loads, to stay out of 7145 // the way of later optimizations. 7146 PendingLoads.push_back(Result); 7147 Result = getRoot(); 7148 DAG.setRoot(Result); 7149 return; 7150 } 7151 case Intrinsic::lifetime_start: 7152 case Intrinsic::lifetime_end: { 7153 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 7154 // Stack coloring is not enabled in O0, discard region information. 7155 if (TM.getOptLevel() == CodeGenOptLevel::None) 7156 return; 7157 7158 const int64_t ObjectSize = 7159 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 7160 Value *const ObjectPtr = I.getArgOperand(1); 7161 SmallVector<const Value *, 4> Allocas; 7162 getUnderlyingObjects(ObjectPtr, Allocas); 7163 7164 for (const Value *Alloca : Allocas) { 7165 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 7166 7167 // Could not find an Alloca. 7168 if (!LifetimeObject) 7169 continue; 7170 7171 // First check that the Alloca is static, otherwise it won't have a 7172 // valid frame index. 7173 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 7174 if (SI == FuncInfo.StaticAllocaMap.end()) 7175 return; 7176 7177 const int FrameIndex = SI->second; 7178 int64_t Offset; 7179 if (GetPointerBaseWithConstantOffset( 7180 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 7181 Offset = -1; // Cannot determine offset from alloca to lifetime object. 7182 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 7183 Offset); 7184 DAG.setRoot(Res); 7185 } 7186 return; 7187 } 7188 case Intrinsic::pseudoprobe: { 7189 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 7190 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 7191 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 7192 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 7193 DAG.setRoot(Res); 7194 return; 7195 } 7196 case Intrinsic::invariant_start: 7197 // Discard region information. 7198 setValue(&I, 7199 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType()))); 7200 return; 7201 case Intrinsic::invariant_end: 7202 // Discard region information. 7203 return; 7204 case Intrinsic::clear_cache: 7205 /// FunctionName may be null. 7206 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 7207 lowerCallToExternalSymbol(I, FunctionName); 7208 return; 7209 case Intrinsic::donothing: 7210 case Intrinsic::seh_try_begin: 7211 case Intrinsic::seh_scope_begin: 7212 case Intrinsic::seh_try_end: 7213 case Intrinsic::seh_scope_end: 7214 // ignore 7215 return; 7216 case Intrinsic::experimental_stackmap: 7217 visitStackmap(I); 7218 return; 7219 case Intrinsic::experimental_patchpoint_void: 7220 case Intrinsic::experimental_patchpoint_i64: 7221 visitPatchpoint(I); 7222 return; 7223 case Intrinsic::experimental_gc_statepoint: 7224 LowerStatepoint(cast<GCStatepointInst>(I)); 7225 return; 7226 case Intrinsic::experimental_gc_result: 7227 visitGCResult(cast<GCResultInst>(I)); 7228 return; 7229 case Intrinsic::experimental_gc_relocate: 7230 visitGCRelocate(cast<GCRelocateInst>(I)); 7231 return; 7232 case Intrinsic::instrprof_cover: 7233 llvm_unreachable("instrprof failed to lower a cover"); 7234 case Intrinsic::instrprof_increment: 7235 llvm_unreachable("instrprof failed to lower an increment"); 7236 case Intrinsic::instrprof_timestamp: 7237 llvm_unreachable("instrprof failed to lower a timestamp"); 7238 case Intrinsic::instrprof_value_profile: 7239 llvm_unreachable("instrprof failed to lower a value profiling call"); 7240 case Intrinsic::instrprof_mcdc_parameters: 7241 llvm_unreachable("instrprof failed to lower mcdc parameters"); 7242 case Intrinsic::instrprof_mcdc_tvbitmap_update: 7243 llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update"); 7244 case Intrinsic::instrprof_mcdc_condbitmap_update: 7245 llvm_unreachable("instrprof failed to lower an mcdc condbitmap update"); 7246 case Intrinsic::localescape: { 7247 MachineFunction &MF = DAG.getMachineFunction(); 7248 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 7249 7250 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 7251 // is the same on all targets. 7252 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) { 7253 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 7254 if (isa<ConstantPointerNull>(Arg)) 7255 continue; // Skip null pointers. They represent a hole in index space. 7256 AllocaInst *Slot = cast<AllocaInst>(Arg); 7257 assert(FuncInfo.StaticAllocaMap.count(Slot) && 7258 "can only escape static allocas"); 7259 int FI = FuncInfo.StaticAllocaMap[Slot]; 7260 MCSymbol *FrameAllocSym = 7261 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7262 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 7263 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 7264 TII->get(TargetOpcode::LOCAL_ESCAPE)) 7265 .addSym(FrameAllocSym) 7266 .addFrameIndex(FI); 7267 } 7268 7269 return; 7270 } 7271 7272 case Intrinsic::localrecover: { 7273 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 7274 MachineFunction &MF = DAG.getMachineFunction(); 7275 7276 // Get the symbol that defines the frame offset. 7277 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 7278 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 7279 unsigned IdxVal = 7280 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 7281 MCSymbol *FrameAllocSym = 7282 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7283 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 7284 7285 Value *FP = I.getArgOperand(1); 7286 SDValue FPVal = getValue(FP); 7287 EVT PtrVT = FPVal.getValueType(); 7288 7289 // Create a MCSymbol for the label to avoid any target lowering 7290 // that would make this PC relative. 7291 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 7292 SDValue OffsetVal = 7293 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 7294 7295 // Add the offset to the FP. 7296 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 7297 setValue(&I, Add); 7298 7299 return; 7300 } 7301 7302 case Intrinsic::eh_exceptionpointer: 7303 case Intrinsic::eh_exceptioncode: { 7304 // Get the exception pointer vreg, copy from it, and resize it to fit. 7305 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 7306 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 7307 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 7308 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 7309 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT); 7310 if (Intrinsic == Intrinsic::eh_exceptioncode) 7311 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32); 7312 setValue(&I, N); 7313 return; 7314 } 7315 case Intrinsic::xray_customevent: { 7316 // Here we want to make sure that the intrinsic behaves as if it has a 7317 // specific calling convention. 7318 const auto &Triple = DAG.getTarget().getTargetTriple(); 7319 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64) 7320 return; 7321 7322 SmallVector<SDValue, 8> Ops; 7323 7324 // We want to say that we always want the arguments in registers. 7325 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 7326 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 7327 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7328 SDValue Chain = getRoot(); 7329 Ops.push_back(LogEntryVal); 7330 Ops.push_back(StrSizeVal); 7331 Ops.push_back(Chain); 7332 7333 // We need to enforce the calling convention for the callsite, so that 7334 // argument ordering is enforced correctly, and that register allocation can 7335 // see that some registers may be assumed clobbered and have to preserve 7336 // them across calls to the intrinsic. 7337 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 7338 sdl, NodeTys, Ops); 7339 SDValue patchableNode = SDValue(MN, 0); 7340 DAG.setRoot(patchableNode); 7341 setValue(&I, patchableNode); 7342 return; 7343 } 7344 case Intrinsic::xray_typedevent: { 7345 // Here we want to make sure that the intrinsic behaves as if it has a 7346 // specific calling convention. 7347 const auto &Triple = DAG.getTarget().getTargetTriple(); 7348 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64) 7349 return; 7350 7351 SmallVector<SDValue, 8> Ops; 7352 7353 // We want to say that we always want the arguments in registers. 7354 // It's unclear to me how manipulating the selection DAG here forces callers 7355 // to provide arguments in registers instead of on the stack. 7356 SDValue LogTypeId = getValue(I.getArgOperand(0)); 7357 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 7358 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 7359 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7360 SDValue Chain = getRoot(); 7361 Ops.push_back(LogTypeId); 7362 Ops.push_back(LogEntryVal); 7363 Ops.push_back(StrSizeVal); 7364 Ops.push_back(Chain); 7365 7366 // We need to enforce the calling convention for the callsite, so that 7367 // argument ordering is enforced correctly, and that register allocation can 7368 // see that some registers may be assumed clobbered and have to preserve 7369 // them across calls to the intrinsic. 7370 MachineSDNode *MN = DAG.getMachineNode( 7371 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops); 7372 SDValue patchableNode = SDValue(MN, 0); 7373 DAG.setRoot(patchableNode); 7374 setValue(&I, patchableNode); 7375 return; 7376 } 7377 case Intrinsic::experimental_deoptimize: 7378 LowerDeoptimizeCall(&I); 7379 return; 7380 case Intrinsic::experimental_stepvector: 7381 visitStepVector(I); 7382 return; 7383 case Intrinsic::vector_reduce_fadd: 7384 case Intrinsic::vector_reduce_fmul: 7385 case Intrinsic::vector_reduce_add: 7386 case Intrinsic::vector_reduce_mul: 7387 case Intrinsic::vector_reduce_and: 7388 case Intrinsic::vector_reduce_or: 7389 case Intrinsic::vector_reduce_xor: 7390 case Intrinsic::vector_reduce_smax: 7391 case Intrinsic::vector_reduce_smin: 7392 case Intrinsic::vector_reduce_umax: 7393 case Intrinsic::vector_reduce_umin: 7394 case Intrinsic::vector_reduce_fmax: 7395 case Intrinsic::vector_reduce_fmin: 7396 case Intrinsic::vector_reduce_fmaximum: 7397 case Intrinsic::vector_reduce_fminimum: 7398 visitVectorReduce(I, Intrinsic); 7399 return; 7400 7401 case Intrinsic::icall_branch_funnel: { 7402 SmallVector<SDValue, 16> Ops; 7403 Ops.push_back(getValue(I.getArgOperand(0))); 7404 7405 int64_t Offset; 7406 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7407 I.getArgOperand(1), Offset, DAG.getDataLayout())); 7408 if (!Base) 7409 report_fatal_error( 7410 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7411 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0)); 7412 7413 struct BranchFunnelTarget { 7414 int64_t Offset; 7415 SDValue Target; 7416 }; 7417 SmallVector<BranchFunnelTarget, 8> Targets; 7418 7419 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) { 7420 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7421 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7422 if (ElemBase != Base) 7423 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7424 "to the same GlobalValue"); 7425 7426 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7427 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7428 if (!GA) 7429 report_fatal_error( 7430 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7431 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7432 GA->getGlobal(), sdl, Val.getValueType(), 7433 GA->getOffset())}); 7434 } 7435 llvm::sort(Targets, 7436 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7437 return T1.Offset < T2.Offset; 7438 }); 7439 7440 for (auto &T : Targets) { 7441 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32)); 7442 Ops.push_back(T.Target); 7443 } 7444 7445 Ops.push_back(DAG.getRoot()); // Chain 7446 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl, 7447 MVT::Other, Ops), 7448 0); 7449 DAG.setRoot(N); 7450 setValue(&I, N); 7451 HasTailCall = true; 7452 return; 7453 } 7454 7455 case Intrinsic::wasm_landingpad_index: 7456 // Information this intrinsic contained has been transferred to 7457 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7458 // delete it now. 7459 return; 7460 7461 case Intrinsic::aarch64_settag: 7462 case Intrinsic::aarch64_settag_zero: { 7463 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7464 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7465 SDValue Val = TSI.EmitTargetCodeForSetTag( 7466 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)), 7467 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7468 ZeroMemory); 7469 DAG.setRoot(Val); 7470 setValue(&I, Val); 7471 return; 7472 } 7473 case Intrinsic::amdgcn_cs_chain: { 7474 assert(I.arg_size() == 5 && "Additional args not supported yet"); 7475 assert(cast<ConstantInt>(I.getOperand(4))->isZero() && 7476 "Non-zero flags not supported yet"); 7477 7478 // At this point we don't care if it's amdgpu_cs_chain or 7479 // amdgpu_cs_chain_preserve. 7480 CallingConv::ID CC = CallingConv::AMDGPU_CS_Chain; 7481 7482 Type *RetTy = I.getType(); 7483 assert(RetTy->isVoidTy() && "Should not return"); 7484 7485 SDValue Callee = getValue(I.getOperand(0)); 7486 7487 // We only have 2 actual args: one for the SGPRs and one for the VGPRs. 7488 // We'll also tack the value of the EXEC mask at the end. 7489 TargetLowering::ArgListTy Args; 7490 Args.reserve(3); 7491 7492 for (unsigned Idx : {2, 3, 1}) { 7493 TargetLowering::ArgListEntry Arg; 7494 Arg.Node = getValue(I.getOperand(Idx)); 7495 Arg.Ty = I.getOperand(Idx)->getType(); 7496 Arg.setAttributes(&I, Idx); 7497 Args.push_back(Arg); 7498 } 7499 7500 assert(Args[0].IsInReg && "SGPR args should be marked inreg"); 7501 assert(!Args[1].IsInReg && "VGPR args should not be marked inreg"); 7502 Args[2].IsInReg = true; // EXEC should be inreg 7503 7504 TargetLowering::CallLoweringInfo CLI(DAG); 7505 CLI.setDebugLoc(getCurSDLoc()) 7506 .setChain(getRoot()) 7507 .setCallee(CC, RetTy, Callee, std::move(Args)) 7508 .setNoReturn(true) 7509 .setTailCall(true) 7510 .setConvergent(I.isConvergent()); 7511 CLI.CB = &I; 7512 std::pair<SDValue, SDValue> Result = 7513 lowerInvokable(CLI, /*EHPadBB*/ nullptr); 7514 (void)Result; 7515 assert(!Result.first.getNode() && !Result.second.getNode() && 7516 "Should've lowered as tail call"); 7517 7518 HasTailCall = true; 7519 return; 7520 } 7521 case Intrinsic::ptrmask: { 7522 SDValue Ptr = getValue(I.getOperand(0)); 7523 SDValue Mask = getValue(I.getOperand(1)); 7524 7525 EVT PtrVT = Ptr.getValueType(); 7526 assert(PtrVT == Mask.getValueType() && 7527 "Pointers with different index type are not supported by SDAG"); 7528 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask)); 7529 return; 7530 } 7531 case Intrinsic::threadlocal_address: { 7532 setValue(&I, getValue(I.getOperand(0))); 7533 return; 7534 } 7535 case Intrinsic::get_active_lane_mask: { 7536 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7537 SDValue Index = getValue(I.getOperand(0)); 7538 EVT ElementVT = Index.getValueType(); 7539 7540 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) { 7541 visitTargetIntrinsic(I, Intrinsic); 7542 return; 7543 } 7544 7545 SDValue TripCount = getValue(I.getOperand(1)); 7546 EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT, 7547 CCVT.getVectorElementCount()); 7548 7549 SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index); 7550 SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount); 7551 SDValue VectorStep = DAG.getStepVector(sdl, VecTy); 7552 SDValue VectorInduction = DAG.getNode( 7553 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep); 7554 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction, 7555 VectorTripCount, ISD::CondCode::SETULT); 7556 setValue(&I, SetCC); 7557 return; 7558 } 7559 case Intrinsic::experimental_get_vector_length: { 7560 assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 && 7561 "Expected positive VF"); 7562 unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue(); 7563 bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne(); 7564 7565 SDValue Count = getValue(I.getOperand(0)); 7566 EVT CountVT = Count.getValueType(); 7567 7568 if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) { 7569 visitTargetIntrinsic(I, Intrinsic); 7570 return; 7571 } 7572 7573 // Expand to a umin between the trip count and the maximum elements the type 7574 // can hold. 7575 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7576 7577 // Extend the trip count to at least the result VT. 7578 if (CountVT.bitsLT(VT)) { 7579 Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count); 7580 CountVT = VT; 7581 } 7582 7583 SDValue MaxEVL = DAG.getElementCount(sdl, CountVT, 7584 ElementCount::get(VF, IsScalable)); 7585 7586 SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL); 7587 // Clip to the result type if needed. 7588 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin); 7589 7590 setValue(&I, Trunc); 7591 return; 7592 } 7593 case Intrinsic::experimental_cttz_elts: { 7594 auto DL = getCurSDLoc(); 7595 SDValue Op = getValue(I.getOperand(0)); 7596 EVT OpVT = Op.getValueType(); 7597 7598 if (!TLI.shouldExpandCttzElements(OpVT)) { 7599 visitTargetIntrinsic(I, Intrinsic); 7600 return; 7601 } 7602 7603 if (OpVT.getScalarType() != MVT::i1) { 7604 // Compare the input vector elements to zero & use to count trailing zeros 7605 SDValue AllZero = DAG.getConstant(0, DL, OpVT); 7606 OpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, 7607 OpVT.getVectorElementCount()); 7608 Op = DAG.getSetCC(DL, OpVT, Op, AllZero, ISD::SETNE); 7609 } 7610 7611 // Find the smallest "sensible" element type to use for the expansion. 7612 ConstantRange CR( 7613 APInt(64, OpVT.getVectorElementCount().getKnownMinValue())); 7614 if (OpVT.isScalableVT()) 7615 CR = CR.umul_sat(getVScaleRange(I.getCaller(), 64)); 7616 7617 // If the zero-is-poison flag is set, we can assume the upper limit 7618 // of the result is VF-1. 7619 if (!cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero()) 7620 CR = CR.subtract(APInt(64, 1)); 7621 7622 unsigned EltWidth = I.getType()->getScalarSizeInBits(); 7623 EltWidth = std::min(EltWidth, (unsigned)CR.getActiveBits()); 7624 EltWidth = std::max(llvm::bit_ceil(EltWidth), (unsigned)8); 7625 7626 MVT NewEltTy = MVT::getIntegerVT(EltWidth); 7627 7628 // Create the new vector type & get the vector length 7629 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), NewEltTy, 7630 OpVT.getVectorElementCount()); 7631 7632 SDValue VL = 7633 DAG.getElementCount(DL, NewEltTy, OpVT.getVectorElementCount()); 7634 7635 SDValue StepVec = DAG.getStepVector(DL, NewVT); 7636 SDValue SplatVL = DAG.getSplat(NewVT, DL, VL); 7637 SDValue StepVL = DAG.getNode(ISD::SUB, DL, NewVT, SplatVL, StepVec); 7638 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, Op); 7639 SDValue And = DAG.getNode(ISD::AND, DL, NewVT, StepVL, Ext); 7640 SDValue Max = DAG.getNode(ISD::VECREDUCE_UMAX, DL, NewEltTy, And); 7641 SDValue Sub = DAG.getNode(ISD::SUB, DL, NewEltTy, VL, Max); 7642 7643 EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7644 SDValue Ret = DAG.getZExtOrTrunc(Sub, DL, RetTy); 7645 7646 setValue(&I, Ret); 7647 return; 7648 } 7649 case Intrinsic::vector_insert: { 7650 SDValue Vec = getValue(I.getOperand(0)); 7651 SDValue SubVec = getValue(I.getOperand(1)); 7652 SDValue Index = getValue(I.getOperand(2)); 7653 7654 // The intrinsic's index type is i64, but the SDNode requires an index type 7655 // suitable for the target. Convert the index as required. 7656 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7657 if (Index.getValueType() != VectorIdxTy) 7658 Index = DAG.getVectorIdxConstant( 7659 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7660 7661 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7662 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec, 7663 Index)); 7664 return; 7665 } 7666 case Intrinsic::vector_extract: { 7667 SDValue Vec = getValue(I.getOperand(0)); 7668 SDValue Index = getValue(I.getOperand(1)); 7669 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7670 7671 // The intrinsic's index type is i64, but the SDNode requires an index type 7672 // suitable for the target. Convert the index as required. 7673 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7674 if (Index.getValueType() != VectorIdxTy) 7675 Index = DAG.getVectorIdxConstant( 7676 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7677 7678 setValue(&I, 7679 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index)); 7680 return; 7681 } 7682 case Intrinsic::experimental_vector_reverse: 7683 visitVectorReverse(I); 7684 return; 7685 case Intrinsic::experimental_vector_splice: 7686 visitVectorSplice(I); 7687 return; 7688 case Intrinsic::callbr_landingpad: 7689 visitCallBrLandingPad(I); 7690 return; 7691 case Intrinsic::experimental_vector_interleave2: 7692 visitVectorInterleave(I); 7693 return; 7694 case Intrinsic::experimental_vector_deinterleave2: 7695 visitVectorDeinterleave(I); 7696 return; 7697 } 7698 } 7699 7700 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7701 const ConstrainedFPIntrinsic &FPI) { 7702 SDLoc sdl = getCurSDLoc(); 7703 7704 // We do not need to serialize constrained FP intrinsics against 7705 // each other or against (nonvolatile) loads, so they can be 7706 // chained like loads. 7707 SDValue Chain = DAG.getRoot(); 7708 SmallVector<SDValue, 4> Opers; 7709 Opers.push_back(Chain); 7710 if (FPI.isUnaryOp()) { 7711 Opers.push_back(getValue(FPI.getArgOperand(0))); 7712 } else if (FPI.isTernaryOp()) { 7713 Opers.push_back(getValue(FPI.getArgOperand(0))); 7714 Opers.push_back(getValue(FPI.getArgOperand(1))); 7715 Opers.push_back(getValue(FPI.getArgOperand(2))); 7716 } else { 7717 Opers.push_back(getValue(FPI.getArgOperand(0))); 7718 Opers.push_back(getValue(FPI.getArgOperand(1))); 7719 } 7720 7721 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7722 assert(Result.getNode()->getNumValues() == 2); 7723 7724 // Push node to the appropriate list so that future instructions can be 7725 // chained up correctly. 7726 SDValue OutChain = Result.getValue(1); 7727 switch (EB) { 7728 case fp::ExceptionBehavior::ebIgnore: 7729 // The only reason why ebIgnore nodes still need to be chained is that 7730 // they might depend on the current rounding mode, and therefore must 7731 // not be moved across instruction that may change that mode. 7732 [[fallthrough]]; 7733 case fp::ExceptionBehavior::ebMayTrap: 7734 // These must not be moved across calls or instructions that may change 7735 // floating-point exception masks. 7736 PendingConstrainedFP.push_back(OutChain); 7737 break; 7738 case fp::ExceptionBehavior::ebStrict: 7739 // These must not be moved across calls or instructions that may change 7740 // floating-point exception masks or read floating-point exception flags. 7741 // In addition, they cannot be optimized out even if unused. 7742 PendingConstrainedFPStrict.push_back(OutChain); 7743 break; 7744 } 7745 }; 7746 7747 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7748 EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType()); 7749 SDVTList VTs = DAG.getVTList(VT, MVT::Other); 7750 fp::ExceptionBehavior EB = *FPI.getExceptionBehavior(); 7751 7752 SDNodeFlags Flags; 7753 if (EB == fp::ExceptionBehavior::ebIgnore) 7754 Flags.setNoFPExcept(true); 7755 7756 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7757 Flags.copyFMF(*FPOp); 7758 7759 unsigned Opcode; 7760 switch (FPI.getIntrinsicID()) { 7761 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7762 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7763 case Intrinsic::INTRINSIC: \ 7764 Opcode = ISD::STRICT_##DAGN; \ 7765 break; 7766 #include "llvm/IR/ConstrainedOps.def" 7767 case Intrinsic::experimental_constrained_fmuladd: { 7768 Opcode = ISD::STRICT_FMA; 7769 // Break fmuladd into fmul and fadd. 7770 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7771 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 7772 Opers.pop_back(); 7773 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7774 pushOutChain(Mul, EB); 7775 Opcode = ISD::STRICT_FADD; 7776 Opers.clear(); 7777 Opers.push_back(Mul.getValue(1)); 7778 Opers.push_back(Mul.getValue(0)); 7779 Opers.push_back(getValue(FPI.getArgOperand(2))); 7780 } 7781 break; 7782 } 7783 } 7784 7785 // A few strict DAG nodes carry additional operands that are not 7786 // set up by the default code above. 7787 switch (Opcode) { 7788 default: break; 7789 case ISD::STRICT_FP_ROUND: 7790 Opers.push_back( 7791 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7792 break; 7793 case ISD::STRICT_FSETCC: 7794 case ISD::STRICT_FSETCCS: { 7795 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7796 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 7797 if (TM.Options.NoNaNsFPMath) 7798 Condition = getFCmpCodeWithoutNaN(Condition); 7799 Opers.push_back(DAG.getCondCode(Condition)); 7800 break; 7801 } 7802 } 7803 7804 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7805 pushOutChain(Result, EB); 7806 7807 SDValue FPResult = Result.getValue(0); 7808 setValue(&FPI, FPResult); 7809 } 7810 7811 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 7812 std::optional<unsigned> ResOPC; 7813 switch (VPIntrin.getIntrinsicID()) { 7814 case Intrinsic::vp_ctlz: { 7815 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 7816 ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ; 7817 break; 7818 } 7819 case Intrinsic::vp_cttz: { 7820 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 7821 ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ; 7822 break; 7823 } 7824 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \ 7825 case Intrinsic::VPID: \ 7826 ResOPC = ISD::VPSD; \ 7827 break; 7828 #include "llvm/IR/VPIntrinsics.def" 7829 } 7830 7831 if (!ResOPC) 7832 llvm_unreachable( 7833 "Inconsistency: no SDNode available for this VPIntrinsic!"); 7834 7835 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD || 7836 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) { 7837 if (VPIntrin.getFastMathFlags().allowReassoc()) 7838 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD 7839 : ISD::VP_REDUCE_FMUL; 7840 } 7841 7842 return *ResOPC; 7843 } 7844 7845 void SelectionDAGBuilder::visitVPLoad( 7846 const VPIntrinsic &VPIntrin, EVT VT, 7847 const SmallVectorImpl<SDValue> &OpValues) { 7848 SDLoc DL = getCurSDLoc(); 7849 Value *PtrOperand = VPIntrin.getArgOperand(0); 7850 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7851 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7852 const MDNode *Ranges = getRangeMetadata(VPIntrin); 7853 SDValue LD; 7854 // Do not serialize variable-length loads of constant memory with 7855 // anything. 7856 if (!Alignment) 7857 Alignment = DAG.getEVTAlign(VT); 7858 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7859 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7860 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7861 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7862 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7863 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7864 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2], 7865 MMO, false /*IsExpanding */); 7866 if (AddToChain) 7867 PendingLoads.push_back(LD.getValue(1)); 7868 setValue(&VPIntrin, LD); 7869 } 7870 7871 void SelectionDAGBuilder::visitVPGather( 7872 const VPIntrinsic &VPIntrin, EVT VT, 7873 const SmallVectorImpl<SDValue> &OpValues) { 7874 SDLoc DL = getCurSDLoc(); 7875 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7876 Value *PtrOperand = VPIntrin.getArgOperand(0); 7877 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7878 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7879 const MDNode *Ranges = getRangeMetadata(VPIntrin); 7880 SDValue LD; 7881 if (!Alignment) 7882 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7883 unsigned AS = 7884 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7885 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7886 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 7887 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7888 SDValue Base, Index, Scale; 7889 ISD::MemIndexType IndexType; 7890 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7891 this, VPIntrin.getParent(), 7892 VT.getScalarStoreSize()); 7893 if (!UniformBase) { 7894 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7895 Index = getValue(PtrOperand); 7896 IndexType = ISD::SIGNED_SCALED; 7897 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7898 } 7899 EVT IdxVT = Index.getValueType(); 7900 EVT EltTy = IdxVT.getVectorElementType(); 7901 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7902 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7903 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7904 } 7905 LD = DAG.getGatherVP( 7906 DAG.getVTList(VT, MVT::Other), VT, DL, 7907 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO, 7908 IndexType); 7909 PendingLoads.push_back(LD.getValue(1)); 7910 setValue(&VPIntrin, LD); 7911 } 7912 7913 void SelectionDAGBuilder::visitVPStore( 7914 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 7915 SDLoc DL = getCurSDLoc(); 7916 Value *PtrOperand = VPIntrin.getArgOperand(1); 7917 EVT VT = OpValues[0].getValueType(); 7918 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7919 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7920 SDValue ST; 7921 if (!Alignment) 7922 Alignment = DAG.getEVTAlign(VT); 7923 SDValue Ptr = OpValues[1]; 7924 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 7925 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7926 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7927 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7928 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset, 7929 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED, 7930 /* IsTruncating */ false, /*IsCompressing*/ false); 7931 DAG.setRoot(ST); 7932 setValue(&VPIntrin, ST); 7933 } 7934 7935 void SelectionDAGBuilder::visitVPScatter( 7936 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 7937 SDLoc DL = getCurSDLoc(); 7938 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7939 Value *PtrOperand = VPIntrin.getArgOperand(1); 7940 EVT VT = OpValues[0].getValueType(); 7941 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7942 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7943 SDValue ST; 7944 if (!Alignment) 7945 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7946 unsigned AS = 7947 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7948 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7949 MachinePointerInfo(AS), MachineMemOperand::MOStore, 7950 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7951 SDValue Base, Index, Scale; 7952 ISD::MemIndexType IndexType; 7953 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7954 this, VPIntrin.getParent(), 7955 VT.getScalarStoreSize()); 7956 if (!UniformBase) { 7957 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7958 Index = getValue(PtrOperand); 7959 IndexType = ISD::SIGNED_SCALED; 7960 Scale = 7961 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7962 } 7963 EVT IdxVT = Index.getValueType(); 7964 EVT EltTy = IdxVT.getVectorElementType(); 7965 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7966 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7967 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7968 } 7969 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL, 7970 {getMemoryRoot(), OpValues[0], Base, Index, Scale, 7971 OpValues[2], OpValues[3]}, 7972 MMO, IndexType); 7973 DAG.setRoot(ST); 7974 setValue(&VPIntrin, ST); 7975 } 7976 7977 void SelectionDAGBuilder::visitVPStridedLoad( 7978 const VPIntrinsic &VPIntrin, EVT VT, 7979 const SmallVectorImpl<SDValue> &OpValues) { 7980 SDLoc DL = getCurSDLoc(); 7981 Value *PtrOperand = VPIntrin.getArgOperand(0); 7982 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7983 if (!Alignment) 7984 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7985 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7986 const MDNode *Ranges = getRangeMetadata(VPIntrin); 7987 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7988 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7989 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7990 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7991 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7992 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7993 7994 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], 7995 OpValues[2], OpValues[3], MMO, 7996 false /*IsExpanding*/); 7997 7998 if (AddToChain) 7999 PendingLoads.push_back(LD.getValue(1)); 8000 setValue(&VPIntrin, LD); 8001 } 8002 8003 void SelectionDAGBuilder::visitVPStridedStore( 8004 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 8005 SDLoc DL = getCurSDLoc(); 8006 Value *PtrOperand = VPIntrin.getArgOperand(1); 8007 EVT VT = OpValues[0].getValueType(); 8008 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8009 if (!Alignment) 8010 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8011 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8012 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8013 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 8014 MemoryLocation::UnknownSize, *Alignment, AAInfo); 8015 8016 SDValue ST = DAG.getStridedStoreVP( 8017 getMemoryRoot(), DL, OpValues[0], OpValues[1], 8018 DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3], 8019 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false, 8020 /*IsCompressing*/ false); 8021 8022 DAG.setRoot(ST); 8023 setValue(&VPIntrin, ST); 8024 } 8025 8026 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) { 8027 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8028 SDLoc DL = getCurSDLoc(); 8029 8030 ISD::CondCode Condition; 8031 CmpInst::Predicate CondCode = VPIntrin.getPredicate(); 8032 bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy(); 8033 if (IsFP) { 8034 // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan) 8035 // flags, but calls that don't return floating-point types can't be 8036 // FPMathOperators, like vp.fcmp. This affects constrained fcmp too. 8037 Condition = getFCmpCondCode(CondCode); 8038 if (TM.Options.NoNaNsFPMath) 8039 Condition = getFCmpCodeWithoutNaN(Condition); 8040 } else { 8041 Condition = getICmpCondCode(CondCode); 8042 } 8043 8044 SDValue Op1 = getValue(VPIntrin.getOperand(0)); 8045 SDValue Op2 = getValue(VPIntrin.getOperand(1)); 8046 // #2 is the condition code 8047 SDValue MaskOp = getValue(VPIntrin.getOperand(3)); 8048 SDValue EVL = getValue(VPIntrin.getOperand(4)); 8049 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 8050 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 8051 "Unexpected target EVL type"); 8052 EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL); 8053 8054 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8055 VPIntrin.getType()); 8056 setValue(&VPIntrin, 8057 DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL)); 8058 } 8059 8060 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 8061 const VPIntrinsic &VPIntrin) { 8062 SDLoc DL = getCurSDLoc(); 8063 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 8064 8065 auto IID = VPIntrin.getIntrinsicID(); 8066 8067 if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin)) 8068 return visitVPCmp(*CmpI); 8069 8070 SmallVector<EVT, 4> ValueVTs; 8071 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8072 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 8073 SDVTList VTs = DAG.getVTList(ValueVTs); 8074 8075 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID); 8076 8077 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 8078 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 8079 "Unexpected target EVL type"); 8080 8081 // Request operands. 8082 SmallVector<SDValue, 7> OpValues; 8083 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) { 8084 auto Op = getValue(VPIntrin.getArgOperand(I)); 8085 if (I == EVLParamPos) 8086 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op); 8087 OpValues.push_back(Op); 8088 } 8089 8090 switch (Opcode) { 8091 default: { 8092 SDNodeFlags SDFlags; 8093 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 8094 SDFlags.copyFMF(*FPMO); 8095 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags); 8096 setValue(&VPIntrin, Result); 8097 break; 8098 } 8099 case ISD::VP_LOAD: 8100 visitVPLoad(VPIntrin, ValueVTs[0], OpValues); 8101 break; 8102 case ISD::VP_GATHER: 8103 visitVPGather(VPIntrin, ValueVTs[0], OpValues); 8104 break; 8105 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: 8106 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues); 8107 break; 8108 case ISD::VP_STORE: 8109 visitVPStore(VPIntrin, OpValues); 8110 break; 8111 case ISD::VP_SCATTER: 8112 visitVPScatter(VPIntrin, OpValues); 8113 break; 8114 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: 8115 visitVPStridedStore(VPIntrin, OpValues); 8116 break; 8117 case ISD::VP_FMULADD: { 8118 assert(OpValues.size() == 5 && "Unexpected number of operands"); 8119 SDNodeFlags SDFlags; 8120 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 8121 SDFlags.copyFMF(*FPMO); 8122 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 8123 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) { 8124 setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags)); 8125 } else { 8126 SDValue Mul = DAG.getNode( 8127 ISD::VP_FMUL, DL, VTs, 8128 {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags); 8129 SDValue Add = 8130 DAG.getNode(ISD::VP_FADD, DL, VTs, 8131 {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags); 8132 setValue(&VPIntrin, Add); 8133 } 8134 break; 8135 } 8136 case ISD::VP_IS_FPCLASS: { 8137 const DataLayout DLayout = DAG.getDataLayout(); 8138 EVT DestVT = TLI.getValueType(DLayout, VPIntrin.getType()); 8139 auto Constant = cast<ConstantSDNode>(OpValues[1])->getZExtValue(); 8140 SDValue Check = DAG.getTargetConstant(Constant, DL, MVT::i32); 8141 SDValue V = DAG.getNode(ISD::VP_IS_FPCLASS, DL, DestVT, 8142 {OpValues[0], Check, OpValues[2], OpValues[3]}); 8143 setValue(&VPIntrin, V); 8144 return; 8145 } 8146 case ISD::VP_INTTOPTR: { 8147 SDValue N = OpValues[0]; 8148 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType()); 8149 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType()); 8150 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 8151 OpValues[2]); 8152 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 8153 OpValues[2]); 8154 setValue(&VPIntrin, N); 8155 break; 8156 } 8157 case ISD::VP_PTRTOINT: { 8158 SDValue N = OpValues[0]; 8159 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8160 VPIntrin.getType()); 8161 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), 8162 VPIntrin.getOperand(0)->getType()); 8163 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 8164 OpValues[2]); 8165 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 8166 OpValues[2]); 8167 setValue(&VPIntrin, N); 8168 break; 8169 } 8170 case ISD::VP_ABS: 8171 case ISD::VP_CTLZ: 8172 case ISD::VP_CTLZ_ZERO_UNDEF: 8173 case ISD::VP_CTTZ: 8174 case ISD::VP_CTTZ_ZERO_UNDEF: { 8175 SDValue Result = 8176 DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]}); 8177 setValue(&VPIntrin, Result); 8178 break; 8179 } 8180 } 8181 } 8182 8183 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 8184 const BasicBlock *EHPadBB, 8185 MCSymbol *&BeginLabel) { 8186 MachineFunction &MF = DAG.getMachineFunction(); 8187 MachineModuleInfo &MMI = MF.getMMI(); 8188 8189 // Insert a label before the invoke call to mark the try range. This can be 8190 // used to detect deletion of the invoke via the MachineModuleInfo. 8191 BeginLabel = MMI.getContext().createTempSymbol(); 8192 8193 // For SjLj, keep track of which landing pads go with which invokes 8194 // so as to maintain the ordering of pads in the LSDA. 8195 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 8196 if (CallSiteIndex) { 8197 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 8198 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 8199 8200 // Now that the call site is handled, stop tracking it. 8201 MMI.setCurrentCallSite(0); 8202 } 8203 8204 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 8205 } 8206 8207 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 8208 const BasicBlock *EHPadBB, 8209 MCSymbol *BeginLabel) { 8210 assert(BeginLabel && "BeginLabel should've been set"); 8211 8212 MachineFunction &MF = DAG.getMachineFunction(); 8213 MachineModuleInfo &MMI = MF.getMMI(); 8214 8215 // Insert a label at the end of the invoke call to mark the try range. This 8216 // can be used to detect deletion of the invoke via the MachineModuleInfo. 8217 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 8218 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 8219 8220 // Inform MachineModuleInfo of range. 8221 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 8222 // There is a platform (e.g. wasm) that uses funclet style IR but does not 8223 // actually use outlined funclets and their LSDA info style. 8224 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 8225 assert(II && "II should've been set"); 8226 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 8227 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 8228 } else if (!isScopedEHPersonality(Pers)) { 8229 assert(EHPadBB); 8230 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 8231 } 8232 8233 return Chain; 8234 } 8235 8236 std::pair<SDValue, SDValue> 8237 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 8238 const BasicBlock *EHPadBB) { 8239 MCSymbol *BeginLabel = nullptr; 8240 8241 if (EHPadBB) { 8242 // Both PendingLoads and PendingExports must be flushed here; 8243 // this call might not return. 8244 (void)getRoot(); 8245 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 8246 CLI.setChain(getRoot()); 8247 } 8248 8249 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8250 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 8251 8252 assert((CLI.IsTailCall || Result.second.getNode()) && 8253 "Non-null chain expected with non-tail call!"); 8254 assert((Result.second.getNode() || !Result.first.getNode()) && 8255 "Null value expected with tail call!"); 8256 8257 if (!Result.second.getNode()) { 8258 // As a special case, a null chain means that a tail call has been emitted 8259 // and the DAG root is already updated. 8260 HasTailCall = true; 8261 8262 // Since there's no actual continuation from this block, nothing can be 8263 // relying on us setting vregs for them. 8264 PendingExports.clear(); 8265 } else { 8266 DAG.setRoot(Result.second); 8267 } 8268 8269 if (EHPadBB) { 8270 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 8271 BeginLabel)); 8272 } 8273 8274 return Result; 8275 } 8276 8277 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 8278 bool isTailCall, 8279 bool isMustTailCall, 8280 const BasicBlock *EHPadBB) { 8281 auto &DL = DAG.getDataLayout(); 8282 FunctionType *FTy = CB.getFunctionType(); 8283 Type *RetTy = CB.getType(); 8284 8285 TargetLowering::ArgListTy Args; 8286 Args.reserve(CB.arg_size()); 8287 8288 const Value *SwiftErrorVal = nullptr; 8289 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8290 8291 if (isTailCall) { 8292 // Avoid emitting tail calls in functions with the disable-tail-calls 8293 // attribute. 8294 auto *Caller = CB.getParent()->getParent(); 8295 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 8296 "true" && !isMustTailCall) 8297 isTailCall = false; 8298 8299 // We can't tail call inside a function with a swifterror argument. Lowering 8300 // does not support this yet. It would have to move into the swifterror 8301 // register before the call. 8302 if (TLI.supportSwiftError() && 8303 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 8304 isTailCall = false; 8305 } 8306 8307 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 8308 TargetLowering::ArgListEntry Entry; 8309 const Value *V = *I; 8310 8311 // Skip empty types 8312 if (V->getType()->isEmptyTy()) 8313 continue; 8314 8315 SDValue ArgNode = getValue(V); 8316 Entry.Node = ArgNode; Entry.Ty = V->getType(); 8317 8318 Entry.setAttributes(&CB, I - CB.arg_begin()); 8319 8320 // Use swifterror virtual register as input to the call. 8321 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 8322 SwiftErrorVal = V; 8323 // We find the virtual register for the actual swifterror argument. 8324 // Instead of using the Value, we use the virtual register instead. 8325 Entry.Node = 8326 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 8327 EVT(TLI.getPointerTy(DL))); 8328 } 8329 8330 Args.push_back(Entry); 8331 8332 // If we have an explicit sret argument that is an Instruction, (i.e., it 8333 // might point to function-local memory), we can't meaningfully tail-call. 8334 if (Entry.IsSRet && isa<Instruction>(V)) 8335 isTailCall = false; 8336 } 8337 8338 // If call site has a cfguardtarget operand bundle, create and add an 8339 // additional ArgListEntry. 8340 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 8341 TargetLowering::ArgListEntry Entry; 8342 Value *V = Bundle->Inputs[0]; 8343 SDValue ArgNode = getValue(V); 8344 Entry.Node = ArgNode; 8345 Entry.Ty = V->getType(); 8346 Entry.IsCFGuardTarget = true; 8347 Args.push_back(Entry); 8348 } 8349 8350 // Check if target-independent constraints permit a tail call here. 8351 // Target-dependent constraints are checked within TLI->LowerCallTo. 8352 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 8353 isTailCall = false; 8354 8355 // Disable tail calls if there is an swifterror argument. Targets have not 8356 // been updated to support tail calls. 8357 if (TLI.supportSwiftError() && SwiftErrorVal) 8358 isTailCall = false; 8359 8360 ConstantInt *CFIType = nullptr; 8361 if (CB.isIndirectCall()) { 8362 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) { 8363 if (!TLI.supportKCFIBundles()) 8364 report_fatal_error( 8365 "Target doesn't support calls with kcfi operand bundles."); 8366 CFIType = cast<ConstantInt>(Bundle->Inputs[0]); 8367 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type"); 8368 } 8369 } 8370 8371 TargetLowering::CallLoweringInfo CLI(DAG); 8372 CLI.setDebugLoc(getCurSDLoc()) 8373 .setChain(getRoot()) 8374 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 8375 .setTailCall(isTailCall) 8376 .setConvergent(CB.isConvergent()) 8377 .setIsPreallocated( 8378 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0) 8379 .setCFIType(CFIType); 8380 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8381 8382 if (Result.first.getNode()) { 8383 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 8384 setValue(&CB, Result.first); 8385 } 8386 8387 // The last element of CLI.InVals has the SDValue for swifterror return. 8388 // Here we copy it to a virtual register and update SwiftErrorMap for 8389 // book-keeping. 8390 if (SwiftErrorVal && TLI.supportSwiftError()) { 8391 // Get the last element of InVals. 8392 SDValue Src = CLI.InVals.back(); 8393 Register VReg = 8394 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 8395 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 8396 DAG.setRoot(CopyNode); 8397 } 8398 } 8399 8400 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 8401 SelectionDAGBuilder &Builder) { 8402 // Check to see if this load can be trivially constant folded, e.g. if the 8403 // input is from a string literal. 8404 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 8405 // Cast pointer to the type we really want to load. 8406 Type *LoadTy = 8407 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 8408 if (LoadVT.isVector()) 8409 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 8410 8411 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 8412 PointerType::getUnqual(LoadTy)); 8413 8414 if (const Constant *LoadCst = 8415 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput), 8416 LoadTy, Builder.DAG.getDataLayout())) 8417 return Builder.getValue(LoadCst); 8418 } 8419 8420 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 8421 // still constant memory, the input chain can be the entry node. 8422 SDValue Root; 8423 bool ConstantMemory = false; 8424 8425 // Do not serialize (non-volatile) loads of constant memory with anything. 8426 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 8427 Root = Builder.DAG.getEntryNode(); 8428 ConstantMemory = true; 8429 } else { 8430 // Do not serialize non-volatile loads against each other. 8431 Root = Builder.DAG.getRoot(); 8432 } 8433 8434 SDValue Ptr = Builder.getValue(PtrVal); 8435 SDValue LoadVal = 8436 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 8437 MachinePointerInfo(PtrVal), Align(1)); 8438 8439 if (!ConstantMemory) 8440 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 8441 return LoadVal; 8442 } 8443 8444 /// Record the value for an instruction that produces an integer result, 8445 /// converting the type where necessary. 8446 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 8447 SDValue Value, 8448 bool IsSigned) { 8449 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8450 I.getType(), true); 8451 Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT); 8452 setValue(&I, Value); 8453 } 8454 8455 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 8456 /// true and lower it. Otherwise return false, and it will be lowered like a 8457 /// normal call. 8458 /// The caller already checked that \p I calls the appropriate LibFunc with a 8459 /// correct prototype. 8460 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 8461 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 8462 const Value *Size = I.getArgOperand(2); 8463 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size)); 8464 if (CSize && CSize->getZExtValue() == 0) { 8465 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8466 I.getType(), true); 8467 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 8468 return true; 8469 } 8470 8471 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8472 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 8473 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 8474 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 8475 if (Res.first.getNode()) { 8476 processIntegerCallValue(I, Res.first, true); 8477 PendingLoads.push_back(Res.second); 8478 return true; 8479 } 8480 8481 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 8482 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 8483 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 8484 return false; 8485 8486 // If the target has a fast compare for the given size, it will return a 8487 // preferred load type for that size. Require that the load VT is legal and 8488 // that the target supports unaligned loads of that type. Otherwise, return 8489 // INVALID. 8490 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 8491 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8492 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 8493 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 8494 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 8495 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 8496 // TODO: Check alignment of src and dest ptrs. 8497 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 8498 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 8499 if (!TLI.isTypeLegal(LVT) || 8500 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 8501 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 8502 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 8503 } 8504 8505 return LVT; 8506 }; 8507 8508 // This turns into unaligned loads. We only do this if the target natively 8509 // supports the MVT we'll be loading or if it is small enough (<= 4) that 8510 // we'll only produce a small number of byte loads. 8511 MVT LoadVT; 8512 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 8513 switch (NumBitsToCompare) { 8514 default: 8515 return false; 8516 case 16: 8517 LoadVT = MVT::i16; 8518 break; 8519 case 32: 8520 LoadVT = MVT::i32; 8521 break; 8522 case 64: 8523 case 128: 8524 case 256: 8525 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 8526 break; 8527 } 8528 8529 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 8530 return false; 8531 8532 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 8533 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 8534 8535 // Bitcast to a wide integer type if the loads are vectors. 8536 if (LoadVT.isVector()) { 8537 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 8538 LoadL = DAG.getBitcast(CmpVT, LoadL); 8539 LoadR = DAG.getBitcast(CmpVT, LoadR); 8540 } 8541 8542 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 8543 processIntegerCallValue(I, Cmp, false); 8544 return true; 8545 } 8546 8547 /// See if we can lower a memchr call into an optimized form. If so, return 8548 /// true and lower it. Otherwise return false, and it will be lowered like a 8549 /// normal call. 8550 /// The caller already checked that \p I calls the appropriate LibFunc with a 8551 /// correct prototype. 8552 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 8553 const Value *Src = I.getArgOperand(0); 8554 const Value *Char = I.getArgOperand(1); 8555 const Value *Length = I.getArgOperand(2); 8556 8557 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8558 std::pair<SDValue, SDValue> Res = 8559 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 8560 getValue(Src), getValue(Char), getValue(Length), 8561 MachinePointerInfo(Src)); 8562 if (Res.first.getNode()) { 8563 setValue(&I, Res.first); 8564 PendingLoads.push_back(Res.second); 8565 return true; 8566 } 8567 8568 return false; 8569 } 8570 8571 /// See if we can lower a mempcpy call into an optimized form. If so, return 8572 /// true and lower it. Otherwise return false, and it will be lowered like a 8573 /// normal call. 8574 /// The caller already checked that \p I calls the appropriate LibFunc with a 8575 /// correct prototype. 8576 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 8577 SDValue Dst = getValue(I.getArgOperand(0)); 8578 SDValue Src = getValue(I.getArgOperand(1)); 8579 SDValue Size = getValue(I.getArgOperand(2)); 8580 8581 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 8582 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 8583 // DAG::getMemcpy needs Alignment to be defined. 8584 Align Alignment = std::min(DstAlign, SrcAlign); 8585 8586 SDLoc sdl = getCurSDLoc(); 8587 8588 // In the mempcpy context we need to pass in a false value for isTailCall 8589 // because the return pointer needs to be adjusted by the size of 8590 // the copied memory. 8591 SDValue Root = getMemoryRoot(); 8592 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, false, false, 8593 /*isTailCall=*/false, 8594 MachinePointerInfo(I.getArgOperand(0)), 8595 MachinePointerInfo(I.getArgOperand(1)), 8596 I.getAAMetadata()); 8597 assert(MC.getNode() != nullptr && 8598 "** memcpy should not be lowered as TailCall in mempcpy context **"); 8599 DAG.setRoot(MC); 8600 8601 // Check if Size needs to be truncated or extended. 8602 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 8603 8604 // Adjust return pointer to point just past the last dst byte. 8605 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 8606 Dst, Size); 8607 setValue(&I, DstPlusSize); 8608 return true; 8609 } 8610 8611 /// See if we can lower a strcpy call into an optimized form. If so, return 8612 /// true and lower it, otherwise return false and it will be lowered like a 8613 /// normal call. 8614 /// The caller already checked that \p I calls the appropriate LibFunc with a 8615 /// correct prototype. 8616 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 8617 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8618 8619 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8620 std::pair<SDValue, SDValue> Res = 8621 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 8622 getValue(Arg0), getValue(Arg1), 8623 MachinePointerInfo(Arg0), 8624 MachinePointerInfo(Arg1), isStpcpy); 8625 if (Res.first.getNode()) { 8626 setValue(&I, Res.first); 8627 DAG.setRoot(Res.second); 8628 return true; 8629 } 8630 8631 return false; 8632 } 8633 8634 /// See if we can lower a strcmp call into an optimized form. If so, return 8635 /// true and lower it, otherwise return false and it will be lowered like a 8636 /// normal call. 8637 /// The caller already checked that \p I calls the appropriate LibFunc with a 8638 /// correct prototype. 8639 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 8640 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8641 8642 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8643 std::pair<SDValue, SDValue> Res = 8644 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 8645 getValue(Arg0), getValue(Arg1), 8646 MachinePointerInfo(Arg0), 8647 MachinePointerInfo(Arg1)); 8648 if (Res.first.getNode()) { 8649 processIntegerCallValue(I, Res.first, true); 8650 PendingLoads.push_back(Res.second); 8651 return true; 8652 } 8653 8654 return false; 8655 } 8656 8657 /// See if we can lower a strlen call into an optimized form. If so, return 8658 /// true and lower it, otherwise return false and it will be lowered like a 8659 /// normal call. 8660 /// The caller already checked that \p I calls the appropriate LibFunc with a 8661 /// correct prototype. 8662 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 8663 const Value *Arg0 = I.getArgOperand(0); 8664 8665 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8666 std::pair<SDValue, SDValue> Res = 8667 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 8668 getValue(Arg0), MachinePointerInfo(Arg0)); 8669 if (Res.first.getNode()) { 8670 processIntegerCallValue(I, Res.first, false); 8671 PendingLoads.push_back(Res.second); 8672 return true; 8673 } 8674 8675 return false; 8676 } 8677 8678 /// See if we can lower a strnlen call into an optimized form. If so, return 8679 /// true and lower it, otherwise return false and it will be lowered like a 8680 /// normal call. 8681 /// The caller already checked that \p I calls the appropriate LibFunc with a 8682 /// correct prototype. 8683 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 8684 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8685 8686 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8687 std::pair<SDValue, SDValue> Res = 8688 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 8689 getValue(Arg0), getValue(Arg1), 8690 MachinePointerInfo(Arg0)); 8691 if (Res.first.getNode()) { 8692 processIntegerCallValue(I, Res.first, false); 8693 PendingLoads.push_back(Res.second); 8694 return true; 8695 } 8696 8697 return false; 8698 } 8699 8700 /// See if we can lower a unary floating-point operation into an SDNode with 8701 /// the specified Opcode. If so, return true and lower it, otherwise return 8702 /// false and it will be lowered like a normal call. 8703 /// The caller already checked that \p I calls the appropriate LibFunc with a 8704 /// correct prototype. 8705 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 8706 unsigned Opcode) { 8707 // We already checked this call's prototype; verify it doesn't modify errno. 8708 if (!I.onlyReadsMemory()) 8709 return false; 8710 8711 SDNodeFlags Flags; 8712 Flags.copyFMF(cast<FPMathOperator>(I)); 8713 8714 SDValue Tmp = getValue(I.getArgOperand(0)); 8715 setValue(&I, 8716 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 8717 return true; 8718 } 8719 8720 /// See if we can lower a binary floating-point operation into an SDNode with 8721 /// the specified Opcode. If so, return true and lower it. Otherwise return 8722 /// false, and it will be lowered like a normal call. 8723 /// The caller already checked that \p I calls the appropriate LibFunc with a 8724 /// correct prototype. 8725 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 8726 unsigned Opcode) { 8727 // We already checked this call's prototype; verify it doesn't modify errno. 8728 if (!I.onlyReadsMemory()) 8729 return false; 8730 8731 SDNodeFlags Flags; 8732 Flags.copyFMF(cast<FPMathOperator>(I)); 8733 8734 SDValue Tmp0 = getValue(I.getArgOperand(0)); 8735 SDValue Tmp1 = getValue(I.getArgOperand(1)); 8736 EVT VT = Tmp0.getValueType(); 8737 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 8738 return true; 8739 } 8740 8741 void SelectionDAGBuilder::visitCall(const CallInst &I) { 8742 // Handle inline assembly differently. 8743 if (I.isInlineAsm()) { 8744 visitInlineAsm(I); 8745 return; 8746 } 8747 8748 diagnoseDontCall(I); 8749 8750 if (Function *F = I.getCalledFunction()) { 8751 if (F->isDeclaration()) { 8752 // Is this an LLVM intrinsic or a target-specific intrinsic? 8753 unsigned IID = F->getIntrinsicID(); 8754 if (!IID) 8755 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 8756 IID = II->getIntrinsicID(F); 8757 8758 if (IID) { 8759 visitIntrinsicCall(I, IID); 8760 return; 8761 } 8762 } 8763 8764 // Check for well-known libc/libm calls. If the function is internal, it 8765 // can't be a library call. Don't do the check if marked as nobuiltin for 8766 // some reason or the call site requires strict floating point semantics. 8767 LibFunc Func; 8768 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 8769 F->hasName() && LibInfo->getLibFunc(*F, Func) && 8770 LibInfo->hasOptimizedCodeGen(Func)) { 8771 switch (Func) { 8772 default: break; 8773 case LibFunc_bcmp: 8774 if (visitMemCmpBCmpCall(I)) 8775 return; 8776 break; 8777 case LibFunc_copysign: 8778 case LibFunc_copysignf: 8779 case LibFunc_copysignl: 8780 // We already checked this call's prototype; verify it doesn't modify 8781 // errno. 8782 if (I.onlyReadsMemory()) { 8783 SDValue LHS = getValue(I.getArgOperand(0)); 8784 SDValue RHS = getValue(I.getArgOperand(1)); 8785 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 8786 LHS.getValueType(), LHS, RHS)); 8787 return; 8788 } 8789 break; 8790 case LibFunc_fabs: 8791 case LibFunc_fabsf: 8792 case LibFunc_fabsl: 8793 if (visitUnaryFloatCall(I, ISD::FABS)) 8794 return; 8795 break; 8796 case LibFunc_fmin: 8797 case LibFunc_fminf: 8798 case LibFunc_fminl: 8799 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 8800 return; 8801 break; 8802 case LibFunc_fmax: 8803 case LibFunc_fmaxf: 8804 case LibFunc_fmaxl: 8805 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 8806 return; 8807 break; 8808 case LibFunc_sin: 8809 case LibFunc_sinf: 8810 case LibFunc_sinl: 8811 if (visitUnaryFloatCall(I, ISD::FSIN)) 8812 return; 8813 break; 8814 case LibFunc_cos: 8815 case LibFunc_cosf: 8816 case LibFunc_cosl: 8817 if (visitUnaryFloatCall(I, ISD::FCOS)) 8818 return; 8819 break; 8820 case LibFunc_sqrt: 8821 case LibFunc_sqrtf: 8822 case LibFunc_sqrtl: 8823 case LibFunc_sqrt_finite: 8824 case LibFunc_sqrtf_finite: 8825 case LibFunc_sqrtl_finite: 8826 if (visitUnaryFloatCall(I, ISD::FSQRT)) 8827 return; 8828 break; 8829 case LibFunc_floor: 8830 case LibFunc_floorf: 8831 case LibFunc_floorl: 8832 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 8833 return; 8834 break; 8835 case LibFunc_nearbyint: 8836 case LibFunc_nearbyintf: 8837 case LibFunc_nearbyintl: 8838 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 8839 return; 8840 break; 8841 case LibFunc_ceil: 8842 case LibFunc_ceilf: 8843 case LibFunc_ceill: 8844 if (visitUnaryFloatCall(I, ISD::FCEIL)) 8845 return; 8846 break; 8847 case LibFunc_rint: 8848 case LibFunc_rintf: 8849 case LibFunc_rintl: 8850 if (visitUnaryFloatCall(I, ISD::FRINT)) 8851 return; 8852 break; 8853 case LibFunc_round: 8854 case LibFunc_roundf: 8855 case LibFunc_roundl: 8856 if (visitUnaryFloatCall(I, ISD::FROUND)) 8857 return; 8858 break; 8859 case LibFunc_trunc: 8860 case LibFunc_truncf: 8861 case LibFunc_truncl: 8862 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 8863 return; 8864 break; 8865 case LibFunc_log2: 8866 case LibFunc_log2f: 8867 case LibFunc_log2l: 8868 if (visitUnaryFloatCall(I, ISD::FLOG2)) 8869 return; 8870 break; 8871 case LibFunc_exp2: 8872 case LibFunc_exp2f: 8873 case LibFunc_exp2l: 8874 if (visitUnaryFloatCall(I, ISD::FEXP2)) 8875 return; 8876 break; 8877 case LibFunc_exp10: 8878 case LibFunc_exp10f: 8879 case LibFunc_exp10l: 8880 if (visitUnaryFloatCall(I, ISD::FEXP10)) 8881 return; 8882 break; 8883 case LibFunc_ldexp: 8884 case LibFunc_ldexpf: 8885 case LibFunc_ldexpl: 8886 if (visitBinaryFloatCall(I, ISD::FLDEXP)) 8887 return; 8888 break; 8889 case LibFunc_memcmp: 8890 if (visitMemCmpBCmpCall(I)) 8891 return; 8892 break; 8893 case LibFunc_mempcpy: 8894 if (visitMemPCpyCall(I)) 8895 return; 8896 break; 8897 case LibFunc_memchr: 8898 if (visitMemChrCall(I)) 8899 return; 8900 break; 8901 case LibFunc_strcpy: 8902 if (visitStrCpyCall(I, false)) 8903 return; 8904 break; 8905 case LibFunc_stpcpy: 8906 if (visitStrCpyCall(I, true)) 8907 return; 8908 break; 8909 case LibFunc_strcmp: 8910 if (visitStrCmpCall(I)) 8911 return; 8912 break; 8913 case LibFunc_strlen: 8914 if (visitStrLenCall(I)) 8915 return; 8916 break; 8917 case LibFunc_strnlen: 8918 if (visitStrNLenCall(I)) 8919 return; 8920 break; 8921 } 8922 } 8923 } 8924 8925 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 8926 // have to do anything here to lower funclet bundles. 8927 // CFGuardTarget bundles are lowered in LowerCallTo. 8928 assert(!I.hasOperandBundlesOtherThan( 8929 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 8930 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 8931 LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) && 8932 "Cannot lower calls with arbitrary operand bundles!"); 8933 8934 SDValue Callee = getValue(I.getCalledOperand()); 8935 8936 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 8937 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 8938 else 8939 // Check if we can potentially perform a tail call. More detailed checking 8940 // is be done within LowerCallTo, after more information about the call is 8941 // known. 8942 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 8943 } 8944 8945 namespace { 8946 8947 /// AsmOperandInfo - This contains information for each constraint that we are 8948 /// lowering. 8949 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 8950 public: 8951 /// CallOperand - If this is the result output operand or a clobber 8952 /// this is null, otherwise it is the incoming operand to the CallInst. 8953 /// This gets modified as the asm is processed. 8954 SDValue CallOperand; 8955 8956 /// AssignedRegs - If this is a register or register class operand, this 8957 /// contains the set of register corresponding to the operand. 8958 RegsForValue AssignedRegs; 8959 8960 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 8961 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 8962 } 8963 8964 /// Whether or not this operand accesses memory 8965 bool hasMemory(const TargetLowering &TLI) const { 8966 // Indirect operand accesses access memory. 8967 if (isIndirect) 8968 return true; 8969 8970 for (const auto &Code : Codes) 8971 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 8972 return true; 8973 8974 return false; 8975 } 8976 }; 8977 8978 8979 } // end anonymous namespace 8980 8981 /// Make sure that the output operand \p OpInfo and its corresponding input 8982 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 8983 /// out). 8984 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 8985 SDISelAsmOperandInfo &MatchingOpInfo, 8986 SelectionDAG &DAG) { 8987 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 8988 return; 8989 8990 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 8991 const auto &TLI = DAG.getTargetLoweringInfo(); 8992 8993 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 8994 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 8995 OpInfo.ConstraintVT); 8996 std::pair<unsigned, const TargetRegisterClass *> InputRC = 8997 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 8998 MatchingOpInfo.ConstraintVT); 8999 if ((OpInfo.ConstraintVT.isInteger() != 9000 MatchingOpInfo.ConstraintVT.isInteger()) || 9001 (MatchRC.second != InputRC.second)) { 9002 // FIXME: error out in a more elegant fashion 9003 report_fatal_error("Unsupported asm: input constraint" 9004 " with a matching output constraint of" 9005 " incompatible type!"); 9006 } 9007 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 9008 } 9009 9010 /// Get a direct memory input to behave well as an indirect operand. 9011 /// This may introduce stores, hence the need for a \p Chain. 9012 /// \return The (possibly updated) chain. 9013 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 9014 SDISelAsmOperandInfo &OpInfo, 9015 SelectionDAG &DAG) { 9016 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9017 9018 // If we don't have an indirect input, put it in the constpool if we can, 9019 // otherwise spill it to a stack slot. 9020 // TODO: This isn't quite right. We need to handle these according to 9021 // the addressing mode that the constraint wants. Also, this may take 9022 // an additional register for the computation and we don't want that 9023 // either. 9024 9025 // If the operand is a float, integer, or vector constant, spill to a 9026 // constant pool entry to get its address. 9027 const Value *OpVal = OpInfo.CallOperandVal; 9028 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 9029 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 9030 OpInfo.CallOperand = DAG.getConstantPool( 9031 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 9032 return Chain; 9033 } 9034 9035 // Otherwise, create a stack slot and emit a store to it before the asm. 9036 Type *Ty = OpVal->getType(); 9037 auto &DL = DAG.getDataLayout(); 9038 uint64_t TySize = DL.getTypeAllocSize(Ty); 9039 MachineFunction &MF = DAG.getMachineFunction(); 9040 int SSFI = MF.getFrameInfo().CreateStackObject( 9041 TySize, DL.getPrefTypeAlign(Ty), false); 9042 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 9043 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 9044 MachinePointerInfo::getFixedStack(MF, SSFI), 9045 TLI.getMemValueType(DL, Ty)); 9046 OpInfo.CallOperand = StackSlot; 9047 9048 return Chain; 9049 } 9050 9051 /// GetRegistersForValue - Assign registers (virtual or physical) for the 9052 /// specified operand. We prefer to assign virtual registers, to allow the 9053 /// register allocator to handle the assignment process. However, if the asm 9054 /// uses features that we can't model on machineinstrs, we have SDISel do the 9055 /// allocation. This produces generally horrible, but correct, code. 9056 /// 9057 /// OpInfo describes the operand 9058 /// RefOpInfo describes the matching operand if any, the operand otherwise 9059 static std::optional<unsigned> 9060 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 9061 SDISelAsmOperandInfo &OpInfo, 9062 SDISelAsmOperandInfo &RefOpInfo) { 9063 LLVMContext &Context = *DAG.getContext(); 9064 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9065 9066 MachineFunction &MF = DAG.getMachineFunction(); 9067 SmallVector<unsigned, 4> Regs; 9068 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9069 9070 // No work to do for memory/address operands. 9071 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 9072 OpInfo.ConstraintType == TargetLowering::C_Address) 9073 return std::nullopt; 9074 9075 // If this is a constraint for a single physreg, or a constraint for a 9076 // register class, find it. 9077 unsigned AssignedReg; 9078 const TargetRegisterClass *RC; 9079 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 9080 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 9081 // RC is unset only on failure. Return immediately. 9082 if (!RC) 9083 return std::nullopt; 9084 9085 // Get the actual register value type. This is important, because the user 9086 // may have asked for (e.g.) the AX register in i32 type. We need to 9087 // remember that AX is actually i16 to get the right extension. 9088 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 9089 9090 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) { 9091 // If this is an FP operand in an integer register (or visa versa), or more 9092 // generally if the operand value disagrees with the register class we plan 9093 // to stick it in, fix the operand type. 9094 // 9095 // If this is an input value, the bitcast to the new type is done now. 9096 // Bitcast for output value is done at the end of visitInlineAsm(). 9097 if ((OpInfo.Type == InlineAsm::isOutput || 9098 OpInfo.Type == InlineAsm::isInput) && 9099 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 9100 // Try to convert to the first EVT that the reg class contains. If the 9101 // types are identical size, use a bitcast to convert (e.g. two differing 9102 // vector types). Note: output bitcast is done at the end of 9103 // visitInlineAsm(). 9104 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 9105 // Exclude indirect inputs while they are unsupported because the code 9106 // to perform the load is missing and thus OpInfo.CallOperand still 9107 // refers to the input address rather than the pointed-to value. 9108 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 9109 OpInfo.CallOperand = 9110 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 9111 OpInfo.ConstraintVT = RegVT; 9112 // If the operand is an FP value and we want it in integer registers, 9113 // use the corresponding integer type. This turns an f64 value into 9114 // i64, which can be passed with two i32 values on a 32-bit machine. 9115 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 9116 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 9117 if (OpInfo.Type == InlineAsm::isInput) 9118 OpInfo.CallOperand = 9119 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 9120 OpInfo.ConstraintVT = VT; 9121 } 9122 } 9123 } 9124 9125 // No need to allocate a matching input constraint since the constraint it's 9126 // matching to has already been allocated. 9127 if (OpInfo.isMatchingInputConstraint()) 9128 return std::nullopt; 9129 9130 EVT ValueVT = OpInfo.ConstraintVT; 9131 if (OpInfo.ConstraintVT == MVT::Other) 9132 ValueVT = RegVT; 9133 9134 // Initialize NumRegs. 9135 unsigned NumRegs = 1; 9136 if (OpInfo.ConstraintVT != MVT::Other) 9137 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT); 9138 9139 // If this is a constraint for a specific physical register, like {r17}, 9140 // assign it now. 9141 9142 // If this associated to a specific register, initialize iterator to correct 9143 // place. If virtual, make sure we have enough registers 9144 9145 // Initialize iterator if necessary 9146 TargetRegisterClass::iterator I = RC->begin(); 9147 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9148 9149 // Do not check for single registers. 9150 if (AssignedReg) { 9151 I = std::find(I, RC->end(), AssignedReg); 9152 if (I == RC->end()) { 9153 // RC does not contain the selected register, which indicates a 9154 // mismatch between the register and the required type/bitwidth. 9155 return {AssignedReg}; 9156 } 9157 } 9158 9159 for (; NumRegs; --NumRegs, ++I) { 9160 assert(I != RC->end() && "Ran out of registers to allocate!"); 9161 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 9162 Regs.push_back(R); 9163 } 9164 9165 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 9166 return std::nullopt; 9167 } 9168 9169 static unsigned 9170 findMatchingInlineAsmOperand(unsigned OperandNo, 9171 const std::vector<SDValue> &AsmNodeOperands) { 9172 // Scan until we find the definition we already emitted of this operand. 9173 unsigned CurOp = InlineAsm::Op_FirstOperand; 9174 for (; OperandNo; --OperandNo) { 9175 // Advance to the next operand. 9176 unsigned OpFlag = 9177 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 9178 const InlineAsm::Flag F(OpFlag); 9179 assert( 9180 (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) && 9181 "Skipped past definitions?"); 9182 CurOp += F.getNumOperandRegisters() + 1; 9183 } 9184 return CurOp; 9185 } 9186 9187 namespace { 9188 9189 class ExtraFlags { 9190 unsigned Flags = 0; 9191 9192 public: 9193 explicit ExtraFlags(const CallBase &Call) { 9194 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 9195 if (IA->hasSideEffects()) 9196 Flags |= InlineAsm::Extra_HasSideEffects; 9197 if (IA->isAlignStack()) 9198 Flags |= InlineAsm::Extra_IsAlignStack; 9199 if (Call.isConvergent()) 9200 Flags |= InlineAsm::Extra_IsConvergent; 9201 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 9202 } 9203 9204 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 9205 // Ideally, we would only check against memory constraints. However, the 9206 // meaning of an Other constraint can be target-specific and we can't easily 9207 // reason about it. Therefore, be conservative and set MayLoad/MayStore 9208 // for Other constraints as well. 9209 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 9210 OpInfo.ConstraintType == TargetLowering::C_Other) { 9211 if (OpInfo.Type == InlineAsm::isInput) 9212 Flags |= InlineAsm::Extra_MayLoad; 9213 else if (OpInfo.Type == InlineAsm::isOutput) 9214 Flags |= InlineAsm::Extra_MayStore; 9215 else if (OpInfo.Type == InlineAsm::isClobber) 9216 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 9217 } 9218 } 9219 9220 unsigned get() const { return Flags; } 9221 }; 9222 9223 } // end anonymous namespace 9224 9225 static bool isFunction(SDValue Op) { 9226 if (Op && Op.getOpcode() == ISD::GlobalAddress) { 9227 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 9228 auto Fn = dyn_cast_or_null<Function>(GA->getGlobal()); 9229 9230 // In normal "call dllimport func" instruction (non-inlineasm) it force 9231 // indirect access by specifing call opcode. And usually specially print 9232 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can 9233 // not do in this way now. (In fact, this is similar with "Data Access" 9234 // action). So here we ignore dllimport function. 9235 if (Fn && !Fn->hasDLLImportStorageClass()) 9236 return true; 9237 } 9238 } 9239 return false; 9240 } 9241 9242 /// visitInlineAsm - Handle a call to an InlineAsm object. 9243 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 9244 const BasicBlock *EHPadBB) { 9245 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 9246 9247 /// ConstraintOperands - Information about all of the constraints. 9248 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 9249 9250 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9251 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 9252 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 9253 9254 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 9255 // AsmDialect, MayLoad, MayStore). 9256 bool HasSideEffect = IA->hasSideEffects(); 9257 ExtraFlags ExtraInfo(Call); 9258 9259 for (auto &T : TargetConstraints) { 9260 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 9261 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 9262 9263 if (OpInfo.CallOperandVal) 9264 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 9265 9266 if (!HasSideEffect) 9267 HasSideEffect = OpInfo.hasMemory(TLI); 9268 9269 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 9270 // FIXME: Could we compute this on OpInfo rather than T? 9271 9272 // Compute the constraint code and ConstraintType to use. 9273 TLI.ComputeConstraintToUse(T, SDValue()); 9274 9275 if (T.ConstraintType == TargetLowering::C_Immediate && 9276 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 9277 // We've delayed emitting a diagnostic like the "n" constraint because 9278 // inlining could cause an integer showing up. 9279 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 9280 "' expects an integer constant " 9281 "expression"); 9282 9283 ExtraInfo.update(T); 9284 } 9285 9286 // We won't need to flush pending loads if this asm doesn't touch 9287 // memory and is nonvolatile. 9288 SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 9289 9290 bool EmitEHLabels = isa<InvokeInst>(Call); 9291 if (EmitEHLabels) { 9292 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 9293 } 9294 bool IsCallBr = isa<CallBrInst>(Call); 9295 9296 if (IsCallBr || EmitEHLabels) { 9297 // If this is a callbr or invoke we need to flush pending exports since 9298 // inlineasm_br and invoke are terminators. 9299 // We need to do this before nodes are glued to the inlineasm_br node. 9300 Chain = getControlRoot(); 9301 } 9302 9303 MCSymbol *BeginLabel = nullptr; 9304 if (EmitEHLabels) { 9305 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 9306 } 9307 9308 int OpNo = -1; 9309 SmallVector<StringRef> AsmStrs; 9310 IA->collectAsmStrs(AsmStrs); 9311 9312 // Second pass over the constraints: compute which constraint option to use. 9313 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9314 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput) 9315 OpNo++; 9316 9317 // If this is an output operand with a matching input operand, look up the 9318 // matching input. If their types mismatch, e.g. one is an integer, the 9319 // other is floating point, or their sizes are different, flag it as an 9320 // error. 9321 if (OpInfo.hasMatchingInput()) { 9322 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 9323 patchMatchingInput(OpInfo, Input, DAG); 9324 } 9325 9326 // Compute the constraint code and ConstraintType to use. 9327 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 9328 9329 if ((OpInfo.ConstraintType == TargetLowering::C_Memory && 9330 OpInfo.Type == InlineAsm::isClobber) || 9331 OpInfo.ConstraintType == TargetLowering::C_Address) 9332 continue; 9333 9334 // In Linux PIC model, there are 4 cases about value/label addressing: 9335 // 9336 // 1: Function call or Label jmp inside the module. 9337 // 2: Data access (such as global variable, static variable) inside module. 9338 // 3: Function call or Label jmp outside the module. 9339 // 4: Data access (such as global variable) outside the module. 9340 // 9341 // Due to current llvm inline asm architecture designed to not "recognize" 9342 // the asm code, there are quite troubles for us to treat mem addressing 9343 // differently for same value/adress used in different instuctions. 9344 // For example, in pic model, call a func may in plt way or direclty 9345 // pc-related, but lea/mov a function adress may use got. 9346 // 9347 // Here we try to "recognize" function call for the case 1 and case 3 in 9348 // inline asm. And try to adjust the constraint for them. 9349 // 9350 // TODO: Due to current inline asm didn't encourage to jmp to the outsider 9351 // label, so here we don't handle jmp function label now, but we need to 9352 // enhance it (especilly in PIC model) if we meet meaningful requirements. 9353 if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) && 9354 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) && 9355 TM.getCodeModel() != CodeModel::Large) { 9356 OpInfo.isIndirect = false; 9357 OpInfo.ConstraintType = TargetLowering::C_Address; 9358 } 9359 9360 // If this is a memory input, and if the operand is not indirect, do what we 9361 // need to provide an address for the memory input. 9362 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 9363 !OpInfo.isIndirect) { 9364 assert((OpInfo.isMultipleAlternative || 9365 (OpInfo.Type == InlineAsm::isInput)) && 9366 "Can only indirectify direct input operands!"); 9367 9368 // Memory operands really want the address of the value. 9369 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 9370 9371 // There is no longer a Value* corresponding to this operand. 9372 OpInfo.CallOperandVal = nullptr; 9373 9374 // It is now an indirect operand. 9375 OpInfo.isIndirect = true; 9376 } 9377 9378 } 9379 9380 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 9381 std::vector<SDValue> AsmNodeOperands; 9382 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 9383 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 9384 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 9385 9386 // If we have a !srcloc metadata node associated with it, we want to attach 9387 // this to the ultimately generated inline asm machineinstr. To do this, we 9388 // pass in the third operand as this (potentially null) inline asm MDNode. 9389 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 9390 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 9391 9392 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 9393 // bits as operand 3. 9394 AsmNodeOperands.push_back(DAG.getTargetConstant( 9395 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9396 9397 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 9398 // this, assign virtual and physical registers for inputs and otput. 9399 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9400 // Assign Registers. 9401 SDISelAsmOperandInfo &RefOpInfo = 9402 OpInfo.isMatchingInputConstraint() 9403 ? ConstraintOperands[OpInfo.getMatchedOperand()] 9404 : OpInfo; 9405 const auto RegError = 9406 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 9407 if (RegError) { 9408 const MachineFunction &MF = DAG.getMachineFunction(); 9409 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9410 const char *RegName = TRI.getName(*RegError); 9411 emitInlineAsmError(Call, "register '" + Twine(RegName) + 9412 "' allocated for constraint '" + 9413 Twine(OpInfo.ConstraintCode) + 9414 "' does not match required type"); 9415 return; 9416 } 9417 9418 auto DetectWriteToReservedRegister = [&]() { 9419 const MachineFunction &MF = DAG.getMachineFunction(); 9420 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9421 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 9422 if (Register::isPhysicalRegister(Reg) && 9423 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 9424 const char *RegName = TRI.getName(Reg); 9425 emitInlineAsmError(Call, "write to reserved register '" + 9426 Twine(RegName) + "'"); 9427 return true; 9428 } 9429 } 9430 return false; 9431 }; 9432 assert((OpInfo.ConstraintType != TargetLowering::C_Address || 9433 (OpInfo.Type == InlineAsm::isInput && 9434 !OpInfo.isMatchingInputConstraint())) && 9435 "Only address as input operand is allowed."); 9436 9437 switch (OpInfo.Type) { 9438 case InlineAsm::isOutput: 9439 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9440 const InlineAsm::ConstraintCode ConstraintID = 9441 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9442 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 9443 "Failed to convert memory constraint code to constraint id."); 9444 9445 // Add information to the INLINEASM node to know about this output. 9446 InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1); 9447 OpFlags.setMemConstraint(ConstraintID); 9448 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 9449 MVT::i32)); 9450 AsmNodeOperands.push_back(OpInfo.CallOperand); 9451 } else { 9452 // Otherwise, this outputs to a register (directly for C_Register / 9453 // C_RegisterClass, and a target-defined fashion for 9454 // C_Immediate/C_Other). Find a register that we can use. 9455 if (OpInfo.AssignedRegs.Regs.empty()) { 9456 emitInlineAsmError( 9457 Call, "couldn't allocate output register for constraint '" + 9458 Twine(OpInfo.ConstraintCode) + "'"); 9459 return; 9460 } 9461 9462 if (DetectWriteToReservedRegister()) 9463 return; 9464 9465 // Add information to the INLINEASM node to know that this register is 9466 // set. 9467 OpInfo.AssignedRegs.AddInlineAsmOperands( 9468 OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber 9469 : InlineAsm::Kind::RegDef, 9470 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 9471 } 9472 break; 9473 9474 case InlineAsm::isInput: 9475 case InlineAsm::isLabel: { 9476 SDValue InOperandVal = OpInfo.CallOperand; 9477 9478 if (OpInfo.isMatchingInputConstraint()) { 9479 // If this is required to match an output register we have already set, 9480 // just use its register. 9481 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 9482 AsmNodeOperands); 9483 InlineAsm::Flag Flag( 9484 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue()); 9485 if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) { 9486 if (OpInfo.isIndirect) { 9487 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 9488 emitInlineAsmError(Call, "inline asm not supported yet: " 9489 "don't know how to handle tied " 9490 "indirect register inputs"); 9491 return; 9492 } 9493 9494 SmallVector<unsigned, 4> Regs; 9495 MachineFunction &MF = DAG.getMachineFunction(); 9496 MachineRegisterInfo &MRI = MF.getRegInfo(); 9497 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9498 auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]); 9499 Register TiedReg = R->getReg(); 9500 MVT RegVT = R->getSimpleValueType(0); 9501 const TargetRegisterClass *RC = 9502 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg) 9503 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT) 9504 : TRI.getMinimalPhysRegClass(TiedReg); 9505 for (unsigned i = 0, e = Flag.getNumOperandRegisters(); i != e; ++i) 9506 Regs.push_back(MRI.createVirtualRegister(RC)); 9507 9508 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 9509 9510 SDLoc dl = getCurSDLoc(); 9511 // Use the produced MatchedRegs object to 9512 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call); 9513 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, true, 9514 OpInfo.getMatchedOperand(), dl, DAG, 9515 AsmNodeOperands); 9516 break; 9517 } 9518 9519 assert(Flag.isMemKind() && "Unknown matching constraint!"); 9520 assert(Flag.getNumOperandRegisters() == 1 && 9521 "Unexpected number of operands"); 9522 // Add information to the INLINEASM node to know about this input. 9523 // See InlineAsm.h isUseOperandTiedToDef. 9524 Flag.clearMemConstraint(); 9525 Flag.setMatchingOp(OpInfo.getMatchedOperand()); 9526 AsmNodeOperands.push_back(DAG.getTargetConstant( 9527 Flag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9528 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 9529 break; 9530 } 9531 9532 // Treat indirect 'X' constraint as memory. 9533 if (OpInfo.ConstraintType == TargetLowering::C_Other && 9534 OpInfo.isIndirect) 9535 OpInfo.ConstraintType = TargetLowering::C_Memory; 9536 9537 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 9538 OpInfo.ConstraintType == TargetLowering::C_Other) { 9539 std::vector<SDValue> Ops; 9540 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 9541 Ops, DAG); 9542 if (Ops.empty()) { 9543 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 9544 if (isa<ConstantSDNode>(InOperandVal)) { 9545 emitInlineAsmError(Call, "value out of range for constraint '" + 9546 Twine(OpInfo.ConstraintCode) + "'"); 9547 return; 9548 } 9549 9550 emitInlineAsmError(Call, 9551 "invalid operand for inline asm constraint '" + 9552 Twine(OpInfo.ConstraintCode) + "'"); 9553 return; 9554 } 9555 9556 // Add information to the INLINEASM node to know about this input. 9557 InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size()); 9558 AsmNodeOperands.push_back(DAG.getTargetConstant( 9559 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9560 llvm::append_range(AsmNodeOperands, Ops); 9561 break; 9562 } 9563 9564 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9565 assert((OpInfo.isIndirect || 9566 OpInfo.ConstraintType != TargetLowering::C_Memory) && 9567 "Operand must be indirect to be a mem!"); 9568 assert(InOperandVal.getValueType() == 9569 TLI.getPointerTy(DAG.getDataLayout()) && 9570 "Memory operands expect pointer values"); 9571 9572 const InlineAsm::ConstraintCode ConstraintID = 9573 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9574 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 9575 "Failed to convert memory constraint code to constraint id."); 9576 9577 // Add information to the INLINEASM node to know about this input. 9578 InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1); 9579 ResOpType.setMemConstraint(ConstraintID); 9580 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 9581 getCurSDLoc(), 9582 MVT::i32)); 9583 AsmNodeOperands.push_back(InOperandVal); 9584 break; 9585 } 9586 9587 if (OpInfo.ConstraintType == TargetLowering::C_Address) { 9588 const InlineAsm::ConstraintCode ConstraintID = 9589 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9590 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 9591 "Failed to convert memory constraint code to constraint id."); 9592 9593 InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1); 9594 9595 SDValue AsmOp = InOperandVal; 9596 if (isFunction(InOperandVal)) { 9597 auto *GA = cast<GlobalAddressSDNode>(InOperandVal); 9598 ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1); 9599 AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(), 9600 InOperandVal.getValueType(), 9601 GA->getOffset()); 9602 } 9603 9604 // Add information to the INLINEASM node to know about this input. 9605 ResOpType.setMemConstraint(ConstraintID); 9606 9607 AsmNodeOperands.push_back( 9608 DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32)); 9609 9610 AsmNodeOperands.push_back(AsmOp); 9611 break; 9612 } 9613 9614 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 9615 OpInfo.ConstraintType == TargetLowering::C_Register) && 9616 "Unknown constraint type!"); 9617 9618 // TODO: Support this. 9619 if (OpInfo.isIndirect) { 9620 emitInlineAsmError( 9621 Call, "Don't know how to handle indirect register inputs yet " 9622 "for constraint '" + 9623 Twine(OpInfo.ConstraintCode) + "'"); 9624 return; 9625 } 9626 9627 // Copy the input into the appropriate registers. 9628 if (OpInfo.AssignedRegs.Regs.empty()) { 9629 emitInlineAsmError(Call, 9630 "couldn't allocate input reg for constraint '" + 9631 Twine(OpInfo.ConstraintCode) + "'"); 9632 return; 9633 } 9634 9635 if (DetectWriteToReservedRegister()) 9636 return; 9637 9638 SDLoc dl = getCurSDLoc(); 9639 9640 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, 9641 &Call); 9642 9643 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, false, 9644 0, dl, DAG, AsmNodeOperands); 9645 break; 9646 } 9647 case InlineAsm::isClobber: 9648 // Add the clobbered value to the operand list, so that the register 9649 // allocator is aware that the physreg got clobbered. 9650 if (!OpInfo.AssignedRegs.Regs.empty()) 9651 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::Clobber, 9652 false, 0, getCurSDLoc(), DAG, 9653 AsmNodeOperands); 9654 break; 9655 } 9656 } 9657 9658 // Finish up input operands. Set the input chain and add the flag last. 9659 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 9660 if (Glue.getNode()) AsmNodeOperands.push_back(Glue); 9661 9662 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 9663 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 9664 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 9665 Glue = Chain.getValue(1); 9666 9667 // Do additional work to generate outputs. 9668 9669 SmallVector<EVT, 1> ResultVTs; 9670 SmallVector<SDValue, 1> ResultValues; 9671 SmallVector<SDValue, 8> OutChains; 9672 9673 llvm::Type *CallResultType = Call.getType(); 9674 ArrayRef<Type *> ResultTypes; 9675 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 9676 ResultTypes = StructResult->elements(); 9677 else if (!CallResultType->isVoidTy()) 9678 ResultTypes = ArrayRef(CallResultType); 9679 9680 auto CurResultType = ResultTypes.begin(); 9681 auto handleRegAssign = [&](SDValue V) { 9682 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 9683 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 9684 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 9685 ++CurResultType; 9686 // If the type of the inline asm call site return value is different but has 9687 // same size as the type of the asm output bitcast it. One example of this 9688 // is for vectors with different width / number of elements. This can 9689 // happen for register classes that can contain multiple different value 9690 // types. The preg or vreg allocated may not have the same VT as was 9691 // expected. 9692 // 9693 // This can also happen for a return value that disagrees with the register 9694 // class it is put in, eg. a double in a general-purpose register on a 9695 // 32-bit machine. 9696 if (ResultVT != V.getValueType() && 9697 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 9698 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 9699 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 9700 V.getValueType().isInteger()) { 9701 // If a result value was tied to an input value, the computed result 9702 // may have a wider width than the expected result. Extract the 9703 // relevant portion. 9704 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 9705 } 9706 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 9707 ResultVTs.push_back(ResultVT); 9708 ResultValues.push_back(V); 9709 }; 9710 9711 // Deal with output operands. 9712 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9713 if (OpInfo.Type == InlineAsm::isOutput) { 9714 SDValue Val; 9715 // Skip trivial output operands. 9716 if (OpInfo.AssignedRegs.Regs.empty()) 9717 continue; 9718 9719 switch (OpInfo.ConstraintType) { 9720 case TargetLowering::C_Register: 9721 case TargetLowering::C_RegisterClass: 9722 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 9723 Chain, &Glue, &Call); 9724 break; 9725 case TargetLowering::C_Immediate: 9726 case TargetLowering::C_Other: 9727 Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(), 9728 OpInfo, DAG); 9729 break; 9730 case TargetLowering::C_Memory: 9731 break; // Already handled. 9732 case TargetLowering::C_Address: 9733 break; // Silence warning. 9734 case TargetLowering::C_Unknown: 9735 assert(false && "Unexpected unknown constraint"); 9736 } 9737 9738 // Indirect output manifest as stores. Record output chains. 9739 if (OpInfo.isIndirect) { 9740 const Value *Ptr = OpInfo.CallOperandVal; 9741 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 9742 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 9743 MachinePointerInfo(Ptr)); 9744 OutChains.push_back(Store); 9745 } else { 9746 // generate CopyFromRegs to associated registers. 9747 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 9748 if (Val.getOpcode() == ISD::MERGE_VALUES) { 9749 for (const SDValue &V : Val->op_values()) 9750 handleRegAssign(V); 9751 } else 9752 handleRegAssign(Val); 9753 } 9754 } 9755 } 9756 9757 // Set results. 9758 if (!ResultValues.empty()) { 9759 assert(CurResultType == ResultTypes.end() && 9760 "Mismatch in number of ResultTypes"); 9761 assert(ResultValues.size() == ResultTypes.size() && 9762 "Mismatch in number of output operands in asm result"); 9763 9764 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 9765 DAG.getVTList(ResultVTs), ResultValues); 9766 setValue(&Call, V); 9767 } 9768 9769 // Collect store chains. 9770 if (!OutChains.empty()) 9771 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 9772 9773 if (EmitEHLabels) { 9774 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 9775 } 9776 9777 // Only Update Root if inline assembly has a memory effect. 9778 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 9779 EmitEHLabels) 9780 DAG.setRoot(Chain); 9781 } 9782 9783 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 9784 const Twine &Message) { 9785 LLVMContext &Ctx = *DAG.getContext(); 9786 Ctx.emitError(&Call, Message); 9787 9788 // Make sure we leave the DAG in a valid state 9789 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9790 SmallVector<EVT, 1> ValueVTs; 9791 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 9792 9793 if (ValueVTs.empty()) 9794 return; 9795 9796 SmallVector<SDValue, 1> Ops; 9797 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 9798 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 9799 9800 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 9801 } 9802 9803 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 9804 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 9805 MVT::Other, getRoot(), 9806 getValue(I.getArgOperand(0)), 9807 DAG.getSrcValue(I.getArgOperand(0)))); 9808 } 9809 9810 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 9811 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9812 const DataLayout &DL = DAG.getDataLayout(); 9813 SDValue V = DAG.getVAArg( 9814 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 9815 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 9816 DL.getABITypeAlign(I.getType()).value()); 9817 DAG.setRoot(V.getValue(1)); 9818 9819 if (I.getType()->isPointerTy()) 9820 V = DAG.getPtrExtOrTrunc( 9821 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 9822 setValue(&I, V); 9823 } 9824 9825 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 9826 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 9827 MVT::Other, getRoot(), 9828 getValue(I.getArgOperand(0)), 9829 DAG.getSrcValue(I.getArgOperand(0)))); 9830 } 9831 9832 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 9833 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 9834 MVT::Other, getRoot(), 9835 getValue(I.getArgOperand(0)), 9836 getValue(I.getArgOperand(1)), 9837 DAG.getSrcValue(I.getArgOperand(0)), 9838 DAG.getSrcValue(I.getArgOperand(1)))); 9839 } 9840 9841 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 9842 const Instruction &I, 9843 SDValue Op) { 9844 const MDNode *Range = getRangeMetadata(I); 9845 if (!Range) 9846 return Op; 9847 9848 ConstantRange CR = getConstantRangeFromMetadata(*Range); 9849 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 9850 return Op; 9851 9852 APInt Lo = CR.getUnsignedMin(); 9853 if (!Lo.isMinValue()) 9854 return Op; 9855 9856 APInt Hi = CR.getUnsignedMax(); 9857 unsigned Bits = std::max(Hi.getActiveBits(), 9858 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 9859 9860 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9861 9862 SDLoc SL = getCurSDLoc(); 9863 9864 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 9865 DAG.getValueType(SmallVT)); 9866 unsigned NumVals = Op.getNode()->getNumValues(); 9867 if (NumVals == 1) 9868 return ZExt; 9869 9870 SmallVector<SDValue, 4> Ops; 9871 9872 Ops.push_back(ZExt); 9873 for (unsigned I = 1; I != NumVals; ++I) 9874 Ops.push_back(Op.getValue(I)); 9875 9876 return DAG.getMergeValues(Ops, SL); 9877 } 9878 9879 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 9880 /// the call being lowered. 9881 /// 9882 /// This is a helper for lowering intrinsics that follow a target calling 9883 /// convention or require stack pointer adjustment. Only a subset of the 9884 /// intrinsic's operands need to participate in the calling convention. 9885 void SelectionDAGBuilder::populateCallLoweringInfo( 9886 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 9887 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 9888 AttributeSet RetAttrs, bool IsPatchPoint) { 9889 TargetLowering::ArgListTy Args; 9890 Args.reserve(NumArgs); 9891 9892 // Populate the argument list. 9893 // Attributes for args start at offset 1, after the return attribute. 9894 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 9895 ArgI != ArgE; ++ArgI) { 9896 const Value *V = Call->getOperand(ArgI); 9897 9898 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 9899 9900 TargetLowering::ArgListEntry Entry; 9901 Entry.Node = getValue(V); 9902 Entry.Ty = V->getType(); 9903 Entry.setAttributes(Call, ArgI); 9904 Args.push_back(Entry); 9905 } 9906 9907 CLI.setDebugLoc(getCurSDLoc()) 9908 .setChain(getRoot()) 9909 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args), 9910 RetAttrs) 9911 .setDiscardResult(Call->use_empty()) 9912 .setIsPatchPoint(IsPatchPoint) 9913 .setIsPreallocated( 9914 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 9915 } 9916 9917 /// Add a stack map intrinsic call's live variable operands to a stackmap 9918 /// or patchpoint target node's operand list. 9919 /// 9920 /// Constants are converted to TargetConstants purely as an optimization to 9921 /// avoid constant materialization and register allocation. 9922 /// 9923 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 9924 /// generate addess computation nodes, and so FinalizeISel can convert the 9925 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 9926 /// address materialization and register allocation, but may also be required 9927 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 9928 /// alloca in the entry block, then the runtime may assume that the alloca's 9929 /// StackMap location can be read immediately after compilation and that the 9930 /// location is valid at any point during execution (this is similar to the 9931 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 9932 /// only available in a register, then the runtime would need to trap when 9933 /// execution reaches the StackMap in order to read the alloca's location. 9934 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 9935 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 9936 SelectionDAGBuilder &Builder) { 9937 SelectionDAG &DAG = Builder.DAG; 9938 for (unsigned I = StartIdx; I < Call.arg_size(); I++) { 9939 SDValue Op = Builder.getValue(Call.getArgOperand(I)); 9940 9941 // Things on the stack are pointer-typed, meaning that they are already 9942 // legal and can be emitted directly to target nodes. 9943 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) { 9944 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType())); 9945 } else { 9946 // Otherwise emit a target independent node to be legalised. 9947 Ops.push_back(Builder.getValue(Call.getArgOperand(I))); 9948 } 9949 } 9950 } 9951 9952 /// Lower llvm.experimental.stackmap. 9953 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 9954 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>, 9955 // [live variables...]) 9956 9957 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 9958 9959 SDValue Chain, InGlue, Callee; 9960 SmallVector<SDValue, 32> Ops; 9961 9962 SDLoc DL = getCurSDLoc(); 9963 Callee = getValue(CI.getCalledOperand()); 9964 9965 // The stackmap intrinsic only records the live variables (the arguments 9966 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 9967 // intrinsic, this won't be lowered to a function call. This means we don't 9968 // have to worry about calling conventions and target specific lowering code. 9969 // Instead we perform the call lowering right here. 9970 // 9971 // chain, flag = CALLSEQ_START(chain, 0, 0) 9972 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 9973 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 9974 // 9975 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 9976 InGlue = Chain.getValue(1); 9977 9978 // Add the STACKMAP operands, starting with DAG house-keeping. 9979 Ops.push_back(Chain); 9980 Ops.push_back(InGlue); 9981 9982 // Add the <id>, <numShadowBytes> operands. 9983 // 9984 // These do not require legalisation, and can be emitted directly to target 9985 // constant nodes. 9986 SDValue ID = getValue(CI.getArgOperand(0)); 9987 assert(ID.getValueType() == MVT::i64); 9988 SDValue IDConst = DAG.getTargetConstant( 9989 cast<ConstantSDNode>(ID)->getZExtValue(), DL, ID.getValueType()); 9990 Ops.push_back(IDConst); 9991 9992 SDValue Shad = getValue(CI.getArgOperand(1)); 9993 assert(Shad.getValueType() == MVT::i32); 9994 SDValue ShadConst = DAG.getTargetConstant( 9995 cast<ConstantSDNode>(Shad)->getZExtValue(), DL, Shad.getValueType()); 9996 Ops.push_back(ShadConst); 9997 9998 // Add the live variables. 9999 addStackMapLiveVars(CI, 2, DL, Ops, *this); 10000 10001 // Create the STACKMAP node. 10002 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10003 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops); 10004 InGlue = Chain.getValue(1); 10005 10006 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL); 10007 10008 // Stackmaps don't generate values, so nothing goes into the NodeMap. 10009 10010 // Set the root to the target-lowered call chain. 10011 DAG.setRoot(Chain); 10012 10013 // Inform the Frame Information that we have a stackmap in this function. 10014 FuncInfo.MF->getFrameInfo().setHasStackMap(); 10015 } 10016 10017 /// Lower llvm.experimental.patchpoint directly to its target opcode. 10018 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 10019 const BasicBlock *EHPadBB) { 10020 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 10021 // i32 <numBytes>, 10022 // i8* <target>, 10023 // i32 <numArgs>, 10024 // [Args...], 10025 // [live variables...]) 10026 10027 CallingConv::ID CC = CB.getCallingConv(); 10028 bool IsAnyRegCC = CC == CallingConv::AnyReg; 10029 bool HasDef = !CB.getType()->isVoidTy(); 10030 SDLoc dl = getCurSDLoc(); 10031 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 10032 10033 // Handle immediate and symbolic callees. 10034 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 10035 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 10036 /*isTarget=*/true); 10037 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 10038 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 10039 SDLoc(SymbolicCallee), 10040 SymbolicCallee->getValueType(0)); 10041 10042 // Get the real number of arguments participating in the call <numArgs> 10043 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 10044 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 10045 10046 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 10047 // Intrinsics include all meta-operands up to but not including CC. 10048 unsigned NumMetaOpers = PatchPointOpers::CCPos; 10049 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 10050 "Not enough arguments provided to the patchpoint intrinsic"); 10051 10052 // For AnyRegCC the arguments are lowered later on manually. 10053 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 10054 Type *ReturnTy = 10055 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 10056 10057 TargetLowering::CallLoweringInfo CLI(DAG); 10058 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 10059 ReturnTy, CB.getAttributes().getRetAttrs(), true); 10060 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 10061 10062 SDNode *CallEnd = Result.second.getNode(); 10063 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 10064 CallEnd = CallEnd->getOperand(0).getNode(); 10065 10066 /// Get a call instruction from the call sequence chain. 10067 /// Tail calls are not allowed. 10068 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 10069 "Expected a callseq node."); 10070 SDNode *Call = CallEnd->getOperand(0).getNode(); 10071 bool HasGlue = Call->getGluedNode(); 10072 10073 // Replace the target specific call node with the patchable intrinsic. 10074 SmallVector<SDValue, 8> Ops; 10075 10076 // Push the chain. 10077 Ops.push_back(*(Call->op_begin())); 10078 10079 // Optionally, push the glue (if any). 10080 if (HasGlue) 10081 Ops.push_back(*(Call->op_end() - 1)); 10082 10083 // Push the register mask info. 10084 if (HasGlue) 10085 Ops.push_back(*(Call->op_end() - 2)); 10086 else 10087 Ops.push_back(*(Call->op_end() - 1)); 10088 10089 // Add the <id> and <numBytes> constants. 10090 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 10091 Ops.push_back(DAG.getTargetConstant( 10092 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 10093 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 10094 Ops.push_back(DAG.getTargetConstant( 10095 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 10096 MVT::i32)); 10097 10098 // Add the callee. 10099 Ops.push_back(Callee); 10100 10101 // Adjust <numArgs> to account for any arguments that have been passed on the 10102 // stack instead. 10103 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 10104 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 10105 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 10106 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 10107 10108 // Add the calling convention 10109 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 10110 10111 // Add the arguments we omitted previously. The register allocator should 10112 // place these in any free register. 10113 if (IsAnyRegCC) 10114 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 10115 Ops.push_back(getValue(CB.getArgOperand(i))); 10116 10117 // Push the arguments from the call instruction. 10118 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 10119 Ops.append(Call->op_begin() + 2, e); 10120 10121 // Push live variables for the stack map. 10122 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 10123 10124 SDVTList NodeTys; 10125 if (IsAnyRegCC && HasDef) { 10126 // Create the return types based on the intrinsic definition 10127 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10128 SmallVector<EVT, 3> ValueVTs; 10129 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 10130 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 10131 10132 // There is always a chain and a glue type at the end 10133 ValueVTs.push_back(MVT::Other); 10134 ValueVTs.push_back(MVT::Glue); 10135 NodeTys = DAG.getVTList(ValueVTs); 10136 } else 10137 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10138 10139 // Replace the target specific call node with a PATCHPOINT node. 10140 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops); 10141 10142 // Update the NodeMap. 10143 if (HasDef) { 10144 if (IsAnyRegCC) 10145 setValue(&CB, SDValue(PPV.getNode(), 0)); 10146 else 10147 setValue(&CB, Result.first); 10148 } 10149 10150 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 10151 // call sequence. Furthermore the location of the chain and glue can change 10152 // when the AnyReg calling convention is used and the intrinsic returns a 10153 // value. 10154 if (IsAnyRegCC && HasDef) { 10155 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 10156 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)}; 10157 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 10158 } else 10159 DAG.ReplaceAllUsesWith(Call, PPV.getNode()); 10160 DAG.DeleteNode(Call); 10161 10162 // Inform the Frame Information that we have a patchpoint in this function. 10163 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 10164 } 10165 10166 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 10167 unsigned Intrinsic) { 10168 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10169 SDValue Op1 = getValue(I.getArgOperand(0)); 10170 SDValue Op2; 10171 if (I.arg_size() > 1) 10172 Op2 = getValue(I.getArgOperand(1)); 10173 SDLoc dl = getCurSDLoc(); 10174 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 10175 SDValue Res; 10176 SDNodeFlags SDFlags; 10177 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 10178 SDFlags.copyFMF(*FPMO); 10179 10180 switch (Intrinsic) { 10181 case Intrinsic::vector_reduce_fadd: 10182 if (SDFlags.hasAllowReassociation()) 10183 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 10184 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 10185 SDFlags); 10186 else 10187 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 10188 break; 10189 case Intrinsic::vector_reduce_fmul: 10190 if (SDFlags.hasAllowReassociation()) 10191 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 10192 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 10193 SDFlags); 10194 else 10195 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 10196 break; 10197 case Intrinsic::vector_reduce_add: 10198 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 10199 break; 10200 case Intrinsic::vector_reduce_mul: 10201 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 10202 break; 10203 case Intrinsic::vector_reduce_and: 10204 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 10205 break; 10206 case Intrinsic::vector_reduce_or: 10207 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 10208 break; 10209 case Intrinsic::vector_reduce_xor: 10210 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 10211 break; 10212 case Intrinsic::vector_reduce_smax: 10213 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 10214 break; 10215 case Intrinsic::vector_reduce_smin: 10216 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 10217 break; 10218 case Intrinsic::vector_reduce_umax: 10219 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 10220 break; 10221 case Intrinsic::vector_reduce_umin: 10222 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 10223 break; 10224 case Intrinsic::vector_reduce_fmax: 10225 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 10226 break; 10227 case Intrinsic::vector_reduce_fmin: 10228 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 10229 break; 10230 case Intrinsic::vector_reduce_fmaximum: 10231 Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags); 10232 break; 10233 case Intrinsic::vector_reduce_fminimum: 10234 Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags); 10235 break; 10236 default: 10237 llvm_unreachable("Unhandled vector reduce intrinsic"); 10238 } 10239 setValue(&I, Res); 10240 } 10241 10242 /// Returns an AttributeList representing the attributes applied to the return 10243 /// value of the given call. 10244 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 10245 SmallVector<Attribute::AttrKind, 2> Attrs; 10246 if (CLI.RetSExt) 10247 Attrs.push_back(Attribute::SExt); 10248 if (CLI.RetZExt) 10249 Attrs.push_back(Attribute::ZExt); 10250 if (CLI.IsInReg) 10251 Attrs.push_back(Attribute::InReg); 10252 10253 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 10254 Attrs); 10255 } 10256 10257 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 10258 /// implementation, which just calls LowerCall. 10259 /// FIXME: When all targets are 10260 /// migrated to using LowerCall, this hook should be integrated into SDISel. 10261 std::pair<SDValue, SDValue> 10262 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 10263 // Handle the incoming return values from the call. 10264 CLI.Ins.clear(); 10265 Type *OrigRetTy = CLI.RetTy; 10266 SmallVector<EVT, 4> RetTys; 10267 SmallVector<uint64_t, 4> Offsets; 10268 auto &DL = CLI.DAG.getDataLayout(); 10269 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets, 0); 10270 10271 if (CLI.IsPostTypeLegalization) { 10272 // If we are lowering a libcall after legalization, split the return type. 10273 SmallVector<EVT, 4> OldRetTys; 10274 SmallVector<uint64_t, 4> OldOffsets; 10275 RetTys.swap(OldRetTys); 10276 Offsets.swap(OldOffsets); 10277 10278 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 10279 EVT RetVT = OldRetTys[i]; 10280 uint64_t Offset = OldOffsets[i]; 10281 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 10282 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 10283 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 10284 RetTys.append(NumRegs, RegisterVT); 10285 for (unsigned j = 0; j != NumRegs; ++j) 10286 Offsets.push_back(Offset + j * RegisterVTByteSZ); 10287 } 10288 } 10289 10290 SmallVector<ISD::OutputArg, 4> Outs; 10291 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 10292 10293 bool CanLowerReturn = 10294 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 10295 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 10296 10297 SDValue DemoteStackSlot; 10298 int DemoteStackIdx = -100; 10299 if (!CanLowerReturn) { 10300 // FIXME: equivalent assert? 10301 // assert(!CS.hasInAllocaArgument() && 10302 // "sret demotion is incompatible with inalloca"); 10303 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 10304 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 10305 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10306 DemoteStackIdx = 10307 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 10308 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 10309 DL.getAllocaAddrSpace()); 10310 10311 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 10312 ArgListEntry Entry; 10313 Entry.Node = DemoteStackSlot; 10314 Entry.Ty = StackSlotPtrType; 10315 Entry.IsSExt = false; 10316 Entry.IsZExt = false; 10317 Entry.IsInReg = false; 10318 Entry.IsSRet = true; 10319 Entry.IsNest = false; 10320 Entry.IsByVal = false; 10321 Entry.IsByRef = false; 10322 Entry.IsReturned = false; 10323 Entry.IsSwiftSelf = false; 10324 Entry.IsSwiftAsync = false; 10325 Entry.IsSwiftError = false; 10326 Entry.IsCFGuardTarget = false; 10327 Entry.Alignment = Alignment; 10328 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 10329 CLI.NumFixedArgs += 1; 10330 CLI.getArgs()[0].IndirectType = CLI.RetTy; 10331 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 10332 10333 // sret demotion isn't compatible with tail-calls, since the sret argument 10334 // points into the callers stack frame. 10335 CLI.IsTailCall = false; 10336 } else { 10337 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10338 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL); 10339 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 10340 ISD::ArgFlagsTy Flags; 10341 if (NeedsRegBlock) { 10342 Flags.setInConsecutiveRegs(); 10343 if (I == RetTys.size() - 1) 10344 Flags.setInConsecutiveRegsLast(); 10345 } 10346 EVT VT = RetTys[I]; 10347 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10348 CLI.CallConv, VT); 10349 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10350 CLI.CallConv, VT); 10351 for (unsigned i = 0; i != NumRegs; ++i) { 10352 ISD::InputArg MyFlags; 10353 MyFlags.Flags = Flags; 10354 MyFlags.VT = RegisterVT; 10355 MyFlags.ArgVT = VT; 10356 MyFlags.Used = CLI.IsReturnValueUsed; 10357 if (CLI.RetTy->isPointerTy()) { 10358 MyFlags.Flags.setPointer(); 10359 MyFlags.Flags.setPointerAddrSpace( 10360 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 10361 } 10362 if (CLI.RetSExt) 10363 MyFlags.Flags.setSExt(); 10364 if (CLI.RetZExt) 10365 MyFlags.Flags.setZExt(); 10366 if (CLI.IsInReg) 10367 MyFlags.Flags.setInReg(); 10368 CLI.Ins.push_back(MyFlags); 10369 } 10370 } 10371 } 10372 10373 // We push in swifterror return as the last element of CLI.Ins. 10374 ArgListTy &Args = CLI.getArgs(); 10375 if (supportSwiftError()) { 10376 for (const ArgListEntry &Arg : Args) { 10377 if (Arg.IsSwiftError) { 10378 ISD::InputArg MyFlags; 10379 MyFlags.VT = getPointerTy(DL); 10380 MyFlags.ArgVT = EVT(getPointerTy(DL)); 10381 MyFlags.Flags.setSwiftError(); 10382 CLI.Ins.push_back(MyFlags); 10383 } 10384 } 10385 } 10386 10387 // Handle all of the outgoing arguments. 10388 CLI.Outs.clear(); 10389 CLI.OutVals.clear(); 10390 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 10391 SmallVector<EVT, 4> ValueVTs; 10392 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 10393 // FIXME: Split arguments if CLI.IsPostTypeLegalization 10394 Type *FinalType = Args[i].Ty; 10395 if (Args[i].IsByVal) 10396 FinalType = Args[i].IndirectType; 10397 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10398 FinalType, CLI.CallConv, CLI.IsVarArg, DL); 10399 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 10400 ++Value) { 10401 EVT VT = ValueVTs[Value]; 10402 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 10403 SDValue Op = SDValue(Args[i].Node.getNode(), 10404 Args[i].Node.getResNo() + Value); 10405 ISD::ArgFlagsTy Flags; 10406 10407 // Certain targets (such as MIPS), may have a different ABI alignment 10408 // for a type depending on the context. Give the target a chance to 10409 // specify the alignment it wants. 10410 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 10411 Flags.setOrigAlign(OriginalAlignment); 10412 10413 if (Args[i].Ty->isPointerTy()) { 10414 Flags.setPointer(); 10415 Flags.setPointerAddrSpace( 10416 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 10417 } 10418 if (Args[i].IsZExt) 10419 Flags.setZExt(); 10420 if (Args[i].IsSExt) 10421 Flags.setSExt(); 10422 if (Args[i].IsInReg) { 10423 // If we are using vectorcall calling convention, a structure that is 10424 // passed InReg - is surely an HVA 10425 if (CLI.CallConv == CallingConv::X86_VectorCall && 10426 isa<StructType>(FinalType)) { 10427 // The first value of a structure is marked 10428 if (0 == Value) 10429 Flags.setHvaStart(); 10430 Flags.setHva(); 10431 } 10432 // Set InReg Flag 10433 Flags.setInReg(); 10434 } 10435 if (Args[i].IsSRet) 10436 Flags.setSRet(); 10437 if (Args[i].IsSwiftSelf) 10438 Flags.setSwiftSelf(); 10439 if (Args[i].IsSwiftAsync) 10440 Flags.setSwiftAsync(); 10441 if (Args[i].IsSwiftError) 10442 Flags.setSwiftError(); 10443 if (Args[i].IsCFGuardTarget) 10444 Flags.setCFGuardTarget(); 10445 if (Args[i].IsByVal) 10446 Flags.setByVal(); 10447 if (Args[i].IsByRef) 10448 Flags.setByRef(); 10449 if (Args[i].IsPreallocated) { 10450 Flags.setPreallocated(); 10451 // Set the byval flag for CCAssignFn callbacks that don't know about 10452 // preallocated. This way we can know how many bytes we should've 10453 // allocated and how many bytes a callee cleanup function will pop. If 10454 // we port preallocated to more targets, we'll have to add custom 10455 // preallocated handling in the various CC lowering callbacks. 10456 Flags.setByVal(); 10457 } 10458 if (Args[i].IsInAlloca) { 10459 Flags.setInAlloca(); 10460 // Set the byval flag for CCAssignFn callbacks that don't know about 10461 // inalloca. This way we can know how many bytes we should've allocated 10462 // and how many bytes a callee cleanup function will pop. If we port 10463 // inalloca to more targets, we'll have to add custom inalloca handling 10464 // in the various CC lowering callbacks. 10465 Flags.setByVal(); 10466 } 10467 Align MemAlign; 10468 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 10469 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType); 10470 Flags.setByValSize(FrameSize); 10471 10472 // info is not there but there are cases it cannot get right. 10473 if (auto MA = Args[i].Alignment) 10474 MemAlign = *MA; 10475 else 10476 MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL)); 10477 } else if (auto MA = Args[i].Alignment) { 10478 MemAlign = *MA; 10479 } else { 10480 MemAlign = OriginalAlignment; 10481 } 10482 Flags.setMemAlign(MemAlign); 10483 if (Args[i].IsNest) 10484 Flags.setNest(); 10485 if (NeedsRegBlock) 10486 Flags.setInConsecutiveRegs(); 10487 10488 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10489 CLI.CallConv, VT); 10490 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10491 CLI.CallConv, VT); 10492 SmallVector<SDValue, 4> Parts(NumParts); 10493 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 10494 10495 if (Args[i].IsSExt) 10496 ExtendKind = ISD::SIGN_EXTEND; 10497 else if (Args[i].IsZExt) 10498 ExtendKind = ISD::ZERO_EXTEND; 10499 10500 // Conservatively only handle 'returned' on non-vectors that can be lowered, 10501 // for now. 10502 if (Args[i].IsReturned && !Op.getValueType().isVector() && 10503 CanLowerReturn) { 10504 assert((CLI.RetTy == Args[i].Ty || 10505 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 10506 CLI.RetTy->getPointerAddressSpace() == 10507 Args[i].Ty->getPointerAddressSpace())) && 10508 RetTys.size() == NumValues && "unexpected use of 'returned'"); 10509 // Before passing 'returned' to the target lowering code, ensure that 10510 // either the register MVT and the actual EVT are the same size or that 10511 // the return value and argument are extended in the same way; in these 10512 // cases it's safe to pass the argument register value unchanged as the 10513 // return register value (although it's at the target's option whether 10514 // to do so) 10515 // TODO: allow code generation to take advantage of partially preserved 10516 // registers rather than clobbering the entire register when the 10517 // parameter extension method is not compatible with the return 10518 // extension method 10519 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 10520 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 10521 CLI.RetZExt == Args[i].IsZExt)) 10522 Flags.setReturned(); 10523 } 10524 10525 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 10526 CLI.CallConv, ExtendKind); 10527 10528 for (unsigned j = 0; j != NumParts; ++j) { 10529 // if it isn't first piece, alignment must be 1 10530 // For scalable vectors the scalable part is currently handled 10531 // by individual targets, so we just use the known minimum size here. 10532 ISD::OutputArg MyFlags( 10533 Flags, Parts[j].getValueType().getSimpleVT(), VT, 10534 i < CLI.NumFixedArgs, i, 10535 j * Parts[j].getValueType().getStoreSize().getKnownMinValue()); 10536 if (NumParts > 1 && j == 0) 10537 MyFlags.Flags.setSplit(); 10538 else if (j != 0) { 10539 MyFlags.Flags.setOrigAlign(Align(1)); 10540 if (j == NumParts - 1) 10541 MyFlags.Flags.setSplitEnd(); 10542 } 10543 10544 CLI.Outs.push_back(MyFlags); 10545 CLI.OutVals.push_back(Parts[j]); 10546 } 10547 10548 if (NeedsRegBlock && Value == NumValues - 1) 10549 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 10550 } 10551 } 10552 10553 SmallVector<SDValue, 4> InVals; 10554 CLI.Chain = LowerCall(CLI, InVals); 10555 10556 // Update CLI.InVals to use outside of this function. 10557 CLI.InVals = InVals; 10558 10559 // Verify that the target's LowerCall behaved as expected. 10560 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 10561 "LowerCall didn't return a valid chain!"); 10562 assert((!CLI.IsTailCall || InVals.empty()) && 10563 "LowerCall emitted a return value for a tail call!"); 10564 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 10565 "LowerCall didn't emit the correct number of values!"); 10566 10567 // For a tail call, the return value is merely live-out and there aren't 10568 // any nodes in the DAG representing it. Return a special value to 10569 // indicate that a tail call has been emitted and no more Instructions 10570 // should be processed in the current block. 10571 if (CLI.IsTailCall) { 10572 CLI.DAG.setRoot(CLI.Chain); 10573 return std::make_pair(SDValue(), SDValue()); 10574 } 10575 10576 #ifndef NDEBUG 10577 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 10578 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 10579 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 10580 "LowerCall emitted a value with the wrong type!"); 10581 } 10582 #endif 10583 10584 SmallVector<SDValue, 4> ReturnValues; 10585 if (!CanLowerReturn) { 10586 // The instruction result is the result of loading from the 10587 // hidden sret parameter. 10588 SmallVector<EVT, 1> PVTs; 10589 Type *PtrRetTy = 10590 PointerType::get(OrigRetTy->getContext(), DL.getAllocaAddrSpace()); 10591 10592 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 10593 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 10594 EVT PtrVT = PVTs[0]; 10595 10596 unsigned NumValues = RetTys.size(); 10597 ReturnValues.resize(NumValues); 10598 SmallVector<SDValue, 4> Chains(NumValues); 10599 10600 // An aggregate return value cannot wrap around the address space, so 10601 // offsets to its parts don't wrap either. 10602 SDNodeFlags Flags; 10603 Flags.setNoUnsignedWrap(true); 10604 10605 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10606 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 10607 for (unsigned i = 0; i < NumValues; ++i) { 10608 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 10609 CLI.DAG.getConstant(Offsets[i], CLI.DL, 10610 PtrVT), Flags); 10611 SDValue L = CLI.DAG.getLoad( 10612 RetTys[i], CLI.DL, CLI.Chain, Add, 10613 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 10614 DemoteStackIdx, Offsets[i]), 10615 HiddenSRetAlign); 10616 ReturnValues[i] = L; 10617 Chains[i] = L.getValue(1); 10618 } 10619 10620 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 10621 } else { 10622 // Collect the legal value parts into potentially illegal values 10623 // that correspond to the original function's return values. 10624 std::optional<ISD::NodeType> AssertOp; 10625 if (CLI.RetSExt) 10626 AssertOp = ISD::AssertSext; 10627 else if (CLI.RetZExt) 10628 AssertOp = ISD::AssertZext; 10629 unsigned CurReg = 0; 10630 for (EVT VT : RetTys) { 10631 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10632 CLI.CallConv, VT); 10633 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10634 CLI.CallConv, VT); 10635 10636 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 10637 NumRegs, RegisterVT, VT, nullptr, 10638 CLI.CallConv, AssertOp)); 10639 CurReg += NumRegs; 10640 } 10641 10642 // For a function returning void, there is no return value. We can't create 10643 // such a node, so we just return a null return value in that case. In 10644 // that case, nothing will actually look at the value. 10645 if (ReturnValues.empty()) 10646 return std::make_pair(SDValue(), CLI.Chain); 10647 } 10648 10649 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 10650 CLI.DAG.getVTList(RetTys), ReturnValues); 10651 return std::make_pair(Res, CLI.Chain); 10652 } 10653 10654 /// Places new result values for the node in Results (their number 10655 /// and types must exactly match those of the original return values of 10656 /// the node), or leaves Results empty, which indicates that the node is not 10657 /// to be custom lowered after all. 10658 void TargetLowering::LowerOperationWrapper(SDNode *N, 10659 SmallVectorImpl<SDValue> &Results, 10660 SelectionDAG &DAG) const { 10661 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 10662 10663 if (!Res.getNode()) 10664 return; 10665 10666 // If the original node has one result, take the return value from 10667 // LowerOperation as is. It might not be result number 0. 10668 if (N->getNumValues() == 1) { 10669 Results.push_back(Res); 10670 return; 10671 } 10672 10673 // If the original node has multiple results, then the return node should 10674 // have the same number of results. 10675 assert((N->getNumValues() == Res->getNumValues()) && 10676 "Lowering returned the wrong number of results!"); 10677 10678 // Places new result values base on N result number. 10679 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 10680 Results.push_back(Res.getValue(I)); 10681 } 10682 10683 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10684 llvm_unreachable("LowerOperation not implemented for this target!"); 10685 } 10686 10687 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, 10688 unsigned Reg, 10689 ISD::NodeType ExtendType) { 10690 SDValue Op = getNonRegisterValue(V); 10691 assert((Op.getOpcode() != ISD::CopyFromReg || 10692 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 10693 "Copy from a reg to the same reg!"); 10694 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 10695 10696 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10697 // If this is an InlineAsm we have to match the registers required, not the 10698 // notional registers required by the type. 10699 10700 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 10701 std::nullopt); // This is not an ABI copy. 10702 SDValue Chain = DAG.getEntryNode(); 10703 10704 if (ExtendType == ISD::ANY_EXTEND) { 10705 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V); 10706 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end()) 10707 ExtendType = PreferredExtendIt->second; 10708 } 10709 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 10710 PendingExports.push_back(Chain); 10711 } 10712 10713 #include "llvm/CodeGen/SelectionDAGISel.h" 10714 10715 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 10716 /// entry block, return true. This includes arguments used by switches, since 10717 /// the switch may expand into multiple basic blocks. 10718 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 10719 // With FastISel active, we may be splitting blocks, so force creation 10720 // of virtual registers for all non-dead arguments. 10721 if (FastISel) 10722 return A->use_empty(); 10723 10724 const BasicBlock &Entry = A->getParent()->front(); 10725 for (const User *U : A->users()) 10726 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 10727 return false; // Use not in entry block. 10728 10729 return true; 10730 } 10731 10732 using ArgCopyElisionMapTy = 10733 DenseMap<const Argument *, 10734 std::pair<const AllocaInst *, const StoreInst *>>; 10735 10736 /// Scan the entry block of the function in FuncInfo for arguments that look 10737 /// like copies into a local alloca. Record any copied arguments in 10738 /// ArgCopyElisionCandidates. 10739 static void 10740 findArgumentCopyElisionCandidates(const DataLayout &DL, 10741 FunctionLoweringInfo *FuncInfo, 10742 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 10743 // Record the state of every static alloca used in the entry block. Argument 10744 // allocas are all used in the entry block, so we need approximately as many 10745 // entries as we have arguments. 10746 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 10747 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 10748 unsigned NumArgs = FuncInfo->Fn->arg_size(); 10749 StaticAllocas.reserve(NumArgs * 2); 10750 10751 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 10752 if (!V) 10753 return nullptr; 10754 V = V->stripPointerCasts(); 10755 const auto *AI = dyn_cast<AllocaInst>(V); 10756 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 10757 return nullptr; 10758 auto Iter = StaticAllocas.insert({AI, Unknown}); 10759 return &Iter.first->second; 10760 }; 10761 10762 // Look for stores of arguments to static allocas. Look through bitcasts and 10763 // GEPs to handle type coercions, as long as the alloca is fully initialized 10764 // by the store. Any non-store use of an alloca escapes it and any subsequent 10765 // unanalyzed store might write it. 10766 // FIXME: Handle structs initialized with multiple stores. 10767 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 10768 // Look for stores, and handle non-store uses conservatively. 10769 const auto *SI = dyn_cast<StoreInst>(&I); 10770 if (!SI) { 10771 // We will look through cast uses, so ignore them completely. 10772 if (I.isCast()) 10773 continue; 10774 // Ignore debug info and pseudo op intrinsics, they don't escape or store 10775 // to allocas. 10776 if (I.isDebugOrPseudoInst()) 10777 continue; 10778 // This is an unknown instruction. Assume it escapes or writes to all 10779 // static alloca operands. 10780 for (const Use &U : I.operands()) { 10781 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 10782 *Info = StaticAllocaInfo::Clobbered; 10783 } 10784 continue; 10785 } 10786 10787 // If the stored value is a static alloca, mark it as escaped. 10788 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 10789 *Info = StaticAllocaInfo::Clobbered; 10790 10791 // Check if the destination is a static alloca. 10792 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 10793 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 10794 if (!Info) 10795 continue; 10796 const AllocaInst *AI = cast<AllocaInst>(Dst); 10797 10798 // Skip allocas that have been initialized or clobbered. 10799 if (*Info != StaticAllocaInfo::Unknown) 10800 continue; 10801 10802 // Check if the stored value is an argument, and that this store fully 10803 // initializes the alloca. 10804 // If the argument type has padding bits we can't directly forward a pointer 10805 // as the upper bits may contain garbage. 10806 // Don't elide copies from the same argument twice. 10807 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 10808 const auto *Arg = dyn_cast<Argument>(Val); 10809 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 10810 Arg->getType()->isEmptyTy() || 10811 DL.getTypeStoreSize(Arg->getType()) != 10812 DL.getTypeAllocSize(AI->getAllocatedType()) || 10813 !DL.typeSizeEqualsStoreSize(Arg->getType()) || 10814 ArgCopyElisionCandidates.count(Arg)) { 10815 *Info = StaticAllocaInfo::Clobbered; 10816 continue; 10817 } 10818 10819 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 10820 << '\n'); 10821 10822 // Mark this alloca and store for argument copy elision. 10823 *Info = StaticAllocaInfo::Elidable; 10824 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 10825 10826 // Stop scanning if we've seen all arguments. This will happen early in -O0 10827 // builds, which is useful, because -O0 builds have large entry blocks and 10828 // many allocas. 10829 if (ArgCopyElisionCandidates.size() == NumArgs) 10830 break; 10831 } 10832 } 10833 10834 /// Try to elide argument copies from memory into a local alloca. Succeeds if 10835 /// ArgVal is a load from a suitable fixed stack object. 10836 static void tryToElideArgumentCopy( 10837 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 10838 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 10839 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 10840 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 10841 ArrayRef<SDValue> ArgVals, bool &ArgHasUses) { 10842 // Check if this is a load from a fixed stack object. 10843 auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]); 10844 if (!LNode) 10845 return; 10846 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 10847 if (!FINode) 10848 return; 10849 10850 // Check that the fixed stack object is the right size and alignment. 10851 // Look at the alignment that the user wrote on the alloca instead of looking 10852 // at the stack object. 10853 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 10854 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 10855 const AllocaInst *AI = ArgCopyIter->second.first; 10856 int FixedIndex = FINode->getIndex(); 10857 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 10858 int OldIndex = AllocaIndex; 10859 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 10860 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 10861 LLVM_DEBUG( 10862 dbgs() << " argument copy elision failed due to bad fixed stack " 10863 "object size\n"); 10864 return; 10865 } 10866 Align RequiredAlignment = AI->getAlign(); 10867 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 10868 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 10869 "greater than stack argument alignment (" 10870 << DebugStr(RequiredAlignment) << " vs " 10871 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 10872 return; 10873 } 10874 10875 // Perform the elision. Delete the old stack object and replace its only use 10876 // in the variable info map. Mark the stack object as mutable. 10877 LLVM_DEBUG({ 10878 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 10879 << " Replacing frame index " << OldIndex << " with " << FixedIndex 10880 << '\n'; 10881 }); 10882 MFI.RemoveStackObject(OldIndex); 10883 MFI.setIsImmutableObjectIndex(FixedIndex, false); 10884 AllocaIndex = FixedIndex; 10885 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 10886 for (SDValue ArgVal : ArgVals) 10887 Chains.push_back(ArgVal.getValue(1)); 10888 10889 // Avoid emitting code for the store implementing the copy. 10890 const StoreInst *SI = ArgCopyIter->second.second; 10891 ElidedArgCopyInstrs.insert(SI); 10892 10893 // Check for uses of the argument again so that we can avoid exporting ArgVal 10894 // if it is't used by anything other than the store. 10895 for (const Value *U : Arg.users()) { 10896 if (U != SI) { 10897 ArgHasUses = true; 10898 break; 10899 } 10900 } 10901 } 10902 10903 void SelectionDAGISel::LowerArguments(const Function &F) { 10904 SelectionDAG &DAG = SDB->DAG; 10905 SDLoc dl = SDB->getCurSDLoc(); 10906 const DataLayout &DL = DAG.getDataLayout(); 10907 SmallVector<ISD::InputArg, 16> Ins; 10908 10909 // In Naked functions we aren't going to save any registers. 10910 if (F.hasFnAttribute(Attribute::Naked)) 10911 return; 10912 10913 if (!FuncInfo->CanLowerReturn) { 10914 // Put in an sret pointer parameter before all the other parameters. 10915 SmallVector<EVT, 1> ValueVTs; 10916 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10917 PointerType::get(F.getContext(), 10918 DAG.getDataLayout().getAllocaAddrSpace()), 10919 ValueVTs); 10920 10921 // NOTE: Assuming that a pointer will never break down to more than one VT 10922 // or one register. 10923 ISD::ArgFlagsTy Flags; 10924 Flags.setSRet(); 10925 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 10926 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 10927 ISD::InputArg::NoArgIndex, 0); 10928 Ins.push_back(RetArg); 10929 } 10930 10931 // Look for stores of arguments to static allocas. Mark such arguments with a 10932 // flag to ask the target to give us the memory location of that argument if 10933 // available. 10934 ArgCopyElisionMapTy ArgCopyElisionCandidates; 10935 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 10936 ArgCopyElisionCandidates); 10937 10938 // Set up the incoming argument description vector. 10939 for (const Argument &Arg : F.args()) { 10940 unsigned ArgNo = Arg.getArgNo(); 10941 SmallVector<EVT, 4> ValueVTs; 10942 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10943 bool isArgValueUsed = !Arg.use_empty(); 10944 unsigned PartBase = 0; 10945 Type *FinalType = Arg.getType(); 10946 if (Arg.hasAttribute(Attribute::ByVal)) 10947 FinalType = Arg.getParamByValType(); 10948 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 10949 FinalType, F.getCallingConv(), F.isVarArg(), DL); 10950 for (unsigned Value = 0, NumValues = ValueVTs.size(); 10951 Value != NumValues; ++Value) { 10952 EVT VT = ValueVTs[Value]; 10953 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 10954 ISD::ArgFlagsTy Flags; 10955 10956 10957 if (Arg.getType()->isPointerTy()) { 10958 Flags.setPointer(); 10959 Flags.setPointerAddrSpace( 10960 cast<PointerType>(Arg.getType())->getAddressSpace()); 10961 } 10962 if (Arg.hasAttribute(Attribute::ZExt)) 10963 Flags.setZExt(); 10964 if (Arg.hasAttribute(Attribute::SExt)) 10965 Flags.setSExt(); 10966 if (Arg.hasAttribute(Attribute::InReg)) { 10967 // If we are using vectorcall calling convention, a structure that is 10968 // passed InReg - is surely an HVA 10969 if (F.getCallingConv() == CallingConv::X86_VectorCall && 10970 isa<StructType>(Arg.getType())) { 10971 // The first value of a structure is marked 10972 if (0 == Value) 10973 Flags.setHvaStart(); 10974 Flags.setHva(); 10975 } 10976 // Set InReg Flag 10977 Flags.setInReg(); 10978 } 10979 if (Arg.hasAttribute(Attribute::StructRet)) 10980 Flags.setSRet(); 10981 if (Arg.hasAttribute(Attribute::SwiftSelf)) 10982 Flags.setSwiftSelf(); 10983 if (Arg.hasAttribute(Attribute::SwiftAsync)) 10984 Flags.setSwiftAsync(); 10985 if (Arg.hasAttribute(Attribute::SwiftError)) 10986 Flags.setSwiftError(); 10987 if (Arg.hasAttribute(Attribute::ByVal)) 10988 Flags.setByVal(); 10989 if (Arg.hasAttribute(Attribute::ByRef)) 10990 Flags.setByRef(); 10991 if (Arg.hasAttribute(Attribute::InAlloca)) { 10992 Flags.setInAlloca(); 10993 // Set the byval flag for CCAssignFn callbacks that don't know about 10994 // inalloca. This way we can know how many bytes we should've allocated 10995 // and how many bytes a callee cleanup function will pop. If we port 10996 // inalloca to more targets, we'll have to add custom inalloca handling 10997 // in the various CC lowering callbacks. 10998 Flags.setByVal(); 10999 } 11000 if (Arg.hasAttribute(Attribute::Preallocated)) { 11001 Flags.setPreallocated(); 11002 // Set the byval flag for CCAssignFn callbacks that don't know about 11003 // preallocated. This way we can know how many bytes we should've 11004 // allocated and how many bytes a callee cleanup function will pop. If 11005 // we port preallocated to more targets, we'll have to add custom 11006 // preallocated handling in the various CC lowering callbacks. 11007 Flags.setByVal(); 11008 } 11009 11010 // Certain targets (such as MIPS), may have a different ABI alignment 11011 // for a type depending on the context. Give the target a chance to 11012 // specify the alignment it wants. 11013 const Align OriginalAlignment( 11014 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 11015 Flags.setOrigAlign(OriginalAlignment); 11016 11017 Align MemAlign; 11018 Type *ArgMemTy = nullptr; 11019 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 11020 Flags.isByRef()) { 11021 if (!ArgMemTy) 11022 ArgMemTy = Arg.getPointeeInMemoryValueType(); 11023 11024 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 11025 11026 // For in-memory arguments, size and alignment should be passed from FE. 11027 // BE will guess if this info is not there but there are cases it cannot 11028 // get right. 11029 if (auto ParamAlign = Arg.getParamStackAlign()) 11030 MemAlign = *ParamAlign; 11031 else if ((ParamAlign = Arg.getParamAlign())) 11032 MemAlign = *ParamAlign; 11033 else 11034 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 11035 if (Flags.isByRef()) 11036 Flags.setByRefSize(MemSize); 11037 else 11038 Flags.setByValSize(MemSize); 11039 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 11040 MemAlign = *ParamAlign; 11041 } else { 11042 MemAlign = OriginalAlignment; 11043 } 11044 Flags.setMemAlign(MemAlign); 11045 11046 if (Arg.hasAttribute(Attribute::Nest)) 11047 Flags.setNest(); 11048 if (NeedsRegBlock) 11049 Flags.setInConsecutiveRegs(); 11050 if (ArgCopyElisionCandidates.count(&Arg)) 11051 Flags.setCopyElisionCandidate(); 11052 if (Arg.hasAttribute(Attribute::Returned)) 11053 Flags.setReturned(); 11054 11055 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 11056 *CurDAG->getContext(), F.getCallingConv(), VT); 11057 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 11058 *CurDAG->getContext(), F.getCallingConv(), VT); 11059 for (unsigned i = 0; i != NumRegs; ++i) { 11060 // For scalable vectors, use the minimum size; individual targets 11061 // are responsible for handling scalable vector arguments and 11062 // return values. 11063 ISD::InputArg MyFlags( 11064 Flags, RegisterVT, VT, isArgValueUsed, ArgNo, 11065 PartBase + i * RegisterVT.getStoreSize().getKnownMinValue()); 11066 if (NumRegs > 1 && i == 0) 11067 MyFlags.Flags.setSplit(); 11068 // if it isn't first piece, alignment must be 1 11069 else if (i > 0) { 11070 MyFlags.Flags.setOrigAlign(Align(1)); 11071 if (i == NumRegs - 1) 11072 MyFlags.Flags.setSplitEnd(); 11073 } 11074 Ins.push_back(MyFlags); 11075 } 11076 if (NeedsRegBlock && Value == NumValues - 1) 11077 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 11078 PartBase += VT.getStoreSize().getKnownMinValue(); 11079 } 11080 } 11081 11082 // Call the target to set up the argument values. 11083 SmallVector<SDValue, 8> InVals; 11084 SDValue NewRoot = TLI->LowerFormalArguments( 11085 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 11086 11087 // Verify that the target's LowerFormalArguments behaved as expected. 11088 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 11089 "LowerFormalArguments didn't return a valid chain!"); 11090 assert(InVals.size() == Ins.size() && 11091 "LowerFormalArguments didn't emit the correct number of values!"); 11092 LLVM_DEBUG({ 11093 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 11094 assert(InVals[i].getNode() && 11095 "LowerFormalArguments emitted a null value!"); 11096 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 11097 "LowerFormalArguments emitted a value with the wrong type!"); 11098 } 11099 }); 11100 11101 // Update the DAG with the new chain value resulting from argument lowering. 11102 DAG.setRoot(NewRoot); 11103 11104 // Set up the argument values. 11105 unsigned i = 0; 11106 if (!FuncInfo->CanLowerReturn) { 11107 // Create a virtual register for the sret pointer, and put in a copy 11108 // from the sret argument into it. 11109 SmallVector<EVT, 1> ValueVTs; 11110 ComputeValueVTs(*TLI, DAG.getDataLayout(), 11111 PointerType::get(F.getContext(), 11112 DAG.getDataLayout().getAllocaAddrSpace()), 11113 ValueVTs); 11114 MVT VT = ValueVTs[0].getSimpleVT(); 11115 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 11116 std::optional<ISD::NodeType> AssertOp; 11117 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 11118 nullptr, F.getCallingConv(), AssertOp); 11119 11120 MachineFunction& MF = SDB->DAG.getMachineFunction(); 11121 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 11122 Register SRetReg = 11123 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 11124 FuncInfo->DemoteRegister = SRetReg; 11125 NewRoot = 11126 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 11127 DAG.setRoot(NewRoot); 11128 11129 // i indexes lowered arguments. Bump it past the hidden sret argument. 11130 ++i; 11131 } 11132 11133 SmallVector<SDValue, 4> Chains; 11134 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 11135 for (const Argument &Arg : F.args()) { 11136 SmallVector<SDValue, 4> ArgValues; 11137 SmallVector<EVT, 4> ValueVTs; 11138 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 11139 unsigned NumValues = ValueVTs.size(); 11140 if (NumValues == 0) 11141 continue; 11142 11143 bool ArgHasUses = !Arg.use_empty(); 11144 11145 // Elide the copying store if the target loaded this argument from a 11146 // suitable fixed stack object. 11147 if (Ins[i].Flags.isCopyElisionCandidate()) { 11148 unsigned NumParts = 0; 11149 for (EVT VT : ValueVTs) 11150 NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), 11151 F.getCallingConv(), VT); 11152 11153 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 11154 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 11155 ArrayRef(&InVals[i], NumParts), ArgHasUses); 11156 } 11157 11158 // If this argument is unused then remember its value. It is used to generate 11159 // debugging information. 11160 bool isSwiftErrorArg = 11161 TLI->supportSwiftError() && 11162 Arg.hasAttribute(Attribute::SwiftError); 11163 if (!ArgHasUses && !isSwiftErrorArg) { 11164 SDB->setUnusedArgValue(&Arg, InVals[i]); 11165 11166 // Also remember any frame index for use in FastISel. 11167 if (FrameIndexSDNode *FI = 11168 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 11169 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11170 } 11171 11172 for (unsigned Val = 0; Val != NumValues; ++Val) { 11173 EVT VT = ValueVTs[Val]; 11174 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 11175 F.getCallingConv(), VT); 11176 unsigned NumParts = TLI->getNumRegistersForCallingConv( 11177 *CurDAG->getContext(), F.getCallingConv(), VT); 11178 11179 // Even an apparent 'unused' swifterror argument needs to be returned. So 11180 // we do generate a copy for it that can be used on return from the 11181 // function. 11182 if (ArgHasUses || isSwiftErrorArg) { 11183 std::optional<ISD::NodeType> AssertOp; 11184 if (Arg.hasAttribute(Attribute::SExt)) 11185 AssertOp = ISD::AssertSext; 11186 else if (Arg.hasAttribute(Attribute::ZExt)) 11187 AssertOp = ISD::AssertZext; 11188 11189 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 11190 PartVT, VT, nullptr, 11191 F.getCallingConv(), AssertOp)); 11192 } 11193 11194 i += NumParts; 11195 } 11196 11197 // We don't need to do anything else for unused arguments. 11198 if (ArgValues.empty()) 11199 continue; 11200 11201 // Note down frame index. 11202 if (FrameIndexSDNode *FI = 11203 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 11204 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11205 11206 SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues), 11207 SDB->getCurSDLoc()); 11208 11209 SDB->setValue(&Arg, Res); 11210 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 11211 // We want to associate the argument with the frame index, among 11212 // involved operands, that correspond to the lowest address. The 11213 // getCopyFromParts function, called earlier, is swapping the order of 11214 // the operands to BUILD_PAIR depending on endianness. The result of 11215 // that swapping is that the least significant bits of the argument will 11216 // be in the first operand of the BUILD_PAIR node, and the most 11217 // significant bits will be in the second operand. 11218 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 11219 if (LoadSDNode *LNode = 11220 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 11221 if (FrameIndexSDNode *FI = 11222 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 11223 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11224 } 11225 11226 // Analyses past this point are naive and don't expect an assertion. 11227 if (Res.getOpcode() == ISD::AssertZext) 11228 Res = Res.getOperand(0); 11229 11230 // Update the SwiftErrorVRegDefMap. 11231 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 11232 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 11233 if (Register::isVirtualRegister(Reg)) 11234 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 11235 Reg); 11236 } 11237 11238 // If this argument is live outside of the entry block, insert a copy from 11239 // wherever we got it to the vreg that other BB's will reference it as. 11240 if (Res.getOpcode() == ISD::CopyFromReg) { 11241 // If we can, though, try to skip creating an unnecessary vreg. 11242 // FIXME: This isn't very clean... it would be nice to make this more 11243 // general. 11244 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 11245 if (Register::isVirtualRegister(Reg)) { 11246 FuncInfo->ValueMap[&Arg] = Reg; 11247 continue; 11248 } 11249 } 11250 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 11251 FuncInfo->InitializeRegForValue(&Arg); 11252 SDB->CopyToExportRegsIfNeeded(&Arg); 11253 } 11254 } 11255 11256 if (!Chains.empty()) { 11257 Chains.push_back(NewRoot); 11258 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 11259 } 11260 11261 DAG.setRoot(NewRoot); 11262 11263 assert(i == InVals.size() && "Argument register count mismatch!"); 11264 11265 // If any argument copy elisions occurred and we have debug info, update the 11266 // stale frame indices used in the dbg.declare variable info table. 11267 if (!ArgCopyElisionFrameIndexMap.empty()) { 11268 for (MachineFunction::VariableDbgInfo &VI : 11269 MF->getInStackSlotVariableDbgInfo()) { 11270 auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot()); 11271 if (I != ArgCopyElisionFrameIndexMap.end()) 11272 VI.updateStackSlot(I->second); 11273 } 11274 } 11275 11276 // Finally, if the target has anything special to do, allow it to do so. 11277 emitFunctionEntryCode(); 11278 } 11279 11280 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 11281 /// ensure constants are generated when needed. Remember the virtual registers 11282 /// that need to be added to the Machine PHI nodes as input. We cannot just 11283 /// directly add them, because expansion might result in multiple MBB's for one 11284 /// BB. As such, the start of the BB might correspond to a different MBB than 11285 /// the end. 11286 void 11287 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 11288 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11289 11290 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 11291 11292 // Check PHI nodes in successors that expect a value to be available from this 11293 // block. 11294 for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) { 11295 if (!isa<PHINode>(SuccBB->begin())) continue; 11296 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 11297 11298 // If this terminator has multiple identical successors (common for 11299 // switches), only handle each succ once. 11300 if (!SuccsHandled.insert(SuccMBB).second) 11301 continue; 11302 11303 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 11304 11305 // At this point we know that there is a 1-1 correspondence between LLVM PHI 11306 // nodes and Machine PHI nodes, but the incoming operands have not been 11307 // emitted yet. 11308 for (const PHINode &PN : SuccBB->phis()) { 11309 // Ignore dead phi's. 11310 if (PN.use_empty()) 11311 continue; 11312 11313 // Skip empty types 11314 if (PN.getType()->isEmptyTy()) 11315 continue; 11316 11317 unsigned Reg; 11318 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 11319 11320 if (const auto *C = dyn_cast<Constant>(PHIOp)) { 11321 unsigned &RegOut = ConstantsOut[C]; 11322 if (RegOut == 0) { 11323 RegOut = FuncInfo.CreateRegs(C); 11324 // We need to zero/sign extend ConstantInt phi operands to match 11325 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo. 11326 ISD::NodeType ExtendType = ISD::ANY_EXTEND; 11327 if (auto *CI = dyn_cast<ConstantInt>(C)) 11328 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND 11329 : ISD::ZERO_EXTEND; 11330 CopyValueToVirtualRegister(C, RegOut, ExtendType); 11331 } 11332 Reg = RegOut; 11333 } else { 11334 DenseMap<const Value *, Register>::iterator I = 11335 FuncInfo.ValueMap.find(PHIOp); 11336 if (I != FuncInfo.ValueMap.end()) 11337 Reg = I->second; 11338 else { 11339 assert(isa<AllocaInst>(PHIOp) && 11340 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 11341 "Didn't codegen value into a register!??"); 11342 Reg = FuncInfo.CreateRegs(PHIOp); 11343 CopyValueToVirtualRegister(PHIOp, Reg); 11344 } 11345 } 11346 11347 // Remember that this register needs to added to the machine PHI node as 11348 // the input for this MBB. 11349 SmallVector<EVT, 4> ValueVTs; 11350 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 11351 for (EVT VT : ValueVTs) { 11352 const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 11353 for (unsigned i = 0; i != NumRegisters; ++i) 11354 FuncInfo.PHINodesToUpdate.push_back( 11355 std::make_pair(&*MBBI++, Reg + i)); 11356 Reg += NumRegisters; 11357 } 11358 } 11359 } 11360 11361 ConstantsOut.clear(); 11362 } 11363 11364 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 11365 MachineFunction::iterator I(MBB); 11366 if (++I == FuncInfo.MF->end()) 11367 return nullptr; 11368 return &*I; 11369 } 11370 11371 /// During lowering new call nodes can be created (such as memset, etc.). 11372 /// Those will become new roots of the current DAG, but complications arise 11373 /// when they are tail calls. In such cases, the call lowering will update 11374 /// the root, but the builder still needs to know that a tail call has been 11375 /// lowered in order to avoid generating an additional return. 11376 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 11377 // If the node is null, we do have a tail call. 11378 if (MaybeTC.getNode() != nullptr) 11379 DAG.setRoot(MaybeTC); 11380 else 11381 HasTailCall = true; 11382 } 11383 11384 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 11385 MachineBasicBlock *SwitchMBB, 11386 MachineBasicBlock *DefaultMBB) { 11387 MachineFunction *CurMF = FuncInfo.MF; 11388 MachineBasicBlock *NextMBB = nullptr; 11389 MachineFunction::iterator BBI(W.MBB); 11390 if (++BBI != FuncInfo.MF->end()) 11391 NextMBB = &*BBI; 11392 11393 unsigned Size = W.LastCluster - W.FirstCluster + 1; 11394 11395 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11396 11397 if (Size == 2 && W.MBB == SwitchMBB) { 11398 // If any two of the cases has the same destination, and if one value 11399 // is the same as the other, but has one bit unset that the other has set, 11400 // use bit manipulation to do two compares at once. For example: 11401 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 11402 // TODO: This could be extended to merge any 2 cases in switches with 3 11403 // cases. 11404 // TODO: Handle cases where W.CaseBB != SwitchBB. 11405 CaseCluster &Small = *W.FirstCluster; 11406 CaseCluster &Big = *W.LastCluster; 11407 11408 if (Small.Low == Small.High && Big.Low == Big.High && 11409 Small.MBB == Big.MBB) { 11410 const APInt &SmallValue = Small.Low->getValue(); 11411 const APInt &BigValue = Big.Low->getValue(); 11412 11413 // Check that there is only one bit different. 11414 APInt CommonBit = BigValue ^ SmallValue; 11415 if (CommonBit.isPowerOf2()) { 11416 SDValue CondLHS = getValue(Cond); 11417 EVT VT = CondLHS.getValueType(); 11418 SDLoc DL = getCurSDLoc(); 11419 11420 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 11421 DAG.getConstant(CommonBit, DL, VT)); 11422 SDValue Cond = DAG.getSetCC( 11423 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 11424 ISD::SETEQ); 11425 11426 // Update successor info. 11427 // Both Small and Big will jump to Small.BB, so we sum up the 11428 // probabilities. 11429 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 11430 if (BPI) 11431 addSuccessorWithProb( 11432 SwitchMBB, DefaultMBB, 11433 // The default destination is the first successor in IR. 11434 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 11435 else 11436 addSuccessorWithProb(SwitchMBB, DefaultMBB); 11437 11438 // Insert the true branch. 11439 SDValue BrCond = 11440 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 11441 DAG.getBasicBlock(Small.MBB)); 11442 // Insert the false branch. 11443 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 11444 DAG.getBasicBlock(DefaultMBB)); 11445 11446 DAG.setRoot(BrCond); 11447 return; 11448 } 11449 } 11450 } 11451 11452 if (TM.getOptLevel() != CodeGenOptLevel::None) { 11453 // Here, we order cases by probability so the most likely case will be 11454 // checked first. However, two clusters can have the same probability in 11455 // which case their relative ordering is non-deterministic. So we use Low 11456 // as a tie-breaker as clusters are guaranteed to never overlap. 11457 llvm::sort(W.FirstCluster, W.LastCluster + 1, 11458 [](const CaseCluster &a, const CaseCluster &b) { 11459 return a.Prob != b.Prob ? 11460 a.Prob > b.Prob : 11461 a.Low->getValue().slt(b.Low->getValue()); 11462 }); 11463 11464 // Rearrange the case blocks so that the last one falls through if possible 11465 // without changing the order of probabilities. 11466 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 11467 --I; 11468 if (I->Prob > W.LastCluster->Prob) 11469 break; 11470 if (I->Kind == CC_Range && I->MBB == NextMBB) { 11471 std::swap(*I, *W.LastCluster); 11472 break; 11473 } 11474 } 11475 } 11476 11477 // Compute total probability. 11478 BranchProbability DefaultProb = W.DefaultProb; 11479 BranchProbability UnhandledProbs = DefaultProb; 11480 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 11481 UnhandledProbs += I->Prob; 11482 11483 MachineBasicBlock *CurMBB = W.MBB; 11484 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 11485 bool FallthroughUnreachable = false; 11486 MachineBasicBlock *Fallthrough; 11487 if (I == W.LastCluster) { 11488 // For the last cluster, fall through to the default destination. 11489 Fallthrough = DefaultMBB; 11490 FallthroughUnreachable = isa<UnreachableInst>( 11491 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 11492 } else { 11493 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 11494 CurMF->insert(BBI, Fallthrough); 11495 // Put Cond in a virtual register to make it available from the new blocks. 11496 ExportFromCurrentBlock(Cond); 11497 } 11498 UnhandledProbs -= I->Prob; 11499 11500 switch (I->Kind) { 11501 case CC_JumpTable: { 11502 // FIXME: Optimize away range check based on pivot comparisons. 11503 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 11504 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 11505 11506 // The jump block hasn't been inserted yet; insert it here. 11507 MachineBasicBlock *JumpMBB = JT->MBB; 11508 CurMF->insert(BBI, JumpMBB); 11509 11510 auto JumpProb = I->Prob; 11511 auto FallthroughProb = UnhandledProbs; 11512 11513 // If the default statement is a target of the jump table, we evenly 11514 // distribute the default probability to successors of CurMBB. Also 11515 // update the probability on the edge from JumpMBB to Fallthrough. 11516 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 11517 SE = JumpMBB->succ_end(); 11518 SI != SE; ++SI) { 11519 if (*SI == DefaultMBB) { 11520 JumpProb += DefaultProb / 2; 11521 FallthroughProb -= DefaultProb / 2; 11522 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 11523 JumpMBB->normalizeSuccProbs(); 11524 break; 11525 } 11526 } 11527 11528 // If the default clause is unreachable, propagate that knowledge into 11529 // JTH->FallthroughUnreachable which will use it to suppress the range 11530 // check. 11531 // 11532 // However, don't do this if we're doing branch target enforcement, 11533 // because a table branch _without_ a range check can be a tempting JOP 11534 // gadget - out-of-bounds inputs that are impossible in correct 11535 // execution become possible again if an attacker can influence the 11536 // control flow. So if an attacker doesn't already have a BTI bypass 11537 // available, we don't want them to be able to get one out of this 11538 // table branch. 11539 if (FallthroughUnreachable) { 11540 Function &CurFunc = CurMF->getFunction(); 11541 bool HasBranchTargetEnforcement = false; 11542 if (CurFunc.hasFnAttribute("branch-target-enforcement")) { 11543 HasBranchTargetEnforcement = 11544 CurFunc.getFnAttribute("branch-target-enforcement") 11545 .getValueAsBool(); 11546 } else { 11547 HasBranchTargetEnforcement = 11548 CurMF->getMMI().getModule()->getModuleFlag( 11549 "branch-target-enforcement"); 11550 } 11551 if (!HasBranchTargetEnforcement) 11552 JTH->FallthroughUnreachable = true; 11553 } 11554 11555 if (!JTH->FallthroughUnreachable) 11556 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 11557 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 11558 CurMBB->normalizeSuccProbs(); 11559 11560 // The jump table header will be inserted in our current block, do the 11561 // range check, and fall through to our fallthrough block. 11562 JTH->HeaderBB = CurMBB; 11563 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 11564 11565 // If we're in the right place, emit the jump table header right now. 11566 if (CurMBB == SwitchMBB) { 11567 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 11568 JTH->Emitted = true; 11569 } 11570 break; 11571 } 11572 case CC_BitTests: { 11573 // FIXME: Optimize away range check based on pivot comparisons. 11574 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 11575 11576 // The bit test blocks haven't been inserted yet; insert them here. 11577 for (BitTestCase &BTC : BTB->Cases) 11578 CurMF->insert(BBI, BTC.ThisBB); 11579 11580 // Fill in fields of the BitTestBlock. 11581 BTB->Parent = CurMBB; 11582 BTB->Default = Fallthrough; 11583 11584 BTB->DefaultProb = UnhandledProbs; 11585 // If the cases in bit test don't form a contiguous range, we evenly 11586 // distribute the probability on the edge to Fallthrough to two 11587 // successors of CurMBB. 11588 if (!BTB->ContiguousRange) { 11589 BTB->Prob += DefaultProb / 2; 11590 BTB->DefaultProb -= DefaultProb / 2; 11591 } 11592 11593 if (FallthroughUnreachable) 11594 BTB->FallthroughUnreachable = true; 11595 11596 // If we're in the right place, emit the bit test header right now. 11597 if (CurMBB == SwitchMBB) { 11598 visitBitTestHeader(*BTB, SwitchMBB); 11599 BTB->Emitted = true; 11600 } 11601 break; 11602 } 11603 case CC_Range: { 11604 const Value *RHS, *LHS, *MHS; 11605 ISD::CondCode CC; 11606 if (I->Low == I->High) { 11607 // Check Cond == I->Low. 11608 CC = ISD::SETEQ; 11609 LHS = Cond; 11610 RHS=I->Low; 11611 MHS = nullptr; 11612 } else { 11613 // Check I->Low <= Cond <= I->High. 11614 CC = ISD::SETLE; 11615 LHS = I->Low; 11616 MHS = Cond; 11617 RHS = I->High; 11618 } 11619 11620 // If Fallthrough is unreachable, fold away the comparison. 11621 if (FallthroughUnreachable) 11622 CC = ISD::SETTRUE; 11623 11624 // The false probability is the sum of all unhandled cases. 11625 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 11626 getCurSDLoc(), I->Prob, UnhandledProbs); 11627 11628 if (CurMBB == SwitchMBB) 11629 visitSwitchCase(CB, SwitchMBB); 11630 else 11631 SL->SwitchCases.push_back(CB); 11632 11633 break; 11634 } 11635 } 11636 CurMBB = Fallthrough; 11637 } 11638 } 11639 11640 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 11641 CaseClusterIt First, 11642 CaseClusterIt Last) { 11643 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 11644 if (X.Prob != CC.Prob) 11645 return X.Prob > CC.Prob; 11646 11647 // Ties are broken by comparing the case value. 11648 return X.Low->getValue().slt(CC.Low->getValue()); 11649 }); 11650 } 11651 11652 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 11653 const SwitchWorkListItem &W, 11654 Value *Cond, 11655 MachineBasicBlock *SwitchMBB) { 11656 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 11657 "Clusters not sorted?"); 11658 11659 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 11660 11661 // Balance the tree based on branch probabilities to create a near-optimal (in 11662 // terms of search time given key frequency) binary search tree. See e.g. Kurt 11663 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 11664 CaseClusterIt LastLeft = W.FirstCluster; 11665 CaseClusterIt FirstRight = W.LastCluster; 11666 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 11667 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 11668 11669 // Move LastLeft and FirstRight towards each other from opposite directions to 11670 // find a partitioning of the clusters which balances the probability on both 11671 // sides. If LeftProb and RightProb are equal, alternate which side is 11672 // taken to ensure 0-probability nodes are distributed evenly. 11673 unsigned I = 0; 11674 while (LastLeft + 1 < FirstRight) { 11675 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 11676 LeftProb += (++LastLeft)->Prob; 11677 else 11678 RightProb += (--FirstRight)->Prob; 11679 I++; 11680 } 11681 11682 while (true) { 11683 // Our binary search tree differs from a typical BST in that ours can have up 11684 // to three values in each leaf. The pivot selection above doesn't take that 11685 // into account, which means the tree might require more nodes and be less 11686 // efficient. We compensate for this here. 11687 11688 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 11689 unsigned NumRight = W.LastCluster - FirstRight + 1; 11690 11691 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 11692 // If one side has less than 3 clusters, and the other has more than 3, 11693 // consider taking a cluster from the other side. 11694 11695 if (NumLeft < NumRight) { 11696 // Consider moving the first cluster on the right to the left side. 11697 CaseCluster &CC = *FirstRight; 11698 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11699 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11700 if (LeftSideRank <= RightSideRank) { 11701 // Moving the cluster to the left does not demote it. 11702 ++LastLeft; 11703 ++FirstRight; 11704 continue; 11705 } 11706 } else { 11707 assert(NumRight < NumLeft); 11708 // Consider moving the last element on the left to the right side. 11709 CaseCluster &CC = *LastLeft; 11710 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11711 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11712 if (RightSideRank <= LeftSideRank) { 11713 // Moving the cluster to the right does not demot it. 11714 --LastLeft; 11715 --FirstRight; 11716 continue; 11717 } 11718 } 11719 } 11720 break; 11721 } 11722 11723 assert(LastLeft + 1 == FirstRight); 11724 assert(LastLeft >= W.FirstCluster); 11725 assert(FirstRight <= W.LastCluster); 11726 11727 // Use the first element on the right as pivot since we will make less-than 11728 // comparisons against it. 11729 CaseClusterIt PivotCluster = FirstRight; 11730 assert(PivotCluster > W.FirstCluster); 11731 assert(PivotCluster <= W.LastCluster); 11732 11733 CaseClusterIt FirstLeft = W.FirstCluster; 11734 CaseClusterIt LastRight = W.LastCluster; 11735 11736 const ConstantInt *Pivot = PivotCluster->Low; 11737 11738 // New blocks will be inserted immediately after the current one. 11739 MachineFunction::iterator BBI(W.MBB); 11740 ++BBI; 11741 11742 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 11743 // we can branch to its destination directly if it's squeezed exactly in 11744 // between the known lower bound and Pivot - 1. 11745 MachineBasicBlock *LeftMBB; 11746 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 11747 FirstLeft->Low == W.GE && 11748 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 11749 LeftMBB = FirstLeft->MBB; 11750 } else { 11751 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11752 FuncInfo.MF->insert(BBI, LeftMBB); 11753 WorkList.push_back( 11754 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 11755 // Put Cond in a virtual register to make it available from the new blocks. 11756 ExportFromCurrentBlock(Cond); 11757 } 11758 11759 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 11760 // single cluster, RHS.Low == Pivot, and we can branch to its destination 11761 // directly if RHS.High equals the current upper bound. 11762 MachineBasicBlock *RightMBB; 11763 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 11764 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 11765 RightMBB = FirstRight->MBB; 11766 } else { 11767 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11768 FuncInfo.MF->insert(BBI, RightMBB); 11769 WorkList.push_back( 11770 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 11771 // Put Cond in a virtual register to make it available from the new blocks. 11772 ExportFromCurrentBlock(Cond); 11773 } 11774 11775 // Create the CaseBlock record that will be used to lower the branch. 11776 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 11777 getCurSDLoc(), LeftProb, RightProb); 11778 11779 if (W.MBB == SwitchMBB) 11780 visitSwitchCase(CB, SwitchMBB); 11781 else 11782 SL->SwitchCases.push_back(CB); 11783 } 11784 11785 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 11786 // from the swith statement. 11787 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 11788 BranchProbability PeeledCaseProb) { 11789 if (PeeledCaseProb == BranchProbability::getOne()) 11790 return BranchProbability::getZero(); 11791 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 11792 11793 uint32_t Numerator = CaseProb.getNumerator(); 11794 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 11795 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 11796 } 11797 11798 // Try to peel the top probability case if it exceeds the threshold. 11799 // Return current MachineBasicBlock for the switch statement if the peeling 11800 // does not occur. 11801 // If the peeling is performed, return the newly created MachineBasicBlock 11802 // for the peeled switch statement. Also update Clusters to remove the peeled 11803 // case. PeeledCaseProb is the BranchProbability for the peeled case. 11804 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 11805 const SwitchInst &SI, CaseClusterVector &Clusters, 11806 BranchProbability &PeeledCaseProb) { 11807 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11808 // Don't perform if there is only one cluster or optimizing for size. 11809 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 11810 TM.getOptLevel() == CodeGenOptLevel::None || 11811 SwitchMBB->getParent()->getFunction().hasMinSize()) 11812 return SwitchMBB; 11813 11814 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 11815 unsigned PeeledCaseIndex = 0; 11816 bool SwitchPeeled = false; 11817 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 11818 CaseCluster &CC = Clusters[Index]; 11819 if (CC.Prob < TopCaseProb) 11820 continue; 11821 TopCaseProb = CC.Prob; 11822 PeeledCaseIndex = Index; 11823 SwitchPeeled = true; 11824 } 11825 if (!SwitchPeeled) 11826 return SwitchMBB; 11827 11828 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 11829 << TopCaseProb << "\n"); 11830 11831 // Record the MBB for the peeled switch statement. 11832 MachineFunction::iterator BBI(SwitchMBB); 11833 ++BBI; 11834 MachineBasicBlock *PeeledSwitchMBB = 11835 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 11836 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 11837 11838 ExportFromCurrentBlock(SI.getCondition()); 11839 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 11840 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 11841 nullptr, nullptr, TopCaseProb.getCompl()}; 11842 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 11843 11844 Clusters.erase(PeeledCaseIt); 11845 for (CaseCluster &CC : Clusters) { 11846 LLVM_DEBUG( 11847 dbgs() << "Scale the probablity for one cluster, before scaling: " 11848 << CC.Prob << "\n"); 11849 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 11850 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 11851 } 11852 PeeledCaseProb = TopCaseProb; 11853 return PeeledSwitchMBB; 11854 } 11855 11856 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 11857 // Extract cases from the switch. 11858 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11859 CaseClusterVector Clusters; 11860 Clusters.reserve(SI.getNumCases()); 11861 for (auto I : SI.cases()) { 11862 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 11863 const ConstantInt *CaseVal = I.getCaseValue(); 11864 BranchProbability Prob = 11865 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 11866 : BranchProbability(1, SI.getNumCases() + 1); 11867 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 11868 } 11869 11870 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 11871 11872 // Cluster adjacent cases with the same destination. We do this at all 11873 // optimization levels because it's cheap to do and will make codegen faster 11874 // if there are many clusters. 11875 sortAndRangeify(Clusters); 11876 11877 // The branch probablity of the peeled case. 11878 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 11879 MachineBasicBlock *PeeledSwitchMBB = 11880 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 11881 11882 // If there is only the default destination, jump there directly. 11883 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11884 if (Clusters.empty()) { 11885 assert(PeeledSwitchMBB == SwitchMBB); 11886 SwitchMBB->addSuccessor(DefaultMBB); 11887 if (DefaultMBB != NextBlock(SwitchMBB)) { 11888 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 11889 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 11890 } 11891 return; 11892 } 11893 11894 SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(), 11895 DAG.getBFI()); 11896 SL->findBitTestClusters(Clusters, &SI); 11897 11898 LLVM_DEBUG({ 11899 dbgs() << "Case clusters: "; 11900 for (const CaseCluster &C : Clusters) { 11901 if (C.Kind == CC_JumpTable) 11902 dbgs() << "JT:"; 11903 if (C.Kind == CC_BitTests) 11904 dbgs() << "BT:"; 11905 11906 C.Low->getValue().print(dbgs(), true); 11907 if (C.Low != C.High) { 11908 dbgs() << '-'; 11909 C.High->getValue().print(dbgs(), true); 11910 } 11911 dbgs() << ' '; 11912 } 11913 dbgs() << '\n'; 11914 }); 11915 11916 assert(!Clusters.empty()); 11917 SwitchWorkList WorkList; 11918 CaseClusterIt First = Clusters.begin(); 11919 CaseClusterIt Last = Clusters.end() - 1; 11920 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 11921 // Scale the branchprobability for DefaultMBB if the peel occurs and 11922 // DefaultMBB is not replaced. 11923 if (PeeledCaseProb != BranchProbability::getZero() && 11924 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 11925 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 11926 WorkList.push_back( 11927 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 11928 11929 while (!WorkList.empty()) { 11930 SwitchWorkListItem W = WorkList.pop_back_val(); 11931 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 11932 11933 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None && 11934 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 11935 // For optimized builds, lower large range as a balanced binary tree. 11936 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 11937 continue; 11938 } 11939 11940 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 11941 } 11942 } 11943 11944 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 11945 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11946 auto DL = getCurSDLoc(); 11947 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11948 setValue(&I, DAG.getStepVector(DL, ResultVT)); 11949 } 11950 11951 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 11952 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11953 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11954 11955 SDLoc DL = getCurSDLoc(); 11956 SDValue V = getValue(I.getOperand(0)); 11957 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 11958 11959 if (VT.isScalableVector()) { 11960 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 11961 return; 11962 } 11963 11964 // Use VECTOR_SHUFFLE for the fixed-length vector 11965 // to maintain existing behavior. 11966 SmallVector<int, 8> Mask; 11967 unsigned NumElts = VT.getVectorMinNumElements(); 11968 for (unsigned i = 0; i != NumElts; ++i) 11969 Mask.push_back(NumElts - 1 - i); 11970 11971 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 11972 } 11973 11974 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) { 11975 auto DL = getCurSDLoc(); 11976 SDValue InVec = getValue(I.getOperand(0)); 11977 EVT OutVT = 11978 InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 11979 11980 unsigned OutNumElts = OutVT.getVectorMinNumElements(); 11981 11982 // ISD Node needs the input vectors split into two equal parts 11983 SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 11984 DAG.getVectorIdxConstant(0, DL)); 11985 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 11986 DAG.getVectorIdxConstant(OutNumElts, DL)); 11987 11988 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 11989 // legalisation and combines. 11990 if (OutVT.isFixedLengthVector()) { 11991 SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 11992 createStrideMask(0, 2, OutNumElts)); 11993 SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 11994 createStrideMask(1, 2, OutNumElts)); 11995 SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc()); 11996 setValue(&I, Res); 11997 return; 11998 } 11999 12000 SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL, 12001 DAG.getVTList(OutVT, OutVT), Lo, Hi); 12002 setValue(&I, Res); 12003 } 12004 12005 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) { 12006 auto DL = getCurSDLoc(); 12007 EVT InVT = getValue(I.getOperand(0)).getValueType(); 12008 SDValue InVec0 = getValue(I.getOperand(0)); 12009 SDValue InVec1 = getValue(I.getOperand(1)); 12010 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12011 EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12012 12013 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 12014 // legalisation and combines. 12015 if (OutVT.isFixedLengthVector()) { 12016 unsigned NumElts = InVT.getVectorMinNumElements(); 12017 SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1); 12018 setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT), 12019 createInterleaveMask(NumElts, 2))); 12020 return; 12021 } 12022 12023 SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, 12024 DAG.getVTList(InVT, InVT), InVec0, InVec1); 12025 Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0), 12026 Res.getValue(1)); 12027 setValue(&I, Res); 12028 } 12029 12030 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 12031 SmallVector<EVT, 4> ValueVTs; 12032 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 12033 ValueVTs); 12034 unsigned NumValues = ValueVTs.size(); 12035 if (NumValues == 0) return; 12036 12037 SmallVector<SDValue, 4> Values(NumValues); 12038 SDValue Op = getValue(I.getOperand(0)); 12039 12040 for (unsigned i = 0; i != NumValues; ++i) 12041 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 12042 SDValue(Op.getNode(), Op.getResNo() + i)); 12043 12044 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 12045 DAG.getVTList(ValueVTs), Values)); 12046 } 12047 12048 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 12049 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12050 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12051 12052 SDLoc DL = getCurSDLoc(); 12053 SDValue V1 = getValue(I.getOperand(0)); 12054 SDValue V2 = getValue(I.getOperand(1)); 12055 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 12056 12057 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 12058 if (VT.isScalableVector()) { 12059 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 12060 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 12061 DAG.getConstant(Imm, DL, IdxVT))); 12062 return; 12063 } 12064 12065 unsigned NumElts = VT.getVectorNumElements(); 12066 12067 uint64_t Idx = (NumElts + Imm) % NumElts; 12068 12069 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 12070 SmallVector<int, 8> Mask; 12071 for (unsigned i = 0; i < NumElts; ++i) 12072 Mask.push_back(Idx + i); 12073 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 12074 } 12075 12076 // Consider the following MIR after SelectionDAG, which produces output in 12077 // phyregs in the first case or virtregs in the second case. 12078 // 12079 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx 12080 // %5:gr32 = COPY $ebx 12081 // %6:gr32 = COPY $edx 12082 // %1:gr32 = COPY %6:gr32 12083 // %0:gr32 = COPY %5:gr32 12084 // 12085 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32 12086 // %1:gr32 = COPY %6:gr32 12087 // %0:gr32 = COPY %5:gr32 12088 // 12089 // Given %0, we'd like to return $ebx in the first case and %5 in the second. 12090 // Given %1, we'd like to return $edx in the first case and %6 in the second. 12091 // 12092 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap 12093 // to a single virtreg (such as %0). The remaining outputs monotonically 12094 // increase in virtreg number from there. If a callbr has no outputs, then it 12095 // should not have a corresponding callbr landingpad; in fact, the callbr 12096 // landingpad would not even be able to refer to such a callbr. 12097 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) { 12098 MachineInstr *MI = MRI.def_begin(Reg)->getParent(); 12099 // There is definitely at least one copy. 12100 assert(MI->getOpcode() == TargetOpcode::COPY && 12101 "start of copy chain MUST be COPY"); 12102 Reg = MI->getOperand(1).getReg(); 12103 MI = MRI.def_begin(Reg)->getParent(); 12104 // There may be an optional second copy. 12105 if (MI->getOpcode() == TargetOpcode::COPY) { 12106 assert(Reg.isVirtual() && "expected COPY of virtual register"); 12107 Reg = MI->getOperand(1).getReg(); 12108 assert(Reg.isPhysical() && "expected COPY of physical register"); 12109 MI = MRI.def_begin(Reg)->getParent(); 12110 } 12111 // The start of the chain must be an INLINEASM_BR. 12112 assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR && 12113 "end of copy chain MUST be INLINEASM_BR"); 12114 return Reg; 12115 } 12116 12117 // We must do this walk rather than the simpler 12118 // setValue(&I, getCopyFromRegs(CBR, CBR->getType())); 12119 // otherwise we will end up with copies of virtregs only valid along direct 12120 // edges. 12121 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) { 12122 SmallVector<EVT, 8> ResultVTs; 12123 SmallVector<SDValue, 8> ResultValues; 12124 const auto *CBR = 12125 cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator()); 12126 12127 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12128 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 12129 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 12130 12131 unsigned InitialDef = FuncInfo.ValueMap[CBR]; 12132 SDValue Chain = DAG.getRoot(); 12133 12134 // Re-parse the asm constraints string. 12135 TargetLowering::AsmOperandInfoVector TargetConstraints = 12136 TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR); 12137 for (auto &T : TargetConstraints) { 12138 SDISelAsmOperandInfo OpInfo(T); 12139 if (OpInfo.Type != InlineAsm::isOutput) 12140 continue; 12141 12142 // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the 12143 // individual constraint. 12144 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 12145 12146 switch (OpInfo.ConstraintType) { 12147 case TargetLowering::C_Register: 12148 case TargetLowering::C_RegisterClass: { 12149 // Fill in OpInfo.AssignedRegs.Regs. 12150 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo); 12151 12152 // getRegistersForValue may produce 1 to many registers based on whether 12153 // the OpInfo.ConstraintVT is legal on the target or not. 12154 for (size_t i = 0, e = OpInfo.AssignedRegs.Regs.size(); i != e; ++i) { 12155 Register OriginalDef = FollowCopyChain(MRI, InitialDef++); 12156 if (Register::isPhysicalRegister(OriginalDef)) 12157 FuncInfo.MBB->addLiveIn(OriginalDef); 12158 // Update the assigned registers to use the original defs. 12159 OpInfo.AssignedRegs.Regs[i] = OriginalDef; 12160 } 12161 12162 SDValue V = OpInfo.AssignedRegs.getCopyFromRegs( 12163 DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR); 12164 ResultValues.push_back(V); 12165 ResultVTs.push_back(OpInfo.ConstraintVT); 12166 break; 12167 } 12168 case TargetLowering::C_Other: { 12169 SDValue Flag; 12170 SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 12171 OpInfo, DAG); 12172 ++InitialDef; 12173 ResultValues.push_back(V); 12174 ResultVTs.push_back(OpInfo.ConstraintVT); 12175 break; 12176 } 12177 default: 12178 break; 12179 } 12180 } 12181 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 12182 DAG.getVTList(ResultVTs), ResultValues); 12183 setValue(&I, V); 12184 } 12185