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::visit(const Instruction &I) { 1152 // Set up outgoing PHI node register values before emitting the terminator. 1153 if (I.isTerminator()) { 1154 HandlePHINodesInSuccessorBlocks(I.getParent()); 1155 } 1156 1157 // Add SDDbgValue nodes for any var locs here. Do so before updating 1158 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1159 if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) { 1160 // Add SDDbgValue nodes for any var locs here. Do so before updating 1161 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1162 for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I); 1163 It != End; ++It) { 1164 auto *Var = FnVarLocs->getDILocalVariable(It->VariableID); 1165 dropDanglingDebugInfo(Var, It->Expr); 1166 if (It->Values.isKillLocation(It->Expr)) { 1167 handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder); 1168 continue; 1169 } 1170 SmallVector<Value *> Values(It->Values.location_ops()); 1171 if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder, 1172 It->Values.hasArgList())) 1173 addDanglingDebugInfo(It, SDNodeOrder); 1174 } 1175 } 1176 1177 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1178 if (!isa<DbgInfoIntrinsic>(I)) 1179 ++SDNodeOrder; 1180 1181 CurInst = &I; 1182 1183 // Set inserted listener only if required. 1184 bool NodeInserted = false; 1185 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener; 1186 MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections); 1187 if (PCSectionsMD) { 1188 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>( 1189 DAG, [&](SDNode *) { NodeInserted = true; }); 1190 } 1191 1192 visit(I.getOpcode(), I); 1193 1194 if (!I.isTerminator() && !HasTailCall && 1195 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1196 CopyToExportRegsIfNeeded(&I); 1197 1198 // Handle metadata. 1199 if (PCSectionsMD) { 1200 auto It = NodeMap.find(&I); 1201 if (It != NodeMap.end()) { 1202 DAG.addPCSections(It->second.getNode(), PCSectionsMD); 1203 } else if (NodeInserted) { 1204 // This should not happen; if it does, don't let it go unnoticed so we can 1205 // fix it. Relevant visit*() function is probably missing a setValue(). 1206 errs() << "warning: loosing !pcsections metadata [" 1207 << I.getModule()->getName() << "]\n"; 1208 LLVM_DEBUG(I.dump()); 1209 assert(false); 1210 } 1211 } 1212 1213 CurInst = nullptr; 1214 } 1215 1216 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1217 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1218 } 1219 1220 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1221 // Note: this doesn't use InstVisitor, because it has to work with 1222 // ConstantExpr's in addition to instructions. 1223 switch (Opcode) { 1224 default: llvm_unreachable("Unknown instruction type encountered!"); 1225 // Build the switch statement using the Instruction.def file. 1226 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1227 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1228 #include "llvm/IR/Instruction.def" 1229 } 1230 } 1231 1232 static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG, 1233 DILocalVariable *Variable, 1234 DebugLoc DL, unsigned Order, 1235 RawLocationWrapper Values, 1236 DIExpression *Expression) { 1237 if (!Values.hasArgList()) 1238 return false; 1239 // For variadic dbg_values we will now insert an undef. 1240 // FIXME: We can potentially recover these! 1241 SmallVector<SDDbgOperand, 2> Locs; 1242 for (const Value *V : Values.location_ops()) { 1243 auto *Undef = UndefValue::get(V->getType()); 1244 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1245 } 1246 SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {}, 1247 /*IsIndirect=*/false, DL, Order, 1248 /*IsVariadic=*/true); 1249 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1250 return true; 1251 } 1252 1253 void SelectionDAGBuilder::addDanglingDebugInfo(const VarLocInfo *VarLoc, 1254 unsigned Order) { 1255 if (!handleDanglingVariadicDebugInfo( 1256 DAG, 1257 const_cast<DILocalVariable *>(DAG.getFunctionVarLocs() 1258 ->getVariable(VarLoc->VariableID) 1259 .getVariable()), 1260 VarLoc->DL, Order, VarLoc->Values, VarLoc->Expr)) { 1261 DanglingDebugInfoMap[VarLoc->Values.getVariableLocationOp(0)].emplace_back( 1262 VarLoc, Order); 1263 } 1264 } 1265 1266 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI, 1267 unsigned Order) { 1268 // We treat variadic dbg_values differently at this stage. 1269 if (!handleDanglingVariadicDebugInfo( 1270 DAG, DI->getVariable(), DI->getDebugLoc(), Order, 1271 DI->getWrappedLocation(), DI->getExpression())) { 1272 // TODO: Dangling debug info will eventually either be resolved or produce 1273 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1274 // between the original dbg.value location and its resolved DBG_VALUE, 1275 // which we should ideally fill with an extra Undef DBG_VALUE. 1276 assert(DI->getNumVariableLocationOps() == 1 && 1277 "DbgValueInst without an ArgList should have a single location " 1278 "operand."); 1279 DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, Order); 1280 } 1281 } 1282 1283 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1284 const DIExpression *Expr) { 1285 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1286 DIVariable *DanglingVariable = DDI.getVariable(DAG.getFunctionVarLocs()); 1287 DIExpression *DanglingExpr = DDI.getExpression(); 1288 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1289 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << printDDI(DDI) 1290 << "\n"); 1291 return true; 1292 } 1293 return false; 1294 }; 1295 1296 for (auto &DDIMI : DanglingDebugInfoMap) { 1297 DanglingDebugInfoVector &DDIV = DDIMI.second; 1298 1299 // If debug info is to be dropped, run it through final checks to see 1300 // whether it can be salvaged. 1301 for (auto &DDI : DDIV) 1302 if (isMatchingDbgValue(DDI)) 1303 salvageUnresolvedDbgValue(DDI); 1304 1305 erase_if(DDIV, isMatchingDbgValue); 1306 } 1307 } 1308 1309 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1310 // generate the debug data structures now that we've seen its definition. 1311 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1312 SDValue Val) { 1313 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1314 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1315 return; 1316 1317 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1318 for (auto &DDI : DDIV) { 1319 DebugLoc DL = DDI.getDebugLoc(); 1320 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1321 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1322 DILocalVariable *Variable = DDI.getVariable(DAG.getFunctionVarLocs()); 1323 DIExpression *Expr = DDI.getExpression(); 1324 assert(Variable->isValidLocationForIntrinsic(DL) && 1325 "Expected inlined-at fields to agree"); 1326 SDDbgValue *SDV; 1327 if (Val.getNode()) { 1328 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1329 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1330 // we couldn't resolve it directly when examining the DbgValue intrinsic 1331 // in the first place we should not be more successful here). Unless we 1332 // have some test case that prove this to be correct we should avoid 1333 // calling EmitFuncArgumentDbgValue here. 1334 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL, 1335 FuncArgumentDbgValueKind::Value, Val)) { 1336 LLVM_DEBUG(dbgs() << "Resolve dangling debug info for " << printDDI(DDI) 1337 << "\n"); 1338 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1339 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1340 // inserted after the definition of Val when emitting the instructions 1341 // after ISel. An alternative could be to teach 1342 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1343 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1344 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1345 << ValSDNodeOrder << "\n"); 1346 SDV = getDbgValue(Val, Variable, Expr, DL, 1347 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1348 DAG.AddDbgValue(SDV, false); 1349 } else 1350 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " 1351 << printDDI(DDI) << " in EmitFuncArgumentDbgValue\n"); 1352 } else { 1353 LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(DDI) << "\n"); 1354 auto Undef = UndefValue::get(V->getType()); 1355 auto SDV = 1356 DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder); 1357 DAG.AddDbgValue(SDV, false); 1358 } 1359 } 1360 DDIV.clear(); 1361 } 1362 1363 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1364 // TODO: For the variadic implementation, instead of only checking the fail 1365 // state of `handleDebugValue`, we need know specifically which values were 1366 // invalid, so that we attempt to salvage only those values when processing 1367 // a DIArgList. 1368 Value *V = DDI.getVariableLocationOp(0); 1369 Value *OrigV = V; 1370 DILocalVariable *Var = DDI.getVariable(DAG.getFunctionVarLocs()); 1371 DIExpression *Expr = DDI.getExpression(); 1372 DebugLoc DL = DDI.getDebugLoc(); 1373 unsigned SDOrder = DDI.getSDNodeOrder(); 1374 1375 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1376 // that DW_OP_stack_value is desired. 1377 bool StackValue = true; 1378 1379 // Can this Value can be encoded without any further work? 1380 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) 1381 return; 1382 1383 // Attempt to salvage back through as many instructions as possible. Bail if 1384 // a non-instruction is seen, such as a constant expression or global 1385 // variable. FIXME: Further work could recover those too. 1386 while (isa<Instruction>(V)) { 1387 Instruction &VAsInst = *cast<Instruction>(V); 1388 // Temporary "0", awaiting real implementation. 1389 SmallVector<uint64_t, 16> Ops; 1390 SmallVector<Value *, 4> AdditionalValues; 1391 V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops, 1392 AdditionalValues); 1393 // If we cannot salvage any further, and haven't yet found a suitable debug 1394 // expression, bail out. 1395 if (!V) 1396 break; 1397 1398 // TODO: If AdditionalValues isn't empty, then the salvage can only be 1399 // represented with a DBG_VALUE_LIST, so we give up. When we have support 1400 // here for variadic dbg_values, remove that condition. 1401 if (!AdditionalValues.empty()) 1402 break; 1403 1404 // New value and expr now represent this debuginfo. 1405 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue); 1406 1407 // Some kind of simplification occurred: check whether the operand of the 1408 // salvaged debug expression can be encoded in this DAG. 1409 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) { 1410 LLVM_DEBUG( 1411 dbgs() << "Salvaged debug location info for:\n " << *Var << "\n" 1412 << *OrigV << "\nBy stripping back to:\n " << *V << "\n"); 1413 return; 1414 } 1415 } 1416 1417 // This was the final opportunity to salvage this debug information, and it 1418 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1419 // any earlier variable location. 1420 assert(OrigV && "V shouldn't be null"); 1421 auto *Undef = UndefValue::get(OrigV->getType()); 1422 auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1423 DAG.AddDbgValue(SDV, false); 1424 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << printDDI(DDI) 1425 << "\n"); 1426 } 1427 1428 void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var, 1429 DIExpression *Expr, 1430 DebugLoc DbgLoc, 1431 unsigned Order) { 1432 Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context)); 1433 DIExpression *NewExpr = 1434 const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr)); 1435 handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order, 1436 /*IsVariadic*/ false); 1437 } 1438 1439 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1440 DILocalVariable *Var, 1441 DIExpression *Expr, DebugLoc DbgLoc, 1442 unsigned Order, bool IsVariadic) { 1443 if (Values.empty()) 1444 return true; 1445 SmallVector<SDDbgOperand> LocationOps; 1446 SmallVector<SDNode *> Dependencies; 1447 for (const Value *V : Values) { 1448 // Constant value. 1449 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1450 isa<ConstantPointerNull>(V)) { 1451 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1452 continue; 1453 } 1454 1455 // Look through IntToPtr constants. 1456 if (auto *CE = dyn_cast<ConstantExpr>(V)) 1457 if (CE->getOpcode() == Instruction::IntToPtr) { 1458 LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0))); 1459 continue; 1460 } 1461 1462 // If the Value is a frame index, we can create a FrameIndex debug value 1463 // without relying on the DAG at all. 1464 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1465 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1466 if (SI != FuncInfo.StaticAllocaMap.end()) { 1467 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1468 continue; 1469 } 1470 } 1471 1472 // Do not use getValue() in here; we don't want to generate code at 1473 // this point if it hasn't been done yet. 1474 SDValue N = NodeMap[V]; 1475 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1476 N = UnusedArgNodeMap[V]; 1477 if (N.getNode()) { 1478 // Only emit func arg dbg value for non-variadic dbg.values for now. 1479 if (!IsVariadic && 1480 EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc, 1481 FuncArgumentDbgValueKind::Value, N)) 1482 return true; 1483 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1484 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1485 // describe stack slot locations. 1486 // 1487 // Consider "int x = 0; int *px = &x;". There are two kinds of 1488 // interesting debug values here after optimization: 1489 // 1490 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1491 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1492 // 1493 // Both describe the direct values of their associated variables. 1494 Dependencies.push_back(N.getNode()); 1495 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1496 continue; 1497 } 1498 LocationOps.emplace_back( 1499 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1500 continue; 1501 } 1502 1503 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1504 // Special rules apply for the first dbg.values of parameter variables in a 1505 // function. Identify them by the fact they reference Argument Values, that 1506 // they're parameters, and they are parameters of the current function. We 1507 // need to let them dangle until they get an SDNode. 1508 bool IsParamOfFunc = 1509 isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt(); 1510 if (IsParamOfFunc) 1511 return false; 1512 1513 // The value is not used in this block yet (or it would have an SDNode). 1514 // We still want the value to appear for the user if possible -- if it has 1515 // an associated VReg, we can refer to that instead. 1516 auto VMI = FuncInfo.ValueMap.find(V); 1517 if (VMI != FuncInfo.ValueMap.end()) { 1518 unsigned Reg = VMI->second; 1519 // If this is a PHI node, it may be split up into several MI PHI nodes 1520 // (in FunctionLoweringInfo::set). 1521 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1522 V->getType(), std::nullopt); 1523 if (RFV.occupiesMultipleRegs()) { 1524 // FIXME: We could potentially support variadic dbg_values here. 1525 if (IsVariadic) 1526 return false; 1527 unsigned Offset = 0; 1528 unsigned BitsToDescribe = 0; 1529 if (auto VarSize = Var->getSizeInBits()) 1530 BitsToDescribe = *VarSize; 1531 if (auto Fragment = Expr->getFragmentInfo()) 1532 BitsToDescribe = Fragment->SizeInBits; 1533 for (const auto &RegAndSize : RFV.getRegsAndSizes()) { 1534 // Bail out if all bits are described already. 1535 if (Offset >= BitsToDescribe) 1536 break; 1537 // TODO: handle scalable vectors. 1538 unsigned RegisterSize = RegAndSize.second; 1539 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1540 ? BitsToDescribe - Offset 1541 : RegisterSize; 1542 auto FragmentExpr = DIExpression::createFragmentExpression( 1543 Expr, Offset, FragmentSize); 1544 if (!FragmentExpr) 1545 continue; 1546 SDDbgValue *SDV = DAG.getVRegDbgValue( 1547 Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, SDNodeOrder); 1548 DAG.AddDbgValue(SDV, false); 1549 Offset += RegisterSize; 1550 } 1551 return true; 1552 } 1553 // We can use simple vreg locations for variadic dbg_values as well. 1554 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1555 continue; 1556 } 1557 // We failed to create a SDDbgOperand for V. 1558 return false; 1559 } 1560 1561 // We have created a SDDbgOperand for each Value in Values. 1562 // Should use Order instead of SDNodeOrder? 1563 assert(!LocationOps.empty()); 1564 SDDbgValue *SDV = DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1565 /*IsIndirect=*/false, DbgLoc, 1566 SDNodeOrder, IsVariadic); 1567 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1568 return true; 1569 } 1570 1571 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1572 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1573 for (auto &Pair : DanglingDebugInfoMap) 1574 for (auto &DDI : Pair.second) 1575 salvageUnresolvedDbgValue(DDI); 1576 clearDanglingDebugInfo(); 1577 } 1578 1579 /// getCopyFromRegs - If there was virtual register allocated for the value V 1580 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1581 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1582 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1583 SDValue Result; 1584 1585 if (It != FuncInfo.ValueMap.end()) { 1586 Register InReg = It->second; 1587 1588 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1589 DAG.getDataLayout(), InReg, Ty, 1590 std::nullopt); // This is not an ABI copy. 1591 SDValue Chain = DAG.getEntryNode(); 1592 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1593 V); 1594 resolveDanglingDebugInfo(V, Result); 1595 } 1596 1597 return Result; 1598 } 1599 1600 /// getValue - Return an SDValue for the given Value. 1601 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1602 // If we already have an SDValue for this value, use it. It's important 1603 // to do this first, so that we don't create a CopyFromReg if we already 1604 // have a regular SDValue. 1605 SDValue &N = NodeMap[V]; 1606 if (N.getNode()) return N; 1607 1608 // If there's a virtual register allocated and initialized for this 1609 // value, use it. 1610 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1611 return copyFromReg; 1612 1613 // Otherwise create a new SDValue and remember it. 1614 SDValue Val = getValueImpl(V); 1615 NodeMap[V] = Val; 1616 resolveDanglingDebugInfo(V, Val); 1617 return Val; 1618 } 1619 1620 /// getNonRegisterValue - Return an SDValue for the given Value, but 1621 /// don't look in FuncInfo.ValueMap for a virtual register. 1622 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1623 // If we already have an SDValue for this value, use it. 1624 SDValue &N = NodeMap[V]; 1625 if (N.getNode()) { 1626 if (isIntOrFPConstant(N)) { 1627 // Remove the debug location from the node as the node is about to be used 1628 // in a location which may differ from the original debug location. This 1629 // is relevant to Constant and ConstantFP nodes because they can appear 1630 // as constant expressions inside PHI nodes. 1631 N->setDebugLoc(DebugLoc()); 1632 } 1633 return N; 1634 } 1635 1636 // Otherwise create a new SDValue and remember it. 1637 SDValue Val = getValueImpl(V); 1638 NodeMap[V] = Val; 1639 resolveDanglingDebugInfo(V, Val); 1640 return Val; 1641 } 1642 1643 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1644 /// Create an SDValue for the given value. 1645 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1646 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1647 1648 if (const Constant *C = dyn_cast<Constant>(V)) { 1649 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1650 1651 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1652 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1653 1654 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1655 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1656 1657 if (isa<ConstantPointerNull>(C)) { 1658 unsigned AS = V->getType()->getPointerAddressSpace(); 1659 return DAG.getConstant(0, getCurSDLoc(), 1660 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1661 } 1662 1663 if (match(C, m_VScale())) 1664 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1665 1666 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1667 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1668 1669 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1670 return DAG.getUNDEF(VT); 1671 1672 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1673 visit(CE->getOpcode(), *CE); 1674 SDValue N1 = NodeMap[V]; 1675 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1676 return N1; 1677 } 1678 1679 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1680 SmallVector<SDValue, 4> Constants; 1681 for (const Use &U : C->operands()) { 1682 SDNode *Val = getValue(U).getNode(); 1683 // If the operand is an empty aggregate, there are no values. 1684 if (!Val) continue; 1685 // Add each leaf value from the operand to the Constants list 1686 // to form a flattened list of all the values. 1687 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1688 Constants.push_back(SDValue(Val, i)); 1689 } 1690 1691 return DAG.getMergeValues(Constants, getCurSDLoc()); 1692 } 1693 1694 if (const ConstantDataSequential *CDS = 1695 dyn_cast<ConstantDataSequential>(C)) { 1696 SmallVector<SDValue, 4> Ops; 1697 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1698 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1699 // Add each leaf value from the operand to the Constants list 1700 // to form a flattened list of all the values. 1701 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1702 Ops.push_back(SDValue(Val, i)); 1703 } 1704 1705 if (isa<ArrayType>(CDS->getType())) 1706 return DAG.getMergeValues(Ops, getCurSDLoc()); 1707 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1708 } 1709 1710 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1711 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1712 "Unknown struct or array constant!"); 1713 1714 SmallVector<EVT, 4> ValueVTs; 1715 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1716 unsigned NumElts = ValueVTs.size(); 1717 if (NumElts == 0) 1718 return SDValue(); // empty struct 1719 SmallVector<SDValue, 4> Constants(NumElts); 1720 for (unsigned i = 0; i != NumElts; ++i) { 1721 EVT EltVT = ValueVTs[i]; 1722 if (isa<UndefValue>(C)) 1723 Constants[i] = DAG.getUNDEF(EltVT); 1724 else if (EltVT.isFloatingPoint()) 1725 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1726 else 1727 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1728 } 1729 1730 return DAG.getMergeValues(Constants, getCurSDLoc()); 1731 } 1732 1733 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1734 return DAG.getBlockAddress(BA, VT); 1735 1736 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1737 return getValue(Equiv->getGlobalValue()); 1738 1739 if (const auto *NC = dyn_cast<NoCFIValue>(C)) 1740 return getValue(NC->getGlobalValue()); 1741 1742 if (VT == MVT::aarch64svcount) { 1743 assert(C->isNullValue() && "Can only zero this target type!"); 1744 return DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, 1745 DAG.getConstant(0, getCurSDLoc(), MVT::nxv16i1)); 1746 } 1747 1748 VectorType *VecTy = cast<VectorType>(V->getType()); 1749 1750 // Now that we know the number and type of the elements, get that number of 1751 // elements into the Ops array based on what kind of constant it is. 1752 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1753 SmallVector<SDValue, 16> Ops; 1754 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1755 for (unsigned i = 0; i != NumElements; ++i) 1756 Ops.push_back(getValue(CV->getOperand(i))); 1757 1758 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1759 } 1760 1761 if (isa<ConstantAggregateZero>(C)) { 1762 EVT EltVT = 1763 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1764 1765 SDValue Op; 1766 if (EltVT.isFloatingPoint()) 1767 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1768 else 1769 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1770 1771 return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op); 1772 } 1773 1774 llvm_unreachable("Unknown vector constant"); 1775 } 1776 1777 // If this is a static alloca, generate it as the frameindex instead of 1778 // computation. 1779 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1780 DenseMap<const AllocaInst*, int>::iterator SI = 1781 FuncInfo.StaticAllocaMap.find(AI); 1782 if (SI != FuncInfo.StaticAllocaMap.end()) 1783 return DAG.getFrameIndex( 1784 SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType())); 1785 } 1786 1787 // If this is an instruction which fast-isel has deferred, select it now. 1788 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1789 Register InReg = FuncInfo.InitializeRegForValue(Inst); 1790 1791 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1792 Inst->getType(), std::nullopt); 1793 SDValue Chain = DAG.getEntryNode(); 1794 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1795 } 1796 1797 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) 1798 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1799 1800 if (const auto *BB = dyn_cast<BasicBlock>(V)) 1801 return DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 1802 1803 llvm_unreachable("Can't get register for value!"); 1804 } 1805 1806 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1807 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1808 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1809 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1810 bool IsSEH = isAsynchronousEHPersonality(Pers); 1811 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1812 if (!IsSEH) 1813 CatchPadMBB->setIsEHScopeEntry(); 1814 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1815 if (IsMSVCCXX || IsCoreCLR) 1816 CatchPadMBB->setIsEHFuncletEntry(); 1817 } 1818 1819 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1820 // Update machine-CFG edge. 1821 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1822 FuncInfo.MBB->addSuccessor(TargetMBB); 1823 TargetMBB->setIsEHCatchretTarget(true); 1824 DAG.getMachineFunction().setHasEHCatchret(true); 1825 1826 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1827 bool IsSEH = isAsynchronousEHPersonality(Pers); 1828 if (IsSEH) { 1829 // If this is not a fall-through branch or optimizations are switched off, 1830 // emit the branch. 1831 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1832 TM.getOptLevel() == CodeGenOptLevel::None) 1833 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1834 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1835 return; 1836 } 1837 1838 // Figure out the funclet membership for the catchret's successor. 1839 // This will be used by the FuncletLayout pass to determine how to order the 1840 // BB's. 1841 // A 'catchret' returns to the outer scope's color. 1842 Value *ParentPad = I.getCatchSwitchParentPad(); 1843 const BasicBlock *SuccessorColor; 1844 if (isa<ConstantTokenNone>(ParentPad)) 1845 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1846 else 1847 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1848 assert(SuccessorColor && "No parent funclet for catchret!"); 1849 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1850 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1851 1852 // Create the terminator node. 1853 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1854 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1855 DAG.getBasicBlock(SuccessorColorMBB)); 1856 DAG.setRoot(Ret); 1857 } 1858 1859 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1860 // Don't emit any special code for the cleanuppad instruction. It just marks 1861 // the start of an EH scope/funclet. 1862 FuncInfo.MBB->setIsEHScopeEntry(); 1863 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1864 if (Pers != EHPersonality::Wasm_CXX) { 1865 FuncInfo.MBB->setIsEHFuncletEntry(); 1866 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1867 } 1868 } 1869 1870 // In wasm EH, even though a catchpad may not catch an exception if a tag does 1871 // not match, it is OK to add only the first unwind destination catchpad to the 1872 // successors, because there will be at least one invoke instruction within the 1873 // catch scope that points to the next unwind destination, if one exists, so 1874 // CFGSort cannot mess up with BB sorting order. 1875 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 1876 // call within them, and catchpads only consisting of 'catch (...)' have a 1877 // '__cxa_end_catch' call within them, both of which generate invokes in case 1878 // the next unwind destination exists, i.e., the next unwind destination is not 1879 // the caller.) 1880 // 1881 // Having at most one EH pad successor is also simpler and helps later 1882 // transformations. 1883 // 1884 // For example, 1885 // current: 1886 // invoke void @foo to ... unwind label %catch.dispatch 1887 // catch.dispatch: 1888 // %0 = catchswitch within ... [label %catch.start] unwind label %next 1889 // catch.start: 1890 // ... 1891 // ... in this BB or some other child BB dominated by this BB there will be an 1892 // invoke that points to 'next' BB as an unwind destination 1893 // 1894 // next: ; We don't need to add this to 'current' BB's successor 1895 // ... 1896 static void findWasmUnwindDestinations( 1897 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1898 BranchProbability Prob, 1899 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1900 &UnwindDests) { 1901 while (EHPadBB) { 1902 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1903 if (isa<CleanupPadInst>(Pad)) { 1904 // Stop on cleanup pads. 1905 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1906 UnwindDests.back().first->setIsEHScopeEntry(); 1907 break; 1908 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1909 // Add the catchpad handlers to the possible destinations. We don't 1910 // continue to the unwind destination of the catchswitch for wasm. 1911 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1912 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1913 UnwindDests.back().first->setIsEHScopeEntry(); 1914 } 1915 break; 1916 } else { 1917 continue; 1918 } 1919 } 1920 } 1921 1922 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1923 /// many places it could ultimately go. In the IR, we have a single unwind 1924 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1925 /// This function skips over imaginary basic blocks that hold catchswitch 1926 /// instructions, and finds all the "real" machine 1927 /// basic block destinations. As those destinations may not be successors of 1928 /// EHPadBB, here we also calculate the edge probability to those destinations. 1929 /// The passed-in Prob is the edge probability to EHPadBB. 1930 static void findUnwindDestinations( 1931 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1932 BranchProbability Prob, 1933 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1934 &UnwindDests) { 1935 EHPersonality Personality = 1936 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1937 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1938 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1939 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1940 bool IsSEH = isAsynchronousEHPersonality(Personality); 1941 1942 if (IsWasmCXX) { 1943 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1944 assert(UnwindDests.size() <= 1 && 1945 "There should be at most one unwind destination for wasm"); 1946 return; 1947 } 1948 1949 while (EHPadBB) { 1950 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1951 BasicBlock *NewEHPadBB = nullptr; 1952 if (isa<LandingPadInst>(Pad)) { 1953 // Stop on landingpads. They are not funclets. 1954 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1955 break; 1956 } else if (isa<CleanupPadInst>(Pad)) { 1957 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1958 // personalities. 1959 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1960 UnwindDests.back().first->setIsEHScopeEntry(); 1961 UnwindDests.back().first->setIsEHFuncletEntry(); 1962 break; 1963 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1964 // Add the catchpad handlers to the possible destinations. 1965 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1966 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1967 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1968 if (IsMSVCCXX || IsCoreCLR) 1969 UnwindDests.back().first->setIsEHFuncletEntry(); 1970 if (!IsSEH) 1971 UnwindDests.back().first->setIsEHScopeEntry(); 1972 } 1973 NewEHPadBB = CatchSwitch->getUnwindDest(); 1974 } else { 1975 continue; 1976 } 1977 1978 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1979 if (BPI && NewEHPadBB) 1980 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1981 EHPadBB = NewEHPadBB; 1982 } 1983 } 1984 1985 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1986 // Update successor info. 1987 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1988 auto UnwindDest = I.getUnwindDest(); 1989 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1990 BranchProbability UnwindDestProb = 1991 (BPI && UnwindDest) 1992 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1993 : BranchProbability::getZero(); 1994 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1995 for (auto &UnwindDest : UnwindDests) { 1996 UnwindDest.first->setIsEHPad(); 1997 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1998 } 1999 FuncInfo.MBB->normalizeSuccProbs(); 2000 2001 // Create the terminator node. 2002 SDValue Ret = 2003 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 2004 DAG.setRoot(Ret); 2005 } 2006 2007 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 2008 report_fatal_error("visitCatchSwitch not yet implemented!"); 2009 } 2010 2011 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 2012 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2013 auto &DL = DAG.getDataLayout(); 2014 SDValue Chain = getControlRoot(); 2015 SmallVector<ISD::OutputArg, 8> Outs; 2016 SmallVector<SDValue, 8> OutVals; 2017 2018 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 2019 // lower 2020 // 2021 // %val = call <ty> @llvm.experimental.deoptimize() 2022 // ret <ty> %val 2023 // 2024 // differently. 2025 if (I.getParent()->getTerminatingDeoptimizeCall()) { 2026 LowerDeoptimizingReturn(); 2027 return; 2028 } 2029 2030 if (!FuncInfo.CanLowerReturn) { 2031 unsigned DemoteReg = FuncInfo.DemoteRegister; 2032 const Function *F = I.getParent()->getParent(); 2033 2034 // Emit a store of the return value through the virtual register. 2035 // Leave Outs empty so that LowerReturn won't try to load return 2036 // registers the usual way. 2037 SmallVector<EVT, 1> PtrValueVTs; 2038 ComputeValueVTs(TLI, DL, 2039 PointerType::get(F->getContext(), 2040 DAG.getDataLayout().getAllocaAddrSpace()), 2041 PtrValueVTs); 2042 2043 SDValue RetPtr = 2044 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]); 2045 SDValue RetOp = getValue(I.getOperand(0)); 2046 2047 SmallVector<EVT, 4> ValueVTs, MemVTs; 2048 SmallVector<uint64_t, 4> Offsets; 2049 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 2050 &Offsets, 0); 2051 unsigned NumValues = ValueVTs.size(); 2052 2053 SmallVector<SDValue, 4> Chains(NumValues); 2054 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 2055 for (unsigned i = 0; i != NumValues; ++i) { 2056 // An aggregate return value cannot wrap around the address space, so 2057 // offsets to its parts don't wrap either. 2058 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 2059 TypeSize::Fixed(Offsets[i])); 2060 2061 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 2062 if (MemVTs[i] != ValueVTs[i]) 2063 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 2064 Chains[i] = DAG.getStore( 2065 Chain, getCurSDLoc(), Val, 2066 // FIXME: better loc info would be nice. 2067 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 2068 commonAlignment(BaseAlign, Offsets[i])); 2069 } 2070 2071 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 2072 MVT::Other, Chains); 2073 } else if (I.getNumOperands() != 0) { 2074 SmallVector<EVT, 4> ValueVTs; 2075 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 2076 unsigned NumValues = ValueVTs.size(); 2077 if (NumValues) { 2078 SDValue RetOp = getValue(I.getOperand(0)); 2079 2080 const Function *F = I.getParent()->getParent(); 2081 2082 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 2083 I.getOperand(0)->getType(), F->getCallingConv(), 2084 /*IsVarArg*/ false, DL); 2085 2086 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 2087 if (F->getAttributes().hasRetAttr(Attribute::SExt)) 2088 ExtendKind = ISD::SIGN_EXTEND; 2089 else if (F->getAttributes().hasRetAttr(Attribute::ZExt)) 2090 ExtendKind = ISD::ZERO_EXTEND; 2091 2092 LLVMContext &Context = F->getContext(); 2093 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg); 2094 2095 for (unsigned j = 0; j != NumValues; ++j) { 2096 EVT VT = ValueVTs[j]; 2097 2098 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 2099 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 2100 2101 CallingConv::ID CC = F->getCallingConv(); 2102 2103 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 2104 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 2105 SmallVector<SDValue, 4> Parts(NumParts); 2106 getCopyToParts(DAG, getCurSDLoc(), 2107 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 2108 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 2109 2110 // 'inreg' on function refers to return value 2111 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2112 if (RetInReg) 2113 Flags.setInReg(); 2114 2115 if (I.getOperand(0)->getType()->isPointerTy()) { 2116 Flags.setPointer(); 2117 Flags.setPointerAddrSpace( 2118 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 2119 } 2120 2121 if (NeedsRegBlock) { 2122 Flags.setInConsecutiveRegs(); 2123 if (j == NumValues - 1) 2124 Flags.setInConsecutiveRegsLast(); 2125 } 2126 2127 // Propagate extension type if any 2128 if (ExtendKind == ISD::SIGN_EXTEND) 2129 Flags.setSExt(); 2130 else if (ExtendKind == ISD::ZERO_EXTEND) 2131 Flags.setZExt(); 2132 2133 for (unsigned i = 0; i < NumParts; ++i) { 2134 Outs.push_back(ISD::OutputArg(Flags, 2135 Parts[i].getValueType().getSimpleVT(), 2136 VT, /*isfixed=*/true, 0, 0)); 2137 OutVals.push_back(Parts[i]); 2138 } 2139 } 2140 } 2141 } 2142 2143 // Push in swifterror virtual register as the last element of Outs. This makes 2144 // sure swifterror virtual register will be returned in the swifterror 2145 // physical register. 2146 const Function *F = I.getParent()->getParent(); 2147 if (TLI.supportSwiftError() && 2148 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2149 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2150 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2151 Flags.setSwiftError(); 2152 Outs.push_back(ISD::OutputArg( 2153 Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)), 2154 /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0)); 2155 // Create SDNode for the swifterror virtual register. 2156 OutVals.push_back( 2157 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2158 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2159 EVT(TLI.getPointerTy(DL)))); 2160 } 2161 2162 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2163 CallingConv::ID CallConv = 2164 DAG.getMachineFunction().getFunction().getCallingConv(); 2165 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2166 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2167 2168 // Verify that the target's LowerReturn behaved as expected. 2169 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2170 "LowerReturn didn't return a valid chain!"); 2171 2172 // Update the DAG with the new chain value resulting from return lowering. 2173 DAG.setRoot(Chain); 2174 } 2175 2176 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2177 /// created for it, emit nodes to copy the value into the virtual 2178 /// registers. 2179 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2180 // Skip empty types 2181 if (V->getType()->isEmptyTy()) 2182 return; 2183 2184 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2185 if (VMI != FuncInfo.ValueMap.end()) { 2186 assert((!V->use_empty() || isa<CallBrInst>(V)) && 2187 "Unused value assigned virtual registers!"); 2188 CopyValueToVirtualRegister(V, VMI->second); 2189 } 2190 } 2191 2192 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2193 /// the current basic block, add it to ValueMap now so that we'll get a 2194 /// CopyTo/FromReg. 2195 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2196 // No need to export constants. 2197 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2198 2199 // Already exported? 2200 if (FuncInfo.isExportedInst(V)) return; 2201 2202 Register Reg = FuncInfo.InitializeRegForValue(V); 2203 CopyValueToVirtualRegister(V, Reg); 2204 } 2205 2206 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2207 const BasicBlock *FromBB) { 2208 // The operands of the setcc have to be in this block. We don't know 2209 // how to export them from some other block. 2210 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2211 // Can export from current BB. 2212 if (VI->getParent() == FromBB) 2213 return true; 2214 2215 // Is already exported, noop. 2216 return FuncInfo.isExportedInst(V); 2217 } 2218 2219 // If this is an argument, we can export it if the BB is the entry block or 2220 // if it is already exported. 2221 if (isa<Argument>(V)) { 2222 if (FromBB->isEntryBlock()) 2223 return true; 2224 2225 // Otherwise, can only export this if it is already exported. 2226 return FuncInfo.isExportedInst(V); 2227 } 2228 2229 // Otherwise, constants can always be exported. 2230 return true; 2231 } 2232 2233 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2234 BranchProbability 2235 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2236 const MachineBasicBlock *Dst) const { 2237 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2238 const BasicBlock *SrcBB = Src->getBasicBlock(); 2239 const BasicBlock *DstBB = Dst->getBasicBlock(); 2240 if (!BPI) { 2241 // If BPI is not available, set the default probability as 1 / N, where N is 2242 // the number of successors. 2243 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2244 return BranchProbability(1, SuccSize); 2245 } 2246 return BPI->getEdgeProbability(SrcBB, DstBB); 2247 } 2248 2249 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2250 MachineBasicBlock *Dst, 2251 BranchProbability Prob) { 2252 if (!FuncInfo.BPI) 2253 Src->addSuccessorWithoutProb(Dst); 2254 else { 2255 if (Prob.isUnknown()) 2256 Prob = getEdgeProbability(Src, Dst); 2257 Src->addSuccessor(Dst, Prob); 2258 } 2259 } 2260 2261 static bool InBlock(const Value *V, const BasicBlock *BB) { 2262 if (const Instruction *I = dyn_cast<Instruction>(V)) 2263 return I->getParent() == BB; 2264 return true; 2265 } 2266 2267 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2268 /// This function emits a branch and is used at the leaves of an OR or an 2269 /// AND operator tree. 2270 void 2271 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2272 MachineBasicBlock *TBB, 2273 MachineBasicBlock *FBB, 2274 MachineBasicBlock *CurBB, 2275 MachineBasicBlock *SwitchBB, 2276 BranchProbability TProb, 2277 BranchProbability FProb, 2278 bool InvertCond) { 2279 const BasicBlock *BB = CurBB->getBasicBlock(); 2280 2281 // If the leaf of the tree is a comparison, merge the condition into 2282 // the caseblock. 2283 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2284 // The operands of the cmp have to be in this block. We don't know 2285 // how to export them from some other block. If this is the first block 2286 // of the sequence, no exporting is needed. 2287 if (CurBB == SwitchBB || 2288 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2289 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2290 ISD::CondCode Condition; 2291 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2292 ICmpInst::Predicate Pred = 2293 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2294 Condition = getICmpCondCode(Pred); 2295 } else { 2296 const FCmpInst *FC = cast<FCmpInst>(Cond); 2297 FCmpInst::Predicate Pred = 2298 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2299 Condition = getFCmpCondCode(Pred); 2300 if (TM.Options.NoNaNsFPMath) 2301 Condition = getFCmpCodeWithoutNaN(Condition); 2302 } 2303 2304 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2305 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2306 SL->SwitchCases.push_back(CB); 2307 return; 2308 } 2309 } 2310 2311 // Create a CaseBlock record representing this branch. 2312 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2313 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2314 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2315 SL->SwitchCases.push_back(CB); 2316 } 2317 2318 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2319 MachineBasicBlock *TBB, 2320 MachineBasicBlock *FBB, 2321 MachineBasicBlock *CurBB, 2322 MachineBasicBlock *SwitchBB, 2323 Instruction::BinaryOps Opc, 2324 BranchProbability TProb, 2325 BranchProbability FProb, 2326 bool InvertCond) { 2327 // Skip over not part of the tree and remember to invert op and operands at 2328 // next level. 2329 Value *NotCond; 2330 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2331 InBlock(NotCond, CurBB->getBasicBlock())) { 2332 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2333 !InvertCond); 2334 return; 2335 } 2336 2337 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2338 const Value *BOpOp0, *BOpOp1; 2339 // Compute the effective opcode for Cond, taking into account whether it needs 2340 // to be inverted, e.g. 2341 // and (not (or A, B)), C 2342 // gets lowered as 2343 // and (and (not A, not B), C) 2344 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2345 if (BOp) { 2346 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2347 ? Instruction::And 2348 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2349 ? Instruction::Or 2350 : (Instruction::BinaryOps)0); 2351 if (InvertCond) { 2352 if (BOpc == Instruction::And) 2353 BOpc = Instruction::Or; 2354 else if (BOpc == Instruction::Or) 2355 BOpc = Instruction::And; 2356 } 2357 } 2358 2359 // If this node is not part of the or/and tree, emit it as a branch. 2360 // Note that all nodes in the tree should have same opcode. 2361 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2362 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2363 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2364 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2365 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2366 TProb, FProb, InvertCond); 2367 return; 2368 } 2369 2370 // Create TmpBB after CurBB. 2371 MachineFunction::iterator BBI(CurBB); 2372 MachineFunction &MF = DAG.getMachineFunction(); 2373 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2374 CurBB->getParent()->insert(++BBI, TmpBB); 2375 2376 if (Opc == Instruction::Or) { 2377 // Codegen X | Y as: 2378 // BB1: 2379 // jmp_if_X TBB 2380 // jmp TmpBB 2381 // TmpBB: 2382 // jmp_if_Y TBB 2383 // jmp FBB 2384 // 2385 2386 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2387 // The requirement is that 2388 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2389 // = TrueProb for original BB. 2390 // Assuming the original probabilities are A and B, one choice is to set 2391 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2392 // A/(1+B) and 2B/(1+B). This choice assumes that 2393 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2394 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2395 // TmpBB, but the math is more complicated. 2396 2397 auto NewTrueProb = TProb / 2; 2398 auto NewFalseProb = TProb / 2 + FProb; 2399 // Emit the LHS condition. 2400 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2401 NewFalseProb, InvertCond); 2402 2403 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2404 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2405 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2406 // Emit the RHS condition into TmpBB. 2407 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2408 Probs[1], InvertCond); 2409 } else { 2410 assert(Opc == Instruction::And && "Unknown merge op!"); 2411 // Codegen X & Y as: 2412 // BB1: 2413 // jmp_if_X TmpBB 2414 // jmp FBB 2415 // TmpBB: 2416 // jmp_if_Y TBB 2417 // jmp FBB 2418 // 2419 // This requires creation of TmpBB after CurBB. 2420 2421 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2422 // The requirement is that 2423 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2424 // = FalseProb for original BB. 2425 // Assuming the original probabilities are A and B, one choice is to set 2426 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2427 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2428 // TrueProb for BB1 * FalseProb for TmpBB. 2429 2430 auto NewTrueProb = TProb + FProb / 2; 2431 auto NewFalseProb = FProb / 2; 2432 // Emit the LHS condition. 2433 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2434 NewFalseProb, InvertCond); 2435 2436 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2437 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2438 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2439 // Emit the RHS condition into TmpBB. 2440 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2441 Probs[1], InvertCond); 2442 } 2443 } 2444 2445 /// If the set of cases should be emitted as a series of branches, return true. 2446 /// If we should emit this as a bunch of and/or'd together conditions, return 2447 /// false. 2448 bool 2449 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2450 if (Cases.size() != 2) return true; 2451 2452 // If this is two comparisons of the same values or'd or and'd together, they 2453 // will get folded into a single comparison, so don't emit two blocks. 2454 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2455 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2456 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2457 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2458 return false; 2459 } 2460 2461 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2462 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2463 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2464 Cases[0].CC == Cases[1].CC && 2465 isa<Constant>(Cases[0].CmpRHS) && 2466 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2467 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2468 return false; 2469 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2470 return false; 2471 } 2472 2473 return true; 2474 } 2475 2476 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2477 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2478 2479 // Update machine-CFG edges. 2480 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2481 2482 if (I.isUnconditional()) { 2483 // Update machine-CFG edges. 2484 BrMBB->addSuccessor(Succ0MBB); 2485 2486 // If this is not a fall-through branch or optimizations are switched off, 2487 // emit the branch. 2488 if (Succ0MBB != NextBlock(BrMBB) || 2489 TM.getOptLevel() == CodeGenOptLevel::None) { 2490 auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 2491 getControlRoot(), DAG.getBasicBlock(Succ0MBB)); 2492 setValue(&I, Br); 2493 DAG.setRoot(Br); 2494 } 2495 2496 return; 2497 } 2498 2499 // If this condition is one of the special cases we handle, do special stuff 2500 // now. 2501 const Value *CondVal = I.getCondition(); 2502 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2503 2504 // If this is a series of conditions that are or'd or and'd together, emit 2505 // this as a sequence of branches instead of setcc's with and/or operations. 2506 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2507 // unpredictable branches, and vector extracts because those jumps are likely 2508 // expensive for any target), this should improve performance. 2509 // For example, instead of something like: 2510 // cmp A, B 2511 // C = seteq 2512 // cmp D, E 2513 // F = setle 2514 // or C, F 2515 // jnz foo 2516 // Emit: 2517 // cmp A, B 2518 // je foo 2519 // cmp D, E 2520 // jle foo 2521 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2522 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2523 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2524 Value *Vec; 2525 const Value *BOp0, *BOp1; 2526 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2527 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2528 Opcode = Instruction::And; 2529 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2530 Opcode = Instruction::Or; 2531 2532 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2533 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2534 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2535 getEdgeProbability(BrMBB, Succ0MBB), 2536 getEdgeProbability(BrMBB, Succ1MBB), 2537 /*InvertCond=*/false); 2538 // If the compares in later blocks need to use values not currently 2539 // exported from this block, export them now. This block should always 2540 // be the first entry. 2541 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2542 2543 // Allow some cases to be rejected. 2544 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2545 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2546 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2547 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2548 } 2549 2550 // Emit the branch for this block. 2551 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2552 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2553 return; 2554 } 2555 2556 // Okay, we decided not to do this, remove any inserted MBB's and clear 2557 // SwitchCases. 2558 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2559 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2560 2561 SL->SwitchCases.clear(); 2562 } 2563 } 2564 2565 // Create a CaseBlock record representing this branch. 2566 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2567 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2568 2569 // Use visitSwitchCase to actually insert the fast branch sequence for this 2570 // cond branch. 2571 visitSwitchCase(CB, BrMBB); 2572 } 2573 2574 /// visitSwitchCase - Emits the necessary code to represent a single node in 2575 /// the binary search tree resulting from lowering a switch instruction. 2576 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2577 MachineBasicBlock *SwitchBB) { 2578 SDValue Cond; 2579 SDValue CondLHS = getValue(CB.CmpLHS); 2580 SDLoc dl = CB.DL; 2581 2582 if (CB.CC == ISD::SETTRUE) { 2583 // Branch or fall through to TrueBB. 2584 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2585 SwitchBB->normalizeSuccProbs(); 2586 if (CB.TrueBB != NextBlock(SwitchBB)) { 2587 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2588 DAG.getBasicBlock(CB.TrueBB))); 2589 } 2590 return; 2591 } 2592 2593 auto &TLI = DAG.getTargetLoweringInfo(); 2594 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2595 2596 // Build the setcc now. 2597 if (!CB.CmpMHS) { 2598 // Fold "(X == true)" to X and "(X == false)" to !X to 2599 // handle common cases produced by branch lowering. 2600 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2601 CB.CC == ISD::SETEQ) 2602 Cond = CondLHS; 2603 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2604 CB.CC == ISD::SETEQ) { 2605 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2606 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2607 } else { 2608 SDValue CondRHS = getValue(CB.CmpRHS); 2609 2610 // If a pointer's DAG type is larger than its memory type then the DAG 2611 // values are zero-extended. This breaks signed comparisons so truncate 2612 // back to the underlying type before doing the compare. 2613 if (CondLHS.getValueType() != MemVT) { 2614 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2615 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2616 } 2617 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2618 } 2619 } else { 2620 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2621 2622 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2623 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2624 2625 SDValue CmpOp = getValue(CB.CmpMHS); 2626 EVT VT = CmpOp.getValueType(); 2627 2628 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2629 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2630 ISD::SETLE); 2631 } else { 2632 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2633 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2634 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2635 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2636 } 2637 } 2638 2639 // Update successor info 2640 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2641 // TrueBB and FalseBB are always different unless the incoming IR is 2642 // degenerate. This only happens when running llc on weird IR. 2643 if (CB.TrueBB != CB.FalseBB) 2644 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2645 SwitchBB->normalizeSuccProbs(); 2646 2647 // If the lhs block is the next block, invert the condition so that we can 2648 // fall through to the lhs instead of the rhs block. 2649 if (CB.TrueBB == NextBlock(SwitchBB)) { 2650 std::swap(CB.TrueBB, CB.FalseBB); 2651 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2652 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2653 } 2654 2655 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2656 MVT::Other, getControlRoot(), Cond, 2657 DAG.getBasicBlock(CB.TrueBB)); 2658 2659 setValue(CurInst, BrCond); 2660 2661 // Insert the false branch. Do this even if it's a fall through branch, 2662 // this makes it easier to do DAG optimizations which require inverting 2663 // the branch condition. 2664 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2665 DAG.getBasicBlock(CB.FalseBB)); 2666 2667 DAG.setRoot(BrCond); 2668 } 2669 2670 /// visitJumpTable - Emit JumpTable node in the current MBB 2671 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2672 // Emit the code for the jump table 2673 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2674 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2675 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2676 JT.Reg, PTy); 2677 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2678 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2679 MVT::Other, Index.getValue(1), 2680 Table, Index); 2681 DAG.setRoot(BrJumpTable); 2682 } 2683 2684 /// visitJumpTableHeader - This function emits necessary code to produce index 2685 /// in the JumpTable from switch case. 2686 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2687 JumpTableHeader &JTH, 2688 MachineBasicBlock *SwitchBB) { 2689 SDLoc dl = getCurSDLoc(); 2690 2691 // Subtract the lowest switch case value from the value being switched on. 2692 SDValue SwitchOp = getValue(JTH.SValue); 2693 EVT VT = SwitchOp.getValueType(); 2694 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2695 DAG.getConstant(JTH.First, dl, VT)); 2696 2697 // The SDNode we just created, which holds the value being switched on minus 2698 // the smallest case value, needs to be copied to a virtual register so it 2699 // can be used as an index into the jump table in a subsequent basic block. 2700 // This value may be smaller or larger than the target's pointer type, and 2701 // therefore require extension or truncating. 2702 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2703 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2704 2705 unsigned JumpTableReg = 2706 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2707 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2708 JumpTableReg, SwitchOp); 2709 JT.Reg = JumpTableReg; 2710 2711 if (!JTH.FallthroughUnreachable) { 2712 // Emit the range check for the jump table, and branch to the default block 2713 // for the switch statement if the value being switched on exceeds the 2714 // largest case in the switch. 2715 SDValue CMP = DAG.getSetCC( 2716 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2717 Sub.getValueType()), 2718 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2719 2720 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2721 MVT::Other, CopyTo, CMP, 2722 DAG.getBasicBlock(JT.Default)); 2723 2724 // Avoid emitting unnecessary branches to the next block. 2725 if (JT.MBB != NextBlock(SwitchBB)) 2726 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2727 DAG.getBasicBlock(JT.MBB)); 2728 2729 DAG.setRoot(BrCond); 2730 } else { 2731 // Avoid emitting unnecessary branches to the next block. 2732 if (JT.MBB != NextBlock(SwitchBB)) 2733 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2734 DAG.getBasicBlock(JT.MBB))); 2735 else 2736 DAG.setRoot(CopyTo); 2737 } 2738 } 2739 2740 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2741 /// variable if there exists one. 2742 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2743 SDValue &Chain) { 2744 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2745 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2746 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2747 MachineFunction &MF = DAG.getMachineFunction(); 2748 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2749 MachineSDNode *Node = 2750 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2751 if (Global) { 2752 MachinePointerInfo MPInfo(Global); 2753 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2754 MachineMemOperand::MODereferenceable; 2755 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2756 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2757 DAG.setNodeMemRefs(Node, {MemRef}); 2758 } 2759 if (PtrTy != PtrMemTy) 2760 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2761 return SDValue(Node, 0); 2762 } 2763 2764 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2765 /// tail spliced into a stack protector check success bb. 2766 /// 2767 /// For a high level explanation of how this fits into the stack protector 2768 /// generation see the comment on the declaration of class 2769 /// StackProtectorDescriptor. 2770 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2771 MachineBasicBlock *ParentBB) { 2772 2773 // First create the loads to the guard/stack slot for the comparison. 2774 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2775 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2776 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2777 2778 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2779 int FI = MFI.getStackProtectorIndex(); 2780 2781 SDValue Guard; 2782 SDLoc dl = getCurSDLoc(); 2783 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2784 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2785 Align Align = 2786 DAG.getDataLayout().getPrefTypeAlign(PointerType::get(M.getContext(), 0)); 2787 2788 // Generate code to load the content of the guard slot. 2789 SDValue GuardVal = DAG.getLoad( 2790 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2791 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2792 MachineMemOperand::MOVolatile); 2793 2794 if (TLI.useStackGuardXorFP()) 2795 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2796 2797 // Retrieve guard check function, nullptr if instrumentation is inlined. 2798 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2799 // The target provides a guard check function to validate the guard value. 2800 // Generate a call to that function with the content of the guard slot as 2801 // argument. 2802 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2803 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2804 2805 TargetLowering::ArgListTy Args; 2806 TargetLowering::ArgListEntry Entry; 2807 Entry.Node = GuardVal; 2808 Entry.Ty = FnTy->getParamType(0); 2809 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg)) 2810 Entry.IsInReg = true; 2811 Args.push_back(Entry); 2812 2813 TargetLowering::CallLoweringInfo CLI(DAG); 2814 CLI.setDebugLoc(getCurSDLoc()) 2815 .setChain(DAG.getEntryNode()) 2816 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2817 getValue(GuardCheckFn), std::move(Args)); 2818 2819 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2820 DAG.setRoot(Result.second); 2821 return; 2822 } 2823 2824 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2825 // Otherwise, emit a volatile load to retrieve the stack guard value. 2826 SDValue Chain = DAG.getEntryNode(); 2827 if (TLI.useLoadStackGuardNode()) { 2828 Guard = getLoadStackGuard(DAG, dl, Chain); 2829 } else { 2830 const Value *IRGuard = TLI.getSDagStackGuard(M); 2831 SDValue GuardPtr = getValue(IRGuard); 2832 2833 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2834 MachinePointerInfo(IRGuard, 0), Align, 2835 MachineMemOperand::MOVolatile); 2836 } 2837 2838 // Perform the comparison via a getsetcc. 2839 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2840 *DAG.getContext(), 2841 Guard.getValueType()), 2842 Guard, GuardVal, ISD::SETNE); 2843 2844 // If the guard/stackslot do not equal, branch to failure MBB. 2845 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2846 MVT::Other, GuardVal.getOperand(0), 2847 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2848 // Otherwise branch to success MBB. 2849 SDValue Br = DAG.getNode(ISD::BR, dl, 2850 MVT::Other, BrCond, 2851 DAG.getBasicBlock(SPD.getSuccessMBB())); 2852 2853 DAG.setRoot(Br); 2854 } 2855 2856 /// Codegen the failure basic block for a stack protector check. 2857 /// 2858 /// A failure stack protector machine basic block consists simply of a call to 2859 /// __stack_chk_fail(). 2860 /// 2861 /// For a high level explanation of how this fits into the stack protector 2862 /// generation see the comment on the declaration of class 2863 /// StackProtectorDescriptor. 2864 void 2865 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2866 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2867 TargetLowering::MakeLibCallOptions CallOptions; 2868 CallOptions.setDiscardResult(true); 2869 SDValue Chain = 2870 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2871 std::nullopt, CallOptions, getCurSDLoc()) 2872 .second; 2873 // On PS4/PS5, the "return address" must still be within the calling 2874 // function, even if it's at the very end, so emit an explicit TRAP here. 2875 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2876 if (TM.getTargetTriple().isPS()) 2877 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2878 // WebAssembly needs an unreachable instruction after a non-returning call, 2879 // because the function return type can be different from __stack_chk_fail's 2880 // return type (void). 2881 if (TM.getTargetTriple().isWasm()) 2882 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2883 2884 DAG.setRoot(Chain); 2885 } 2886 2887 /// visitBitTestHeader - This function emits necessary code to produce value 2888 /// suitable for "bit tests" 2889 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2890 MachineBasicBlock *SwitchBB) { 2891 SDLoc dl = getCurSDLoc(); 2892 2893 // Subtract the minimum value. 2894 SDValue SwitchOp = getValue(B.SValue); 2895 EVT VT = SwitchOp.getValueType(); 2896 SDValue RangeSub = 2897 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2898 2899 // Determine the type of the test operands. 2900 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2901 bool UsePtrType = false; 2902 if (!TLI.isTypeLegal(VT)) { 2903 UsePtrType = true; 2904 } else { 2905 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2906 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2907 // Switch table case range are encoded into series of masks. 2908 // Just use pointer type, it's guaranteed to fit. 2909 UsePtrType = true; 2910 break; 2911 } 2912 } 2913 SDValue Sub = RangeSub; 2914 if (UsePtrType) { 2915 VT = TLI.getPointerTy(DAG.getDataLayout()); 2916 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2917 } 2918 2919 B.RegVT = VT.getSimpleVT(); 2920 B.Reg = FuncInfo.CreateReg(B.RegVT); 2921 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2922 2923 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2924 2925 if (!B.FallthroughUnreachable) 2926 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2927 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2928 SwitchBB->normalizeSuccProbs(); 2929 2930 SDValue Root = CopyTo; 2931 if (!B.FallthroughUnreachable) { 2932 // Conditional branch to the default block. 2933 SDValue RangeCmp = DAG.getSetCC(dl, 2934 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2935 RangeSub.getValueType()), 2936 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2937 ISD::SETUGT); 2938 2939 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2940 DAG.getBasicBlock(B.Default)); 2941 } 2942 2943 // Avoid emitting unnecessary branches to the next block. 2944 if (MBB != NextBlock(SwitchBB)) 2945 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2946 2947 DAG.setRoot(Root); 2948 } 2949 2950 /// visitBitTestCase - this function produces one "bit test" 2951 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2952 MachineBasicBlock* NextMBB, 2953 BranchProbability BranchProbToNext, 2954 unsigned Reg, 2955 BitTestCase &B, 2956 MachineBasicBlock *SwitchBB) { 2957 SDLoc dl = getCurSDLoc(); 2958 MVT VT = BB.RegVT; 2959 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2960 SDValue Cmp; 2961 unsigned PopCount = llvm::popcount(B.Mask); 2962 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2963 if (PopCount == 1) { 2964 // Testing for a single bit; just compare the shift count with what it 2965 // would need to be to shift a 1 bit in that position. 2966 Cmp = DAG.getSetCC( 2967 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2968 ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT), 2969 ISD::SETEQ); 2970 } else if (PopCount == BB.Range) { 2971 // There is only one zero bit in the range, test for it directly. 2972 Cmp = DAG.getSetCC( 2973 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2974 ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE); 2975 } else { 2976 // Make desired shift 2977 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2978 DAG.getConstant(1, dl, VT), ShiftOp); 2979 2980 // Emit bit tests and jumps 2981 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2982 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2983 Cmp = DAG.getSetCC( 2984 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2985 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2986 } 2987 2988 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2989 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2990 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2991 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2992 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2993 // one as they are relative probabilities (and thus work more like weights), 2994 // and hence we need to normalize them to let the sum of them become one. 2995 SwitchBB->normalizeSuccProbs(); 2996 2997 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2998 MVT::Other, getControlRoot(), 2999 Cmp, DAG.getBasicBlock(B.TargetBB)); 3000 3001 // Avoid emitting unnecessary branches to the next block. 3002 if (NextMBB != NextBlock(SwitchBB)) 3003 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 3004 DAG.getBasicBlock(NextMBB)); 3005 3006 DAG.setRoot(BrAnd); 3007 } 3008 3009 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 3010 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 3011 3012 // Retrieve successors. Look through artificial IR level blocks like 3013 // catchswitch for successors. 3014 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 3015 const BasicBlock *EHPadBB = I.getSuccessor(1); 3016 MachineBasicBlock *EHPadMBB = FuncInfo.MBBMap[EHPadBB]; 3017 3018 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3019 // have to do anything here to lower funclet bundles. 3020 assert(!I.hasOperandBundlesOtherThan( 3021 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 3022 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 3023 LLVMContext::OB_cfguardtarget, 3024 LLVMContext::OB_clang_arc_attachedcall}) && 3025 "Cannot lower invokes with arbitrary operand bundles yet!"); 3026 3027 const Value *Callee(I.getCalledOperand()); 3028 const Function *Fn = dyn_cast<Function>(Callee); 3029 if (isa<InlineAsm>(Callee)) 3030 visitInlineAsm(I, EHPadBB); 3031 else if (Fn && Fn->isIntrinsic()) { 3032 switch (Fn->getIntrinsicID()) { 3033 default: 3034 llvm_unreachable("Cannot invoke this intrinsic"); 3035 case Intrinsic::donothing: 3036 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 3037 case Intrinsic::seh_try_begin: 3038 case Intrinsic::seh_scope_begin: 3039 case Intrinsic::seh_try_end: 3040 case Intrinsic::seh_scope_end: 3041 if (EHPadMBB) 3042 // a block referenced by EH table 3043 // so dtor-funclet not removed by opts 3044 EHPadMBB->setMachineBlockAddressTaken(); 3045 break; 3046 case Intrinsic::experimental_patchpoint_void: 3047 case Intrinsic::experimental_patchpoint_i64: 3048 visitPatchpoint(I, EHPadBB); 3049 break; 3050 case Intrinsic::experimental_gc_statepoint: 3051 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 3052 break; 3053 case Intrinsic::wasm_rethrow: { 3054 // This is usually done in visitTargetIntrinsic, but this intrinsic is 3055 // special because it can be invoked, so we manually lower it to a DAG 3056 // node here. 3057 SmallVector<SDValue, 8> Ops; 3058 Ops.push_back(getRoot()); // inchain 3059 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3060 Ops.push_back( 3061 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 3062 TLI.getPointerTy(DAG.getDataLayout()))); 3063 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 3064 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 3065 break; 3066 } 3067 } 3068 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 3069 // Currently we do not lower any intrinsic calls with deopt operand bundles. 3070 // Eventually we will support lowering the @llvm.experimental.deoptimize 3071 // intrinsic, and right now there are no plans to support other intrinsics 3072 // with deopt state. 3073 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 3074 } else { 3075 LowerCallTo(I, getValue(Callee), false, false, EHPadBB); 3076 } 3077 3078 // If the value of the invoke is used outside of its defining block, make it 3079 // available as a virtual register. 3080 // We already took care of the exported value for the statepoint instruction 3081 // during call to the LowerStatepoint. 3082 if (!isa<GCStatepointInst>(I)) { 3083 CopyToExportRegsIfNeeded(&I); 3084 } 3085 3086 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 3087 BranchProbabilityInfo *BPI = FuncInfo.BPI; 3088 BranchProbability EHPadBBProb = 3089 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 3090 : BranchProbability::getZero(); 3091 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 3092 3093 // Update successor info. 3094 addSuccessorWithProb(InvokeMBB, Return); 3095 for (auto &UnwindDest : UnwindDests) { 3096 UnwindDest.first->setIsEHPad(); 3097 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 3098 } 3099 InvokeMBB->normalizeSuccProbs(); 3100 3101 // Drop into normal successor. 3102 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 3103 DAG.getBasicBlock(Return))); 3104 } 3105 3106 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 3107 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 3108 3109 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3110 // have to do anything here to lower funclet bundles. 3111 assert(!I.hasOperandBundlesOtherThan( 3112 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 3113 "Cannot lower callbrs with arbitrary operand bundles yet!"); 3114 3115 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 3116 visitInlineAsm(I); 3117 CopyToExportRegsIfNeeded(&I); 3118 3119 // Retrieve successors. 3120 SmallPtrSet<BasicBlock *, 8> Dests; 3121 Dests.insert(I.getDefaultDest()); 3122 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 3123 3124 // Update successor info. 3125 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 3126 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 3127 BasicBlock *Dest = I.getIndirectDest(i); 3128 MachineBasicBlock *Target = FuncInfo.MBBMap[Dest]; 3129 Target->setIsInlineAsmBrIndirectTarget(); 3130 Target->setMachineBlockAddressTaken(); 3131 Target->setLabelMustBeEmitted(); 3132 // Don't add duplicate machine successors. 3133 if (Dests.insert(Dest).second) 3134 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 3135 } 3136 CallBrMBB->normalizeSuccProbs(); 3137 3138 // Drop into default successor. 3139 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 3140 MVT::Other, getControlRoot(), 3141 DAG.getBasicBlock(Return))); 3142 } 3143 3144 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 3145 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 3146 } 3147 3148 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 3149 assert(FuncInfo.MBB->isEHPad() && 3150 "Call to landingpad not in landing pad!"); 3151 3152 // If there aren't registers to copy the values into (e.g., during SjLj 3153 // exceptions), then don't bother to create these DAG nodes. 3154 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3155 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 3156 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 3157 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 3158 return; 3159 3160 // If landingpad's return type is token type, we don't create DAG nodes 3161 // for its exception pointer and selector value. The extraction of exception 3162 // pointer or selector value from token type landingpads is not currently 3163 // supported. 3164 if (LP.getType()->isTokenTy()) 3165 return; 3166 3167 SmallVector<EVT, 2> ValueVTs; 3168 SDLoc dl = getCurSDLoc(); 3169 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3170 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3171 3172 // Get the two live-in registers as SDValues. The physregs have already been 3173 // copied into virtual registers. 3174 SDValue Ops[2]; 3175 if (FuncInfo.ExceptionPointerVirtReg) { 3176 Ops[0] = DAG.getZExtOrTrunc( 3177 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3178 FuncInfo.ExceptionPointerVirtReg, 3179 TLI.getPointerTy(DAG.getDataLayout())), 3180 dl, ValueVTs[0]); 3181 } else { 3182 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3183 } 3184 Ops[1] = DAG.getZExtOrTrunc( 3185 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3186 FuncInfo.ExceptionSelectorVirtReg, 3187 TLI.getPointerTy(DAG.getDataLayout())), 3188 dl, ValueVTs[1]); 3189 3190 // Merge into one. 3191 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3192 DAG.getVTList(ValueVTs), Ops); 3193 setValue(&LP, Res); 3194 } 3195 3196 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3197 MachineBasicBlock *Last) { 3198 // Update JTCases. 3199 for (JumpTableBlock &JTB : SL->JTCases) 3200 if (JTB.first.HeaderBB == First) 3201 JTB.first.HeaderBB = Last; 3202 3203 // Update BitTestCases. 3204 for (BitTestBlock &BTB : SL->BitTestCases) 3205 if (BTB.Parent == First) 3206 BTB.Parent = Last; 3207 } 3208 3209 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3210 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3211 3212 // Update machine-CFG edges with unique successors. 3213 SmallSet<BasicBlock*, 32> Done; 3214 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3215 BasicBlock *BB = I.getSuccessor(i); 3216 bool Inserted = Done.insert(BB).second; 3217 if (!Inserted) 3218 continue; 3219 3220 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3221 addSuccessorWithProb(IndirectBrMBB, Succ); 3222 } 3223 IndirectBrMBB->normalizeSuccProbs(); 3224 3225 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3226 MVT::Other, getControlRoot(), 3227 getValue(I.getAddress()))); 3228 } 3229 3230 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3231 if (!DAG.getTarget().Options.TrapUnreachable) 3232 return; 3233 3234 // We may be able to ignore unreachable behind a noreturn call. 3235 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3236 if (const CallInst *Call = dyn_cast_or_null<CallInst>(I.getPrevNode())) { 3237 if (Call->doesNotReturn()) 3238 return; 3239 } 3240 } 3241 3242 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3243 } 3244 3245 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3246 SDNodeFlags Flags; 3247 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3248 Flags.copyFMF(*FPOp); 3249 3250 SDValue Op = getValue(I.getOperand(0)); 3251 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3252 Op, Flags); 3253 setValue(&I, UnNodeValue); 3254 } 3255 3256 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3257 SDNodeFlags Flags; 3258 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3259 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3260 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3261 } 3262 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3263 Flags.setExact(ExactOp->isExact()); 3264 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3265 Flags.copyFMF(*FPOp); 3266 3267 SDValue Op1 = getValue(I.getOperand(0)); 3268 SDValue Op2 = getValue(I.getOperand(1)); 3269 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3270 Op1, Op2, Flags); 3271 setValue(&I, BinNodeValue); 3272 } 3273 3274 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3275 SDValue Op1 = getValue(I.getOperand(0)); 3276 SDValue Op2 = getValue(I.getOperand(1)); 3277 3278 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3279 Op1.getValueType(), DAG.getDataLayout()); 3280 3281 // Coerce the shift amount to the right type if we can. This exposes the 3282 // truncate or zext to optimization early. 3283 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3284 assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) && 3285 "Unexpected shift type"); 3286 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy); 3287 } 3288 3289 bool nuw = false; 3290 bool nsw = false; 3291 bool exact = false; 3292 3293 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3294 3295 if (const OverflowingBinaryOperator *OFBinOp = 3296 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3297 nuw = OFBinOp->hasNoUnsignedWrap(); 3298 nsw = OFBinOp->hasNoSignedWrap(); 3299 } 3300 if (const PossiblyExactOperator *ExactOp = 3301 dyn_cast<const PossiblyExactOperator>(&I)) 3302 exact = ExactOp->isExact(); 3303 } 3304 SDNodeFlags Flags; 3305 Flags.setExact(exact); 3306 Flags.setNoSignedWrap(nsw); 3307 Flags.setNoUnsignedWrap(nuw); 3308 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3309 Flags); 3310 setValue(&I, Res); 3311 } 3312 3313 void SelectionDAGBuilder::visitSDiv(const User &I) { 3314 SDValue Op1 = getValue(I.getOperand(0)); 3315 SDValue Op2 = getValue(I.getOperand(1)); 3316 3317 SDNodeFlags Flags; 3318 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3319 cast<PossiblyExactOperator>(&I)->isExact()); 3320 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3321 Op2, Flags)); 3322 } 3323 3324 void SelectionDAGBuilder::visitICmp(const User &I) { 3325 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3326 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3327 predicate = IC->getPredicate(); 3328 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3329 predicate = ICmpInst::Predicate(IC->getPredicate()); 3330 SDValue Op1 = getValue(I.getOperand(0)); 3331 SDValue Op2 = getValue(I.getOperand(1)); 3332 ISD::CondCode Opcode = getICmpCondCode(predicate); 3333 3334 auto &TLI = DAG.getTargetLoweringInfo(); 3335 EVT MemVT = 3336 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3337 3338 // If a pointer's DAG type is larger than its memory type then the DAG values 3339 // are zero-extended. This breaks signed comparisons so truncate back to the 3340 // underlying type before doing the compare. 3341 if (Op1.getValueType() != MemVT) { 3342 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3343 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3344 } 3345 3346 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3347 I.getType()); 3348 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3349 } 3350 3351 void SelectionDAGBuilder::visitFCmp(const User &I) { 3352 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3353 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3354 predicate = FC->getPredicate(); 3355 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3356 predicate = FCmpInst::Predicate(FC->getPredicate()); 3357 SDValue Op1 = getValue(I.getOperand(0)); 3358 SDValue Op2 = getValue(I.getOperand(1)); 3359 3360 ISD::CondCode Condition = getFCmpCondCode(predicate); 3361 auto *FPMO = cast<FPMathOperator>(&I); 3362 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3363 Condition = getFCmpCodeWithoutNaN(Condition); 3364 3365 SDNodeFlags Flags; 3366 Flags.copyFMF(*FPMO); 3367 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3368 3369 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3370 I.getType()); 3371 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3372 } 3373 3374 // Check if the condition of the select has one use or two users that are both 3375 // selects with the same condition. 3376 static bool hasOnlySelectUsers(const Value *Cond) { 3377 return llvm::all_of(Cond->users(), [](const Value *V) { 3378 return isa<SelectInst>(V); 3379 }); 3380 } 3381 3382 void SelectionDAGBuilder::visitSelect(const User &I) { 3383 SmallVector<EVT, 4> ValueVTs; 3384 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3385 ValueVTs); 3386 unsigned NumValues = ValueVTs.size(); 3387 if (NumValues == 0) return; 3388 3389 SmallVector<SDValue, 4> Values(NumValues); 3390 SDValue Cond = getValue(I.getOperand(0)); 3391 SDValue LHSVal = getValue(I.getOperand(1)); 3392 SDValue RHSVal = getValue(I.getOperand(2)); 3393 SmallVector<SDValue, 1> BaseOps(1, Cond); 3394 ISD::NodeType OpCode = 3395 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3396 3397 bool IsUnaryAbs = false; 3398 bool Negate = false; 3399 3400 SDNodeFlags Flags; 3401 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3402 Flags.copyFMF(*FPOp); 3403 3404 Flags.setUnpredictable( 3405 cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable)); 3406 3407 // Min/max matching is only viable if all output VTs are the same. 3408 if (all_equal(ValueVTs)) { 3409 EVT VT = ValueVTs[0]; 3410 LLVMContext &Ctx = *DAG.getContext(); 3411 auto &TLI = DAG.getTargetLoweringInfo(); 3412 3413 // We care about the legality of the operation after it has been type 3414 // legalized. 3415 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3416 VT = TLI.getTypeToTransformTo(Ctx, VT); 3417 3418 // If the vselect is legal, assume we want to leave this as a vector setcc + 3419 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3420 // min/max is legal on the scalar type. 3421 bool UseScalarMinMax = VT.isVector() && 3422 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3423 3424 // ValueTracking's select pattern matching does not account for -0.0, 3425 // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that 3426 // -0.0 is less than +0.0. 3427 Value *LHS, *RHS; 3428 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3429 ISD::NodeType Opc = ISD::DELETED_NODE; 3430 switch (SPR.Flavor) { 3431 case SPF_UMAX: Opc = ISD::UMAX; break; 3432 case SPF_UMIN: Opc = ISD::UMIN; break; 3433 case SPF_SMAX: Opc = ISD::SMAX; break; 3434 case SPF_SMIN: Opc = ISD::SMIN; break; 3435 case SPF_FMINNUM: 3436 switch (SPR.NaNBehavior) { 3437 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3438 case SPNB_RETURNS_NAN: break; 3439 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3440 case SPNB_RETURNS_ANY: 3441 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) || 3442 (UseScalarMinMax && 3443 TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()))) 3444 Opc = ISD::FMINNUM; 3445 break; 3446 } 3447 break; 3448 case SPF_FMAXNUM: 3449 switch (SPR.NaNBehavior) { 3450 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3451 case SPNB_RETURNS_NAN: break; 3452 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3453 case SPNB_RETURNS_ANY: 3454 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) || 3455 (UseScalarMinMax && 3456 TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()))) 3457 Opc = ISD::FMAXNUM; 3458 break; 3459 } 3460 break; 3461 case SPF_NABS: 3462 Negate = true; 3463 [[fallthrough]]; 3464 case SPF_ABS: 3465 IsUnaryAbs = true; 3466 Opc = ISD::ABS; 3467 break; 3468 default: break; 3469 } 3470 3471 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3472 (TLI.isOperationLegalOrCustomOrPromote(Opc, VT) || 3473 (UseScalarMinMax && 3474 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3475 // If the underlying comparison instruction is used by any other 3476 // instruction, the consumed instructions won't be destroyed, so it is 3477 // not profitable to convert to a min/max. 3478 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3479 OpCode = Opc; 3480 LHSVal = getValue(LHS); 3481 RHSVal = getValue(RHS); 3482 BaseOps.clear(); 3483 } 3484 3485 if (IsUnaryAbs) { 3486 OpCode = Opc; 3487 LHSVal = getValue(LHS); 3488 BaseOps.clear(); 3489 } 3490 } 3491 3492 if (IsUnaryAbs) { 3493 for (unsigned i = 0; i != NumValues; ++i) { 3494 SDLoc dl = getCurSDLoc(); 3495 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3496 Values[i] = 3497 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3498 if (Negate) 3499 Values[i] = DAG.getNegative(Values[i], dl, VT); 3500 } 3501 } else { 3502 for (unsigned i = 0; i != NumValues; ++i) { 3503 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3504 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3505 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3506 Values[i] = DAG.getNode( 3507 OpCode, getCurSDLoc(), 3508 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3509 } 3510 } 3511 3512 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3513 DAG.getVTList(ValueVTs), Values)); 3514 } 3515 3516 void SelectionDAGBuilder::visitTrunc(const User &I) { 3517 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3518 SDValue N = getValue(I.getOperand(0)); 3519 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3520 I.getType()); 3521 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3522 } 3523 3524 void SelectionDAGBuilder::visitZExt(const User &I) { 3525 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3526 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3527 SDValue N = getValue(I.getOperand(0)); 3528 auto &TLI = DAG.getTargetLoweringInfo(); 3529 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3530 3531 SDNodeFlags Flags; 3532 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I)) 3533 Flags.setNonNeg(PNI->hasNonNeg()); 3534 3535 // Eagerly use nonneg information to canonicalize towards sign_extend if 3536 // that is the target's preference. 3537 // TODO: Let the target do this later. 3538 if (Flags.hasNonNeg() && 3539 TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) { 3540 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3541 return; 3542 } 3543 3544 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags)); 3545 } 3546 3547 void SelectionDAGBuilder::visitSExt(const User &I) { 3548 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3549 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3550 SDValue N = getValue(I.getOperand(0)); 3551 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3552 I.getType()); 3553 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3554 } 3555 3556 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3557 // FPTrunc is never a no-op cast, no need to check 3558 SDValue N = getValue(I.getOperand(0)); 3559 SDLoc dl = getCurSDLoc(); 3560 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3561 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3562 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3563 DAG.getTargetConstant( 3564 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3565 } 3566 3567 void SelectionDAGBuilder::visitFPExt(const User &I) { 3568 // FPExt is never a no-op cast, no need to check 3569 SDValue N = getValue(I.getOperand(0)); 3570 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3571 I.getType()); 3572 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3573 } 3574 3575 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3576 // FPToUI is never a no-op cast, no need to check 3577 SDValue N = getValue(I.getOperand(0)); 3578 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3579 I.getType()); 3580 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3581 } 3582 3583 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3584 // FPToSI is never a no-op cast, no need to check 3585 SDValue N = getValue(I.getOperand(0)); 3586 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3587 I.getType()); 3588 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3589 } 3590 3591 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3592 // UIToFP is never a no-op cast, no need to check 3593 SDValue N = getValue(I.getOperand(0)); 3594 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3595 I.getType()); 3596 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3597 } 3598 3599 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3600 // SIToFP is never a no-op cast, no need to check 3601 SDValue N = getValue(I.getOperand(0)); 3602 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3603 I.getType()); 3604 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3605 } 3606 3607 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3608 // What to do depends on the size of the integer and the size of the pointer. 3609 // We can either truncate, zero extend, or no-op, accordingly. 3610 SDValue N = getValue(I.getOperand(0)); 3611 auto &TLI = DAG.getTargetLoweringInfo(); 3612 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3613 I.getType()); 3614 EVT PtrMemVT = 3615 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3616 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3617 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3618 setValue(&I, N); 3619 } 3620 3621 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3622 // What to do depends on the size of the integer and the size of the pointer. 3623 // We can either truncate, zero extend, or no-op, accordingly. 3624 SDValue N = getValue(I.getOperand(0)); 3625 auto &TLI = DAG.getTargetLoweringInfo(); 3626 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3627 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3628 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3629 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3630 setValue(&I, N); 3631 } 3632 3633 void SelectionDAGBuilder::visitBitCast(const User &I) { 3634 SDValue N = getValue(I.getOperand(0)); 3635 SDLoc dl = getCurSDLoc(); 3636 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3637 I.getType()); 3638 3639 // BitCast assures us that source and destination are the same size so this is 3640 // either a BITCAST or a no-op. 3641 if (DestVT != N.getValueType()) 3642 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3643 DestVT, N)); // convert types. 3644 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3645 // might fold any kind of constant expression to an integer constant and that 3646 // is not what we are looking for. Only recognize a bitcast of a genuine 3647 // constant integer as an opaque constant. 3648 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3649 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3650 /*isOpaque*/true)); 3651 else 3652 setValue(&I, N); // noop cast. 3653 } 3654 3655 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3656 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3657 const Value *SV = I.getOperand(0); 3658 SDValue N = getValue(SV); 3659 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3660 3661 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3662 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3663 3664 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3665 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3666 3667 setValue(&I, N); 3668 } 3669 3670 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3671 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3672 SDValue InVec = getValue(I.getOperand(0)); 3673 SDValue InVal = getValue(I.getOperand(1)); 3674 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3675 TLI.getVectorIdxTy(DAG.getDataLayout())); 3676 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3677 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3678 InVec, InVal, InIdx)); 3679 } 3680 3681 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3682 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3683 SDValue InVec = getValue(I.getOperand(0)); 3684 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3685 TLI.getVectorIdxTy(DAG.getDataLayout())); 3686 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3687 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3688 InVec, InIdx)); 3689 } 3690 3691 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3692 SDValue Src1 = getValue(I.getOperand(0)); 3693 SDValue Src2 = getValue(I.getOperand(1)); 3694 ArrayRef<int> Mask; 3695 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3696 Mask = SVI->getShuffleMask(); 3697 else 3698 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3699 SDLoc DL = getCurSDLoc(); 3700 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3701 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3702 EVT SrcVT = Src1.getValueType(); 3703 3704 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3705 VT.isScalableVector()) { 3706 // Canonical splat form of first element of first input vector. 3707 SDValue FirstElt = 3708 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3709 DAG.getVectorIdxConstant(0, DL)); 3710 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3711 return; 3712 } 3713 3714 // For now, we only handle splats for scalable vectors. 3715 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3716 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3717 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3718 3719 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3720 unsigned MaskNumElts = Mask.size(); 3721 3722 if (SrcNumElts == MaskNumElts) { 3723 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3724 return; 3725 } 3726 3727 // Normalize the shuffle vector since mask and vector length don't match. 3728 if (SrcNumElts < MaskNumElts) { 3729 // Mask is longer than the source vectors. We can use concatenate vector to 3730 // make the mask and vectors lengths match. 3731 3732 if (MaskNumElts % SrcNumElts == 0) { 3733 // Mask length is a multiple of the source vector length. 3734 // Check if the shuffle is some kind of concatenation of the input 3735 // vectors. 3736 unsigned NumConcat = MaskNumElts / SrcNumElts; 3737 bool IsConcat = true; 3738 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3739 for (unsigned i = 0; i != MaskNumElts; ++i) { 3740 int Idx = Mask[i]; 3741 if (Idx < 0) 3742 continue; 3743 // Ensure the indices in each SrcVT sized piece are sequential and that 3744 // the same source is used for the whole piece. 3745 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3746 (ConcatSrcs[i / SrcNumElts] >= 0 && 3747 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3748 IsConcat = false; 3749 break; 3750 } 3751 // Remember which source this index came from. 3752 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3753 } 3754 3755 // The shuffle is concatenating multiple vectors together. Just emit 3756 // a CONCAT_VECTORS operation. 3757 if (IsConcat) { 3758 SmallVector<SDValue, 8> ConcatOps; 3759 for (auto Src : ConcatSrcs) { 3760 if (Src < 0) 3761 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3762 else if (Src == 0) 3763 ConcatOps.push_back(Src1); 3764 else 3765 ConcatOps.push_back(Src2); 3766 } 3767 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3768 return; 3769 } 3770 } 3771 3772 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3773 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3774 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3775 PaddedMaskNumElts); 3776 3777 // Pad both vectors with undefs to make them the same length as the mask. 3778 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3779 3780 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3781 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3782 MOps1[0] = Src1; 3783 MOps2[0] = Src2; 3784 3785 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3786 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3787 3788 // Readjust mask for new input vector length. 3789 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3790 for (unsigned i = 0; i != MaskNumElts; ++i) { 3791 int Idx = Mask[i]; 3792 if (Idx >= (int)SrcNumElts) 3793 Idx -= SrcNumElts - PaddedMaskNumElts; 3794 MappedOps[i] = Idx; 3795 } 3796 3797 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3798 3799 // If the concatenated vector was padded, extract a subvector with the 3800 // correct number of elements. 3801 if (MaskNumElts != PaddedMaskNumElts) 3802 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3803 DAG.getVectorIdxConstant(0, DL)); 3804 3805 setValue(&I, Result); 3806 return; 3807 } 3808 3809 if (SrcNumElts > MaskNumElts) { 3810 // Analyze the access pattern of the vector to see if we can extract 3811 // two subvectors and do the shuffle. 3812 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3813 bool CanExtract = true; 3814 for (int Idx : Mask) { 3815 unsigned Input = 0; 3816 if (Idx < 0) 3817 continue; 3818 3819 if (Idx >= (int)SrcNumElts) { 3820 Input = 1; 3821 Idx -= SrcNumElts; 3822 } 3823 3824 // If all the indices come from the same MaskNumElts sized portion of 3825 // the sources we can use extract. Also make sure the extract wouldn't 3826 // extract past the end of the source. 3827 int NewStartIdx = alignDown(Idx, MaskNumElts); 3828 if (NewStartIdx + MaskNumElts > SrcNumElts || 3829 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3830 CanExtract = false; 3831 // Make sure we always update StartIdx as we use it to track if all 3832 // elements are undef. 3833 StartIdx[Input] = NewStartIdx; 3834 } 3835 3836 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3837 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3838 return; 3839 } 3840 if (CanExtract) { 3841 // Extract appropriate subvector and generate a vector shuffle 3842 for (unsigned Input = 0; Input < 2; ++Input) { 3843 SDValue &Src = Input == 0 ? Src1 : Src2; 3844 if (StartIdx[Input] < 0) 3845 Src = DAG.getUNDEF(VT); 3846 else { 3847 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3848 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3849 } 3850 } 3851 3852 // Calculate new mask. 3853 SmallVector<int, 8> MappedOps(Mask); 3854 for (int &Idx : MappedOps) { 3855 if (Idx >= (int)SrcNumElts) 3856 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3857 else if (Idx >= 0) 3858 Idx -= StartIdx[0]; 3859 } 3860 3861 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3862 return; 3863 } 3864 } 3865 3866 // We can't use either concat vectors or extract subvectors so fall back to 3867 // replacing the shuffle with extract and build vector. 3868 // to insert and build vector. 3869 EVT EltVT = VT.getVectorElementType(); 3870 SmallVector<SDValue,8> Ops; 3871 for (int Idx : Mask) { 3872 SDValue Res; 3873 3874 if (Idx < 0) { 3875 Res = DAG.getUNDEF(EltVT); 3876 } else { 3877 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3878 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3879 3880 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3881 DAG.getVectorIdxConstant(Idx, DL)); 3882 } 3883 3884 Ops.push_back(Res); 3885 } 3886 3887 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3888 } 3889 3890 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) { 3891 ArrayRef<unsigned> Indices = I.getIndices(); 3892 const Value *Op0 = I.getOperand(0); 3893 const Value *Op1 = I.getOperand(1); 3894 Type *AggTy = I.getType(); 3895 Type *ValTy = Op1->getType(); 3896 bool IntoUndef = isa<UndefValue>(Op0); 3897 bool FromUndef = isa<UndefValue>(Op1); 3898 3899 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3900 3901 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3902 SmallVector<EVT, 4> AggValueVTs; 3903 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3904 SmallVector<EVT, 4> ValValueVTs; 3905 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3906 3907 unsigned NumAggValues = AggValueVTs.size(); 3908 unsigned NumValValues = ValValueVTs.size(); 3909 SmallVector<SDValue, 4> Values(NumAggValues); 3910 3911 // Ignore an insertvalue that produces an empty object 3912 if (!NumAggValues) { 3913 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3914 return; 3915 } 3916 3917 SDValue Agg = getValue(Op0); 3918 unsigned i = 0; 3919 // Copy the beginning value(s) from the original aggregate. 3920 for (; i != LinearIndex; ++i) 3921 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3922 SDValue(Agg.getNode(), Agg.getResNo() + i); 3923 // Copy values from the inserted value(s). 3924 if (NumValValues) { 3925 SDValue Val = getValue(Op1); 3926 for (; i != LinearIndex + NumValValues; ++i) 3927 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3928 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3929 } 3930 // Copy remaining value(s) from the original aggregate. 3931 for (; i != NumAggValues; ++i) 3932 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3933 SDValue(Agg.getNode(), Agg.getResNo() + i); 3934 3935 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3936 DAG.getVTList(AggValueVTs), Values)); 3937 } 3938 3939 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) { 3940 ArrayRef<unsigned> Indices = I.getIndices(); 3941 const Value *Op0 = I.getOperand(0); 3942 Type *AggTy = Op0->getType(); 3943 Type *ValTy = I.getType(); 3944 bool OutOfUndef = isa<UndefValue>(Op0); 3945 3946 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3947 3948 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3949 SmallVector<EVT, 4> ValValueVTs; 3950 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3951 3952 unsigned NumValValues = ValValueVTs.size(); 3953 3954 // Ignore a extractvalue that produces an empty object 3955 if (!NumValValues) { 3956 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3957 return; 3958 } 3959 3960 SmallVector<SDValue, 4> Values(NumValValues); 3961 3962 SDValue Agg = getValue(Op0); 3963 // Copy out the selected value(s). 3964 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3965 Values[i - LinearIndex] = 3966 OutOfUndef ? 3967 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3968 SDValue(Agg.getNode(), Agg.getResNo() + i); 3969 3970 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3971 DAG.getVTList(ValValueVTs), Values)); 3972 } 3973 3974 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3975 Value *Op0 = I.getOperand(0); 3976 // Note that the pointer operand may be a vector of pointers. Take the scalar 3977 // element which holds a pointer. 3978 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3979 SDValue N = getValue(Op0); 3980 SDLoc dl = getCurSDLoc(); 3981 auto &TLI = DAG.getTargetLoweringInfo(); 3982 3983 // Normalize Vector GEP - all scalar operands should be converted to the 3984 // splat vector. 3985 bool IsVectorGEP = I.getType()->isVectorTy(); 3986 ElementCount VectorElementCount = 3987 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3988 : ElementCount::getFixed(0); 3989 3990 if (IsVectorGEP && !N.getValueType().isVector()) { 3991 LLVMContext &Context = *DAG.getContext(); 3992 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3993 N = DAG.getSplat(VT, dl, N); 3994 } 3995 3996 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3997 GTI != E; ++GTI) { 3998 const Value *Idx = GTI.getOperand(); 3999 if (StructType *StTy = GTI.getStructTypeOrNull()) { 4000 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 4001 if (Field) { 4002 // N = N + Offset 4003 uint64_t Offset = 4004 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field); 4005 4006 // In an inbounds GEP with an offset that is nonnegative even when 4007 // interpreted as signed, assume there is no unsigned overflow. 4008 SDNodeFlags Flags; 4009 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 4010 Flags.setNoUnsignedWrap(true); 4011 4012 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 4013 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 4014 } 4015 } else { 4016 // IdxSize is the width of the arithmetic according to IR semantics. 4017 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 4018 // (and fix up the result later). 4019 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 4020 MVT IdxTy = MVT::getIntegerVT(IdxSize); 4021 TypeSize ElementSize = 4022 DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType()); 4023 // We intentionally mask away the high bits here; ElementSize may not 4024 // fit in IdxTy. 4025 APInt ElementMul(IdxSize, ElementSize.getKnownMinValue()); 4026 bool ElementScalable = ElementSize.isScalable(); 4027 4028 // If this is a scalar constant or a splat vector of constants, 4029 // handle it quickly. 4030 const auto *C = dyn_cast<Constant>(Idx); 4031 if (C && isa<VectorType>(C->getType())) 4032 C = C->getSplatValue(); 4033 4034 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 4035 if (CI && CI->isZero()) 4036 continue; 4037 if (CI && !ElementScalable) { 4038 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 4039 LLVMContext &Context = *DAG.getContext(); 4040 SDValue OffsVal; 4041 if (IsVectorGEP) 4042 OffsVal = DAG.getConstant( 4043 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 4044 else 4045 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 4046 4047 // In an inbounds GEP with an offset that is nonnegative even when 4048 // interpreted as signed, assume there is no unsigned overflow. 4049 SDNodeFlags Flags; 4050 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 4051 Flags.setNoUnsignedWrap(true); 4052 4053 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 4054 4055 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 4056 continue; 4057 } 4058 4059 // N = N + Idx * ElementMul; 4060 SDValue IdxN = getValue(Idx); 4061 4062 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 4063 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 4064 VectorElementCount); 4065 IdxN = DAG.getSplat(VT, dl, IdxN); 4066 } 4067 4068 // If the index is smaller or larger than intptr_t, truncate or extend 4069 // it. 4070 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 4071 4072 if (ElementScalable) { 4073 EVT VScaleTy = N.getValueType().getScalarType(); 4074 SDValue VScale = DAG.getNode( 4075 ISD::VSCALE, dl, VScaleTy, 4076 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 4077 if (IsVectorGEP) 4078 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 4079 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 4080 } else { 4081 // If this is a multiply by a power of two, turn it into a shl 4082 // immediately. This is a very common case. 4083 if (ElementMul != 1) { 4084 if (ElementMul.isPowerOf2()) { 4085 unsigned Amt = ElementMul.logBase2(); 4086 IdxN = DAG.getNode(ISD::SHL, dl, 4087 N.getValueType(), IdxN, 4088 DAG.getConstant(Amt, dl, IdxN.getValueType())); 4089 } else { 4090 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 4091 IdxN.getValueType()); 4092 IdxN = DAG.getNode(ISD::MUL, dl, 4093 N.getValueType(), IdxN, Scale); 4094 } 4095 } 4096 } 4097 4098 N = DAG.getNode(ISD::ADD, dl, 4099 N.getValueType(), N, IdxN); 4100 } 4101 } 4102 4103 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 4104 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 4105 if (IsVectorGEP) { 4106 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 4107 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 4108 } 4109 4110 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 4111 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 4112 4113 setValue(&I, N); 4114 } 4115 4116 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 4117 // If this is a fixed sized alloca in the entry block of the function, 4118 // allocate it statically on the stack. 4119 if (FuncInfo.StaticAllocaMap.count(&I)) 4120 return; // getValue will auto-populate this. 4121 4122 SDLoc dl = getCurSDLoc(); 4123 Type *Ty = I.getAllocatedType(); 4124 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4125 auto &DL = DAG.getDataLayout(); 4126 TypeSize TySize = DL.getTypeAllocSize(Ty); 4127 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 4128 4129 SDValue AllocSize = getValue(I.getArraySize()); 4130 4131 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), I.getAddressSpace()); 4132 if (AllocSize.getValueType() != IntPtr) 4133 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 4134 4135 if (TySize.isScalable()) 4136 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4137 DAG.getVScale(dl, IntPtr, 4138 APInt(IntPtr.getScalarSizeInBits(), 4139 TySize.getKnownMinValue()))); 4140 else 4141 AllocSize = 4142 DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4143 DAG.getConstant(TySize.getFixedValue(), dl, IntPtr)); 4144 4145 // Handle alignment. If the requested alignment is less than or equal to 4146 // the stack alignment, ignore it. If the size is greater than or equal to 4147 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4148 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 4149 if (*Alignment <= StackAlign) 4150 Alignment = std::nullopt; 4151 4152 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4153 // Round the size of the allocation up to the stack alignment size 4154 // by add SA-1 to the size. This doesn't overflow because we're computing 4155 // an address inside an alloca. 4156 SDNodeFlags Flags; 4157 Flags.setNoUnsignedWrap(true); 4158 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4159 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4160 4161 // Mask out the low bits for alignment purposes. 4162 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4163 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 4164 4165 SDValue Ops[] = { 4166 getRoot(), AllocSize, 4167 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4168 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4169 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4170 setValue(&I, DSA); 4171 DAG.setRoot(DSA.getValue(1)); 4172 4173 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4174 } 4175 4176 static const MDNode *getRangeMetadata(const Instruction &I) { 4177 // If !noundef is not present, then !range violation results in a poison 4178 // value rather than immediate undefined behavior. In theory, transferring 4179 // these annotations to SDAG is fine, but in practice there are key SDAG 4180 // transforms that are known not to be poison-safe, such as folding logical 4181 // and/or to bitwise and/or. For now, only transfer !range if !noundef is 4182 // also present. 4183 if (!I.hasMetadata(LLVMContext::MD_noundef)) 4184 return nullptr; 4185 return I.getMetadata(LLVMContext::MD_range); 4186 } 4187 4188 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4189 if (I.isAtomic()) 4190 return visitAtomicLoad(I); 4191 4192 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4193 const Value *SV = I.getOperand(0); 4194 if (TLI.supportSwiftError()) { 4195 // Swifterror values can come from either a function parameter with 4196 // swifterror attribute or an alloca with swifterror attribute. 4197 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4198 if (Arg->hasSwiftErrorAttr()) 4199 return visitLoadFromSwiftError(I); 4200 } 4201 4202 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4203 if (Alloca->isSwiftError()) 4204 return visitLoadFromSwiftError(I); 4205 } 4206 } 4207 4208 SDValue Ptr = getValue(SV); 4209 4210 Type *Ty = I.getType(); 4211 SmallVector<EVT, 4> ValueVTs, MemVTs; 4212 SmallVector<TypeSize, 4> Offsets; 4213 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets, 0); 4214 unsigned NumValues = ValueVTs.size(); 4215 if (NumValues == 0) 4216 return; 4217 4218 Align Alignment = I.getAlign(); 4219 AAMDNodes AAInfo = I.getAAMetadata(); 4220 const MDNode *Ranges = getRangeMetadata(I); 4221 bool isVolatile = I.isVolatile(); 4222 MachineMemOperand::Flags MMOFlags = 4223 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 4224 4225 SDValue Root; 4226 bool ConstantMemory = false; 4227 if (isVolatile) 4228 // Serialize volatile loads with other side effects. 4229 Root = getRoot(); 4230 else if (NumValues > MaxParallelChains) 4231 Root = getMemoryRoot(); 4232 else if (AA && 4233 AA->pointsToConstantMemory(MemoryLocation( 4234 SV, 4235 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4236 AAInfo))) { 4237 // Do not serialize (non-volatile) loads of constant memory with anything. 4238 Root = DAG.getEntryNode(); 4239 ConstantMemory = true; 4240 MMOFlags |= MachineMemOperand::MOInvariant; 4241 } else { 4242 // Do not serialize non-volatile loads against each other. 4243 Root = DAG.getRoot(); 4244 } 4245 4246 SDLoc dl = getCurSDLoc(); 4247 4248 if (isVolatile) 4249 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4250 4251 SmallVector<SDValue, 4> Values(NumValues); 4252 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4253 4254 unsigned ChainI = 0; 4255 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4256 // Serializing loads here may result in excessive register pressure, and 4257 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4258 // could recover a bit by hoisting nodes upward in the chain by recognizing 4259 // they are side-effect free or do not alias. The optimizer should really 4260 // avoid this case by converting large object/array copies to llvm.memcpy 4261 // (MaxParallelChains should always remain as failsafe). 4262 if (ChainI == MaxParallelChains) { 4263 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4264 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4265 ArrayRef(Chains.data(), ChainI)); 4266 Root = Chain; 4267 ChainI = 0; 4268 } 4269 4270 // TODO: MachinePointerInfo only supports a fixed length offset. 4271 MachinePointerInfo PtrInfo = 4272 !Offsets[i].isScalable() || Offsets[i].isZero() 4273 ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue()) 4274 : MachinePointerInfo(); 4275 4276 SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]); 4277 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment, 4278 MMOFlags, AAInfo, Ranges); 4279 Chains[ChainI] = L.getValue(1); 4280 4281 if (MemVTs[i] != ValueVTs[i]) 4282 L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]); 4283 4284 Values[i] = L; 4285 } 4286 4287 if (!ConstantMemory) { 4288 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4289 ArrayRef(Chains.data(), ChainI)); 4290 if (isVolatile) 4291 DAG.setRoot(Chain); 4292 else 4293 PendingLoads.push_back(Chain); 4294 } 4295 4296 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4297 DAG.getVTList(ValueVTs), Values)); 4298 } 4299 4300 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4301 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4302 "call visitStoreToSwiftError when backend supports swifterror"); 4303 4304 SmallVector<EVT, 4> ValueVTs; 4305 SmallVector<uint64_t, 4> Offsets; 4306 const Value *SrcV = I.getOperand(0); 4307 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4308 SrcV->getType(), ValueVTs, &Offsets, 0); 4309 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4310 "expect a single EVT for swifterror"); 4311 4312 SDValue Src = getValue(SrcV); 4313 // Create a virtual register, then update the virtual register. 4314 Register VReg = 4315 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4316 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4317 // Chain can be getRoot or getControlRoot. 4318 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4319 SDValue(Src.getNode(), Src.getResNo())); 4320 DAG.setRoot(CopyNode); 4321 } 4322 4323 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4324 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4325 "call visitLoadFromSwiftError when backend supports swifterror"); 4326 4327 assert(!I.isVolatile() && 4328 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4329 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4330 "Support volatile, non temporal, invariant for load_from_swift_error"); 4331 4332 const Value *SV = I.getOperand(0); 4333 Type *Ty = I.getType(); 4334 assert( 4335 (!AA || 4336 !AA->pointsToConstantMemory(MemoryLocation( 4337 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4338 I.getAAMetadata()))) && 4339 "load_from_swift_error should not be constant memory"); 4340 4341 SmallVector<EVT, 4> ValueVTs; 4342 SmallVector<uint64_t, 4> Offsets; 4343 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4344 ValueVTs, &Offsets, 0); 4345 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4346 "expect a single EVT for swifterror"); 4347 4348 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4349 SDValue L = DAG.getCopyFromReg( 4350 getRoot(), getCurSDLoc(), 4351 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4352 4353 setValue(&I, L); 4354 } 4355 4356 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4357 if (I.isAtomic()) 4358 return visitAtomicStore(I); 4359 4360 const Value *SrcV = I.getOperand(0); 4361 const Value *PtrV = I.getOperand(1); 4362 4363 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4364 if (TLI.supportSwiftError()) { 4365 // Swifterror values can come from either a function parameter with 4366 // swifterror attribute or an alloca with swifterror attribute. 4367 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4368 if (Arg->hasSwiftErrorAttr()) 4369 return visitStoreToSwiftError(I); 4370 } 4371 4372 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4373 if (Alloca->isSwiftError()) 4374 return visitStoreToSwiftError(I); 4375 } 4376 } 4377 4378 SmallVector<EVT, 4> ValueVTs, MemVTs; 4379 SmallVector<TypeSize, 4> Offsets; 4380 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4381 SrcV->getType(), ValueVTs, &MemVTs, &Offsets, 0); 4382 unsigned NumValues = ValueVTs.size(); 4383 if (NumValues == 0) 4384 return; 4385 4386 // Get the lowered operands. Note that we do this after 4387 // checking if NumResults is zero, because with zero results 4388 // the operands won't have values in the map. 4389 SDValue Src = getValue(SrcV); 4390 SDValue Ptr = getValue(PtrV); 4391 4392 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4393 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4394 SDLoc dl = getCurSDLoc(); 4395 Align Alignment = I.getAlign(); 4396 AAMDNodes AAInfo = I.getAAMetadata(); 4397 4398 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4399 4400 unsigned ChainI = 0; 4401 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4402 // See visitLoad comments. 4403 if (ChainI == MaxParallelChains) { 4404 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4405 ArrayRef(Chains.data(), ChainI)); 4406 Root = Chain; 4407 ChainI = 0; 4408 } 4409 4410 // TODO: MachinePointerInfo only supports a fixed length offset. 4411 MachinePointerInfo PtrInfo = 4412 !Offsets[i].isScalable() || Offsets[i].isZero() 4413 ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue()) 4414 : MachinePointerInfo(); 4415 4416 SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]); 4417 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4418 if (MemVTs[i] != ValueVTs[i]) 4419 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4420 SDValue St = 4421 DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags, AAInfo); 4422 Chains[ChainI] = St; 4423 } 4424 4425 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4426 ArrayRef(Chains.data(), ChainI)); 4427 setValue(&I, StoreNode); 4428 DAG.setRoot(StoreNode); 4429 } 4430 4431 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4432 bool IsCompressing) { 4433 SDLoc sdl = getCurSDLoc(); 4434 4435 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4436 MaybeAlign &Alignment) { 4437 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4438 Src0 = I.getArgOperand(0); 4439 Ptr = I.getArgOperand(1); 4440 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4441 Mask = I.getArgOperand(3); 4442 }; 4443 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4444 MaybeAlign &Alignment) { 4445 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4446 Src0 = I.getArgOperand(0); 4447 Ptr = I.getArgOperand(1); 4448 Mask = I.getArgOperand(2); 4449 Alignment = std::nullopt; 4450 }; 4451 4452 Value *PtrOperand, *MaskOperand, *Src0Operand; 4453 MaybeAlign Alignment; 4454 if (IsCompressing) 4455 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4456 else 4457 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4458 4459 SDValue Ptr = getValue(PtrOperand); 4460 SDValue Src0 = getValue(Src0Operand); 4461 SDValue Mask = getValue(MaskOperand); 4462 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4463 4464 EVT VT = Src0.getValueType(); 4465 if (!Alignment) 4466 Alignment = DAG.getEVTAlign(VT); 4467 4468 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4469 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4470 MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata()); 4471 SDValue StoreNode = 4472 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4473 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4474 DAG.setRoot(StoreNode); 4475 setValue(&I, StoreNode); 4476 } 4477 4478 // Get a uniform base for the Gather/Scatter intrinsic. 4479 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4480 // We try to represent it as a base pointer + vector of indices. 4481 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4482 // The first operand of the GEP may be a single pointer or a vector of pointers 4483 // Example: 4484 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4485 // or 4486 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4487 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4488 // 4489 // When the first GEP operand is a single pointer - it is the uniform base we 4490 // are looking for. If first operand of the GEP is a splat vector - we 4491 // extract the splat value and use it as a uniform base. 4492 // In all other cases the function returns 'false'. 4493 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4494 ISD::MemIndexType &IndexType, SDValue &Scale, 4495 SelectionDAGBuilder *SDB, const BasicBlock *CurBB, 4496 uint64_t ElemSize) { 4497 SelectionDAG& DAG = SDB->DAG; 4498 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4499 const DataLayout &DL = DAG.getDataLayout(); 4500 4501 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type"); 4502 4503 // Handle splat constant pointer. 4504 if (auto *C = dyn_cast<Constant>(Ptr)) { 4505 C = C->getSplatValue(); 4506 if (!C) 4507 return false; 4508 4509 Base = SDB->getValue(C); 4510 4511 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); 4512 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4513 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4514 IndexType = ISD::SIGNED_SCALED; 4515 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4516 return true; 4517 } 4518 4519 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4520 if (!GEP || GEP->getParent() != CurBB) 4521 return false; 4522 4523 if (GEP->getNumOperands() != 2) 4524 return false; 4525 4526 const Value *BasePtr = GEP->getPointerOperand(); 4527 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4528 4529 // Make sure the base is scalar and the index is a vector. 4530 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4531 return false; 4532 4533 TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType()); 4534 if (ScaleVal.isScalable()) 4535 return false; 4536 4537 // Target may not support the required addressing mode. 4538 if (ScaleVal != 1 && 4539 !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize)) 4540 return false; 4541 4542 Base = SDB->getValue(BasePtr); 4543 Index = SDB->getValue(IndexVal); 4544 IndexType = ISD::SIGNED_SCALED; 4545 4546 Scale = 4547 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4548 return true; 4549 } 4550 4551 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4552 SDLoc sdl = getCurSDLoc(); 4553 4554 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4555 const Value *Ptr = I.getArgOperand(1); 4556 SDValue Src0 = getValue(I.getArgOperand(0)); 4557 SDValue Mask = getValue(I.getArgOperand(3)); 4558 EVT VT = Src0.getValueType(); 4559 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4560 ->getMaybeAlignValue() 4561 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4562 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4563 4564 SDValue Base; 4565 SDValue Index; 4566 ISD::MemIndexType IndexType; 4567 SDValue Scale; 4568 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4569 I.getParent(), VT.getScalarStoreSize()); 4570 4571 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4572 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4573 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4574 // TODO: Make MachineMemOperands aware of scalable 4575 // vectors. 4576 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata()); 4577 if (!UniformBase) { 4578 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4579 Index = getValue(Ptr); 4580 IndexType = ISD::SIGNED_SCALED; 4581 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4582 } 4583 4584 EVT IdxVT = Index.getValueType(); 4585 EVT EltTy = IdxVT.getVectorElementType(); 4586 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4587 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4588 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4589 } 4590 4591 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4592 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4593 Ops, MMO, IndexType, false); 4594 DAG.setRoot(Scatter); 4595 setValue(&I, Scatter); 4596 } 4597 4598 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4599 SDLoc sdl = getCurSDLoc(); 4600 4601 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4602 MaybeAlign &Alignment) { 4603 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4604 Ptr = I.getArgOperand(0); 4605 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4606 Mask = I.getArgOperand(2); 4607 Src0 = I.getArgOperand(3); 4608 }; 4609 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4610 MaybeAlign &Alignment) { 4611 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4612 Ptr = I.getArgOperand(0); 4613 Alignment = std::nullopt; 4614 Mask = I.getArgOperand(1); 4615 Src0 = I.getArgOperand(2); 4616 }; 4617 4618 Value *PtrOperand, *MaskOperand, *Src0Operand; 4619 MaybeAlign Alignment; 4620 if (IsExpanding) 4621 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4622 else 4623 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4624 4625 SDValue Ptr = getValue(PtrOperand); 4626 SDValue Src0 = getValue(Src0Operand); 4627 SDValue Mask = getValue(MaskOperand); 4628 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4629 4630 EVT VT = Src0.getValueType(); 4631 if (!Alignment) 4632 Alignment = DAG.getEVTAlign(VT); 4633 4634 AAMDNodes AAInfo = I.getAAMetadata(); 4635 const MDNode *Ranges = getRangeMetadata(I); 4636 4637 // Do not serialize masked loads of constant memory with anything. 4638 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 4639 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4640 4641 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4642 4643 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4644 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4645 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 4646 4647 SDValue Load = 4648 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4649 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4650 if (AddToChain) 4651 PendingLoads.push_back(Load.getValue(1)); 4652 setValue(&I, Load); 4653 } 4654 4655 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4656 SDLoc sdl = getCurSDLoc(); 4657 4658 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4659 const Value *Ptr = I.getArgOperand(0); 4660 SDValue Src0 = getValue(I.getArgOperand(3)); 4661 SDValue Mask = getValue(I.getArgOperand(2)); 4662 4663 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4664 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4665 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4666 ->getMaybeAlignValue() 4667 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4668 4669 const MDNode *Ranges = getRangeMetadata(I); 4670 4671 SDValue Root = DAG.getRoot(); 4672 SDValue Base; 4673 SDValue Index; 4674 ISD::MemIndexType IndexType; 4675 SDValue Scale; 4676 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4677 I.getParent(), VT.getScalarStoreSize()); 4678 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4679 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4680 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4681 // TODO: Make MachineMemOperands aware of scalable 4682 // vectors. 4683 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges); 4684 4685 if (!UniformBase) { 4686 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4687 Index = getValue(Ptr); 4688 IndexType = ISD::SIGNED_SCALED; 4689 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4690 } 4691 4692 EVT IdxVT = Index.getValueType(); 4693 EVT EltTy = IdxVT.getVectorElementType(); 4694 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4695 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4696 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4697 } 4698 4699 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4700 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4701 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4702 4703 PendingLoads.push_back(Gather.getValue(1)); 4704 setValue(&I, Gather); 4705 } 4706 4707 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4708 SDLoc dl = getCurSDLoc(); 4709 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4710 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4711 SyncScope::ID SSID = I.getSyncScopeID(); 4712 4713 SDValue InChain = getRoot(); 4714 4715 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4716 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4717 4718 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4719 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4720 4721 MachineFunction &MF = DAG.getMachineFunction(); 4722 MachineMemOperand *MMO = MF.getMachineMemOperand( 4723 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4724 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4725 FailureOrdering); 4726 4727 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4728 dl, MemVT, VTs, InChain, 4729 getValue(I.getPointerOperand()), 4730 getValue(I.getCompareOperand()), 4731 getValue(I.getNewValOperand()), MMO); 4732 4733 SDValue OutChain = L.getValue(2); 4734 4735 setValue(&I, L); 4736 DAG.setRoot(OutChain); 4737 } 4738 4739 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4740 SDLoc dl = getCurSDLoc(); 4741 ISD::NodeType NT; 4742 switch (I.getOperation()) { 4743 default: llvm_unreachable("Unknown atomicrmw operation"); 4744 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4745 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4746 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4747 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4748 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4749 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4750 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4751 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4752 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4753 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4754 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4755 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4756 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4757 case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break; 4758 case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break; 4759 case AtomicRMWInst::UIncWrap: 4760 NT = ISD::ATOMIC_LOAD_UINC_WRAP; 4761 break; 4762 case AtomicRMWInst::UDecWrap: 4763 NT = ISD::ATOMIC_LOAD_UDEC_WRAP; 4764 break; 4765 } 4766 AtomicOrdering Ordering = I.getOrdering(); 4767 SyncScope::ID SSID = I.getSyncScopeID(); 4768 4769 SDValue InChain = getRoot(); 4770 4771 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4772 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4773 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4774 4775 MachineFunction &MF = DAG.getMachineFunction(); 4776 MachineMemOperand *MMO = MF.getMachineMemOperand( 4777 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4778 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4779 4780 SDValue L = 4781 DAG.getAtomic(NT, dl, MemVT, InChain, 4782 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4783 MMO); 4784 4785 SDValue OutChain = L.getValue(1); 4786 4787 setValue(&I, L); 4788 DAG.setRoot(OutChain); 4789 } 4790 4791 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4792 SDLoc dl = getCurSDLoc(); 4793 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4794 SDValue Ops[3]; 4795 Ops[0] = getRoot(); 4796 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4797 TLI.getFenceOperandTy(DAG.getDataLayout())); 4798 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4799 TLI.getFenceOperandTy(DAG.getDataLayout())); 4800 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops); 4801 setValue(&I, N); 4802 DAG.setRoot(N); 4803 } 4804 4805 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4806 SDLoc dl = getCurSDLoc(); 4807 AtomicOrdering Order = I.getOrdering(); 4808 SyncScope::ID SSID = I.getSyncScopeID(); 4809 4810 SDValue InChain = getRoot(); 4811 4812 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4813 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4814 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4815 4816 if (!TLI.supportsUnalignedAtomics() && 4817 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4818 report_fatal_error("Cannot generate unaligned atomic load"); 4819 4820 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 4821 4822 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4823 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4824 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4825 4826 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4827 4828 SDValue Ptr = getValue(I.getPointerOperand()); 4829 4830 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4831 // TODO: Once this is better exercised by tests, it should be merged with 4832 // the normal path for loads to prevent future divergence. 4833 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4834 if (MemVT != VT) 4835 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4836 4837 setValue(&I, L); 4838 SDValue OutChain = L.getValue(1); 4839 if (!I.isUnordered()) 4840 DAG.setRoot(OutChain); 4841 else 4842 PendingLoads.push_back(OutChain); 4843 return; 4844 } 4845 4846 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4847 Ptr, MMO); 4848 4849 SDValue OutChain = L.getValue(1); 4850 if (MemVT != VT) 4851 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4852 4853 setValue(&I, L); 4854 DAG.setRoot(OutChain); 4855 } 4856 4857 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4858 SDLoc dl = getCurSDLoc(); 4859 4860 AtomicOrdering Ordering = I.getOrdering(); 4861 SyncScope::ID SSID = I.getSyncScopeID(); 4862 4863 SDValue InChain = getRoot(); 4864 4865 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4866 EVT MemVT = 4867 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4868 4869 if (!TLI.supportsUnalignedAtomics() && 4870 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4871 report_fatal_error("Cannot generate unaligned atomic store"); 4872 4873 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4874 4875 MachineFunction &MF = DAG.getMachineFunction(); 4876 MachineMemOperand *MMO = MF.getMachineMemOperand( 4877 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4878 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4879 4880 SDValue Val = getValue(I.getValueOperand()); 4881 if (Val.getValueType() != MemVT) 4882 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4883 SDValue Ptr = getValue(I.getPointerOperand()); 4884 4885 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4886 // TODO: Once this is better exercised by tests, it should be merged with 4887 // the normal path for stores to prevent future divergence. 4888 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4889 setValue(&I, S); 4890 DAG.setRoot(S); 4891 return; 4892 } 4893 SDValue OutChain = 4894 DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO); 4895 4896 setValue(&I, OutChain); 4897 DAG.setRoot(OutChain); 4898 } 4899 4900 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4901 /// node. 4902 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4903 unsigned Intrinsic) { 4904 // Ignore the callsite's attributes. A specific call site may be marked with 4905 // readnone, but the lowering code will expect the chain based on the 4906 // definition. 4907 const Function *F = I.getCalledFunction(); 4908 bool HasChain = !F->doesNotAccessMemory(); 4909 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4910 4911 // Build the operand list. 4912 SmallVector<SDValue, 8> Ops; 4913 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4914 if (OnlyLoad) { 4915 // We don't need to serialize loads against other loads. 4916 Ops.push_back(DAG.getRoot()); 4917 } else { 4918 Ops.push_back(getRoot()); 4919 } 4920 } 4921 4922 // Info is set by getTgtMemIntrinsic 4923 TargetLowering::IntrinsicInfo Info; 4924 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4925 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4926 DAG.getMachineFunction(), 4927 Intrinsic); 4928 4929 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4930 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4931 Info.opc == ISD::INTRINSIC_W_CHAIN) 4932 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4933 TLI.getPointerTy(DAG.getDataLayout()))); 4934 4935 // Add all operands of the call to the operand list. 4936 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) { 4937 const Value *Arg = I.getArgOperand(i); 4938 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4939 Ops.push_back(getValue(Arg)); 4940 continue; 4941 } 4942 4943 // Use TargetConstant instead of a regular constant for immarg. 4944 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true); 4945 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4946 assert(CI->getBitWidth() <= 64 && 4947 "large intrinsic immediates not handled"); 4948 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4949 } else { 4950 Ops.push_back( 4951 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4952 } 4953 } 4954 4955 SmallVector<EVT, 4> ValueVTs; 4956 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4957 4958 if (HasChain) 4959 ValueVTs.push_back(MVT::Other); 4960 4961 SDVTList VTs = DAG.getVTList(ValueVTs); 4962 4963 // Propagate fast-math-flags from IR to node(s). 4964 SDNodeFlags Flags; 4965 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 4966 Flags.copyFMF(*FPMO); 4967 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 4968 4969 // Create the node. 4970 SDValue Result; 4971 // In some cases, custom collection of operands from CallInst I may be needed. 4972 TLI.CollectTargetIntrinsicOperands(I, Ops, DAG); 4973 if (IsTgtIntrinsic) { 4974 // This is target intrinsic that touches memory 4975 // 4976 // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic 4977 // didn't yield anything useful. 4978 MachinePointerInfo MPI; 4979 if (Info.ptrVal) 4980 MPI = MachinePointerInfo(Info.ptrVal, Info.offset); 4981 else if (Info.fallbackAddressSpace) 4982 MPI = MachinePointerInfo(*Info.fallbackAddressSpace); 4983 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, 4984 Info.memVT, MPI, Info.align, Info.flags, 4985 Info.size, I.getAAMetadata()); 4986 } else if (!HasChain) { 4987 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4988 } else if (!I.getType()->isVoidTy()) { 4989 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4990 } else { 4991 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4992 } 4993 4994 if (HasChain) { 4995 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4996 if (OnlyLoad) 4997 PendingLoads.push_back(Chain); 4998 else 4999 DAG.setRoot(Chain); 5000 } 5001 5002 if (!I.getType()->isVoidTy()) { 5003 if (!isa<VectorType>(I.getType())) 5004 Result = lowerRangeToAssertZExt(DAG, I, Result); 5005 5006 MaybeAlign Alignment = I.getRetAlign(); 5007 5008 // Insert `assertalign` node if there's an alignment. 5009 if (InsertAssertAlign && Alignment) { 5010 Result = 5011 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 5012 } 5013 5014 setValue(&I, Result); 5015 } 5016 } 5017 5018 /// GetSignificand - Get the significand and build it into a floating-point 5019 /// number with exponent of 1: 5020 /// 5021 /// Op = (Op & 0x007fffff) | 0x3f800000; 5022 /// 5023 /// where Op is the hexadecimal representation of floating point value. 5024 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 5025 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 5026 DAG.getConstant(0x007fffff, dl, MVT::i32)); 5027 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 5028 DAG.getConstant(0x3f800000, dl, MVT::i32)); 5029 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 5030 } 5031 5032 /// GetExponent - Get the exponent: 5033 /// 5034 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 5035 /// 5036 /// where Op is the hexadecimal representation of floating point value. 5037 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 5038 const TargetLowering &TLI, const SDLoc &dl) { 5039 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 5040 DAG.getConstant(0x7f800000, dl, MVT::i32)); 5041 SDValue t1 = DAG.getNode( 5042 ISD::SRL, dl, MVT::i32, t0, 5043 DAG.getConstant(23, dl, 5044 TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout()))); 5045 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 5046 DAG.getConstant(127, dl, MVT::i32)); 5047 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 5048 } 5049 5050 /// getF32Constant - Get 32-bit floating point constant. 5051 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 5052 const SDLoc &dl) { 5053 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 5054 MVT::f32); 5055 } 5056 5057 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 5058 SelectionDAG &DAG) { 5059 // TODO: What fast-math-flags should be set on the floating-point nodes? 5060 5061 // IntegerPartOfX = ((int32_t)(t0); 5062 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 5063 5064 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 5065 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 5066 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 5067 5068 // IntegerPartOfX <<= 23; 5069 IntegerPartOfX = 5070 DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 5071 DAG.getConstant(23, dl, 5072 DAG.getTargetLoweringInfo().getShiftAmountTy( 5073 MVT::i32, DAG.getDataLayout()))); 5074 5075 SDValue TwoToFractionalPartOfX; 5076 if (LimitFloatPrecision <= 6) { 5077 // For floating-point precision of 6: 5078 // 5079 // TwoToFractionalPartOfX = 5080 // 0.997535578f + 5081 // (0.735607626f + 0.252464424f * x) * x; 5082 // 5083 // error 0.0144103317, which is 6 bits 5084 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5085 getF32Constant(DAG, 0x3e814304, dl)); 5086 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5087 getF32Constant(DAG, 0x3f3c50c8, dl)); 5088 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5089 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5090 getF32Constant(DAG, 0x3f7f5e7e, dl)); 5091 } else if (LimitFloatPrecision <= 12) { 5092 // For floating-point precision of 12: 5093 // 5094 // TwoToFractionalPartOfX = 5095 // 0.999892986f + 5096 // (0.696457318f + 5097 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 5098 // 5099 // error 0.000107046256, which is 13 to 14 bits 5100 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5101 getF32Constant(DAG, 0x3da235e3, dl)); 5102 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5103 getF32Constant(DAG, 0x3e65b8f3, dl)); 5104 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5105 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5106 getF32Constant(DAG, 0x3f324b07, dl)); 5107 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5108 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5109 getF32Constant(DAG, 0x3f7ff8fd, dl)); 5110 } else { // LimitFloatPrecision <= 18 5111 // For floating-point precision of 18: 5112 // 5113 // TwoToFractionalPartOfX = 5114 // 0.999999982f + 5115 // (0.693148872f + 5116 // (0.240227044f + 5117 // (0.554906021e-1f + 5118 // (0.961591928e-2f + 5119 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 5120 // error 2.47208000*10^(-7), which is better than 18 bits 5121 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5122 getF32Constant(DAG, 0x3924b03e, dl)); 5123 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5124 getF32Constant(DAG, 0x3ab24b87, dl)); 5125 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5126 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5127 getF32Constant(DAG, 0x3c1d8c17, dl)); 5128 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5129 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5130 getF32Constant(DAG, 0x3d634a1d, dl)); 5131 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5132 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5133 getF32Constant(DAG, 0x3e75fe14, dl)); 5134 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5135 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 5136 getF32Constant(DAG, 0x3f317234, dl)); 5137 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 5138 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 5139 getF32Constant(DAG, 0x3f800000, dl)); 5140 } 5141 5142 // Add the exponent into the result in integer domain. 5143 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 5144 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5145 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 5146 } 5147 5148 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5149 /// limited-precision mode. 5150 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5151 const TargetLowering &TLI, SDNodeFlags Flags) { 5152 if (Op.getValueType() == MVT::f32 && 5153 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5154 5155 // Put the exponent in the right bit position for later addition to the 5156 // final result: 5157 // 5158 // t0 = Op * log2(e) 5159 5160 // TODO: What fast-math-flags should be set here? 5161 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5162 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5163 return getLimitedPrecisionExp2(t0, dl, DAG); 5164 } 5165 5166 // No special expansion. 5167 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5168 } 5169 5170 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5171 /// limited-precision mode. 5172 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5173 const TargetLowering &TLI, SDNodeFlags Flags) { 5174 // TODO: What fast-math-flags should be set on the floating-point nodes? 5175 5176 if (Op.getValueType() == MVT::f32 && 5177 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5178 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5179 5180 // Scale the exponent by log(2). 5181 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5182 SDValue LogOfExponent = 5183 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5184 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5185 5186 // Get the significand and build it into a floating-point number with 5187 // exponent of 1. 5188 SDValue X = GetSignificand(DAG, Op1, dl); 5189 5190 SDValue LogOfMantissa; 5191 if (LimitFloatPrecision <= 6) { 5192 // For floating-point precision of 6: 5193 // 5194 // LogofMantissa = 5195 // -1.1609546f + 5196 // (1.4034025f - 0.23903021f * x) * x; 5197 // 5198 // error 0.0034276066, which is better than 8 bits 5199 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5200 getF32Constant(DAG, 0xbe74c456, dl)); 5201 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5202 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5203 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5204 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5205 getF32Constant(DAG, 0x3f949a29, dl)); 5206 } else if (LimitFloatPrecision <= 12) { 5207 // For floating-point precision of 12: 5208 // 5209 // LogOfMantissa = 5210 // -1.7417939f + 5211 // (2.8212026f + 5212 // (-1.4699568f + 5213 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5214 // 5215 // error 0.000061011436, which is 14 bits 5216 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5217 getF32Constant(DAG, 0xbd67b6d6, dl)); 5218 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5219 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5220 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5221 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5222 getF32Constant(DAG, 0x3fbc278b, dl)); 5223 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5224 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5225 getF32Constant(DAG, 0x40348e95, dl)); 5226 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5227 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5228 getF32Constant(DAG, 0x3fdef31a, dl)); 5229 } else { // LimitFloatPrecision <= 18 5230 // For floating-point precision of 18: 5231 // 5232 // LogOfMantissa = 5233 // -2.1072184f + 5234 // (4.2372794f + 5235 // (-3.7029485f + 5236 // (2.2781945f + 5237 // (-0.87823314f + 5238 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5239 // 5240 // error 0.0000023660568, which is better than 18 bits 5241 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5242 getF32Constant(DAG, 0xbc91e5ac, dl)); 5243 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5244 getF32Constant(DAG, 0x3e4350aa, dl)); 5245 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5246 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5247 getF32Constant(DAG, 0x3f60d3e3, dl)); 5248 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5249 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5250 getF32Constant(DAG, 0x4011cdf0, dl)); 5251 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5252 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5253 getF32Constant(DAG, 0x406cfd1c, dl)); 5254 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5255 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5256 getF32Constant(DAG, 0x408797cb, dl)); 5257 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5258 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5259 getF32Constant(DAG, 0x4006dcab, dl)); 5260 } 5261 5262 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5263 } 5264 5265 // No special expansion. 5266 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5267 } 5268 5269 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5270 /// limited-precision mode. 5271 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5272 const TargetLowering &TLI, SDNodeFlags Flags) { 5273 // TODO: What fast-math-flags should be set on the floating-point nodes? 5274 5275 if (Op.getValueType() == MVT::f32 && 5276 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5277 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5278 5279 // Get the exponent. 5280 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5281 5282 // Get the significand and build it into a floating-point number with 5283 // exponent of 1. 5284 SDValue X = GetSignificand(DAG, Op1, dl); 5285 5286 // Different possible minimax approximations of significand in 5287 // floating-point for various degrees of accuracy over [1,2]. 5288 SDValue Log2ofMantissa; 5289 if (LimitFloatPrecision <= 6) { 5290 // For floating-point precision of 6: 5291 // 5292 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5293 // 5294 // error 0.0049451742, which is more than 7 bits 5295 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5296 getF32Constant(DAG, 0xbeb08fe0, dl)); 5297 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5298 getF32Constant(DAG, 0x40019463, dl)); 5299 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5300 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5301 getF32Constant(DAG, 0x3fd6633d, dl)); 5302 } else if (LimitFloatPrecision <= 12) { 5303 // For floating-point precision of 12: 5304 // 5305 // Log2ofMantissa = 5306 // -2.51285454f + 5307 // (4.07009056f + 5308 // (-2.12067489f + 5309 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5310 // 5311 // error 0.0000876136000, which is better than 13 bits 5312 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5313 getF32Constant(DAG, 0xbda7262e, dl)); 5314 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5315 getF32Constant(DAG, 0x3f25280b, dl)); 5316 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5317 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5318 getF32Constant(DAG, 0x4007b923, dl)); 5319 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5320 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5321 getF32Constant(DAG, 0x40823e2f, dl)); 5322 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5323 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5324 getF32Constant(DAG, 0x4020d29c, dl)); 5325 } else { // LimitFloatPrecision <= 18 5326 // For floating-point precision of 18: 5327 // 5328 // Log2ofMantissa = 5329 // -3.0400495f + 5330 // (6.1129976f + 5331 // (-5.3420409f + 5332 // (3.2865683f + 5333 // (-1.2669343f + 5334 // (0.27515199f - 5335 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5336 // 5337 // error 0.0000018516, which is better than 18 bits 5338 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5339 getF32Constant(DAG, 0xbcd2769e, dl)); 5340 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5341 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5342 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5343 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5344 getF32Constant(DAG, 0x3fa22ae7, dl)); 5345 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5346 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5347 getF32Constant(DAG, 0x40525723, dl)); 5348 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5349 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5350 getF32Constant(DAG, 0x40aaf200, dl)); 5351 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5352 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5353 getF32Constant(DAG, 0x40c39dad, dl)); 5354 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5355 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5356 getF32Constant(DAG, 0x4042902c, dl)); 5357 } 5358 5359 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5360 } 5361 5362 // No special expansion. 5363 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5364 } 5365 5366 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5367 /// limited-precision mode. 5368 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5369 const TargetLowering &TLI, SDNodeFlags Flags) { 5370 // TODO: What fast-math-flags should be set on the floating-point nodes? 5371 5372 if (Op.getValueType() == MVT::f32 && 5373 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5374 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5375 5376 // Scale the exponent by log10(2) [0.30102999f]. 5377 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5378 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5379 getF32Constant(DAG, 0x3e9a209a, dl)); 5380 5381 // Get the significand and build it into a floating-point number with 5382 // exponent of 1. 5383 SDValue X = GetSignificand(DAG, Op1, dl); 5384 5385 SDValue Log10ofMantissa; 5386 if (LimitFloatPrecision <= 6) { 5387 // For floating-point precision of 6: 5388 // 5389 // Log10ofMantissa = 5390 // -0.50419619f + 5391 // (0.60948995f - 0.10380950f * x) * x; 5392 // 5393 // error 0.0014886165, which is 6 bits 5394 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5395 getF32Constant(DAG, 0xbdd49a13, dl)); 5396 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5397 getF32Constant(DAG, 0x3f1c0789, dl)); 5398 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5399 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5400 getF32Constant(DAG, 0x3f011300, dl)); 5401 } else if (LimitFloatPrecision <= 12) { 5402 // For floating-point precision of 12: 5403 // 5404 // Log10ofMantissa = 5405 // -0.64831180f + 5406 // (0.91751397f + 5407 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5408 // 5409 // error 0.00019228036, which is better than 12 bits 5410 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5411 getF32Constant(DAG, 0x3d431f31, dl)); 5412 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5413 getF32Constant(DAG, 0x3ea21fb2, dl)); 5414 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5415 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5416 getF32Constant(DAG, 0x3f6ae232, dl)); 5417 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5418 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5419 getF32Constant(DAG, 0x3f25f7c3, dl)); 5420 } else { // LimitFloatPrecision <= 18 5421 // For floating-point precision of 18: 5422 // 5423 // Log10ofMantissa = 5424 // -0.84299375f + 5425 // (1.5327582f + 5426 // (-1.0688956f + 5427 // (0.49102474f + 5428 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5429 // 5430 // error 0.0000037995730, which is better than 18 bits 5431 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5432 getF32Constant(DAG, 0x3c5d51ce, dl)); 5433 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5434 getF32Constant(DAG, 0x3e00685a, dl)); 5435 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5436 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5437 getF32Constant(DAG, 0x3efb6798, dl)); 5438 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5439 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5440 getF32Constant(DAG, 0x3f88d192, dl)); 5441 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5442 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5443 getF32Constant(DAG, 0x3fc4316c, dl)); 5444 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5445 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5446 getF32Constant(DAG, 0x3f57ce70, dl)); 5447 } 5448 5449 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5450 } 5451 5452 // No special expansion. 5453 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5454 } 5455 5456 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5457 /// limited-precision mode. 5458 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5459 const TargetLowering &TLI, SDNodeFlags Flags) { 5460 if (Op.getValueType() == MVT::f32 && 5461 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5462 return getLimitedPrecisionExp2(Op, dl, DAG); 5463 5464 // No special expansion. 5465 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5466 } 5467 5468 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5469 /// limited-precision mode with x == 10.0f. 5470 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5471 SelectionDAG &DAG, const TargetLowering &TLI, 5472 SDNodeFlags Flags) { 5473 bool IsExp10 = false; 5474 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5475 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5476 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5477 APFloat Ten(10.0f); 5478 IsExp10 = LHSC->isExactlyValue(Ten); 5479 } 5480 } 5481 5482 // TODO: What fast-math-flags should be set on the FMUL node? 5483 if (IsExp10) { 5484 // Put the exponent in the right bit position for later addition to the 5485 // final result: 5486 // 5487 // #define LOG2OF10 3.3219281f 5488 // t0 = Op * LOG2OF10; 5489 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5490 getF32Constant(DAG, 0x40549a78, dl)); 5491 return getLimitedPrecisionExp2(t0, dl, DAG); 5492 } 5493 5494 // No special expansion. 5495 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5496 } 5497 5498 /// ExpandPowI - Expand a llvm.powi intrinsic. 5499 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5500 SelectionDAG &DAG) { 5501 // If RHS is a constant, we can expand this out to a multiplication tree if 5502 // it's beneficial on the target, otherwise we end up lowering to a call to 5503 // __powidf2 (for example). 5504 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5505 unsigned Val = RHSC->getSExtValue(); 5506 5507 // powi(x, 0) -> 1.0 5508 if (Val == 0) 5509 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5510 5511 if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI( 5512 Val, DAG.shouldOptForSize())) { 5513 // Get the exponent as a positive value. 5514 if ((int)Val < 0) 5515 Val = -Val; 5516 // We use the simple binary decomposition method to generate the multiply 5517 // sequence. There are more optimal ways to do this (for example, 5518 // powi(x,15) generates one more multiply than it should), but this has 5519 // the benefit of being both really simple and much better than a libcall. 5520 SDValue Res; // Logically starts equal to 1.0 5521 SDValue CurSquare = LHS; 5522 // TODO: Intrinsics should have fast-math-flags that propagate to these 5523 // nodes. 5524 while (Val) { 5525 if (Val & 1) { 5526 if (Res.getNode()) 5527 Res = 5528 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare); 5529 else 5530 Res = CurSquare; // 1.0*CurSquare. 5531 } 5532 5533 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5534 CurSquare, CurSquare); 5535 Val >>= 1; 5536 } 5537 5538 // If the original was negative, invert the result, producing 1/(x*x*x). 5539 if (RHSC->getSExtValue() < 0) 5540 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5541 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5542 return Res; 5543 } 5544 } 5545 5546 // Otherwise, expand to a libcall. 5547 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5548 } 5549 5550 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5551 SDValue LHS, SDValue RHS, SDValue Scale, 5552 SelectionDAG &DAG, const TargetLowering &TLI) { 5553 EVT VT = LHS.getValueType(); 5554 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5555 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5556 LLVMContext &Ctx = *DAG.getContext(); 5557 5558 // If the type is legal but the operation isn't, this node might survive all 5559 // the way to operation legalization. If we end up there and we do not have 5560 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5561 // node. 5562 5563 // Coax the legalizer into expanding the node during type legalization instead 5564 // by bumping the size by one bit. This will force it to Promote, enabling the 5565 // early expansion and avoiding the need to expand later. 5566 5567 // We don't have to do this if Scale is 0; that can always be expanded, unless 5568 // it's a saturating signed operation. Those can experience true integer 5569 // division overflow, a case which we must avoid. 5570 5571 // FIXME: We wouldn't have to do this (or any of the early 5572 // expansion/promotion) if it was possible to expand a libcall of an 5573 // illegal type during operation legalization. But it's not, so things 5574 // get a bit hacky. 5575 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5576 if ((ScaleInt > 0 || (Saturating && Signed)) && 5577 (TLI.isTypeLegal(VT) || 5578 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5579 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5580 Opcode, VT, ScaleInt); 5581 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5582 EVT PromVT; 5583 if (VT.isScalarInteger()) 5584 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5585 else if (VT.isVector()) { 5586 PromVT = VT.getVectorElementType(); 5587 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5588 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5589 } else 5590 llvm_unreachable("Wrong VT for DIVFIX?"); 5591 LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT); 5592 RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT); 5593 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5594 // For saturating operations, we need to shift up the LHS to get the 5595 // proper saturation width, and then shift down again afterwards. 5596 if (Saturating) 5597 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5598 DAG.getConstant(1, DL, ShiftTy)); 5599 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5600 if (Saturating) 5601 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5602 DAG.getConstant(1, DL, ShiftTy)); 5603 return DAG.getZExtOrTrunc(Res, DL, VT); 5604 } 5605 } 5606 5607 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5608 } 5609 5610 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5611 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5612 static void 5613 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5614 const SDValue &N) { 5615 switch (N.getOpcode()) { 5616 case ISD::CopyFromReg: { 5617 SDValue Op = N.getOperand(1); 5618 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5619 Op.getValueType().getSizeInBits()); 5620 return; 5621 } 5622 case ISD::BITCAST: 5623 case ISD::AssertZext: 5624 case ISD::AssertSext: 5625 case ISD::TRUNCATE: 5626 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5627 return; 5628 case ISD::BUILD_PAIR: 5629 case ISD::BUILD_VECTOR: 5630 case ISD::CONCAT_VECTORS: 5631 for (SDValue Op : N->op_values()) 5632 getUnderlyingArgRegs(Regs, Op); 5633 return; 5634 default: 5635 return; 5636 } 5637 } 5638 5639 /// If the DbgValueInst is a dbg_value of a function argument, create the 5640 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5641 /// instruction selection, they will be inserted to the entry BB. 5642 /// We don't currently support this for variadic dbg_values, as they shouldn't 5643 /// appear for function arguments or in the prologue. 5644 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5645 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5646 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) { 5647 const Argument *Arg = dyn_cast<Argument>(V); 5648 if (!Arg) 5649 return false; 5650 5651 MachineFunction &MF = DAG.getMachineFunction(); 5652 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5653 5654 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind 5655 // we've been asked to pursue. 5656 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr, 5657 bool Indirect) { 5658 if (Reg.isVirtual() && MF.useDebugInstrRef()) { 5659 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF 5660 // pointing at the VReg, which will be patched up later. 5661 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF); 5662 SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg( 5663 /* Reg */ Reg, /* isDef */ false, /* isImp */ false, 5664 /* isKill */ false, /* isDead */ false, 5665 /* isUndef */ false, /* isEarlyClobber */ false, 5666 /* SubReg */ 0, /* isDebug */ true)}); 5667 5668 auto *NewDIExpr = FragExpr; 5669 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into 5670 // the DIExpression. 5671 if (Indirect) 5672 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore); 5673 SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0}); 5674 NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops); 5675 return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr); 5676 } else { 5677 // Create a completely standard DBG_VALUE. 5678 auto &Inst = TII->get(TargetOpcode::DBG_VALUE); 5679 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr); 5680 } 5681 }; 5682 5683 if (Kind == FuncArgumentDbgValueKind::Value) { 5684 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5685 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5686 // the entry block. 5687 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5688 if (!IsInEntryBlock) 5689 return false; 5690 5691 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5692 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5693 // variable that also is a param. 5694 // 5695 // Although, if we are at the top of the entry block already, we can still 5696 // emit using ArgDbgValue. This might catch some situations when the 5697 // dbg.value refers to an argument that isn't used in the entry block, so 5698 // any CopyToReg node would be optimized out and the only way to express 5699 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5700 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5701 // we should only emit as ArgDbgValue if the Variable is an argument to the 5702 // current function, and the dbg.value intrinsic is found in the entry 5703 // block. 5704 bool VariableIsFunctionInputArg = Variable->isParameter() && 5705 !DL->getInlinedAt(); 5706 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5707 if (!IsInPrologue && !VariableIsFunctionInputArg) 5708 return false; 5709 5710 // Here we assume that a function argument on IR level only can be used to 5711 // describe one input parameter on source level. If we for example have 5712 // source code like this 5713 // 5714 // struct A { long x, y; }; 5715 // void foo(struct A a, long b) { 5716 // ... 5717 // b = a.x; 5718 // ... 5719 // } 5720 // 5721 // and IR like this 5722 // 5723 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5724 // entry: 5725 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5726 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5727 // call void @llvm.dbg.value(metadata i32 %b, "b", 5728 // ... 5729 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5730 // ... 5731 // 5732 // then the last dbg.value is describing a parameter "b" using a value that 5733 // is an argument. But since we already has used %a1 to describe a parameter 5734 // we should not handle that last dbg.value here (that would result in an 5735 // incorrect hoisting of the DBG_VALUE to the function entry). 5736 // Notice that we allow one dbg.value per IR level argument, to accommodate 5737 // for the situation with fragments above. 5738 if (VariableIsFunctionInputArg) { 5739 unsigned ArgNo = Arg->getArgNo(); 5740 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5741 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5742 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5743 return false; 5744 FuncInfo.DescribedArgs.set(ArgNo); 5745 } 5746 } 5747 5748 bool IsIndirect = false; 5749 std::optional<MachineOperand> Op; 5750 // Some arguments' frame index is recorded during argument lowering. 5751 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5752 if (FI != std::numeric_limits<int>::max()) 5753 Op = MachineOperand::CreateFI(FI); 5754 5755 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 5756 if (!Op && N.getNode()) { 5757 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5758 Register Reg; 5759 if (ArgRegsAndSizes.size() == 1) 5760 Reg = ArgRegsAndSizes.front().first; 5761 5762 if (Reg && Reg.isVirtual()) { 5763 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5764 Register PR = RegInfo.getLiveInPhysReg(Reg); 5765 if (PR) 5766 Reg = PR; 5767 } 5768 if (Reg) { 5769 Op = MachineOperand::CreateReg(Reg, false); 5770 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5771 } 5772 } 5773 5774 if (!Op && N.getNode()) { 5775 // Check if frame index is available. 5776 SDValue LCandidate = peekThroughBitcasts(N); 5777 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5778 if (FrameIndexSDNode *FINode = 5779 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5780 Op = MachineOperand::CreateFI(FINode->getIndex()); 5781 } 5782 5783 if (!Op) { 5784 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5785 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 5786 SplitRegs) { 5787 unsigned Offset = 0; 5788 for (const auto &RegAndSize : SplitRegs) { 5789 // If the expression is already a fragment, the current register 5790 // offset+size might extend beyond the fragment. In this case, only 5791 // the register bits that are inside the fragment are relevant. 5792 int RegFragmentSizeInBits = RegAndSize.second; 5793 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5794 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5795 // The register is entirely outside the expression fragment, 5796 // so is irrelevant for debug info. 5797 if (Offset >= ExprFragmentSizeInBits) 5798 break; 5799 // The register is partially outside the expression fragment, only 5800 // the low bits within the fragment are relevant for debug info. 5801 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5802 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5803 } 5804 } 5805 5806 auto FragmentExpr = DIExpression::createFragmentExpression( 5807 Expr, Offset, RegFragmentSizeInBits); 5808 Offset += RegAndSize.second; 5809 // If a valid fragment expression cannot be created, the variable's 5810 // correct value cannot be determined and so it is set as Undef. 5811 if (!FragmentExpr) { 5812 SDDbgValue *SDV = DAG.getConstantDbgValue( 5813 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5814 DAG.AddDbgValue(SDV, false); 5815 continue; 5816 } 5817 MachineInstr *NewMI = 5818 MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, 5819 Kind != FuncArgumentDbgValueKind::Value); 5820 FuncInfo.ArgDbgValues.push_back(NewMI); 5821 } 5822 }; 5823 5824 // Check if ValueMap has reg number. 5825 DenseMap<const Value *, Register>::const_iterator 5826 VMI = FuncInfo.ValueMap.find(V); 5827 if (VMI != FuncInfo.ValueMap.end()) { 5828 const auto &TLI = DAG.getTargetLoweringInfo(); 5829 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5830 V->getType(), std::nullopt); 5831 if (RFV.occupiesMultipleRegs()) { 5832 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5833 return true; 5834 } 5835 5836 Op = MachineOperand::CreateReg(VMI->second, false); 5837 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5838 } else if (ArgRegsAndSizes.size() > 1) { 5839 // This was split due to the calling convention, and no virtual register 5840 // mapping exists for the value. 5841 splitMultiRegDbgValue(ArgRegsAndSizes); 5842 return true; 5843 } 5844 } 5845 5846 if (!Op) 5847 return false; 5848 5849 assert(Variable->isValidLocationForIntrinsic(DL) && 5850 "Expected inlined-at fields to agree"); 5851 MachineInstr *NewMI = nullptr; 5852 5853 if (Op->isReg()) 5854 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect); 5855 else 5856 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op, 5857 Variable, Expr); 5858 5859 // Otherwise, use ArgDbgValues. 5860 FuncInfo.ArgDbgValues.push_back(NewMI); 5861 return true; 5862 } 5863 5864 /// Return the appropriate SDDbgValue based on N. 5865 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5866 DILocalVariable *Variable, 5867 DIExpression *Expr, 5868 const DebugLoc &dl, 5869 unsigned DbgSDNodeOrder) { 5870 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5871 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5872 // stack slot locations. 5873 // 5874 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5875 // debug values here after optimization: 5876 // 5877 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5878 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5879 // 5880 // Both describe the direct values of their associated variables. 5881 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5882 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5883 } 5884 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5885 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5886 } 5887 5888 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5889 switch (Intrinsic) { 5890 case Intrinsic::smul_fix: 5891 return ISD::SMULFIX; 5892 case Intrinsic::umul_fix: 5893 return ISD::UMULFIX; 5894 case Intrinsic::smul_fix_sat: 5895 return ISD::SMULFIXSAT; 5896 case Intrinsic::umul_fix_sat: 5897 return ISD::UMULFIXSAT; 5898 case Intrinsic::sdiv_fix: 5899 return ISD::SDIVFIX; 5900 case Intrinsic::udiv_fix: 5901 return ISD::UDIVFIX; 5902 case Intrinsic::sdiv_fix_sat: 5903 return ISD::SDIVFIXSAT; 5904 case Intrinsic::udiv_fix_sat: 5905 return ISD::UDIVFIXSAT; 5906 default: 5907 llvm_unreachable("Unhandled fixed point intrinsic"); 5908 } 5909 } 5910 5911 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5912 const char *FunctionName) { 5913 assert(FunctionName && "FunctionName must not be nullptr"); 5914 SDValue Callee = DAG.getExternalSymbol( 5915 FunctionName, 5916 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5917 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 5918 } 5919 5920 /// Given a @llvm.call.preallocated.setup, return the corresponding 5921 /// preallocated call. 5922 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5923 assert(cast<CallBase>(PreallocatedSetup) 5924 ->getCalledFunction() 5925 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5926 "expected call_preallocated_setup Value"); 5927 for (const auto *U : PreallocatedSetup->users()) { 5928 auto *UseCall = cast<CallBase>(U); 5929 const Function *Fn = UseCall->getCalledFunction(); 5930 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5931 return UseCall; 5932 } 5933 } 5934 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5935 } 5936 5937 /// If DI is a debug value with an EntryValue expression, lower it using the 5938 /// corresponding physical register of the associated Argument value 5939 /// (guaranteed to exist by the verifier). 5940 bool SelectionDAGBuilder::visitEntryValueDbgValue(const DbgValueInst &DI) { 5941 DILocalVariable *Variable = DI.getVariable(); 5942 DIExpression *Expr = DI.getExpression(); 5943 if (!Expr->isEntryValue() || !hasSingleElement(DI.getValues())) 5944 return false; 5945 5946 // These properties are guaranteed by the verifier. 5947 Argument *Arg = cast<Argument>(DI.getValue(0)); 5948 assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync)); 5949 5950 auto ArgIt = FuncInfo.ValueMap.find(Arg); 5951 if (ArgIt == FuncInfo.ValueMap.end()) { 5952 LLVM_DEBUG( 5953 dbgs() << "Dropping dbg.value: expression is entry_value but " 5954 "couldn't find an associated register for the Argument\n"); 5955 return true; 5956 } 5957 Register ArgVReg = ArgIt->getSecond(); 5958 5959 for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins()) 5960 if (ArgVReg == VirtReg || ArgVReg == PhysReg) { 5961 SDDbgValue *SDV = 5962 DAG.getVRegDbgValue(Variable, Expr, PhysReg, false /*IsIndidrect*/, 5963 DI.getDebugLoc(), SDNodeOrder); 5964 DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/); 5965 return true; 5966 } 5967 LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but " 5968 "couldn't find a physical register\n"); 5969 return true; 5970 } 5971 5972 /// Lower the call to the specified intrinsic function. 5973 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5974 unsigned Intrinsic) { 5975 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5976 SDLoc sdl = getCurSDLoc(); 5977 DebugLoc dl = getCurDebugLoc(); 5978 SDValue Res; 5979 5980 SDNodeFlags Flags; 5981 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 5982 Flags.copyFMF(*FPOp); 5983 5984 switch (Intrinsic) { 5985 default: 5986 // By default, turn this into a target intrinsic node. 5987 visitTargetIntrinsic(I, Intrinsic); 5988 return; 5989 case Intrinsic::vscale: { 5990 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5991 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1))); 5992 return; 5993 } 5994 case Intrinsic::vastart: visitVAStart(I); return; 5995 case Intrinsic::vaend: visitVAEnd(I); return; 5996 case Intrinsic::vacopy: visitVACopy(I); return; 5997 case Intrinsic::returnaddress: 5998 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5999 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6000 getValue(I.getArgOperand(0)))); 6001 return; 6002 case Intrinsic::addressofreturnaddress: 6003 setValue(&I, 6004 DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 6005 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 6006 return; 6007 case Intrinsic::sponentry: 6008 setValue(&I, 6009 DAG.getNode(ISD::SPONENTRY, sdl, 6010 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 6011 return; 6012 case Intrinsic::frameaddress: 6013 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 6014 TLI.getFrameIndexTy(DAG.getDataLayout()), 6015 getValue(I.getArgOperand(0)))); 6016 return; 6017 case Intrinsic::read_volatile_register: 6018 case Intrinsic::read_register: { 6019 Value *Reg = I.getArgOperand(0); 6020 SDValue Chain = getRoot(); 6021 SDValue RegName = 6022 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 6023 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6024 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 6025 DAG.getVTList(VT, MVT::Other), Chain, RegName); 6026 setValue(&I, Res); 6027 DAG.setRoot(Res.getValue(1)); 6028 return; 6029 } 6030 case Intrinsic::write_register: { 6031 Value *Reg = I.getArgOperand(0); 6032 Value *RegValue = I.getArgOperand(1); 6033 SDValue Chain = getRoot(); 6034 SDValue RegName = 6035 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 6036 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 6037 RegName, getValue(RegValue))); 6038 return; 6039 } 6040 case Intrinsic::memcpy: { 6041 const auto &MCI = cast<MemCpyInst>(I); 6042 SDValue Op1 = getValue(I.getArgOperand(0)); 6043 SDValue Op2 = getValue(I.getArgOperand(1)); 6044 SDValue Op3 = getValue(I.getArgOperand(2)); 6045 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 6046 Align DstAlign = MCI.getDestAlign().valueOrOne(); 6047 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 6048 Align Alignment = std::min(DstAlign, SrcAlign); 6049 bool isVol = MCI.isVolatile(); 6050 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6051 // FIXME: Support passing different dest/src alignments to the memcpy DAG 6052 // node. 6053 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6054 SDValue MC = DAG.getMemcpy( 6055 Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6056 /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)), 6057 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 6058 updateDAGForMaybeTailCall(MC); 6059 return; 6060 } 6061 case Intrinsic::memcpy_inline: { 6062 const auto &MCI = cast<MemCpyInlineInst>(I); 6063 SDValue Dst = getValue(I.getArgOperand(0)); 6064 SDValue Src = getValue(I.getArgOperand(1)); 6065 SDValue Size = getValue(I.getArgOperand(2)); 6066 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 6067 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 6068 Align DstAlign = MCI.getDestAlign().valueOrOne(); 6069 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 6070 Align Alignment = std::min(DstAlign, SrcAlign); 6071 bool isVol = MCI.isVolatile(); 6072 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6073 // FIXME: Support passing different dest/src alignments to the memcpy DAG 6074 // node. 6075 SDValue MC = DAG.getMemcpy( 6076 getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 6077 /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)), 6078 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 6079 updateDAGForMaybeTailCall(MC); 6080 return; 6081 } 6082 case Intrinsic::memset: { 6083 const auto &MSI = cast<MemSetInst>(I); 6084 SDValue Op1 = getValue(I.getArgOperand(0)); 6085 SDValue Op2 = getValue(I.getArgOperand(1)); 6086 SDValue Op3 = getValue(I.getArgOperand(2)); 6087 // @llvm.memset defines 0 and 1 to both mean no alignment. 6088 Align Alignment = MSI.getDestAlign().valueOrOne(); 6089 bool isVol = MSI.isVolatile(); 6090 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6091 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6092 SDValue MS = DAG.getMemset( 6093 Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false, 6094 isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata()); 6095 updateDAGForMaybeTailCall(MS); 6096 return; 6097 } 6098 case Intrinsic::memset_inline: { 6099 const auto &MSII = cast<MemSetInlineInst>(I); 6100 SDValue Dst = getValue(I.getArgOperand(0)); 6101 SDValue Value = getValue(I.getArgOperand(1)); 6102 SDValue Size = getValue(I.getArgOperand(2)); 6103 assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size"); 6104 // @llvm.memset defines 0 and 1 to both mean no alignment. 6105 Align DstAlign = MSII.getDestAlign().valueOrOne(); 6106 bool isVol = MSII.isVolatile(); 6107 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6108 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6109 SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol, 6110 /* AlwaysInline */ true, isTC, 6111 MachinePointerInfo(I.getArgOperand(0)), 6112 I.getAAMetadata()); 6113 updateDAGForMaybeTailCall(MC); 6114 return; 6115 } 6116 case Intrinsic::memmove: { 6117 const auto &MMI = cast<MemMoveInst>(I); 6118 SDValue Op1 = getValue(I.getArgOperand(0)); 6119 SDValue Op2 = getValue(I.getArgOperand(1)); 6120 SDValue Op3 = getValue(I.getArgOperand(2)); 6121 // @llvm.memmove defines 0 and 1 to both mean no alignment. 6122 Align DstAlign = MMI.getDestAlign().valueOrOne(); 6123 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 6124 Align Alignment = std::min(DstAlign, SrcAlign); 6125 bool isVol = MMI.isVolatile(); 6126 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6127 // FIXME: Support passing different dest/src alignments to the memmove DAG 6128 // node. 6129 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6130 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6131 isTC, MachinePointerInfo(I.getArgOperand(0)), 6132 MachinePointerInfo(I.getArgOperand(1)), 6133 I.getAAMetadata(), AA); 6134 updateDAGForMaybeTailCall(MM); 6135 return; 6136 } 6137 case Intrinsic::memcpy_element_unordered_atomic: { 6138 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 6139 SDValue Dst = getValue(MI.getRawDest()); 6140 SDValue Src = getValue(MI.getRawSource()); 6141 SDValue Length = getValue(MI.getLength()); 6142 6143 Type *LengthTy = MI.getLength()->getType(); 6144 unsigned ElemSz = MI.getElementSizeInBytes(); 6145 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6146 SDValue MC = 6147 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6148 isTC, MachinePointerInfo(MI.getRawDest()), 6149 MachinePointerInfo(MI.getRawSource())); 6150 updateDAGForMaybeTailCall(MC); 6151 return; 6152 } 6153 case Intrinsic::memmove_element_unordered_atomic: { 6154 auto &MI = cast<AtomicMemMoveInst>(I); 6155 SDValue Dst = getValue(MI.getRawDest()); 6156 SDValue Src = getValue(MI.getRawSource()); 6157 SDValue Length = getValue(MI.getLength()); 6158 6159 Type *LengthTy = MI.getLength()->getType(); 6160 unsigned ElemSz = MI.getElementSizeInBytes(); 6161 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6162 SDValue MC = 6163 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6164 isTC, MachinePointerInfo(MI.getRawDest()), 6165 MachinePointerInfo(MI.getRawSource())); 6166 updateDAGForMaybeTailCall(MC); 6167 return; 6168 } 6169 case Intrinsic::memset_element_unordered_atomic: { 6170 auto &MI = cast<AtomicMemSetInst>(I); 6171 SDValue Dst = getValue(MI.getRawDest()); 6172 SDValue Val = getValue(MI.getValue()); 6173 SDValue Length = getValue(MI.getLength()); 6174 6175 Type *LengthTy = MI.getLength()->getType(); 6176 unsigned ElemSz = MI.getElementSizeInBytes(); 6177 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6178 SDValue MC = 6179 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz, 6180 isTC, MachinePointerInfo(MI.getRawDest())); 6181 updateDAGForMaybeTailCall(MC); 6182 return; 6183 } 6184 case Intrinsic::call_preallocated_setup: { 6185 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 6186 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6187 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 6188 getRoot(), SrcValue); 6189 setValue(&I, Res); 6190 DAG.setRoot(Res); 6191 return; 6192 } 6193 case Intrinsic::call_preallocated_arg: { 6194 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 6195 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6196 SDValue Ops[3]; 6197 Ops[0] = getRoot(); 6198 Ops[1] = SrcValue; 6199 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 6200 MVT::i32); // arg index 6201 SDValue Res = DAG.getNode( 6202 ISD::PREALLOCATED_ARG, sdl, 6203 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 6204 setValue(&I, Res); 6205 DAG.setRoot(Res.getValue(1)); 6206 return; 6207 } 6208 case Intrinsic::dbg_declare: { 6209 const auto &DI = cast<DbgDeclareInst>(I); 6210 // Debug intrinsics are handled separately in assignment tracking mode. 6211 // Some intrinsics are handled right after Argument lowering. 6212 if (AssignmentTrackingEnabled || 6213 FuncInfo.PreprocessedDbgDeclares.count(&DI)) 6214 return; 6215 // Assume dbg.declare can not currently use DIArgList, i.e. 6216 // it is non-variadic. 6217 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 6218 DILocalVariable *Variable = DI.getVariable(); 6219 DIExpression *Expression = DI.getExpression(); 6220 dropDanglingDebugInfo(Variable, Expression); 6221 assert(Variable && "Missing variable"); 6222 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 6223 << "\n"); 6224 // Check if address has undef value. 6225 const Value *Address = DI.getVariableLocationOp(0); 6226 if (!Address || isa<UndefValue>(Address) || 6227 (Address->use_empty() && !isa<Argument>(Address))) { 6228 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6229 << " (bad/undef/unused-arg address)\n"); 6230 return; 6231 } 6232 6233 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 6234 6235 SDValue &N = NodeMap[Address]; 6236 if (!N.getNode() && isa<Argument>(Address)) 6237 // Check unused arguments map. 6238 N = UnusedArgNodeMap[Address]; 6239 SDDbgValue *SDV; 6240 if (N.getNode()) { 6241 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 6242 Address = BCI->getOperand(0); 6243 // Parameters are handled specially. 6244 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 6245 if (isParameter && FINode) { 6246 // Byval parameter. We have a frame index at this point. 6247 SDV = 6248 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 6249 /*IsIndirect*/ true, dl, SDNodeOrder); 6250 } else if (isa<Argument>(Address)) { 6251 // Address is an argument, so try to emit its dbg value using 6252 // virtual register info from the FuncInfo.ValueMap. 6253 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 6254 FuncArgumentDbgValueKind::Declare, N); 6255 return; 6256 } else { 6257 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 6258 true, dl, SDNodeOrder); 6259 } 6260 DAG.AddDbgValue(SDV, isParameter); 6261 } else { 6262 // If Address is an argument then try to emit its dbg value using 6263 // virtual register info from the FuncInfo.ValueMap. 6264 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 6265 FuncArgumentDbgValueKind::Declare, N)) { 6266 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6267 << " (could not emit func-arg dbg_value)\n"); 6268 } 6269 } 6270 return; 6271 } 6272 case Intrinsic::dbg_label: { 6273 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6274 DILabel *Label = DI.getLabel(); 6275 assert(Label && "Missing label"); 6276 6277 SDDbgLabel *SDV; 6278 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6279 DAG.AddDbgLabel(SDV); 6280 return; 6281 } 6282 case Intrinsic::dbg_assign: { 6283 // Debug intrinsics are handled seperately in assignment tracking mode. 6284 if (AssignmentTrackingEnabled) 6285 return; 6286 // If assignment tracking hasn't been enabled then fall through and treat 6287 // the dbg.assign as a dbg.value. 6288 [[fallthrough]]; 6289 } 6290 case Intrinsic::dbg_value: { 6291 // Debug intrinsics are handled seperately in assignment tracking mode. 6292 if (AssignmentTrackingEnabled) 6293 return; 6294 const DbgValueInst &DI = cast<DbgValueInst>(I); 6295 assert(DI.getVariable() && "Missing variable"); 6296 6297 DILocalVariable *Variable = DI.getVariable(); 6298 DIExpression *Expression = DI.getExpression(); 6299 dropDanglingDebugInfo(Variable, Expression); 6300 6301 if (visitEntryValueDbgValue(DI)) 6302 return; 6303 6304 if (DI.isKillLocation()) { 6305 handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder); 6306 return; 6307 } 6308 6309 SmallVector<Value *, 4> Values(DI.getValues()); 6310 if (Values.empty()) 6311 return; 6312 6313 bool IsVariadic = DI.hasArgList(); 6314 if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(), 6315 SDNodeOrder, IsVariadic)) 6316 addDanglingDebugInfo(&DI, SDNodeOrder); 6317 return; 6318 } 6319 6320 case Intrinsic::eh_typeid_for: { 6321 // Find the type id for the given typeinfo. 6322 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6323 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6324 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6325 setValue(&I, Res); 6326 return; 6327 } 6328 6329 case Intrinsic::eh_return_i32: 6330 case Intrinsic::eh_return_i64: 6331 DAG.getMachineFunction().setCallsEHReturn(true); 6332 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6333 MVT::Other, 6334 getControlRoot(), 6335 getValue(I.getArgOperand(0)), 6336 getValue(I.getArgOperand(1)))); 6337 return; 6338 case Intrinsic::eh_unwind_init: 6339 DAG.getMachineFunction().setCallsUnwindInit(true); 6340 return; 6341 case Intrinsic::eh_dwarf_cfa: 6342 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6343 TLI.getPointerTy(DAG.getDataLayout()), 6344 getValue(I.getArgOperand(0)))); 6345 return; 6346 case Intrinsic::eh_sjlj_callsite: { 6347 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6348 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0)); 6349 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6350 6351 MMI.setCurrentCallSite(CI->getZExtValue()); 6352 return; 6353 } 6354 case Intrinsic::eh_sjlj_functioncontext: { 6355 // Get and store the index of the function context. 6356 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6357 AllocaInst *FnCtx = 6358 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6359 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6360 MFI.setFunctionContextIndex(FI); 6361 return; 6362 } 6363 case Intrinsic::eh_sjlj_setjmp: { 6364 SDValue Ops[2]; 6365 Ops[0] = getRoot(); 6366 Ops[1] = getValue(I.getArgOperand(0)); 6367 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6368 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6369 setValue(&I, Op.getValue(0)); 6370 DAG.setRoot(Op.getValue(1)); 6371 return; 6372 } 6373 case Intrinsic::eh_sjlj_longjmp: 6374 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6375 getRoot(), getValue(I.getArgOperand(0)))); 6376 return; 6377 case Intrinsic::eh_sjlj_setup_dispatch: 6378 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6379 getRoot())); 6380 return; 6381 case Intrinsic::masked_gather: 6382 visitMaskedGather(I); 6383 return; 6384 case Intrinsic::masked_load: 6385 visitMaskedLoad(I); 6386 return; 6387 case Intrinsic::masked_scatter: 6388 visitMaskedScatter(I); 6389 return; 6390 case Intrinsic::masked_store: 6391 visitMaskedStore(I); 6392 return; 6393 case Intrinsic::masked_expandload: 6394 visitMaskedLoad(I, true /* IsExpanding */); 6395 return; 6396 case Intrinsic::masked_compressstore: 6397 visitMaskedStore(I, true /* IsCompressing */); 6398 return; 6399 case Intrinsic::powi: 6400 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6401 getValue(I.getArgOperand(1)), DAG)); 6402 return; 6403 case Intrinsic::log: 6404 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6405 return; 6406 case Intrinsic::log2: 6407 setValue(&I, 6408 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6409 return; 6410 case Intrinsic::log10: 6411 setValue(&I, 6412 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6413 return; 6414 case Intrinsic::exp: 6415 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6416 return; 6417 case Intrinsic::exp2: 6418 setValue(&I, 6419 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6420 return; 6421 case Intrinsic::pow: 6422 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6423 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6424 return; 6425 case Intrinsic::sqrt: 6426 case Intrinsic::fabs: 6427 case Intrinsic::sin: 6428 case Intrinsic::cos: 6429 case Intrinsic::exp10: 6430 case Intrinsic::floor: 6431 case Intrinsic::ceil: 6432 case Intrinsic::trunc: 6433 case Intrinsic::rint: 6434 case Intrinsic::nearbyint: 6435 case Intrinsic::round: 6436 case Intrinsic::roundeven: 6437 case Intrinsic::canonicalize: { 6438 unsigned Opcode; 6439 switch (Intrinsic) { 6440 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6441 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6442 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6443 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6444 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6445 case Intrinsic::exp10: Opcode = ISD::FEXP10; break; 6446 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6447 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6448 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6449 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6450 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6451 case Intrinsic::round: Opcode = ISD::FROUND; break; 6452 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6453 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6454 } 6455 6456 setValue(&I, DAG.getNode(Opcode, sdl, 6457 getValue(I.getArgOperand(0)).getValueType(), 6458 getValue(I.getArgOperand(0)), Flags)); 6459 return; 6460 } 6461 case Intrinsic::lround: 6462 case Intrinsic::llround: 6463 case Intrinsic::lrint: 6464 case Intrinsic::llrint: { 6465 unsigned Opcode; 6466 switch (Intrinsic) { 6467 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6468 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6469 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6470 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6471 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6472 } 6473 6474 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6475 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6476 getValue(I.getArgOperand(0)))); 6477 return; 6478 } 6479 case Intrinsic::minnum: 6480 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6481 getValue(I.getArgOperand(0)).getValueType(), 6482 getValue(I.getArgOperand(0)), 6483 getValue(I.getArgOperand(1)), Flags)); 6484 return; 6485 case Intrinsic::maxnum: 6486 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6487 getValue(I.getArgOperand(0)).getValueType(), 6488 getValue(I.getArgOperand(0)), 6489 getValue(I.getArgOperand(1)), Flags)); 6490 return; 6491 case Intrinsic::minimum: 6492 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6493 getValue(I.getArgOperand(0)).getValueType(), 6494 getValue(I.getArgOperand(0)), 6495 getValue(I.getArgOperand(1)), Flags)); 6496 return; 6497 case Intrinsic::maximum: 6498 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6499 getValue(I.getArgOperand(0)).getValueType(), 6500 getValue(I.getArgOperand(0)), 6501 getValue(I.getArgOperand(1)), Flags)); 6502 return; 6503 case Intrinsic::copysign: 6504 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6505 getValue(I.getArgOperand(0)).getValueType(), 6506 getValue(I.getArgOperand(0)), 6507 getValue(I.getArgOperand(1)), Flags)); 6508 return; 6509 case Intrinsic::ldexp: 6510 setValue(&I, DAG.getNode(ISD::FLDEXP, sdl, 6511 getValue(I.getArgOperand(0)).getValueType(), 6512 getValue(I.getArgOperand(0)), 6513 getValue(I.getArgOperand(1)), Flags)); 6514 return; 6515 case Intrinsic::frexp: { 6516 SmallVector<EVT, 2> ValueVTs; 6517 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 6518 SDVTList VTs = DAG.getVTList(ValueVTs); 6519 setValue(&I, 6520 DAG.getNode(ISD::FFREXP, sdl, VTs, getValue(I.getArgOperand(0)))); 6521 return; 6522 } 6523 case Intrinsic::arithmetic_fence: { 6524 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl, 6525 getValue(I.getArgOperand(0)).getValueType(), 6526 getValue(I.getArgOperand(0)), Flags)); 6527 return; 6528 } 6529 case Intrinsic::fma: 6530 setValue(&I, DAG.getNode( 6531 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6532 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6533 getValue(I.getArgOperand(2)), Flags)); 6534 return; 6535 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6536 case Intrinsic::INTRINSIC: 6537 #include "llvm/IR/ConstrainedOps.def" 6538 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6539 return; 6540 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6541 #include "llvm/IR/VPIntrinsics.def" 6542 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6543 return; 6544 case Intrinsic::fptrunc_round: { 6545 // Get the last argument, the metadata and convert it to an integer in the 6546 // call 6547 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata(); 6548 std::optional<RoundingMode> RoundMode = 6549 convertStrToRoundingMode(cast<MDString>(MD)->getString()); 6550 6551 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6552 6553 // Propagate fast-math-flags from IR to node(s). 6554 SDNodeFlags Flags; 6555 Flags.copyFMF(*cast<FPMathOperator>(&I)); 6556 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 6557 6558 SDValue Result; 6559 Result = DAG.getNode( 6560 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)), 6561 DAG.getTargetConstant((int)*RoundMode, sdl, 6562 TLI.getPointerTy(DAG.getDataLayout()))); 6563 setValue(&I, Result); 6564 6565 return; 6566 } 6567 case Intrinsic::fmuladd: { 6568 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6569 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6570 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6571 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6572 getValue(I.getArgOperand(0)).getValueType(), 6573 getValue(I.getArgOperand(0)), 6574 getValue(I.getArgOperand(1)), 6575 getValue(I.getArgOperand(2)), Flags)); 6576 } else { 6577 // TODO: Intrinsic calls should have fast-math-flags. 6578 SDValue Mul = DAG.getNode( 6579 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6580 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6581 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6582 getValue(I.getArgOperand(0)).getValueType(), 6583 Mul, getValue(I.getArgOperand(2)), Flags); 6584 setValue(&I, Add); 6585 } 6586 return; 6587 } 6588 case Intrinsic::convert_to_fp16: 6589 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6590 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6591 getValue(I.getArgOperand(0)), 6592 DAG.getTargetConstant(0, sdl, 6593 MVT::i32)))); 6594 return; 6595 case Intrinsic::convert_from_fp16: 6596 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6597 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6598 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6599 getValue(I.getArgOperand(0))))); 6600 return; 6601 case Intrinsic::fptosi_sat: { 6602 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6603 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 6604 getValue(I.getArgOperand(0)), 6605 DAG.getValueType(VT.getScalarType()))); 6606 return; 6607 } 6608 case Intrinsic::fptoui_sat: { 6609 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6610 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 6611 getValue(I.getArgOperand(0)), 6612 DAG.getValueType(VT.getScalarType()))); 6613 return; 6614 } 6615 case Intrinsic::set_rounding: 6616 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6617 {getRoot(), getValue(I.getArgOperand(0))}); 6618 setValue(&I, Res); 6619 DAG.setRoot(Res.getValue(0)); 6620 return; 6621 case Intrinsic::is_fpclass: { 6622 const DataLayout DLayout = DAG.getDataLayout(); 6623 EVT DestVT = TLI.getValueType(DLayout, I.getType()); 6624 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType()); 6625 FPClassTest Test = static_cast<FPClassTest>( 6626 cast<ConstantInt>(I.getArgOperand(1))->getZExtValue()); 6627 MachineFunction &MF = DAG.getMachineFunction(); 6628 const Function &F = MF.getFunction(); 6629 SDValue Op = getValue(I.getArgOperand(0)); 6630 SDNodeFlags Flags; 6631 Flags.setNoFPExcept( 6632 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP)); 6633 // If ISD::IS_FPCLASS should be expanded, do it right now, because the 6634 // expansion can use illegal types. Making expansion early allows 6635 // legalizing these types prior to selection. 6636 if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) { 6637 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG); 6638 setValue(&I, Result); 6639 return; 6640 } 6641 6642 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32); 6643 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags); 6644 setValue(&I, V); 6645 return; 6646 } 6647 case Intrinsic::get_fpenv: { 6648 const DataLayout DLayout = DAG.getDataLayout(); 6649 EVT EnvVT = TLI.getValueType(DLayout, I.getType()); 6650 Align TempAlign = DAG.getEVTAlign(EnvVT); 6651 SDValue Chain = getRoot(); 6652 // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node 6653 // and temporary storage in stack. 6654 if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) { 6655 Res = DAG.getNode( 6656 ISD::GET_FPENV, sdl, 6657 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()), 6658 MVT::Other), 6659 Chain); 6660 } else { 6661 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value()); 6662 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex(); 6663 auto MPI = 6664 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI); 6665 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 6666 MPI, MachineMemOperand::MOStore, MemoryLocation::UnknownSize, 6667 TempAlign); 6668 Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO); 6669 Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI); 6670 } 6671 setValue(&I, Res); 6672 DAG.setRoot(Res.getValue(1)); 6673 return; 6674 } 6675 case Intrinsic::set_fpenv: { 6676 const DataLayout DLayout = DAG.getDataLayout(); 6677 SDValue Env = getValue(I.getArgOperand(0)); 6678 EVT EnvVT = Env.getValueType(); 6679 Align TempAlign = DAG.getEVTAlign(EnvVT); 6680 SDValue Chain = getRoot(); 6681 // If SET_FPENV is custom or legal, use it. Otherwise use loading 6682 // environment from memory. 6683 if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) { 6684 Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env); 6685 } else { 6686 // Allocate space in stack, copy environment bits into it and use this 6687 // memory in SET_FPENV_MEM. 6688 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value()); 6689 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex(); 6690 auto MPI = 6691 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI); 6692 Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign, 6693 MachineMemOperand::MOStore); 6694 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 6695 MPI, MachineMemOperand::MOLoad, MemoryLocation::UnknownSize, 6696 TempAlign); 6697 Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO); 6698 } 6699 DAG.setRoot(Chain); 6700 return; 6701 } 6702 case Intrinsic::reset_fpenv: 6703 DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot())); 6704 return; 6705 case Intrinsic::get_fpmode: 6706 Res = DAG.getNode( 6707 ISD::GET_FPMODE, sdl, 6708 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()), 6709 MVT::Other), 6710 DAG.getRoot()); 6711 setValue(&I, Res); 6712 DAG.setRoot(Res.getValue(1)); 6713 return; 6714 case Intrinsic::set_fpmode: 6715 Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()}, 6716 getValue(I.getArgOperand(0))); 6717 DAG.setRoot(Res); 6718 return; 6719 case Intrinsic::reset_fpmode: { 6720 Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot()); 6721 DAG.setRoot(Res); 6722 return; 6723 } 6724 case Intrinsic::pcmarker: { 6725 SDValue Tmp = getValue(I.getArgOperand(0)); 6726 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6727 return; 6728 } 6729 case Intrinsic::readcyclecounter: { 6730 SDValue Op = getRoot(); 6731 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6732 DAG.getVTList(MVT::i64, MVT::Other), Op); 6733 setValue(&I, Res); 6734 DAG.setRoot(Res.getValue(1)); 6735 return; 6736 } 6737 case Intrinsic::bitreverse: 6738 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6739 getValue(I.getArgOperand(0)).getValueType(), 6740 getValue(I.getArgOperand(0)))); 6741 return; 6742 case Intrinsic::bswap: 6743 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6744 getValue(I.getArgOperand(0)).getValueType(), 6745 getValue(I.getArgOperand(0)))); 6746 return; 6747 case Intrinsic::cttz: { 6748 SDValue Arg = getValue(I.getArgOperand(0)); 6749 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6750 EVT Ty = Arg.getValueType(); 6751 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6752 sdl, Ty, Arg)); 6753 return; 6754 } 6755 case Intrinsic::ctlz: { 6756 SDValue Arg = getValue(I.getArgOperand(0)); 6757 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6758 EVT Ty = Arg.getValueType(); 6759 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6760 sdl, Ty, Arg)); 6761 return; 6762 } 6763 case Intrinsic::ctpop: { 6764 SDValue Arg = getValue(I.getArgOperand(0)); 6765 EVT Ty = Arg.getValueType(); 6766 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6767 return; 6768 } 6769 case Intrinsic::fshl: 6770 case Intrinsic::fshr: { 6771 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6772 SDValue X = getValue(I.getArgOperand(0)); 6773 SDValue Y = getValue(I.getArgOperand(1)); 6774 SDValue Z = getValue(I.getArgOperand(2)); 6775 EVT VT = X.getValueType(); 6776 6777 if (X == Y) { 6778 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6779 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6780 } else { 6781 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6782 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6783 } 6784 return; 6785 } 6786 case Intrinsic::sadd_sat: { 6787 SDValue Op1 = getValue(I.getArgOperand(0)); 6788 SDValue Op2 = getValue(I.getArgOperand(1)); 6789 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6790 return; 6791 } 6792 case Intrinsic::uadd_sat: { 6793 SDValue Op1 = getValue(I.getArgOperand(0)); 6794 SDValue Op2 = getValue(I.getArgOperand(1)); 6795 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6796 return; 6797 } 6798 case Intrinsic::ssub_sat: { 6799 SDValue Op1 = getValue(I.getArgOperand(0)); 6800 SDValue Op2 = getValue(I.getArgOperand(1)); 6801 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6802 return; 6803 } 6804 case Intrinsic::usub_sat: { 6805 SDValue Op1 = getValue(I.getArgOperand(0)); 6806 SDValue Op2 = getValue(I.getArgOperand(1)); 6807 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6808 return; 6809 } 6810 case Intrinsic::sshl_sat: { 6811 SDValue Op1 = getValue(I.getArgOperand(0)); 6812 SDValue Op2 = getValue(I.getArgOperand(1)); 6813 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6814 return; 6815 } 6816 case Intrinsic::ushl_sat: { 6817 SDValue Op1 = getValue(I.getArgOperand(0)); 6818 SDValue Op2 = getValue(I.getArgOperand(1)); 6819 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6820 return; 6821 } 6822 case Intrinsic::smul_fix: 6823 case Intrinsic::umul_fix: 6824 case Intrinsic::smul_fix_sat: 6825 case Intrinsic::umul_fix_sat: { 6826 SDValue Op1 = getValue(I.getArgOperand(0)); 6827 SDValue Op2 = getValue(I.getArgOperand(1)); 6828 SDValue Op3 = getValue(I.getArgOperand(2)); 6829 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6830 Op1.getValueType(), Op1, Op2, Op3)); 6831 return; 6832 } 6833 case Intrinsic::sdiv_fix: 6834 case Intrinsic::udiv_fix: 6835 case Intrinsic::sdiv_fix_sat: 6836 case Intrinsic::udiv_fix_sat: { 6837 SDValue Op1 = getValue(I.getArgOperand(0)); 6838 SDValue Op2 = getValue(I.getArgOperand(1)); 6839 SDValue Op3 = getValue(I.getArgOperand(2)); 6840 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6841 Op1, Op2, Op3, DAG, TLI)); 6842 return; 6843 } 6844 case Intrinsic::smax: { 6845 SDValue Op1 = getValue(I.getArgOperand(0)); 6846 SDValue Op2 = getValue(I.getArgOperand(1)); 6847 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6848 return; 6849 } 6850 case Intrinsic::smin: { 6851 SDValue Op1 = getValue(I.getArgOperand(0)); 6852 SDValue Op2 = getValue(I.getArgOperand(1)); 6853 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6854 return; 6855 } 6856 case Intrinsic::umax: { 6857 SDValue Op1 = getValue(I.getArgOperand(0)); 6858 SDValue Op2 = getValue(I.getArgOperand(1)); 6859 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6860 return; 6861 } 6862 case Intrinsic::umin: { 6863 SDValue Op1 = getValue(I.getArgOperand(0)); 6864 SDValue Op2 = getValue(I.getArgOperand(1)); 6865 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6866 return; 6867 } 6868 case Intrinsic::abs: { 6869 // TODO: Preserve "int min is poison" arg in SDAG? 6870 SDValue Op1 = getValue(I.getArgOperand(0)); 6871 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6872 return; 6873 } 6874 case Intrinsic::stacksave: { 6875 SDValue Op = getRoot(); 6876 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6877 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6878 setValue(&I, Res); 6879 DAG.setRoot(Res.getValue(1)); 6880 return; 6881 } 6882 case Intrinsic::stackrestore: 6883 Res = getValue(I.getArgOperand(0)); 6884 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6885 return; 6886 case Intrinsic::get_dynamic_area_offset: { 6887 SDValue Op = getRoot(); 6888 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6889 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6890 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6891 // target. 6892 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 6893 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6894 " intrinsic!"); 6895 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6896 Op); 6897 DAG.setRoot(Op); 6898 setValue(&I, Res); 6899 return; 6900 } 6901 case Intrinsic::stackguard: { 6902 MachineFunction &MF = DAG.getMachineFunction(); 6903 const Module &M = *MF.getFunction().getParent(); 6904 SDValue Chain = getRoot(); 6905 if (TLI.useLoadStackGuardNode()) { 6906 Res = getLoadStackGuard(DAG, sdl, Chain); 6907 } else { 6908 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6909 const Value *Global = TLI.getSDagStackGuard(M); 6910 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType()); 6911 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6912 MachinePointerInfo(Global, 0), Align, 6913 MachineMemOperand::MOVolatile); 6914 } 6915 if (TLI.useStackGuardXorFP()) 6916 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6917 DAG.setRoot(Chain); 6918 setValue(&I, Res); 6919 return; 6920 } 6921 case Intrinsic::stackprotector: { 6922 // Emit code into the DAG to store the stack guard onto the stack. 6923 MachineFunction &MF = DAG.getMachineFunction(); 6924 MachineFrameInfo &MFI = MF.getFrameInfo(); 6925 SDValue Src, Chain = getRoot(); 6926 6927 if (TLI.useLoadStackGuardNode()) 6928 Src = getLoadStackGuard(DAG, sdl, Chain); 6929 else 6930 Src = getValue(I.getArgOperand(0)); // The guard's value. 6931 6932 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6933 6934 int FI = FuncInfo.StaticAllocaMap[Slot]; 6935 MFI.setStackProtectorIndex(FI); 6936 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6937 6938 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6939 6940 // Store the stack protector onto the stack. 6941 Res = DAG.getStore( 6942 Chain, sdl, Src, FIN, 6943 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 6944 MaybeAlign(), MachineMemOperand::MOVolatile); 6945 setValue(&I, Res); 6946 DAG.setRoot(Res); 6947 return; 6948 } 6949 case Intrinsic::objectsize: 6950 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6951 6952 case Intrinsic::is_constant: 6953 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6954 6955 case Intrinsic::annotation: 6956 case Intrinsic::ptr_annotation: 6957 case Intrinsic::launder_invariant_group: 6958 case Intrinsic::strip_invariant_group: 6959 // Drop the intrinsic, but forward the value 6960 setValue(&I, getValue(I.getOperand(0))); 6961 return; 6962 6963 case Intrinsic::assume: 6964 case Intrinsic::experimental_noalias_scope_decl: 6965 case Intrinsic::var_annotation: 6966 case Intrinsic::sideeffect: 6967 // Discard annotate attributes, noalias scope declarations, assumptions, and 6968 // artificial side-effects. 6969 return; 6970 6971 case Intrinsic::codeview_annotation: { 6972 // Emit a label associated with this metadata. 6973 MachineFunction &MF = DAG.getMachineFunction(); 6974 MCSymbol *Label = 6975 MF.getMMI().getContext().createTempSymbol("annotation", true); 6976 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6977 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6978 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6979 DAG.setRoot(Res); 6980 return; 6981 } 6982 6983 case Intrinsic::init_trampoline: { 6984 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6985 6986 SDValue Ops[6]; 6987 Ops[0] = getRoot(); 6988 Ops[1] = getValue(I.getArgOperand(0)); 6989 Ops[2] = getValue(I.getArgOperand(1)); 6990 Ops[3] = getValue(I.getArgOperand(2)); 6991 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6992 Ops[5] = DAG.getSrcValue(F); 6993 6994 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6995 6996 DAG.setRoot(Res); 6997 return; 6998 } 6999 case Intrinsic::adjust_trampoline: 7000 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 7001 TLI.getPointerTy(DAG.getDataLayout()), 7002 getValue(I.getArgOperand(0)))); 7003 return; 7004 case Intrinsic::gcroot: { 7005 assert(DAG.getMachineFunction().getFunction().hasGC() && 7006 "only valid in functions with gc specified, enforced by Verifier"); 7007 assert(GFI && "implied by previous"); 7008 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 7009 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 7010 7011 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 7012 GFI->addStackRoot(FI->getIndex(), TypeMap); 7013 return; 7014 } 7015 case Intrinsic::gcread: 7016 case Intrinsic::gcwrite: 7017 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 7018 case Intrinsic::get_rounding: 7019 Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot()); 7020 setValue(&I, Res); 7021 DAG.setRoot(Res.getValue(1)); 7022 return; 7023 7024 case Intrinsic::expect: 7025 // Just replace __builtin_expect(exp, c) with EXP. 7026 setValue(&I, getValue(I.getArgOperand(0))); 7027 return; 7028 7029 case Intrinsic::ubsantrap: 7030 case Intrinsic::debugtrap: 7031 case Intrinsic::trap: { 7032 StringRef TrapFuncName = 7033 I.getAttributes().getFnAttr("trap-func-name").getValueAsString(); 7034 if (TrapFuncName.empty()) { 7035 switch (Intrinsic) { 7036 case Intrinsic::trap: 7037 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 7038 break; 7039 case Intrinsic::debugtrap: 7040 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 7041 break; 7042 case Intrinsic::ubsantrap: 7043 DAG.setRoot(DAG.getNode( 7044 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 7045 DAG.getTargetConstant( 7046 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 7047 MVT::i32))); 7048 break; 7049 default: llvm_unreachable("unknown trap intrinsic"); 7050 } 7051 return; 7052 } 7053 TargetLowering::ArgListTy Args; 7054 if (Intrinsic == Intrinsic::ubsantrap) { 7055 Args.push_back(TargetLoweringBase::ArgListEntry()); 7056 Args[0].Val = I.getArgOperand(0); 7057 Args[0].Node = getValue(Args[0].Val); 7058 Args[0].Ty = Args[0].Val->getType(); 7059 } 7060 7061 TargetLowering::CallLoweringInfo CLI(DAG); 7062 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 7063 CallingConv::C, I.getType(), 7064 DAG.getExternalSymbol(TrapFuncName.data(), 7065 TLI.getPointerTy(DAG.getDataLayout())), 7066 std::move(Args)); 7067 7068 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7069 DAG.setRoot(Result.second); 7070 return; 7071 } 7072 7073 case Intrinsic::uadd_with_overflow: 7074 case Intrinsic::sadd_with_overflow: 7075 case Intrinsic::usub_with_overflow: 7076 case Intrinsic::ssub_with_overflow: 7077 case Intrinsic::umul_with_overflow: 7078 case Intrinsic::smul_with_overflow: { 7079 ISD::NodeType Op; 7080 switch (Intrinsic) { 7081 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7082 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 7083 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 7084 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 7085 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 7086 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 7087 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 7088 } 7089 SDValue Op1 = getValue(I.getArgOperand(0)); 7090 SDValue Op2 = getValue(I.getArgOperand(1)); 7091 7092 EVT ResultVT = Op1.getValueType(); 7093 EVT OverflowVT = MVT::i1; 7094 if (ResultVT.isVector()) 7095 OverflowVT = EVT::getVectorVT( 7096 *Context, OverflowVT, ResultVT.getVectorElementCount()); 7097 7098 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 7099 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 7100 return; 7101 } 7102 case Intrinsic::prefetch: { 7103 SDValue Ops[5]; 7104 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 7105 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 7106 Ops[0] = DAG.getRoot(); 7107 Ops[1] = getValue(I.getArgOperand(0)); 7108 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 7109 MVT::i32); 7110 Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl, 7111 MVT::i32); 7112 Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl, 7113 MVT::i32); 7114 SDValue Result = DAG.getMemIntrinsicNode( 7115 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 7116 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 7117 /* align */ std::nullopt, Flags); 7118 7119 // Chain the prefetch in parallell with any pending loads, to stay out of 7120 // the way of later optimizations. 7121 PendingLoads.push_back(Result); 7122 Result = getRoot(); 7123 DAG.setRoot(Result); 7124 return; 7125 } 7126 case Intrinsic::lifetime_start: 7127 case Intrinsic::lifetime_end: { 7128 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 7129 // Stack coloring is not enabled in O0, discard region information. 7130 if (TM.getOptLevel() == CodeGenOptLevel::None) 7131 return; 7132 7133 const int64_t ObjectSize = 7134 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 7135 Value *const ObjectPtr = I.getArgOperand(1); 7136 SmallVector<const Value *, 4> Allocas; 7137 getUnderlyingObjects(ObjectPtr, Allocas); 7138 7139 for (const Value *Alloca : Allocas) { 7140 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 7141 7142 // Could not find an Alloca. 7143 if (!LifetimeObject) 7144 continue; 7145 7146 // First check that the Alloca is static, otherwise it won't have a 7147 // valid frame index. 7148 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 7149 if (SI == FuncInfo.StaticAllocaMap.end()) 7150 return; 7151 7152 const int FrameIndex = SI->second; 7153 int64_t Offset; 7154 if (GetPointerBaseWithConstantOffset( 7155 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 7156 Offset = -1; // Cannot determine offset from alloca to lifetime object. 7157 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 7158 Offset); 7159 DAG.setRoot(Res); 7160 } 7161 return; 7162 } 7163 case Intrinsic::pseudoprobe: { 7164 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 7165 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 7166 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 7167 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 7168 DAG.setRoot(Res); 7169 return; 7170 } 7171 case Intrinsic::invariant_start: 7172 // Discard region information. 7173 setValue(&I, 7174 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType()))); 7175 return; 7176 case Intrinsic::invariant_end: 7177 // Discard region information. 7178 return; 7179 case Intrinsic::clear_cache: 7180 /// FunctionName may be null. 7181 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 7182 lowerCallToExternalSymbol(I, FunctionName); 7183 return; 7184 case Intrinsic::donothing: 7185 case Intrinsic::seh_try_begin: 7186 case Intrinsic::seh_scope_begin: 7187 case Intrinsic::seh_try_end: 7188 case Intrinsic::seh_scope_end: 7189 // ignore 7190 return; 7191 case Intrinsic::experimental_stackmap: 7192 visitStackmap(I); 7193 return; 7194 case Intrinsic::experimental_patchpoint_void: 7195 case Intrinsic::experimental_patchpoint_i64: 7196 visitPatchpoint(I); 7197 return; 7198 case Intrinsic::experimental_gc_statepoint: 7199 LowerStatepoint(cast<GCStatepointInst>(I)); 7200 return; 7201 case Intrinsic::experimental_gc_result: 7202 visitGCResult(cast<GCResultInst>(I)); 7203 return; 7204 case Intrinsic::experimental_gc_relocate: 7205 visitGCRelocate(cast<GCRelocateInst>(I)); 7206 return; 7207 case Intrinsic::instrprof_cover: 7208 llvm_unreachable("instrprof failed to lower a cover"); 7209 case Intrinsic::instrprof_increment: 7210 llvm_unreachable("instrprof failed to lower an increment"); 7211 case Intrinsic::instrprof_timestamp: 7212 llvm_unreachable("instrprof failed to lower a timestamp"); 7213 case Intrinsic::instrprof_value_profile: 7214 llvm_unreachable("instrprof failed to lower a value profiling call"); 7215 case Intrinsic::instrprof_mcdc_parameters: 7216 llvm_unreachable("instrprof failed to lower mcdc parameters"); 7217 case Intrinsic::instrprof_mcdc_tvbitmap_update: 7218 llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update"); 7219 case Intrinsic::instrprof_mcdc_condbitmap_update: 7220 llvm_unreachable("instrprof failed to lower an mcdc condbitmap update"); 7221 case Intrinsic::localescape: { 7222 MachineFunction &MF = DAG.getMachineFunction(); 7223 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 7224 7225 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 7226 // is the same on all targets. 7227 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) { 7228 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 7229 if (isa<ConstantPointerNull>(Arg)) 7230 continue; // Skip null pointers. They represent a hole in index space. 7231 AllocaInst *Slot = cast<AllocaInst>(Arg); 7232 assert(FuncInfo.StaticAllocaMap.count(Slot) && 7233 "can only escape static allocas"); 7234 int FI = FuncInfo.StaticAllocaMap[Slot]; 7235 MCSymbol *FrameAllocSym = 7236 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7237 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 7238 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 7239 TII->get(TargetOpcode::LOCAL_ESCAPE)) 7240 .addSym(FrameAllocSym) 7241 .addFrameIndex(FI); 7242 } 7243 7244 return; 7245 } 7246 7247 case Intrinsic::localrecover: { 7248 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 7249 MachineFunction &MF = DAG.getMachineFunction(); 7250 7251 // Get the symbol that defines the frame offset. 7252 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 7253 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 7254 unsigned IdxVal = 7255 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 7256 MCSymbol *FrameAllocSym = 7257 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7258 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 7259 7260 Value *FP = I.getArgOperand(1); 7261 SDValue FPVal = getValue(FP); 7262 EVT PtrVT = FPVal.getValueType(); 7263 7264 // Create a MCSymbol for the label to avoid any target lowering 7265 // that would make this PC relative. 7266 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 7267 SDValue OffsetVal = 7268 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 7269 7270 // Add the offset to the FP. 7271 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 7272 setValue(&I, Add); 7273 7274 return; 7275 } 7276 7277 case Intrinsic::eh_exceptionpointer: 7278 case Intrinsic::eh_exceptioncode: { 7279 // Get the exception pointer vreg, copy from it, and resize it to fit. 7280 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 7281 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 7282 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 7283 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 7284 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT); 7285 if (Intrinsic == Intrinsic::eh_exceptioncode) 7286 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32); 7287 setValue(&I, N); 7288 return; 7289 } 7290 case Intrinsic::xray_customevent: { 7291 // Here we want to make sure that the intrinsic behaves as if it has a 7292 // specific calling convention. 7293 const auto &Triple = DAG.getTarget().getTargetTriple(); 7294 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64) 7295 return; 7296 7297 SmallVector<SDValue, 8> Ops; 7298 7299 // We want to say that we always want the arguments in registers. 7300 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 7301 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 7302 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7303 SDValue Chain = getRoot(); 7304 Ops.push_back(LogEntryVal); 7305 Ops.push_back(StrSizeVal); 7306 Ops.push_back(Chain); 7307 7308 // We need to enforce the calling convention for the callsite, so that 7309 // argument ordering is enforced correctly, and that register allocation can 7310 // see that some registers may be assumed clobbered and have to preserve 7311 // them across calls to the intrinsic. 7312 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 7313 sdl, NodeTys, Ops); 7314 SDValue patchableNode = SDValue(MN, 0); 7315 DAG.setRoot(patchableNode); 7316 setValue(&I, patchableNode); 7317 return; 7318 } 7319 case Intrinsic::xray_typedevent: { 7320 // Here we want to make sure that the intrinsic behaves as if it has a 7321 // specific calling convention. 7322 const auto &Triple = DAG.getTarget().getTargetTriple(); 7323 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64) 7324 return; 7325 7326 SmallVector<SDValue, 8> Ops; 7327 7328 // We want to say that we always want the arguments in registers. 7329 // It's unclear to me how manipulating the selection DAG here forces callers 7330 // to provide arguments in registers instead of on the stack. 7331 SDValue LogTypeId = getValue(I.getArgOperand(0)); 7332 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 7333 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 7334 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7335 SDValue Chain = getRoot(); 7336 Ops.push_back(LogTypeId); 7337 Ops.push_back(LogEntryVal); 7338 Ops.push_back(StrSizeVal); 7339 Ops.push_back(Chain); 7340 7341 // We need to enforce the calling convention for the callsite, so that 7342 // argument ordering is enforced correctly, and that register allocation can 7343 // see that some registers may be assumed clobbered and have to preserve 7344 // them across calls to the intrinsic. 7345 MachineSDNode *MN = DAG.getMachineNode( 7346 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops); 7347 SDValue patchableNode = SDValue(MN, 0); 7348 DAG.setRoot(patchableNode); 7349 setValue(&I, patchableNode); 7350 return; 7351 } 7352 case Intrinsic::experimental_deoptimize: 7353 LowerDeoptimizeCall(&I); 7354 return; 7355 case Intrinsic::experimental_stepvector: 7356 visitStepVector(I); 7357 return; 7358 case Intrinsic::vector_reduce_fadd: 7359 case Intrinsic::vector_reduce_fmul: 7360 case Intrinsic::vector_reduce_add: 7361 case Intrinsic::vector_reduce_mul: 7362 case Intrinsic::vector_reduce_and: 7363 case Intrinsic::vector_reduce_or: 7364 case Intrinsic::vector_reduce_xor: 7365 case Intrinsic::vector_reduce_smax: 7366 case Intrinsic::vector_reduce_smin: 7367 case Intrinsic::vector_reduce_umax: 7368 case Intrinsic::vector_reduce_umin: 7369 case Intrinsic::vector_reduce_fmax: 7370 case Intrinsic::vector_reduce_fmin: 7371 case Intrinsic::vector_reduce_fmaximum: 7372 case Intrinsic::vector_reduce_fminimum: 7373 visitVectorReduce(I, Intrinsic); 7374 return; 7375 7376 case Intrinsic::icall_branch_funnel: { 7377 SmallVector<SDValue, 16> Ops; 7378 Ops.push_back(getValue(I.getArgOperand(0))); 7379 7380 int64_t Offset; 7381 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7382 I.getArgOperand(1), Offset, DAG.getDataLayout())); 7383 if (!Base) 7384 report_fatal_error( 7385 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7386 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0)); 7387 7388 struct BranchFunnelTarget { 7389 int64_t Offset; 7390 SDValue Target; 7391 }; 7392 SmallVector<BranchFunnelTarget, 8> Targets; 7393 7394 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) { 7395 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7396 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7397 if (ElemBase != Base) 7398 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7399 "to the same GlobalValue"); 7400 7401 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7402 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7403 if (!GA) 7404 report_fatal_error( 7405 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7406 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7407 GA->getGlobal(), sdl, Val.getValueType(), 7408 GA->getOffset())}); 7409 } 7410 llvm::sort(Targets, 7411 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7412 return T1.Offset < T2.Offset; 7413 }); 7414 7415 for (auto &T : Targets) { 7416 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32)); 7417 Ops.push_back(T.Target); 7418 } 7419 7420 Ops.push_back(DAG.getRoot()); // Chain 7421 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl, 7422 MVT::Other, Ops), 7423 0); 7424 DAG.setRoot(N); 7425 setValue(&I, N); 7426 HasTailCall = true; 7427 return; 7428 } 7429 7430 case Intrinsic::wasm_landingpad_index: 7431 // Information this intrinsic contained has been transferred to 7432 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7433 // delete it now. 7434 return; 7435 7436 case Intrinsic::aarch64_settag: 7437 case Intrinsic::aarch64_settag_zero: { 7438 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7439 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7440 SDValue Val = TSI.EmitTargetCodeForSetTag( 7441 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)), 7442 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7443 ZeroMemory); 7444 DAG.setRoot(Val); 7445 setValue(&I, Val); 7446 return; 7447 } 7448 case Intrinsic::amdgcn_cs_chain: { 7449 assert(I.arg_size() == 5 && "Additional args not supported yet"); 7450 assert(cast<ConstantInt>(I.getOperand(4))->isZero() && 7451 "Non-zero flags not supported yet"); 7452 7453 // At this point we don't care if it's amdgpu_cs_chain or 7454 // amdgpu_cs_chain_preserve. 7455 CallingConv::ID CC = CallingConv::AMDGPU_CS_Chain; 7456 7457 Type *RetTy = I.getType(); 7458 assert(RetTy->isVoidTy() && "Should not return"); 7459 7460 SDValue Callee = getValue(I.getOperand(0)); 7461 7462 // We only have 2 actual args: one for the SGPRs and one for the VGPRs. 7463 // We'll also tack the value of the EXEC mask at the end. 7464 TargetLowering::ArgListTy Args; 7465 Args.reserve(3); 7466 7467 for (unsigned Idx : {2, 3, 1}) { 7468 TargetLowering::ArgListEntry Arg; 7469 Arg.Node = getValue(I.getOperand(Idx)); 7470 Arg.Ty = I.getOperand(Idx)->getType(); 7471 Arg.setAttributes(&I, Idx); 7472 Args.push_back(Arg); 7473 } 7474 7475 assert(Args[0].IsInReg && "SGPR args should be marked inreg"); 7476 assert(!Args[1].IsInReg && "VGPR args should not be marked inreg"); 7477 Args[2].IsInReg = true; // EXEC should be inreg 7478 7479 TargetLowering::CallLoweringInfo CLI(DAG); 7480 CLI.setDebugLoc(getCurSDLoc()) 7481 .setChain(getRoot()) 7482 .setCallee(CC, RetTy, Callee, std::move(Args)) 7483 .setNoReturn(true) 7484 .setTailCall(true) 7485 .setConvergent(I.isConvergent()); 7486 CLI.CB = &I; 7487 std::pair<SDValue, SDValue> Result = 7488 lowerInvokable(CLI, /*EHPadBB*/ nullptr); 7489 (void)Result; 7490 assert(!Result.first.getNode() && !Result.second.getNode() && 7491 "Should've lowered as tail call"); 7492 7493 HasTailCall = true; 7494 return; 7495 } 7496 case Intrinsic::ptrmask: { 7497 SDValue Ptr = getValue(I.getOperand(0)); 7498 SDValue Mask = getValue(I.getOperand(1)); 7499 7500 EVT PtrVT = Ptr.getValueType(); 7501 assert(PtrVT == Mask.getValueType() && 7502 "Pointers with different index type are not supported by SDAG"); 7503 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask)); 7504 return; 7505 } 7506 case Intrinsic::threadlocal_address: { 7507 setValue(&I, getValue(I.getOperand(0))); 7508 return; 7509 } 7510 case Intrinsic::get_active_lane_mask: { 7511 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7512 SDValue Index = getValue(I.getOperand(0)); 7513 EVT ElementVT = Index.getValueType(); 7514 7515 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) { 7516 visitTargetIntrinsic(I, Intrinsic); 7517 return; 7518 } 7519 7520 SDValue TripCount = getValue(I.getOperand(1)); 7521 EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT, 7522 CCVT.getVectorElementCount()); 7523 7524 SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index); 7525 SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount); 7526 SDValue VectorStep = DAG.getStepVector(sdl, VecTy); 7527 SDValue VectorInduction = DAG.getNode( 7528 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep); 7529 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction, 7530 VectorTripCount, ISD::CondCode::SETULT); 7531 setValue(&I, SetCC); 7532 return; 7533 } 7534 case Intrinsic::experimental_get_vector_length: { 7535 assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 && 7536 "Expected positive VF"); 7537 unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue(); 7538 bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne(); 7539 7540 SDValue Count = getValue(I.getOperand(0)); 7541 EVT CountVT = Count.getValueType(); 7542 7543 if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) { 7544 visitTargetIntrinsic(I, Intrinsic); 7545 return; 7546 } 7547 7548 // Expand to a umin between the trip count and the maximum elements the type 7549 // can hold. 7550 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7551 7552 // Extend the trip count to at least the result VT. 7553 if (CountVT.bitsLT(VT)) { 7554 Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count); 7555 CountVT = VT; 7556 } 7557 7558 SDValue MaxEVL = DAG.getElementCount(sdl, CountVT, 7559 ElementCount::get(VF, IsScalable)); 7560 7561 SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL); 7562 // Clip to the result type if needed. 7563 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin); 7564 7565 setValue(&I, Trunc); 7566 return; 7567 } 7568 case Intrinsic::experimental_cttz_elts: { 7569 auto DL = getCurSDLoc(); 7570 SDValue Op = getValue(I.getOperand(0)); 7571 EVT OpVT = Op.getValueType(); 7572 7573 if (!TLI.shouldExpandCttzElements(OpVT)) { 7574 visitTargetIntrinsic(I, Intrinsic); 7575 return; 7576 } 7577 7578 if (OpVT.getScalarType() != MVT::i1) { 7579 // Compare the input vector elements to zero & use to count trailing zeros 7580 SDValue AllZero = DAG.getConstant(0, DL, OpVT); 7581 OpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, 7582 OpVT.getVectorElementCount()); 7583 Op = DAG.getSetCC(DL, OpVT, Op, AllZero, ISD::SETNE); 7584 } 7585 7586 // Find the smallest "sensible" element type to use for the expansion. 7587 ConstantRange CR( 7588 APInt(64, OpVT.getVectorElementCount().getKnownMinValue())); 7589 if (OpVT.isScalableVT()) 7590 CR = CR.umul_sat(getVScaleRange(I.getCaller(), 64)); 7591 7592 // If the zero-is-poison flag is set, we can assume the upper limit 7593 // of the result is VF-1. 7594 if (!cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero()) 7595 CR = CR.subtract(APInt(64, 1)); 7596 7597 unsigned EltWidth = I.getType()->getScalarSizeInBits(); 7598 EltWidth = std::min(EltWidth, (unsigned)CR.getActiveBits()); 7599 EltWidth = std::max(llvm::bit_ceil(EltWidth), (unsigned)8); 7600 7601 MVT NewEltTy = MVT::getIntegerVT(EltWidth); 7602 7603 // Create the new vector type & get the vector length 7604 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), NewEltTy, 7605 OpVT.getVectorElementCount()); 7606 7607 SDValue VL = 7608 DAG.getElementCount(DL, NewEltTy, OpVT.getVectorElementCount()); 7609 7610 SDValue StepVec = DAG.getStepVector(DL, NewVT); 7611 SDValue SplatVL = DAG.getSplat(NewVT, DL, VL); 7612 SDValue StepVL = DAG.getNode(ISD::SUB, DL, NewVT, SplatVL, StepVec); 7613 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, Op); 7614 SDValue And = DAG.getNode(ISD::AND, DL, NewVT, StepVL, Ext); 7615 SDValue Max = DAG.getNode(ISD::VECREDUCE_UMAX, DL, NewEltTy, And); 7616 SDValue Sub = DAG.getNode(ISD::SUB, DL, NewEltTy, VL, Max); 7617 7618 EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7619 SDValue Ret = DAG.getZExtOrTrunc(Sub, DL, RetTy); 7620 7621 setValue(&I, Ret); 7622 return; 7623 } 7624 case Intrinsic::vector_insert: { 7625 SDValue Vec = getValue(I.getOperand(0)); 7626 SDValue SubVec = getValue(I.getOperand(1)); 7627 SDValue Index = getValue(I.getOperand(2)); 7628 7629 // The intrinsic's index type is i64, but the SDNode requires an index type 7630 // suitable for the target. Convert the index as required. 7631 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7632 if (Index.getValueType() != VectorIdxTy) 7633 Index = DAG.getVectorIdxConstant( 7634 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7635 7636 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7637 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec, 7638 Index)); 7639 return; 7640 } 7641 case Intrinsic::vector_extract: { 7642 SDValue Vec = getValue(I.getOperand(0)); 7643 SDValue Index = getValue(I.getOperand(1)); 7644 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7645 7646 // The intrinsic's index type is i64, but the SDNode requires an index type 7647 // suitable for the target. Convert the index as required. 7648 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7649 if (Index.getValueType() != VectorIdxTy) 7650 Index = DAG.getVectorIdxConstant( 7651 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7652 7653 setValue(&I, 7654 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index)); 7655 return; 7656 } 7657 case Intrinsic::experimental_vector_reverse: 7658 visitVectorReverse(I); 7659 return; 7660 case Intrinsic::experimental_vector_splice: 7661 visitVectorSplice(I); 7662 return; 7663 case Intrinsic::callbr_landingpad: 7664 visitCallBrLandingPad(I); 7665 return; 7666 case Intrinsic::experimental_vector_interleave2: 7667 visitVectorInterleave(I); 7668 return; 7669 case Intrinsic::experimental_vector_deinterleave2: 7670 visitVectorDeinterleave(I); 7671 return; 7672 } 7673 } 7674 7675 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7676 const ConstrainedFPIntrinsic &FPI) { 7677 SDLoc sdl = getCurSDLoc(); 7678 7679 // We do not need to serialize constrained FP intrinsics against 7680 // each other or against (nonvolatile) loads, so they can be 7681 // chained like loads. 7682 SDValue Chain = DAG.getRoot(); 7683 SmallVector<SDValue, 4> Opers; 7684 Opers.push_back(Chain); 7685 if (FPI.isUnaryOp()) { 7686 Opers.push_back(getValue(FPI.getArgOperand(0))); 7687 } else if (FPI.isTernaryOp()) { 7688 Opers.push_back(getValue(FPI.getArgOperand(0))); 7689 Opers.push_back(getValue(FPI.getArgOperand(1))); 7690 Opers.push_back(getValue(FPI.getArgOperand(2))); 7691 } else { 7692 Opers.push_back(getValue(FPI.getArgOperand(0))); 7693 Opers.push_back(getValue(FPI.getArgOperand(1))); 7694 } 7695 7696 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7697 assert(Result.getNode()->getNumValues() == 2); 7698 7699 // Push node to the appropriate list so that future instructions can be 7700 // chained up correctly. 7701 SDValue OutChain = Result.getValue(1); 7702 switch (EB) { 7703 case fp::ExceptionBehavior::ebIgnore: 7704 // The only reason why ebIgnore nodes still need to be chained is that 7705 // they might depend on the current rounding mode, and therefore must 7706 // not be moved across instruction that may change that mode. 7707 [[fallthrough]]; 7708 case fp::ExceptionBehavior::ebMayTrap: 7709 // These must not be moved across calls or instructions that may change 7710 // floating-point exception masks. 7711 PendingConstrainedFP.push_back(OutChain); 7712 break; 7713 case fp::ExceptionBehavior::ebStrict: 7714 // These must not be moved across calls or instructions that may change 7715 // floating-point exception masks or read floating-point exception flags. 7716 // In addition, they cannot be optimized out even if unused. 7717 PendingConstrainedFPStrict.push_back(OutChain); 7718 break; 7719 } 7720 }; 7721 7722 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7723 EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType()); 7724 SDVTList VTs = DAG.getVTList(VT, MVT::Other); 7725 fp::ExceptionBehavior EB = *FPI.getExceptionBehavior(); 7726 7727 SDNodeFlags Flags; 7728 if (EB == fp::ExceptionBehavior::ebIgnore) 7729 Flags.setNoFPExcept(true); 7730 7731 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7732 Flags.copyFMF(*FPOp); 7733 7734 unsigned Opcode; 7735 switch (FPI.getIntrinsicID()) { 7736 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7737 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7738 case Intrinsic::INTRINSIC: \ 7739 Opcode = ISD::STRICT_##DAGN; \ 7740 break; 7741 #include "llvm/IR/ConstrainedOps.def" 7742 case Intrinsic::experimental_constrained_fmuladd: { 7743 Opcode = ISD::STRICT_FMA; 7744 // Break fmuladd into fmul and fadd. 7745 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7746 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 7747 Opers.pop_back(); 7748 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7749 pushOutChain(Mul, EB); 7750 Opcode = ISD::STRICT_FADD; 7751 Opers.clear(); 7752 Opers.push_back(Mul.getValue(1)); 7753 Opers.push_back(Mul.getValue(0)); 7754 Opers.push_back(getValue(FPI.getArgOperand(2))); 7755 } 7756 break; 7757 } 7758 } 7759 7760 // A few strict DAG nodes carry additional operands that are not 7761 // set up by the default code above. 7762 switch (Opcode) { 7763 default: break; 7764 case ISD::STRICT_FP_ROUND: 7765 Opers.push_back( 7766 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7767 break; 7768 case ISD::STRICT_FSETCC: 7769 case ISD::STRICT_FSETCCS: { 7770 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7771 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 7772 if (TM.Options.NoNaNsFPMath) 7773 Condition = getFCmpCodeWithoutNaN(Condition); 7774 Opers.push_back(DAG.getCondCode(Condition)); 7775 break; 7776 } 7777 } 7778 7779 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7780 pushOutChain(Result, EB); 7781 7782 SDValue FPResult = Result.getValue(0); 7783 setValue(&FPI, FPResult); 7784 } 7785 7786 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 7787 std::optional<unsigned> ResOPC; 7788 switch (VPIntrin.getIntrinsicID()) { 7789 case Intrinsic::vp_ctlz: { 7790 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 7791 ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ; 7792 break; 7793 } 7794 case Intrinsic::vp_cttz: { 7795 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 7796 ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ; 7797 break; 7798 } 7799 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \ 7800 case Intrinsic::VPID: \ 7801 ResOPC = ISD::VPSD; \ 7802 break; 7803 #include "llvm/IR/VPIntrinsics.def" 7804 } 7805 7806 if (!ResOPC) 7807 llvm_unreachable( 7808 "Inconsistency: no SDNode available for this VPIntrinsic!"); 7809 7810 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD || 7811 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) { 7812 if (VPIntrin.getFastMathFlags().allowReassoc()) 7813 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD 7814 : ISD::VP_REDUCE_FMUL; 7815 } 7816 7817 return *ResOPC; 7818 } 7819 7820 void SelectionDAGBuilder::visitVPLoad( 7821 const VPIntrinsic &VPIntrin, EVT VT, 7822 const SmallVectorImpl<SDValue> &OpValues) { 7823 SDLoc DL = getCurSDLoc(); 7824 Value *PtrOperand = VPIntrin.getArgOperand(0); 7825 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7826 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7827 const MDNode *Ranges = getRangeMetadata(VPIntrin); 7828 SDValue LD; 7829 // Do not serialize variable-length loads of constant memory with 7830 // anything. 7831 if (!Alignment) 7832 Alignment = DAG.getEVTAlign(VT); 7833 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7834 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7835 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7836 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7837 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7838 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7839 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2], 7840 MMO, false /*IsExpanding */); 7841 if (AddToChain) 7842 PendingLoads.push_back(LD.getValue(1)); 7843 setValue(&VPIntrin, LD); 7844 } 7845 7846 void SelectionDAGBuilder::visitVPGather( 7847 const VPIntrinsic &VPIntrin, EVT VT, 7848 const SmallVectorImpl<SDValue> &OpValues) { 7849 SDLoc DL = getCurSDLoc(); 7850 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7851 Value *PtrOperand = VPIntrin.getArgOperand(0); 7852 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7853 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7854 const MDNode *Ranges = getRangeMetadata(VPIntrin); 7855 SDValue LD; 7856 if (!Alignment) 7857 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7858 unsigned AS = 7859 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7860 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7861 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 7862 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7863 SDValue Base, Index, Scale; 7864 ISD::MemIndexType IndexType; 7865 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7866 this, VPIntrin.getParent(), 7867 VT.getScalarStoreSize()); 7868 if (!UniformBase) { 7869 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7870 Index = getValue(PtrOperand); 7871 IndexType = ISD::SIGNED_SCALED; 7872 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7873 } 7874 EVT IdxVT = Index.getValueType(); 7875 EVT EltTy = IdxVT.getVectorElementType(); 7876 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7877 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7878 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7879 } 7880 LD = DAG.getGatherVP( 7881 DAG.getVTList(VT, MVT::Other), VT, DL, 7882 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO, 7883 IndexType); 7884 PendingLoads.push_back(LD.getValue(1)); 7885 setValue(&VPIntrin, LD); 7886 } 7887 7888 void SelectionDAGBuilder::visitVPStore( 7889 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 7890 SDLoc DL = getCurSDLoc(); 7891 Value *PtrOperand = VPIntrin.getArgOperand(1); 7892 EVT VT = OpValues[0].getValueType(); 7893 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7894 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7895 SDValue ST; 7896 if (!Alignment) 7897 Alignment = DAG.getEVTAlign(VT); 7898 SDValue Ptr = OpValues[1]; 7899 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 7900 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7901 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7902 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7903 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset, 7904 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED, 7905 /* IsTruncating */ false, /*IsCompressing*/ false); 7906 DAG.setRoot(ST); 7907 setValue(&VPIntrin, ST); 7908 } 7909 7910 void SelectionDAGBuilder::visitVPScatter( 7911 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 7912 SDLoc DL = getCurSDLoc(); 7913 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7914 Value *PtrOperand = VPIntrin.getArgOperand(1); 7915 EVT VT = OpValues[0].getValueType(); 7916 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7917 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7918 SDValue ST; 7919 if (!Alignment) 7920 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7921 unsigned AS = 7922 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7923 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7924 MachinePointerInfo(AS), MachineMemOperand::MOStore, 7925 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7926 SDValue Base, Index, Scale; 7927 ISD::MemIndexType IndexType; 7928 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7929 this, VPIntrin.getParent(), 7930 VT.getScalarStoreSize()); 7931 if (!UniformBase) { 7932 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7933 Index = getValue(PtrOperand); 7934 IndexType = ISD::SIGNED_SCALED; 7935 Scale = 7936 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7937 } 7938 EVT IdxVT = Index.getValueType(); 7939 EVT EltTy = IdxVT.getVectorElementType(); 7940 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7941 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7942 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7943 } 7944 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL, 7945 {getMemoryRoot(), OpValues[0], Base, Index, Scale, 7946 OpValues[2], OpValues[3]}, 7947 MMO, IndexType); 7948 DAG.setRoot(ST); 7949 setValue(&VPIntrin, ST); 7950 } 7951 7952 void SelectionDAGBuilder::visitVPStridedLoad( 7953 const VPIntrinsic &VPIntrin, EVT VT, 7954 const SmallVectorImpl<SDValue> &OpValues) { 7955 SDLoc DL = getCurSDLoc(); 7956 Value *PtrOperand = VPIntrin.getArgOperand(0); 7957 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7958 if (!Alignment) 7959 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7960 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7961 const MDNode *Ranges = getRangeMetadata(VPIntrin); 7962 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7963 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7964 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7965 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7966 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7967 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7968 7969 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], 7970 OpValues[2], OpValues[3], MMO, 7971 false /*IsExpanding*/); 7972 7973 if (AddToChain) 7974 PendingLoads.push_back(LD.getValue(1)); 7975 setValue(&VPIntrin, LD); 7976 } 7977 7978 void SelectionDAGBuilder::visitVPStridedStore( 7979 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 7980 SDLoc DL = getCurSDLoc(); 7981 Value *PtrOperand = VPIntrin.getArgOperand(1); 7982 EVT VT = OpValues[0].getValueType(); 7983 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7984 if (!Alignment) 7985 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7986 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7987 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7988 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7989 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7990 7991 SDValue ST = DAG.getStridedStoreVP( 7992 getMemoryRoot(), DL, OpValues[0], OpValues[1], 7993 DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3], 7994 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false, 7995 /*IsCompressing*/ false); 7996 7997 DAG.setRoot(ST); 7998 setValue(&VPIntrin, ST); 7999 } 8000 8001 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) { 8002 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8003 SDLoc DL = getCurSDLoc(); 8004 8005 ISD::CondCode Condition; 8006 CmpInst::Predicate CondCode = VPIntrin.getPredicate(); 8007 bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy(); 8008 if (IsFP) { 8009 // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan) 8010 // flags, but calls that don't return floating-point types can't be 8011 // FPMathOperators, like vp.fcmp. This affects constrained fcmp too. 8012 Condition = getFCmpCondCode(CondCode); 8013 if (TM.Options.NoNaNsFPMath) 8014 Condition = getFCmpCodeWithoutNaN(Condition); 8015 } else { 8016 Condition = getICmpCondCode(CondCode); 8017 } 8018 8019 SDValue Op1 = getValue(VPIntrin.getOperand(0)); 8020 SDValue Op2 = getValue(VPIntrin.getOperand(1)); 8021 // #2 is the condition code 8022 SDValue MaskOp = getValue(VPIntrin.getOperand(3)); 8023 SDValue EVL = getValue(VPIntrin.getOperand(4)); 8024 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 8025 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 8026 "Unexpected target EVL type"); 8027 EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL); 8028 8029 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8030 VPIntrin.getType()); 8031 setValue(&VPIntrin, 8032 DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL)); 8033 } 8034 8035 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 8036 const VPIntrinsic &VPIntrin) { 8037 SDLoc DL = getCurSDLoc(); 8038 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 8039 8040 auto IID = VPIntrin.getIntrinsicID(); 8041 8042 if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin)) 8043 return visitVPCmp(*CmpI); 8044 8045 SmallVector<EVT, 4> ValueVTs; 8046 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8047 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 8048 SDVTList VTs = DAG.getVTList(ValueVTs); 8049 8050 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID); 8051 8052 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 8053 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 8054 "Unexpected target EVL type"); 8055 8056 // Request operands. 8057 SmallVector<SDValue, 7> OpValues; 8058 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) { 8059 auto Op = getValue(VPIntrin.getArgOperand(I)); 8060 if (I == EVLParamPos) 8061 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op); 8062 OpValues.push_back(Op); 8063 } 8064 8065 switch (Opcode) { 8066 default: { 8067 SDNodeFlags SDFlags; 8068 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 8069 SDFlags.copyFMF(*FPMO); 8070 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags); 8071 setValue(&VPIntrin, Result); 8072 break; 8073 } 8074 case ISD::VP_LOAD: 8075 visitVPLoad(VPIntrin, ValueVTs[0], OpValues); 8076 break; 8077 case ISD::VP_GATHER: 8078 visitVPGather(VPIntrin, ValueVTs[0], OpValues); 8079 break; 8080 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: 8081 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues); 8082 break; 8083 case ISD::VP_STORE: 8084 visitVPStore(VPIntrin, OpValues); 8085 break; 8086 case ISD::VP_SCATTER: 8087 visitVPScatter(VPIntrin, OpValues); 8088 break; 8089 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: 8090 visitVPStridedStore(VPIntrin, OpValues); 8091 break; 8092 case ISD::VP_FMULADD: { 8093 assert(OpValues.size() == 5 && "Unexpected number of operands"); 8094 SDNodeFlags SDFlags; 8095 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 8096 SDFlags.copyFMF(*FPMO); 8097 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 8098 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) { 8099 setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags)); 8100 } else { 8101 SDValue Mul = DAG.getNode( 8102 ISD::VP_FMUL, DL, VTs, 8103 {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags); 8104 SDValue Add = 8105 DAG.getNode(ISD::VP_FADD, DL, VTs, 8106 {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags); 8107 setValue(&VPIntrin, Add); 8108 } 8109 break; 8110 } 8111 case ISD::VP_IS_FPCLASS: { 8112 const DataLayout DLayout = DAG.getDataLayout(); 8113 EVT DestVT = TLI.getValueType(DLayout, VPIntrin.getType()); 8114 auto Constant = cast<ConstantSDNode>(OpValues[1])->getZExtValue(); 8115 SDValue Check = DAG.getTargetConstant(Constant, DL, MVT::i32); 8116 SDValue V = DAG.getNode(ISD::VP_IS_FPCLASS, DL, DestVT, 8117 {OpValues[0], Check, OpValues[2], OpValues[3]}); 8118 setValue(&VPIntrin, V); 8119 return; 8120 } 8121 case ISD::VP_INTTOPTR: { 8122 SDValue N = OpValues[0]; 8123 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType()); 8124 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType()); 8125 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 8126 OpValues[2]); 8127 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 8128 OpValues[2]); 8129 setValue(&VPIntrin, N); 8130 break; 8131 } 8132 case ISD::VP_PTRTOINT: { 8133 SDValue N = OpValues[0]; 8134 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8135 VPIntrin.getType()); 8136 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), 8137 VPIntrin.getOperand(0)->getType()); 8138 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 8139 OpValues[2]); 8140 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 8141 OpValues[2]); 8142 setValue(&VPIntrin, N); 8143 break; 8144 } 8145 case ISD::VP_ABS: 8146 case ISD::VP_CTLZ: 8147 case ISD::VP_CTLZ_ZERO_UNDEF: 8148 case ISD::VP_CTTZ: 8149 case ISD::VP_CTTZ_ZERO_UNDEF: { 8150 SDValue Result = 8151 DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]}); 8152 setValue(&VPIntrin, Result); 8153 break; 8154 } 8155 } 8156 } 8157 8158 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 8159 const BasicBlock *EHPadBB, 8160 MCSymbol *&BeginLabel) { 8161 MachineFunction &MF = DAG.getMachineFunction(); 8162 MachineModuleInfo &MMI = MF.getMMI(); 8163 8164 // Insert a label before the invoke call to mark the try range. This can be 8165 // used to detect deletion of the invoke via the MachineModuleInfo. 8166 BeginLabel = MMI.getContext().createTempSymbol(); 8167 8168 // For SjLj, keep track of which landing pads go with which invokes 8169 // so as to maintain the ordering of pads in the LSDA. 8170 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 8171 if (CallSiteIndex) { 8172 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 8173 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 8174 8175 // Now that the call site is handled, stop tracking it. 8176 MMI.setCurrentCallSite(0); 8177 } 8178 8179 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 8180 } 8181 8182 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 8183 const BasicBlock *EHPadBB, 8184 MCSymbol *BeginLabel) { 8185 assert(BeginLabel && "BeginLabel should've been set"); 8186 8187 MachineFunction &MF = DAG.getMachineFunction(); 8188 MachineModuleInfo &MMI = MF.getMMI(); 8189 8190 // Insert a label at the end of the invoke call to mark the try range. This 8191 // can be used to detect deletion of the invoke via the MachineModuleInfo. 8192 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 8193 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 8194 8195 // Inform MachineModuleInfo of range. 8196 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 8197 // There is a platform (e.g. wasm) that uses funclet style IR but does not 8198 // actually use outlined funclets and their LSDA info style. 8199 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 8200 assert(II && "II should've been set"); 8201 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 8202 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 8203 } else if (!isScopedEHPersonality(Pers)) { 8204 assert(EHPadBB); 8205 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 8206 } 8207 8208 return Chain; 8209 } 8210 8211 std::pair<SDValue, SDValue> 8212 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 8213 const BasicBlock *EHPadBB) { 8214 MCSymbol *BeginLabel = nullptr; 8215 8216 if (EHPadBB) { 8217 // Both PendingLoads and PendingExports must be flushed here; 8218 // this call might not return. 8219 (void)getRoot(); 8220 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 8221 CLI.setChain(getRoot()); 8222 } 8223 8224 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8225 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 8226 8227 assert((CLI.IsTailCall || Result.second.getNode()) && 8228 "Non-null chain expected with non-tail call!"); 8229 assert((Result.second.getNode() || !Result.first.getNode()) && 8230 "Null value expected with tail call!"); 8231 8232 if (!Result.second.getNode()) { 8233 // As a special case, a null chain means that a tail call has been emitted 8234 // and the DAG root is already updated. 8235 HasTailCall = true; 8236 8237 // Since there's no actual continuation from this block, nothing can be 8238 // relying on us setting vregs for them. 8239 PendingExports.clear(); 8240 } else { 8241 DAG.setRoot(Result.second); 8242 } 8243 8244 if (EHPadBB) { 8245 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 8246 BeginLabel)); 8247 } 8248 8249 return Result; 8250 } 8251 8252 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 8253 bool isTailCall, 8254 bool isMustTailCall, 8255 const BasicBlock *EHPadBB) { 8256 auto &DL = DAG.getDataLayout(); 8257 FunctionType *FTy = CB.getFunctionType(); 8258 Type *RetTy = CB.getType(); 8259 8260 TargetLowering::ArgListTy Args; 8261 Args.reserve(CB.arg_size()); 8262 8263 const Value *SwiftErrorVal = nullptr; 8264 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8265 8266 if (isTailCall) { 8267 // Avoid emitting tail calls in functions with the disable-tail-calls 8268 // attribute. 8269 auto *Caller = CB.getParent()->getParent(); 8270 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 8271 "true" && !isMustTailCall) 8272 isTailCall = false; 8273 8274 // We can't tail call inside a function with a swifterror argument. Lowering 8275 // does not support this yet. It would have to move into the swifterror 8276 // register before the call. 8277 if (TLI.supportSwiftError() && 8278 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 8279 isTailCall = false; 8280 } 8281 8282 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 8283 TargetLowering::ArgListEntry Entry; 8284 const Value *V = *I; 8285 8286 // Skip empty types 8287 if (V->getType()->isEmptyTy()) 8288 continue; 8289 8290 SDValue ArgNode = getValue(V); 8291 Entry.Node = ArgNode; Entry.Ty = V->getType(); 8292 8293 Entry.setAttributes(&CB, I - CB.arg_begin()); 8294 8295 // Use swifterror virtual register as input to the call. 8296 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 8297 SwiftErrorVal = V; 8298 // We find the virtual register for the actual swifterror argument. 8299 // Instead of using the Value, we use the virtual register instead. 8300 Entry.Node = 8301 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 8302 EVT(TLI.getPointerTy(DL))); 8303 } 8304 8305 Args.push_back(Entry); 8306 8307 // If we have an explicit sret argument that is an Instruction, (i.e., it 8308 // might point to function-local memory), we can't meaningfully tail-call. 8309 if (Entry.IsSRet && isa<Instruction>(V)) 8310 isTailCall = false; 8311 } 8312 8313 // If call site has a cfguardtarget operand bundle, create and add an 8314 // additional ArgListEntry. 8315 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 8316 TargetLowering::ArgListEntry Entry; 8317 Value *V = Bundle->Inputs[0]; 8318 SDValue ArgNode = getValue(V); 8319 Entry.Node = ArgNode; 8320 Entry.Ty = V->getType(); 8321 Entry.IsCFGuardTarget = true; 8322 Args.push_back(Entry); 8323 } 8324 8325 // Check if target-independent constraints permit a tail call here. 8326 // Target-dependent constraints are checked within TLI->LowerCallTo. 8327 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 8328 isTailCall = false; 8329 8330 // Disable tail calls if there is an swifterror argument. Targets have not 8331 // been updated to support tail calls. 8332 if (TLI.supportSwiftError() && SwiftErrorVal) 8333 isTailCall = false; 8334 8335 ConstantInt *CFIType = nullptr; 8336 if (CB.isIndirectCall()) { 8337 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) { 8338 if (!TLI.supportKCFIBundles()) 8339 report_fatal_error( 8340 "Target doesn't support calls with kcfi operand bundles."); 8341 CFIType = cast<ConstantInt>(Bundle->Inputs[0]); 8342 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type"); 8343 } 8344 } 8345 8346 TargetLowering::CallLoweringInfo CLI(DAG); 8347 CLI.setDebugLoc(getCurSDLoc()) 8348 .setChain(getRoot()) 8349 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 8350 .setTailCall(isTailCall) 8351 .setConvergent(CB.isConvergent()) 8352 .setIsPreallocated( 8353 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0) 8354 .setCFIType(CFIType); 8355 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8356 8357 if (Result.first.getNode()) { 8358 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 8359 setValue(&CB, Result.first); 8360 } 8361 8362 // The last element of CLI.InVals has the SDValue for swifterror return. 8363 // Here we copy it to a virtual register and update SwiftErrorMap for 8364 // book-keeping. 8365 if (SwiftErrorVal && TLI.supportSwiftError()) { 8366 // Get the last element of InVals. 8367 SDValue Src = CLI.InVals.back(); 8368 Register VReg = 8369 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 8370 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 8371 DAG.setRoot(CopyNode); 8372 } 8373 } 8374 8375 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 8376 SelectionDAGBuilder &Builder) { 8377 // Check to see if this load can be trivially constant folded, e.g. if the 8378 // input is from a string literal. 8379 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 8380 // Cast pointer to the type we really want to load. 8381 Type *LoadTy = 8382 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 8383 if (LoadVT.isVector()) 8384 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 8385 8386 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 8387 PointerType::getUnqual(LoadTy)); 8388 8389 if (const Constant *LoadCst = 8390 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput), 8391 LoadTy, Builder.DAG.getDataLayout())) 8392 return Builder.getValue(LoadCst); 8393 } 8394 8395 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 8396 // still constant memory, the input chain can be the entry node. 8397 SDValue Root; 8398 bool ConstantMemory = false; 8399 8400 // Do not serialize (non-volatile) loads of constant memory with anything. 8401 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 8402 Root = Builder.DAG.getEntryNode(); 8403 ConstantMemory = true; 8404 } else { 8405 // Do not serialize non-volatile loads against each other. 8406 Root = Builder.DAG.getRoot(); 8407 } 8408 8409 SDValue Ptr = Builder.getValue(PtrVal); 8410 SDValue LoadVal = 8411 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 8412 MachinePointerInfo(PtrVal), Align(1)); 8413 8414 if (!ConstantMemory) 8415 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 8416 return LoadVal; 8417 } 8418 8419 /// Record the value for an instruction that produces an integer result, 8420 /// converting the type where necessary. 8421 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 8422 SDValue Value, 8423 bool IsSigned) { 8424 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8425 I.getType(), true); 8426 Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT); 8427 setValue(&I, Value); 8428 } 8429 8430 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 8431 /// true and lower it. Otherwise return false, and it will be lowered like a 8432 /// normal call. 8433 /// The caller already checked that \p I calls the appropriate LibFunc with a 8434 /// correct prototype. 8435 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 8436 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 8437 const Value *Size = I.getArgOperand(2); 8438 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size)); 8439 if (CSize && CSize->getZExtValue() == 0) { 8440 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8441 I.getType(), true); 8442 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 8443 return true; 8444 } 8445 8446 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8447 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 8448 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 8449 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 8450 if (Res.first.getNode()) { 8451 processIntegerCallValue(I, Res.first, true); 8452 PendingLoads.push_back(Res.second); 8453 return true; 8454 } 8455 8456 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 8457 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 8458 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 8459 return false; 8460 8461 // If the target has a fast compare for the given size, it will return a 8462 // preferred load type for that size. Require that the load VT is legal and 8463 // that the target supports unaligned loads of that type. Otherwise, return 8464 // INVALID. 8465 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 8466 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8467 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 8468 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 8469 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 8470 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 8471 // TODO: Check alignment of src and dest ptrs. 8472 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 8473 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 8474 if (!TLI.isTypeLegal(LVT) || 8475 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 8476 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 8477 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 8478 } 8479 8480 return LVT; 8481 }; 8482 8483 // This turns into unaligned loads. We only do this if the target natively 8484 // supports the MVT we'll be loading or if it is small enough (<= 4) that 8485 // we'll only produce a small number of byte loads. 8486 MVT LoadVT; 8487 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 8488 switch (NumBitsToCompare) { 8489 default: 8490 return false; 8491 case 16: 8492 LoadVT = MVT::i16; 8493 break; 8494 case 32: 8495 LoadVT = MVT::i32; 8496 break; 8497 case 64: 8498 case 128: 8499 case 256: 8500 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 8501 break; 8502 } 8503 8504 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 8505 return false; 8506 8507 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 8508 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 8509 8510 // Bitcast to a wide integer type if the loads are vectors. 8511 if (LoadVT.isVector()) { 8512 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 8513 LoadL = DAG.getBitcast(CmpVT, LoadL); 8514 LoadR = DAG.getBitcast(CmpVT, LoadR); 8515 } 8516 8517 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 8518 processIntegerCallValue(I, Cmp, false); 8519 return true; 8520 } 8521 8522 /// See if we can lower a memchr call into an optimized form. If so, return 8523 /// true and lower it. Otherwise return false, and it will be lowered like a 8524 /// normal call. 8525 /// The caller already checked that \p I calls the appropriate LibFunc with a 8526 /// correct prototype. 8527 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 8528 const Value *Src = I.getArgOperand(0); 8529 const Value *Char = I.getArgOperand(1); 8530 const Value *Length = I.getArgOperand(2); 8531 8532 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8533 std::pair<SDValue, SDValue> Res = 8534 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 8535 getValue(Src), getValue(Char), getValue(Length), 8536 MachinePointerInfo(Src)); 8537 if (Res.first.getNode()) { 8538 setValue(&I, Res.first); 8539 PendingLoads.push_back(Res.second); 8540 return true; 8541 } 8542 8543 return false; 8544 } 8545 8546 /// See if we can lower a mempcpy call into an optimized form. If so, return 8547 /// true and lower it. Otherwise return false, and it will be lowered like a 8548 /// normal call. 8549 /// The caller already checked that \p I calls the appropriate LibFunc with a 8550 /// correct prototype. 8551 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 8552 SDValue Dst = getValue(I.getArgOperand(0)); 8553 SDValue Src = getValue(I.getArgOperand(1)); 8554 SDValue Size = getValue(I.getArgOperand(2)); 8555 8556 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 8557 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 8558 // DAG::getMemcpy needs Alignment to be defined. 8559 Align Alignment = std::min(DstAlign, SrcAlign); 8560 8561 SDLoc sdl = getCurSDLoc(); 8562 8563 // In the mempcpy context we need to pass in a false value for isTailCall 8564 // because the return pointer needs to be adjusted by the size of 8565 // the copied memory. 8566 SDValue Root = getMemoryRoot(); 8567 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, false, false, 8568 /*isTailCall=*/false, 8569 MachinePointerInfo(I.getArgOperand(0)), 8570 MachinePointerInfo(I.getArgOperand(1)), 8571 I.getAAMetadata()); 8572 assert(MC.getNode() != nullptr && 8573 "** memcpy should not be lowered as TailCall in mempcpy context **"); 8574 DAG.setRoot(MC); 8575 8576 // Check if Size needs to be truncated or extended. 8577 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 8578 8579 // Adjust return pointer to point just past the last dst byte. 8580 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 8581 Dst, Size); 8582 setValue(&I, DstPlusSize); 8583 return true; 8584 } 8585 8586 /// See if we can lower a strcpy call into an optimized form. If so, return 8587 /// true and lower it, otherwise return false and it will be lowered like a 8588 /// normal call. 8589 /// The caller already checked that \p I calls the appropriate LibFunc with a 8590 /// correct prototype. 8591 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 8592 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8593 8594 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8595 std::pair<SDValue, SDValue> Res = 8596 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 8597 getValue(Arg0), getValue(Arg1), 8598 MachinePointerInfo(Arg0), 8599 MachinePointerInfo(Arg1), isStpcpy); 8600 if (Res.first.getNode()) { 8601 setValue(&I, Res.first); 8602 DAG.setRoot(Res.second); 8603 return true; 8604 } 8605 8606 return false; 8607 } 8608 8609 /// See if we can lower a strcmp call into an optimized form. If so, return 8610 /// true and lower it, otherwise return false and it will be lowered like a 8611 /// normal call. 8612 /// The caller already checked that \p I calls the appropriate LibFunc with a 8613 /// correct prototype. 8614 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 8615 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8616 8617 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8618 std::pair<SDValue, SDValue> Res = 8619 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 8620 getValue(Arg0), getValue(Arg1), 8621 MachinePointerInfo(Arg0), 8622 MachinePointerInfo(Arg1)); 8623 if (Res.first.getNode()) { 8624 processIntegerCallValue(I, Res.first, true); 8625 PendingLoads.push_back(Res.second); 8626 return true; 8627 } 8628 8629 return false; 8630 } 8631 8632 /// See if we can lower a strlen call into an optimized form. If so, return 8633 /// true and lower it, otherwise return false and it will be lowered like a 8634 /// normal call. 8635 /// The caller already checked that \p I calls the appropriate LibFunc with a 8636 /// correct prototype. 8637 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 8638 const Value *Arg0 = I.getArgOperand(0); 8639 8640 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8641 std::pair<SDValue, SDValue> Res = 8642 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 8643 getValue(Arg0), MachinePointerInfo(Arg0)); 8644 if (Res.first.getNode()) { 8645 processIntegerCallValue(I, Res.first, false); 8646 PendingLoads.push_back(Res.second); 8647 return true; 8648 } 8649 8650 return false; 8651 } 8652 8653 /// See if we can lower a strnlen call into an optimized form. If so, return 8654 /// true and lower it, otherwise return false and it will be lowered like a 8655 /// normal call. 8656 /// The caller already checked that \p I calls the appropriate LibFunc with a 8657 /// correct prototype. 8658 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 8659 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8660 8661 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8662 std::pair<SDValue, SDValue> Res = 8663 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 8664 getValue(Arg0), getValue(Arg1), 8665 MachinePointerInfo(Arg0)); 8666 if (Res.first.getNode()) { 8667 processIntegerCallValue(I, Res.first, false); 8668 PendingLoads.push_back(Res.second); 8669 return true; 8670 } 8671 8672 return false; 8673 } 8674 8675 /// See if we can lower a unary floating-point operation into an SDNode with 8676 /// the specified Opcode. If so, return true and lower it, otherwise return 8677 /// false and it will be lowered like a normal call. 8678 /// The caller already checked that \p I calls the appropriate LibFunc with a 8679 /// correct prototype. 8680 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 8681 unsigned Opcode) { 8682 // We already checked this call's prototype; verify it doesn't modify errno. 8683 if (!I.onlyReadsMemory()) 8684 return false; 8685 8686 SDNodeFlags Flags; 8687 Flags.copyFMF(cast<FPMathOperator>(I)); 8688 8689 SDValue Tmp = getValue(I.getArgOperand(0)); 8690 setValue(&I, 8691 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 8692 return true; 8693 } 8694 8695 /// See if we can lower a binary floating-point operation into an SDNode with 8696 /// the specified Opcode. If so, return true and lower it. Otherwise return 8697 /// false, and it will be lowered like a normal call. 8698 /// The caller already checked that \p I calls the appropriate LibFunc with a 8699 /// correct prototype. 8700 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 8701 unsigned Opcode) { 8702 // We already checked this call's prototype; verify it doesn't modify errno. 8703 if (!I.onlyReadsMemory()) 8704 return false; 8705 8706 SDNodeFlags Flags; 8707 Flags.copyFMF(cast<FPMathOperator>(I)); 8708 8709 SDValue Tmp0 = getValue(I.getArgOperand(0)); 8710 SDValue Tmp1 = getValue(I.getArgOperand(1)); 8711 EVT VT = Tmp0.getValueType(); 8712 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 8713 return true; 8714 } 8715 8716 void SelectionDAGBuilder::visitCall(const CallInst &I) { 8717 // Handle inline assembly differently. 8718 if (I.isInlineAsm()) { 8719 visitInlineAsm(I); 8720 return; 8721 } 8722 8723 diagnoseDontCall(I); 8724 8725 if (Function *F = I.getCalledFunction()) { 8726 if (F->isDeclaration()) { 8727 // Is this an LLVM intrinsic or a target-specific intrinsic? 8728 unsigned IID = F->getIntrinsicID(); 8729 if (!IID) 8730 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 8731 IID = II->getIntrinsicID(F); 8732 8733 if (IID) { 8734 visitIntrinsicCall(I, IID); 8735 return; 8736 } 8737 } 8738 8739 // Check for well-known libc/libm calls. If the function is internal, it 8740 // can't be a library call. Don't do the check if marked as nobuiltin for 8741 // some reason or the call site requires strict floating point semantics. 8742 LibFunc Func; 8743 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 8744 F->hasName() && LibInfo->getLibFunc(*F, Func) && 8745 LibInfo->hasOptimizedCodeGen(Func)) { 8746 switch (Func) { 8747 default: break; 8748 case LibFunc_bcmp: 8749 if (visitMemCmpBCmpCall(I)) 8750 return; 8751 break; 8752 case LibFunc_copysign: 8753 case LibFunc_copysignf: 8754 case LibFunc_copysignl: 8755 // We already checked this call's prototype; verify it doesn't modify 8756 // errno. 8757 if (I.onlyReadsMemory()) { 8758 SDValue LHS = getValue(I.getArgOperand(0)); 8759 SDValue RHS = getValue(I.getArgOperand(1)); 8760 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 8761 LHS.getValueType(), LHS, RHS)); 8762 return; 8763 } 8764 break; 8765 case LibFunc_fabs: 8766 case LibFunc_fabsf: 8767 case LibFunc_fabsl: 8768 if (visitUnaryFloatCall(I, ISD::FABS)) 8769 return; 8770 break; 8771 case LibFunc_fmin: 8772 case LibFunc_fminf: 8773 case LibFunc_fminl: 8774 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 8775 return; 8776 break; 8777 case LibFunc_fmax: 8778 case LibFunc_fmaxf: 8779 case LibFunc_fmaxl: 8780 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 8781 return; 8782 break; 8783 case LibFunc_sin: 8784 case LibFunc_sinf: 8785 case LibFunc_sinl: 8786 if (visitUnaryFloatCall(I, ISD::FSIN)) 8787 return; 8788 break; 8789 case LibFunc_cos: 8790 case LibFunc_cosf: 8791 case LibFunc_cosl: 8792 if (visitUnaryFloatCall(I, ISD::FCOS)) 8793 return; 8794 break; 8795 case LibFunc_sqrt: 8796 case LibFunc_sqrtf: 8797 case LibFunc_sqrtl: 8798 case LibFunc_sqrt_finite: 8799 case LibFunc_sqrtf_finite: 8800 case LibFunc_sqrtl_finite: 8801 if (visitUnaryFloatCall(I, ISD::FSQRT)) 8802 return; 8803 break; 8804 case LibFunc_floor: 8805 case LibFunc_floorf: 8806 case LibFunc_floorl: 8807 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 8808 return; 8809 break; 8810 case LibFunc_nearbyint: 8811 case LibFunc_nearbyintf: 8812 case LibFunc_nearbyintl: 8813 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 8814 return; 8815 break; 8816 case LibFunc_ceil: 8817 case LibFunc_ceilf: 8818 case LibFunc_ceill: 8819 if (visitUnaryFloatCall(I, ISD::FCEIL)) 8820 return; 8821 break; 8822 case LibFunc_rint: 8823 case LibFunc_rintf: 8824 case LibFunc_rintl: 8825 if (visitUnaryFloatCall(I, ISD::FRINT)) 8826 return; 8827 break; 8828 case LibFunc_round: 8829 case LibFunc_roundf: 8830 case LibFunc_roundl: 8831 if (visitUnaryFloatCall(I, ISD::FROUND)) 8832 return; 8833 break; 8834 case LibFunc_trunc: 8835 case LibFunc_truncf: 8836 case LibFunc_truncl: 8837 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 8838 return; 8839 break; 8840 case LibFunc_log2: 8841 case LibFunc_log2f: 8842 case LibFunc_log2l: 8843 if (visitUnaryFloatCall(I, ISD::FLOG2)) 8844 return; 8845 break; 8846 case LibFunc_exp2: 8847 case LibFunc_exp2f: 8848 case LibFunc_exp2l: 8849 if (visitUnaryFloatCall(I, ISD::FEXP2)) 8850 return; 8851 break; 8852 case LibFunc_exp10: 8853 case LibFunc_exp10f: 8854 case LibFunc_exp10l: 8855 if (visitUnaryFloatCall(I, ISD::FEXP10)) 8856 return; 8857 break; 8858 case LibFunc_ldexp: 8859 case LibFunc_ldexpf: 8860 case LibFunc_ldexpl: 8861 if (visitBinaryFloatCall(I, ISD::FLDEXP)) 8862 return; 8863 break; 8864 case LibFunc_memcmp: 8865 if (visitMemCmpBCmpCall(I)) 8866 return; 8867 break; 8868 case LibFunc_mempcpy: 8869 if (visitMemPCpyCall(I)) 8870 return; 8871 break; 8872 case LibFunc_memchr: 8873 if (visitMemChrCall(I)) 8874 return; 8875 break; 8876 case LibFunc_strcpy: 8877 if (visitStrCpyCall(I, false)) 8878 return; 8879 break; 8880 case LibFunc_stpcpy: 8881 if (visitStrCpyCall(I, true)) 8882 return; 8883 break; 8884 case LibFunc_strcmp: 8885 if (visitStrCmpCall(I)) 8886 return; 8887 break; 8888 case LibFunc_strlen: 8889 if (visitStrLenCall(I)) 8890 return; 8891 break; 8892 case LibFunc_strnlen: 8893 if (visitStrNLenCall(I)) 8894 return; 8895 break; 8896 } 8897 } 8898 } 8899 8900 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 8901 // have to do anything here to lower funclet bundles. 8902 // CFGuardTarget bundles are lowered in LowerCallTo. 8903 assert(!I.hasOperandBundlesOtherThan( 8904 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 8905 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 8906 LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) && 8907 "Cannot lower calls with arbitrary operand bundles!"); 8908 8909 SDValue Callee = getValue(I.getCalledOperand()); 8910 8911 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 8912 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 8913 else 8914 // Check if we can potentially perform a tail call. More detailed checking 8915 // is be done within LowerCallTo, after more information about the call is 8916 // known. 8917 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 8918 } 8919 8920 namespace { 8921 8922 /// AsmOperandInfo - This contains information for each constraint that we are 8923 /// lowering. 8924 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 8925 public: 8926 /// CallOperand - If this is the result output operand or a clobber 8927 /// this is null, otherwise it is the incoming operand to the CallInst. 8928 /// This gets modified as the asm is processed. 8929 SDValue CallOperand; 8930 8931 /// AssignedRegs - If this is a register or register class operand, this 8932 /// contains the set of register corresponding to the operand. 8933 RegsForValue AssignedRegs; 8934 8935 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 8936 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 8937 } 8938 8939 /// Whether or not this operand accesses memory 8940 bool hasMemory(const TargetLowering &TLI) const { 8941 // Indirect operand accesses access memory. 8942 if (isIndirect) 8943 return true; 8944 8945 for (const auto &Code : Codes) 8946 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 8947 return true; 8948 8949 return false; 8950 } 8951 }; 8952 8953 8954 } // end anonymous namespace 8955 8956 /// Make sure that the output operand \p OpInfo and its corresponding input 8957 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 8958 /// out). 8959 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 8960 SDISelAsmOperandInfo &MatchingOpInfo, 8961 SelectionDAG &DAG) { 8962 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 8963 return; 8964 8965 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 8966 const auto &TLI = DAG.getTargetLoweringInfo(); 8967 8968 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 8969 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 8970 OpInfo.ConstraintVT); 8971 std::pair<unsigned, const TargetRegisterClass *> InputRC = 8972 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 8973 MatchingOpInfo.ConstraintVT); 8974 if ((OpInfo.ConstraintVT.isInteger() != 8975 MatchingOpInfo.ConstraintVT.isInteger()) || 8976 (MatchRC.second != InputRC.second)) { 8977 // FIXME: error out in a more elegant fashion 8978 report_fatal_error("Unsupported asm: input constraint" 8979 " with a matching output constraint of" 8980 " incompatible type!"); 8981 } 8982 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 8983 } 8984 8985 /// Get a direct memory input to behave well as an indirect operand. 8986 /// This may introduce stores, hence the need for a \p Chain. 8987 /// \return The (possibly updated) chain. 8988 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 8989 SDISelAsmOperandInfo &OpInfo, 8990 SelectionDAG &DAG) { 8991 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8992 8993 // If we don't have an indirect input, put it in the constpool if we can, 8994 // otherwise spill it to a stack slot. 8995 // TODO: This isn't quite right. We need to handle these according to 8996 // the addressing mode that the constraint wants. Also, this may take 8997 // an additional register for the computation and we don't want that 8998 // either. 8999 9000 // If the operand is a float, integer, or vector constant, spill to a 9001 // constant pool entry to get its address. 9002 const Value *OpVal = OpInfo.CallOperandVal; 9003 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 9004 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 9005 OpInfo.CallOperand = DAG.getConstantPool( 9006 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 9007 return Chain; 9008 } 9009 9010 // Otherwise, create a stack slot and emit a store to it before the asm. 9011 Type *Ty = OpVal->getType(); 9012 auto &DL = DAG.getDataLayout(); 9013 uint64_t TySize = DL.getTypeAllocSize(Ty); 9014 MachineFunction &MF = DAG.getMachineFunction(); 9015 int SSFI = MF.getFrameInfo().CreateStackObject( 9016 TySize, DL.getPrefTypeAlign(Ty), false); 9017 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 9018 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 9019 MachinePointerInfo::getFixedStack(MF, SSFI), 9020 TLI.getMemValueType(DL, Ty)); 9021 OpInfo.CallOperand = StackSlot; 9022 9023 return Chain; 9024 } 9025 9026 /// GetRegistersForValue - Assign registers (virtual or physical) for the 9027 /// specified operand. We prefer to assign virtual registers, to allow the 9028 /// register allocator to handle the assignment process. However, if the asm 9029 /// uses features that we can't model on machineinstrs, we have SDISel do the 9030 /// allocation. This produces generally horrible, but correct, code. 9031 /// 9032 /// OpInfo describes the operand 9033 /// RefOpInfo describes the matching operand if any, the operand otherwise 9034 static std::optional<unsigned> 9035 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 9036 SDISelAsmOperandInfo &OpInfo, 9037 SDISelAsmOperandInfo &RefOpInfo) { 9038 LLVMContext &Context = *DAG.getContext(); 9039 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9040 9041 MachineFunction &MF = DAG.getMachineFunction(); 9042 SmallVector<unsigned, 4> Regs; 9043 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9044 9045 // No work to do for memory/address operands. 9046 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 9047 OpInfo.ConstraintType == TargetLowering::C_Address) 9048 return std::nullopt; 9049 9050 // If this is a constraint for a single physreg, or a constraint for a 9051 // register class, find it. 9052 unsigned AssignedReg; 9053 const TargetRegisterClass *RC; 9054 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 9055 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 9056 // RC is unset only on failure. Return immediately. 9057 if (!RC) 9058 return std::nullopt; 9059 9060 // Get the actual register value type. This is important, because the user 9061 // may have asked for (e.g.) the AX register in i32 type. We need to 9062 // remember that AX is actually i16 to get the right extension. 9063 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 9064 9065 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) { 9066 // If this is an FP operand in an integer register (or visa versa), or more 9067 // generally if the operand value disagrees with the register class we plan 9068 // to stick it in, fix the operand type. 9069 // 9070 // If this is an input value, the bitcast to the new type is done now. 9071 // Bitcast for output value is done at the end of visitInlineAsm(). 9072 if ((OpInfo.Type == InlineAsm::isOutput || 9073 OpInfo.Type == InlineAsm::isInput) && 9074 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 9075 // Try to convert to the first EVT that the reg class contains. If the 9076 // types are identical size, use a bitcast to convert (e.g. two differing 9077 // vector types). Note: output bitcast is done at the end of 9078 // visitInlineAsm(). 9079 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 9080 // Exclude indirect inputs while they are unsupported because the code 9081 // to perform the load is missing and thus OpInfo.CallOperand still 9082 // refers to the input address rather than the pointed-to value. 9083 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 9084 OpInfo.CallOperand = 9085 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 9086 OpInfo.ConstraintVT = RegVT; 9087 // If the operand is an FP value and we want it in integer registers, 9088 // use the corresponding integer type. This turns an f64 value into 9089 // i64, which can be passed with two i32 values on a 32-bit machine. 9090 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 9091 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 9092 if (OpInfo.Type == InlineAsm::isInput) 9093 OpInfo.CallOperand = 9094 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 9095 OpInfo.ConstraintVT = VT; 9096 } 9097 } 9098 } 9099 9100 // No need to allocate a matching input constraint since the constraint it's 9101 // matching to has already been allocated. 9102 if (OpInfo.isMatchingInputConstraint()) 9103 return std::nullopt; 9104 9105 EVT ValueVT = OpInfo.ConstraintVT; 9106 if (OpInfo.ConstraintVT == MVT::Other) 9107 ValueVT = RegVT; 9108 9109 // Initialize NumRegs. 9110 unsigned NumRegs = 1; 9111 if (OpInfo.ConstraintVT != MVT::Other) 9112 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT); 9113 9114 // If this is a constraint for a specific physical register, like {r17}, 9115 // assign it now. 9116 9117 // If this associated to a specific register, initialize iterator to correct 9118 // place. If virtual, make sure we have enough registers 9119 9120 // Initialize iterator if necessary 9121 TargetRegisterClass::iterator I = RC->begin(); 9122 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9123 9124 // Do not check for single registers. 9125 if (AssignedReg) { 9126 I = std::find(I, RC->end(), AssignedReg); 9127 if (I == RC->end()) { 9128 // RC does not contain the selected register, which indicates a 9129 // mismatch between the register and the required type/bitwidth. 9130 return {AssignedReg}; 9131 } 9132 } 9133 9134 for (; NumRegs; --NumRegs, ++I) { 9135 assert(I != RC->end() && "Ran out of registers to allocate!"); 9136 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 9137 Regs.push_back(R); 9138 } 9139 9140 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 9141 return std::nullopt; 9142 } 9143 9144 static unsigned 9145 findMatchingInlineAsmOperand(unsigned OperandNo, 9146 const std::vector<SDValue> &AsmNodeOperands) { 9147 // Scan until we find the definition we already emitted of this operand. 9148 unsigned CurOp = InlineAsm::Op_FirstOperand; 9149 for (; OperandNo; --OperandNo) { 9150 // Advance to the next operand. 9151 unsigned OpFlag = 9152 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 9153 const InlineAsm::Flag F(OpFlag); 9154 assert( 9155 (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) && 9156 "Skipped past definitions?"); 9157 CurOp += F.getNumOperandRegisters() + 1; 9158 } 9159 return CurOp; 9160 } 9161 9162 namespace { 9163 9164 class ExtraFlags { 9165 unsigned Flags = 0; 9166 9167 public: 9168 explicit ExtraFlags(const CallBase &Call) { 9169 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 9170 if (IA->hasSideEffects()) 9171 Flags |= InlineAsm::Extra_HasSideEffects; 9172 if (IA->isAlignStack()) 9173 Flags |= InlineAsm::Extra_IsAlignStack; 9174 if (Call.isConvergent()) 9175 Flags |= InlineAsm::Extra_IsConvergent; 9176 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 9177 } 9178 9179 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 9180 // Ideally, we would only check against memory constraints. However, the 9181 // meaning of an Other constraint can be target-specific and we can't easily 9182 // reason about it. Therefore, be conservative and set MayLoad/MayStore 9183 // for Other constraints as well. 9184 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 9185 OpInfo.ConstraintType == TargetLowering::C_Other) { 9186 if (OpInfo.Type == InlineAsm::isInput) 9187 Flags |= InlineAsm::Extra_MayLoad; 9188 else if (OpInfo.Type == InlineAsm::isOutput) 9189 Flags |= InlineAsm::Extra_MayStore; 9190 else if (OpInfo.Type == InlineAsm::isClobber) 9191 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 9192 } 9193 } 9194 9195 unsigned get() const { return Flags; } 9196 }; 9197 9198 } // end anonymous namespace 9199 9200 static bool isFunction(SDValue Op) { 9201 if (Op && Op.getOpcode() == ISD::GlobalAddress) { 9202 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 9203 auto Fn = dyn_cast_or_null<Function>(GA->getGlobal()); 9204 9205 // In normal "call dllimport func" instruction (non-inlineasm) it force 9206 // indirect access by specifing call opcode. And usually specially print 9207 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can 9208 // not do in this way now. (In fact, this is similar with "Data Access" 9209 // action). So here we ignore dllimport function. 9210 if (Fn && !Fn->hasDLLImportStorageClass()) 9211 return true; 9212 } 9213 } 9214 return false; 9215 } 9216 9217 /// visitInlineAsm - Handle a call to an InlineAsm object. 9218 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 9219 const BasicBlock *EHPadBB) { 9220 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 9221 9222 /// ConstraintOperands - Information about all of the constraints. 9223 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 9224 9225 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9226 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 9227 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 9228 9229 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 9230 // AsmDialect, MayLoad, MayStore). 9231 bool HasSideEffect = IA->hasSideEffects(); 9232 ExtraFlags ExtraInfo(Call); 9233 9234 for (auto &T : TargetConstraints) { 9235 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 9236 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 9237 9238 if (OpInfo.CallOperandVal) 9239 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 9240 9241 if (!HasSideEffect) 9242 HasSideEffect = OpInfo.hasMemory(TLI); 9243 9244 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 9245 // FIXME: Could we compute this on OpInfo rather than T? 9246 9247 // Compute the constraint code and ConstraintType to use. 9248 TLI.ComputeConstraintToUse(T, SDValue()); 9249 9250 if (T.ConstraintType == TargetLowering::C_Immediate && 9251 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 9252 // We've delayed emitting a diagnostic like the "n" constraint because 9253 // inlining could cause an integer showing up. 9254 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 9255 "' expects an integer constant " 9256 "expression"); 9257 9258 ExtraInfo.update(T); 9259 } 9260 9261 // We won't need to flush pending loads if this asm doesn't touch 9262 // memory and is nonvolatile. 9263 SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 9264 9265 bool EmitEHLabels = isa<InvokeInst>(Call); 9266 if (EmitEHLabels) { 9267 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 9268 } 9269 bool IsCallBr = isa<CallBrInst>(Call); 9270 9271 if (IsCallBr || EmitEHLabels) { 9272 // If this is a callbr or invoke we need to flush pending exports since 9273 // inlineasm_br and invoke are terminators. 9274 // We need to do this before nodes are glued to the inlineasm_br node. 9275 Chain = getControlRoot(); 9276 } 9277 9278 MCSymbol *BeginLabel = nullptr; 9279 if (EmitEHLabels) { 9280 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 9281 } 9282 9283 int OpNo = -1; 9284 SmallVector<StringRef> AsmStrs; 9285 IA->collectAsmStrs(AsmStrs); 9286 9287 // Second pass over the constraints: compute which constraint option to use. 9288 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9289 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput) 9290 OpNo++; 9291 9292 // If this is an output operand with a matching input operand, look up the 9293 // matching input. If their types mismatch, e.g. one is an integer, the 9294 // other is floating point, or their sizes are different, flag it as an 9295 // error. 9296 if (OpInfo.hasMatchingInput()) { 9297 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 9298 patchMatchingInput(OpInfo, Input, DAG); 9299 } 9300 9301 // Compute the constraint code and ConstraintType to use. 9302 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 9303 9304 if ((OpInfo.ConstraintType == TargetLowering::C_Memory && 9305 OpInfo.Type == InlineAsm::isClobber) || 9306 OpInfo.ConstraintType == TargetLowering::C_Address) 9307 continue; 9308 9309 // In Linux PIC model, there are 4 cases about value/label addressing: 9310 // 9311 // 1: Function call or Label jmp inside the module. 9312 // 2: Data access (such as global variable, static variable) inside module. 9313 // 3: Function call or Label jmp outside the module. 9314 // 4: Data access (such as global variable) outside the module. 9315 // 9316 // Due to current llvm inline asm architecture designed to not "recognize" 9317 // the asm code, there are quite troubles for us to treat mem addressing 9318 // differently for same value/adress used in different instuctions. 9319 // For example, in pic model, call a func may in plt way or direclty 9320 // pc-related, but lea/mov a function adress may use got. 9321 // 9322 // Here we try to "recognize" function call for the case 1 and case 3 in 9323 // inline asm. And try to adjust the constraint for them. 9324 // 9325 // TODO: Due to current inline asm didn't encourage to jmp to the outsider 9326 // label, so here we don't handle jmp function label now, but we need to 9327 // enhance it (especilly in PIC model) if we meet meaningful requirements. 9328 if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) && 9329 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) && 9330 TM.getCodeModel() != CodeModel::Large) { 9331 OpInfo.isIndirect = false; 9332 OpInfo.ConstraintType = TargetLowering::C_Address; 9333 } 9334 9335 // If this is a memory input, and if the operand is not indirect, do what we 9336 // need to provide an address for the memory input. 9337 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 9338 !OpInfo.isIndirect) { 9339 assert((OpInfo.isMultipleAlternative || 9340 (OpInfo.Type == InlineAsm::isInput)) && 9341 "Can only indirectify direct input operands!"); 9342 9343 // Memory operands really want the address of the value. 9344 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 9345 9346 // There is no longer a Value* corresponding to this operand. 9347 OpInfo.CallOperandVal = nullptr; 9348 9349 // It is now an indirect operand. 9350 OpInfo.isIndirect = true; 9351 } 9352 9353 } 9354 9355 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 9356 std::vector<SDValue> AsmNodeOperands; 9357 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 9358 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 9359 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 9360 9361 // If we have a !srcloc metadata node associated with it, we want to attach 9362 // this to the ultimately generated inline asm machineinstr. To do this, we 9363 // pass in the third operand as this (potentially null) inline asm MDNode. 9364 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 9365 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 9366 9367 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 9368 // bits as operand 3. 9369 AsmNodeOperands.push_back(DAG.getTargetConstant( 9370 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9371 9372 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 9373 // this, assign virtual and physical registers for inputs and otput. 9374 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9375 // Assign Registers. 9376 SDISelAsmOperandInfo &RefOpInfo = 9377 OpInfo.isMatchingInputConstraint() 9378 ? ConstraintOperands[OpInfo.getMatchedOperand()] 9379 : OpInfo; 9380 const auto RegError = 9381 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 9382 if (RegError) { 9383 const MachineFunction &MF = DAG.getMachineFunction(); 9384 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9385 const char *RegName = TRI.getName(*RegError); 9386 emitInlineAsmError(Call, "register '" + Twine(RegName) + 9387 "' allocated for constraint '" + 9388 Twine(OpInfo.ConstraintCode) + 9389 "' does not match required type"); 9390 return; 9391 } 9392 9393 auto DetectWriteToReservedRegister = [&]() { 9394 const MachineFunction &MF = DAG.getMachineFunction(); 9395 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9396 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 9397 if (Register::isPhysicalRegister(Reg) && 9398 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 9399 const char *RegName = TRI.getName(Reg); 9400 emitInlineAsmError(Call, "write to reserved register '" + 9401 Twine(RegName) + "'"); 9402 return true; 9403 } 9404 } 9405 return false; 9406 }; 9407 assert((OpInfo.ConstraintType != TargetLowering::C_Address || 9408 (OpInfo.Type == InlineAsm::isInput && 9409 !OpInfo.isMatchingInputConstraint())) && 9410 "Only address as input operand is allowed."); 9411 9412 switch (OpInfo.Type) { 9413 case InlineAsm::isOutput: 9414 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9415 const InlineAsm::ConstraintCode ConstraintID = 9416 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9417 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 9418 "Failed to convert memory constraint code to constraint id."); 9419 9420 // Add information to the INLINEASM node to know about this output. 9421 InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1); 9422 OpFlags.setMemConstraint(ConstraintID); 9423 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 9424 MVT::i32)); 9425 AsmNodeOperands.push_back(OpInfo.CallOperand); 9426 } else { 9427 // Otherwise, this outputs to a register (directly for C_Register / 9428 // C_RegisterClass, and a target-defined fashion for 9429 // C_Immediate/C_Other). Find a register that we can use. 9430 if (OpInfo.AssignedRegs.Regs.empty()) { 9431 emitInlineAsmError( 9432 Call, "couldn't allocate output register for constraint '" + 9433 Twine(OpInfo.ConstraintCode) + "'"); 9434 return; 9435 } 9436 9437 if (DetectWriteToReservedRegister()) 9438 return; 9439 9440 // Add information to the INLINEASM node to know that this register is 9441 // set. 9442 OpInfo.AssignedRegs.AddInlineAsmOperands( 9443 OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber 9444 : InlineAsm::Kind::RegDef, 9445 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 9446 } 9447 break; 9448 9449 case InlineAsm::isInput: 9450 case InlineAsm::isLabel: { 9451 SDValue InOperandVal = OpInfo.CallOperand; 9452 9453 if (OpInfo.isMatchingInputConstraint()) { 9454 // If this is required to match an output register we have already set, 9455 // just use its register. 9456 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 9457 AsmNodeOperands); 9458 InlineAsm::Flag Flag( 9459 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue()); 9460 if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) { 9461 if (OpInfo.isIndirect) { 9462 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 9463 emitInlineAsmError(Call, "inline asm not supported yet: " 9464 "don't know how to handle tied " 9465 "indirect register inputs"); 9466 return; 9467 } 9468 9469 SmallVector<unsigned, 4> Regs; 9470 MachineFunction &MF = DAG.getMachineFunction(); 9471 MachineRegisterInfo &MRI = MF.getRegInfo(); 9472 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9473 auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]); 9474 Register TiedReg = R->getReg(); 9475 MVT RegVT = R->getSimpleValueType(0); 9476 const TargetRegisterClass *RC = 9477 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg) 9478 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT) 9479 : TRI.getMinimalPhysRegClass(TiedReg); 9480 for (unsigned i = 0, e = Flag.getNumOperandRegisters(); i != e; ++i) 9481 Regs.push_back(MRI.createVirtualRegister(RC)); 9482 9483 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 9484 9485 SDLoc dl = getCurSDLoc(); 9486 // Use the produced MatchedRegs object to 9487 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call); 9488 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, true, 9489 OpInfo.getMatchedOperand(), dl, DAG, 9490 AsmNodeOperands); 9491 break; 9492 } 9493 9494 assert(Flag.isMemKind() && "Unknown matching constraint!"); 9495 assert(Flag.getNumOperandRegisters() == 1 && 9496 "Unexpected number of operands"); 9497 // Add information to the INLINEASM node to know about this input. 9498 // See InlineAsm.h isUseOperandTiedToDef. 9499 Flag.clearMemConstraint(); 9500 Flag.setMatchingOp(OpInfo.getMatchedOperand()); 9501 AsmNodeOperands.push_back(DAG.getTargetConstant( 9502 Flag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9503 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 9504 break; 9505 } 9506 9507 // Treat indirect 'X' constraint as memory. 9508 if (OpInfo.ConstraintType == TargetLowering::C_Other && 9509 OpInfo.isIndirect) 9510 OpInfo.ConstraintType = TargetLowering::C_Memory; 9511 9512 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 9513 OpInfo.ConstraintType == TargetLowering::C_Other) { 9514 std::vector<SDValue> Ops; 9515 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 9516 Ops, DAG); 9517 if (Ops.empty()) { 9518 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 9519 if (isa<ConstantSDNode>(InOperandVal)) { 9520 emitInlineAsmError(Call, "value out of range for constraint '" + 9521 Twine(OpInfo.ConstraintCode) + "'"); 9522 return; 9523 } 9524 9525 emitInlineAsmError(Call, 9526 "invalid operand for inline asm constraint '" + 9527 Twine(OpInfo.ConstraintCode) + "'"); 9528 return; 9529 } 9530 9531 // Add information to the INLINEASM node to know about this input. 9532 InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size()); 9533 AsmNodeOperands.push_back(DAG.getTargetConstant( 9534 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9535 llvm::append_range(AsmNodeOperands, Ops); 9536 break; 9537 } 9538 9539 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9540 assert((OpInfo.isIndirect || 9541 OpInfo.ConstraintType != TargetLowering::C_Memory) && 9542 "Operand must be indirect to be a mem!"); 9543 assert(InOperandVal.getValueType() == 9544 TLI.getPointerTy(DAG.getDataLayout()) && 9545 "Memory operands expect pointer values"); 9546 9547 const InlineAsm::ConstraintCode ConstraintID = 9548 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9549 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 9550 "Failed to convert memory constraint code to constraint id."); 9551 9552 // Add information to the INLINEASM node to know about this input. 9553 InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1); 9554 ResOpType.setMemConstraint(ConstraintID); 9555 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 9556 getCurSDLoc(), 9557 MVT::i32)); 9558 AsmNodeOperands.push_back(InOperandVal); 9559 break; 9560 } 9561 9562 if (OpInfo.ConstraintType == TargetLowering::C_Address) { 9563 const InlineAsm::ConstraintCode ConstraintID = 9564 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9565 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 9566 "Failed to convert memory constraint code to constraint id."); 9567 9568 InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1); 9569 9570 SDValue AsmOp = InOperandVal; 9571 if (isFunction(InOperandVal)) { 9572 auto *GA = cast<GlobalAddressSDNode>(InOperandVal); 9573 ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1); 9574 AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(), 9575 InOperandVal.getValueType(), 9576 GA->getOffset()); 9577 } 9578 9579 // Add information to the INLINEASM node to know about this input. 9580 ResOpType.setMemConstraint(ConstraintID); 9581 9582 AsmNodeOperands.push_back( 9583 DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32)); 9584 9585 AsmNodeOperands.push_back(AsmOp); 9586 break; 9587 } 9588 9589 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 9590 OpInfo.ConstraintType == TargetLowering::C_Register) && 9591 "Unknown constraint type!"); 9592 9593 // TODO: Support this. 9594 if (OpInfo.isIndirect) { 9595 emitInlineAsmError( 9596 Call, "Don't know how to handle indirect register inputs yet " 9597 "for constraint '" + 9598 Twine(OpInfo.ConstraintCode) + "'"); 9599 return; 9600 } 9601 9602 // Copy the input into the appropriate registers. 9603 if (OpInfo.AssignedRegs.Regs.empty()) { 9604 emitInlineAsmError(Call, 9605 "couldn't allocate input reg for constraint '" + 9606 Twine(OpInfo.ConstraintCode) + "'"); 9607 return; 9608 } 9609 9610 if (DetectWriteToReservedRegister()) 9611 return; 9612 9613 SDLoc dl = getCurSDLoc(); 9614 9615 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, 9616 &Call); 9617 9618 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, false, 9619 0, dl, DAG, AsmNodeOperands); 9620 break; 9621 } 9622 case InlineAsm::isClobber: 9623 // Add the clobbered value to the operand list, so that the register 9624 // allocator is aware that the physreg got clobbered. 9625 if (!OpInfo.AssignedRegs.Regs.empty()) 9626 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::Clobber, 9627 false, 0, getCurSDLoc(), DAG, 9628 AsmNodeOperands); 9629 break; 9630 } 9631 } 9632 9633 // Finish up input operands. Set the input chain and add the flag last. 9634 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 9635 if (Glue.getNode()) AsmNodeOperands.push_back(Glue); 9636 9637 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 9638 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 9639 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 9640 Glue = Chain.getValue(1); 9641 9642 // Do additional work to generate outputs. 9643 9644 SmallVector<EVT, 1> ResultVTs; 9645 SmallVector<SDValue, 1> ResultValues; 9646 SmallVector<SDValue, 8> OutChains; 9647 9648 llvm::Type *CallResultType = Call.getType(); 9649 ArrayRef<Type *> ResultTypes; 9650 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 9651 ResultTypes = StructResult->elements(); 9652 else if (!CallResultType->isVoidTy()) 9653 ResultTypes = ArrayRef(CallResultType); 9654 9655 auto CurResultType = ResultTypes.begin(); 9656 auto handleRegAssign = [&](SDValue V) { 9657 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 9658 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 9659 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 9660 ++CurResultType; 9661 // If the type of the inline asm call site return value is different but has 9662 // same size as the type of the asm output bitcast it. One example of this 9663 // is for vectors with different width / number of elements. This can 9664 // happen for register classes that can contain multiple different value 9665 // types. The preg or vreg allocated may not have the same VT as was 9666 // expected. 9667 // 9668 // This can also happen for a return value that disagrees with the register 9669 // class it is put in, eg. a double in a general-purpose register on a 9670 // 32-bit machine. 9671 if (ResultVT != V.getValueType() && 9672 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 9673 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 9674 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 9675 V.getValueType().isInteger()) { 9676 // If a result value was tied to an input value, the computed result 9677 // may have a wider width than the expected result. Extract the 9678 // relevant portion. 9679 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 9680 } 9681 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 9682 ResultVTs.push_back(ResultVT); 9683 ResultValues.push_back(V); 9684 }; 9685 9686 // Deal with output operands. 9687 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9688 if (OpInfo.Type == InlineAsm::isOutput) { 9689 SDValue Val; 9690 // Skip trivial output operands. 9691 if (OpInfo.AssignedRegs.Regs.empty()) 9692 continue; 9693 9694 switch (OpInfo.ConstraintType) { 9695 case TargetLowering::C_Register: 9696 case TargetLowering::C_RegisterClass: 9697 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 9698 Chain, &Glue, &Call); 9699 break; 9700 case TargetLowering::C_Immediate: 9701 case TargetLowering::C_Other: 9702 Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(), 9703 OpInfo, DAG); 9704 break; 9705 case TargetLowering::C_Memory: 9706 break; // Already handled. 9707 case TargetLowering::C_Address: 9708 break; // Silence warning. 9709 case TargetLowering::C_Unknown: 9710 assert(false && "Unexpected unknown constraint"); 9711 } 9712 9713 // Indirect output manifest as stores. Record output chains. 9714 if (OpInfo.isIndirect) { 9715 const Value *Ptr = OpInfo.CallOperandVal; 9716 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 9717 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 9718 MachinePointerInfo(Ptr)); 9719 OutChains.push_back(Store); 9720 } else { 9721 // generate CopyFromRegs to associated registers. 9722 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 9723 if (Val.getOpcode() == ISD::MERGE_VALUES) { 9724 for (const SDValue &V : Val->op_values()) 9725 handleRegAssign(V); 9726 } else 9727 handleRegAssign(Val); 9728 } 9729 } 9730 } 9731 9732 // Set results. 9733 if (!ResultValues.empty()) { 9734 assert(CurResultType == ResultTypes.end() && 9735 "Mismatch in number of ResultTypes"); 9736 assert(ResultValues.size() == ResultTypes.size() && 9737 "Mismatch in number of output operands in asm result"); 9738 9739 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 9740 DAG.getVTList(ResultVTs), ResultValues); 9741 setValue(&Call, V); 9742 } 9743 9744 // Collect store chains. 9745 if (!OutChains.empty()) 9746 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 9747 9748 if (EmitEHLabels) { 9749 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 9750 } 9751 9752 // Only Update Root if inline assembly has a memory effect. 9753 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 9754 EmitEHLabels) 9755 DAG.setRoot(Chain); 9756 } 9757 9758 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 9759 const Twine &Message) { 9760 LLVMContext &Ctx = *DAG.getContext(); 9761 Ctx.emitError(&Call, Message); 9762 9763 // Make sure we leave the DAG in a valid state 9764 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9765 SmallVector<EVT, 1> ValueVTs; 9766 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 9767 9768 if (ValueVTs.empty()) 9769 return; 9770 9771 SmallVector<SDValue, 1> Ops; 9772 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 9773 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 9774 9775 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 9776 } 9777 9778 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 9779 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 9780 MVT::Other, getRoot(), 9781 getValue(I.getArgOperand(0)), 9782 DAG.getSrcValue(I.getArgOperand(0)))); 9783 } 9784 9785 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 9786 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9787 const DataLayout &DL = DAG.getDataLayout(); 9788 SDValue V = DAG.getVAArg( 9789 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 9790 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 9791 DL.getABITypeAlign(I.getType()).value()); 9792 DAG.setRoot(V.getValue(1)); 9793 9794 if (I.getType()->isPointerTy()) 9795 V = DAG.getPtrExtOrTrunc( 9796 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 9797 setValue(&I, V); 9798 } 9799 9800 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 9801 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 9802 MVT::Other, getRoot(), 9803 getValue(I.getArgOperand(0)), 9804 DAG.getSrcValue(I.getArgOperand(0)))); 9805 } 9806 9807 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 9808 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 9809 MVT::Other, getRoot(), 9810 getValue(I.getArgOperand(0)), 9811 getValue(I.getArgOperand(1)), 9812 DAG.getSrcValue(I.getArgOperand(0)), 9813 DAG.getSrcValue(I.getArgOperand(1)))); 9814 } 9815 9816 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 9817 const Instruction &I, 9818 SDValue Op) { 9819 const MDNode *Range = getRangeMetadata(I); 9820 if (!Range) 9821 return Op; 9822 9823 ConstantRange CR = getConstantRangeFromMetadata(*Range); 9824 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 9825 return Op; 9826 9827 APInt Lo = CR.getUnsignedMin(); 9828 if (!Lo.isMinValue()) 9829 return Op; 9830 9831 APInt Hi = CR.getUnsignedMax(); 9832 unsigned Bits = std::max(Hi.getActiveBits(), 9833 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 9834 9835 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9836 9837 SDLoc SL = getCurSDLoc(); 9838 9839 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 9840 DAG.getValueType(SmallVT)); 9841 unsigned NumVals = Op.getNode()->getNumValues(); 9842 if (NumVals == 1) 9843 return ZExt; 9844 9845 SmallVector<SDValue, 4> Ops; 9846 9847 Ops.push_back(ZExt); 9848 for (unsigned I = 1; I != NumVals; ++I) 9849 Ops.push_back(Op.getValue(I)); 9850 9851 return DAG.getMergeValues(Ops, SL); 9852 } 9853 9854 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 9855 /// the call being lowered. 9856 /// 9857 /// This is a helper for lowering intrinsics that follow a target calling 9858 /// convention or require stack pointer adjustment. Only a subset of the 9859 /// intrinsic's operands need to participate in the calling convention. 9860 void SelectionDAGBuilder::populateCallLoweringInfo( 9861 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 9862 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 9863 AttributeSet RetAttrs, bool IsPatchPoint) { 9864 TargetLowering::ArgListTy Args; 9865 Args.reserve(NumArgs); 9866 9867 // Populate the argument list. 9868 // Attributes for args start at offset 1, after the return attribute. 9869 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 9870 ArgI != ArgE; ++ArgI) { 9871 const Value *V = Call->getOperand(ArgI); 9872 9873 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 9874 9875 TargetLowering::ArgListEntry Entry; 9876 Entry.Node = getValue(V); 9877 Entry.Ty = V->getType(); 9878 Entry.setAttributes(Call, ArgI); 9879 Args.push_back(Entry); 9880 } 9881 9882 CLI.setDebugLoc(getCurSDLoc()) 9883 .setChain(getRoot()) 9884 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args), 9885 RetAttrs) 9886 .setDiscardResult(Call->use_empty()) 9887 .setIsPatchPoint(IsPatchPoint) 9888 .setIsPreallocated( 9889 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 9890 } 9891 9892 /// Add a stack map intrinsic call's live variable operands to a stackmap 9893 /// or patchpoint target node's operand list. 9894 /// 9895 /// Constants are converted to TargetConstants purely as an optimization to 9896 /// avoid constant materialization and register allocation. 9897 /// 9898 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 9899 /// generate addess computation nodes, and so FinalizeISel can convert the 9900 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 9901 /// address materialization and register allocation, but may also be required 9902 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 9903 /// alloca in the entry block, then the runtime may assume that the alloca's 9904 /// StackMap location can be read immediately after compilation and that the 9905 /// location is valid at any point during execution (this is similar to the 9906 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 9907 /// only available in a register, then the runtime would need to trap when 9908 /// execution reaches the StackMap in order to read the alloca's location. 9909 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 9910 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 9911 SelectionDAGBuilder &Builder) { 9912 SelectionDAG &DAG = Builder.DAG; 9913 for (unsigned I = StartIdx; I < Call.arg_size(); I++) { 9914 SDValue Op = Builder.getValue(Call.getArgOperand(I)); 9915 9916 // Things on the stack are pointer-typed, meaning that they are already 9917 // legal and can be emitted directly to target nodes. 9918 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) { 9919 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType())); 9920 } else { 9921 // Otherwise emit a target independent node to be legalised. 9922 Ops.push_back(Builder.getValue(Call.getArgOperand(I))); 9923 } 9924 } 9925 } 9926 9927 /// Lower llvm.experimental.stackmap. 9928 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 9929 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>, 9930 // [live variables...]) 9931 9932 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 9933 9934 SDValue Chain, InGlue, Callee; 9935 SmallVector<SDValue, 32> Ops; 9936 9937 SDLoc DL = getCurSDLoc(); 9938 Callee = getValue(CI.getCalledOperand()); 9939 9940 // The stackmap intrinsic only records the live variables (the arguments 9941 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 9942 // intrinsic, this won't be lowered to a function call. This means we don't 9943 // have to worry about calling conventions and target specific lowering code. 9944 // Instead we perform the call lowering right here. 9945 // 9946 // chain, flag = CALLSEQ_START(chain, 0, 0) 9947 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 9948 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 9949 // 9950 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 9951 InGlue = Chain.getValue(1); 9952 9953 // Add the STACKMAP operands, starting with DAG house-keeping. 9954 Ops.push_back(Chain); 9955 Ops.push_back(InGlue); 9956 9957 // Add the <id>, <numShadowBytes> operands. 9958 // 9959 // These do not require legalisation, and can be emitted directly to target 9960 // constant nodes. 9961 SDValue ID = getValue(CI.getArgOperand(0)); 9962 assert(ID.getValueType() == MVT::i64); 9963 SDValue IDConst = DAG.getTargetConstant( 9964 cast<ConstantSDNode>(ID)->getZExtValue(), DL, ID.getValueType()); 9965 Ops.push_back(IDConst); 9966 9967 SDValue Shad = getValue(CI.getArgOperand(1)); 9968 assert(Shad.getValueType() == MVT::i32); 9969 SDValue ShadConst = DAG.getTargetConstant( 9970 cast<ConstantSDNode>(Shad)->getZExtValue(), DL, Shad.getValueType()); 9971 Ops.push_back(ShadConst); 9972 9973 // Add the live variables. 9974 addStackMapLiveVars(CI, 2, DL, Ops, *this); 9975 9976 // Create the STACKMAP node. 9977 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9978 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops); 9979 InGlue = Chain.getValue(1); 9980 9981 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL); 9982 9983 // Stackmaps don't generate values, so nothing goes into the NodeMap. 9984 9985 // Set the root to the target-lowered call chain. 9986 DAG.setRoot(Chain); 9987 9988 // Inform the Frame Information that we have a stackmap in this function. 9989 FuncInfo.MF->getFrameInfo().setHasStackMap(); 9990 } 9991 9992 /// Lower llvm.experimental.patchpoint directly to its target opcode. 9993 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 9994 const BasicBlock *EHPadBB) { 9995 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 9996 // i32 <numBytes>, 9997 // i8* <target>, 9998 // i32 <numArgs>, 9999 // [Args...], 10000 // [live variables...]) 10001 10002 CallingConv::ID CC = CB.getCallingConv(); 10003 bool IsAnyRegCC = CC == CallingConv::AnyReg; 10004 bool HasDef = !CB.getType()->isVoidTy(); 10005 SDLoc dl = getCurSDLoc(); 10006 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 10007 10008 // Handle immediate and symbolic callees. 10009 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 10010 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 10011 /*isTarget=*/true); 10012 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 10013 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 10014 SDLoc(SymbolicCallee), 10015 SymbolicCallee->getValueType(0)); 10016 10017 // Get the real number of arguments participating in the call <numArgs> 10018 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 10019 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 10020 10021 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 10022 // Intrinsics include all meta-operands up to but not including CC. 10023 unsigned NumMetaOpers = PatchPointOpers::CCPos; 10024 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 10025 "Not enough arguments provided to the patchpoint intrinsic"); 10026 10027 // For AnyRegCC the arguments are lowered later on manually. 10028 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 10029 Type *ReturnTy = 10030 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 10031 10032 TargetLowering::CallLoweringInfo CLI(DAG); 10033 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 10034 ReturnTy, CB.getAttributes().getRetAttrs(), true); 10035 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 10036 10037 SDNode *CallEnd = Result.second.getNode(); 10038 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 10039 CallEnd = CallEnd->getOperand(0).getNode(); 10040 10041 /// Get a call instruction from the call sequence chain. 10042 /// Tail calls are not allowed. 10043 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 10044 "Expected a callseq node."); 10045 SDNode *Call = CallEnd->getOperand(0).getNode(); 10046 bool HasGlue = Call->getGluedNode(); 10047 10048 // Replace the target specific call node with the patchable intrinsic. 10049 SmallVector<SDValue, 8> Ops; 10050 10051 // Push the chain. 10052 Ops.push_back(*(Call->op_begin())); 10053 10054 // Optionally, push the glue (if any). 10055 if (HasGlue) 10056 Ops.push_back(*(Call->op_end() - 1)); 10057 10058 // Push the register mask info. 10059 if (HasGlue) 10060 Ops.push_back(*(Call->op_end() - 2)); 10061 else 10062 Ops.push_back(*(Call->op_end() - 1)); 10063 10064 // Add the <id> and <numBytes> constants. 10065 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 10066 Ops.push_back(DAG.getTargetConstant( 10067 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 10068 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 10069 Ops.push_back(DAG.getTargetConstant( 10070 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 10071 MVT::i32)); 10072 10073 // Add the callee. 10074 Ops.push_back(Callee); 10075 10076 // Adjust <numArgs> to account for any arguments that have been passed on the 10077 // stack instead. 10078 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 10079 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 10080 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 10081 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 10082 10083 // Add the calling convention 10084 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 10085 10086 // Add the arguments we omitted previously. The register allocator should 10087 // place these in any free register. 10088 if (IsAnyRegCC) 10089 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 10090 Ops.push_back(getValue(CB.getArgOperand(i))); 10091 10092 // Push the arguments from the call instruction. 10093 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 10094 Ops.append(Call->op_begin() + 2, e); 10095 10096 // Push live variables for the stack map. 10097 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 10098 10099 SDVTList NodeTys; 10100 if (IsAnyRegCC && HasDef) { 10101 // Create the return types based on the intrinsic definition 10102 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10103 SmallVector<EVT, 3> ValueVTs; 10104 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 10105 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 10106 10107 // There is always a chain and a glue type at the end 10108 ValueVTs.push_back(MVT::Other); 10109 ValueVTs.push_back(MVT::Glue); 10110 NodeTys = DAG.getVTList(ValueVTs); 10111 } else 10112 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10113 10114 // Replace the target specific call node with a PATCHPOINT node. 10115 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops); 10116 10117 // Update the NodeMap. 10118 if (HasDef) { 10119 if (IsAnyRegCC) 10120 setValue(&CB, SDValue(PPV.getNode(), 0)); 10121 else 10122 setValue(&CB, Result.first); 10123 } 10124 10125 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 10126 // call sequence. Furthermore the location of the chain and glue can change 10127 // when the AnyReg calling convention is used and the intrinsic returns a 10128 // value. 10129 if (IsAnyRegCC && HasDef) { 10130 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 10131 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)}; 10132 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 10133 } else 10134 DAG.ReplaceAllUsesWith(Call, PPV.getNode()); 10135 DAG.DeleteNode(Call); 10136 10137 // Inform the Frame Information that we have a patchpoint in this function. 10138 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 10139 } 10140 10141 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 10142 unsigned Intrinsic) { 10143 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10144 SDValue Op1 = getValue(I.getArgOperand(0)); 10145 SDValue Op2; 10146 if (I.arg_size() > 1) 10147 Op2 = getValue(I.getArgOperand(1)); 10148 SDLoc dl = getCurSDLoc(); 10149 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 10150 SDValue Res; 10151 SDNodeFlags SDFlags; 10152 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 10153 SDFlags.copyFMF(*FPMO); 10154 10155 switch (Intrinsic) { 10156 case Intrinsic::vector_reduce_fadd: 10157 if (SDFlags.hasAllowReassociation()) 10158 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 10159 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 10160 SDFlags); 10161 else 10162 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 10163 break; 10164 case Intrinsic::vector_reduce_fmul: 10165 if (SDFlags.hasAllowReassociation()) 10166 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 10167 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 10168 SDFlags); 10169 else 10170 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 10171 break; 10172 case Intrinsic::vector_reduce_add: 10173 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 10174 break; 10175 case Intrinsic::vector_reduce_mul: 10176 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 10177 break; 10178 case Intrinsic::vector_reduce_and: 10179 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 10180 break; 10181 case Intrinsic::vector_reduce_or: 10182 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 10183 break; 10184 case Intrinsic::vector_reduce_xor: 10185 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 10186 break; 10187 case Intrinsic::vector_reduce_smax: 10188 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 10189 break; 10190 case Intrinsic::vector_reduce_smin: 10191 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 10192 break; 10193 case Intrinsic::vector_reduce_umax: 10194 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 10195 break; 10196 case Intrinsic::vector_reduce_umin: 10197 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 10198 break; 10199 case Intrinsic::vector_reduce_fmax: 10200 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 10201 break; 10202 case Intrinsic::vector_reduce_fmin: 10203 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 10204 break; 10205 case Intrinsic::vector_reduce_fmaximum: 10206 Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags); 10207 break; 10208 case Intrinsic::vector_reduce_fminimum: 10209 Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags); 10210 break; 10211 default: 10212 llvm_unreachable("Unhandled vector reduce intrinsic"); 10213 } 10214 setValue(&I, Res); 10215 } 10216 10217 /// Returns an AttributeList representing the attributes applied to the return 10218 /// value of the given call. 10219 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 10220 SmallVector<Attribute::AttrKind, 2> Attrs; 10221 if (CLI.RetSExt) 10222 Attrs.push_back(Attribute::SExt); 10223 if (CLI.RetZExt) 10224 Attrs.push_back(Attribute::ZExt); 10225 if (CLI.IsInReg) 10226 Attrs.push_back(Attribute::InReg); 10227 10228 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 10229 Attrs); 10230 } 10231 10232 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 10233 /// implementation, which just calls LowerCall. 10234 /// FIXME: When all targets are 10235 /// migrated to using LowerCall, this hook should be integrated into SDISel. 10236 std::pair<SDValue, SDValue> 10237 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 10238 // Handle the incoming return values from the call. 10239 CLI.Ins.clear(); 10240 Type *OrigRetTy = CLI.RetTy; 10241 SmallVector<EVT, 4> RetTys; 10242 SmallVector<uint64_t, 4> Offsets; 10243 auto &DL = CLI.DAG.getDataLayout(); 10244 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets, 0); 10245 10246 if (CLI.IsPostTypeLegalization) { 10247 // If we are lowering a libcall after legalization, split the return type. 10248 SmallVector<EVT, 4> OldRetTys; 10249 SmallVector<uint64_t, 4> OldOffsets; 10250 RetTys.swap(OldRetTys); 10251 Offsets.swap(OldOffsets); 10252 10253 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 10254 EVT RetVT = OldRetTys[i]; 10255 uint64_t Offset = OldOffsets[i]; 10256 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 10257 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 10258 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 10259 RetTys.append(NumRegs, RegisterVT); 10260 for (unsigned j = 0; j != NumRegs; ++j) 10261 Offsets.push_back(Offset + j * RegisterVTByteSZ); 10262 } 10263 } 10264 10265 SmallVector<ISD::OutputArg, 4> Outs; 10266 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 10267 10268 bool CanLowerReturn = 10269 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 10270 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 10271 10272 SDValue DemoteStackSlot; 10273 int DemoteStackIdx = -100; 10274 if (!CanLowerReturn) { 10275 // FIXME: equivalent assert? 10276 // assert(!CS.hasInAllocaArgument() && 10277 // "sret demotion is incompatible with inalloca"); 10278 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 10279 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 10280 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10281 DemoteStackIdx = 10282 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 10283 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 10284 DL.getAllocaAddrSpace()); 10285 10286 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 10287 ArgListEntry Entry; 10288 Entry.Node = DemoteStackSlot; 10289 Entry.Ty = StackSlotPtrType; 10290 Entry.IsSExt = false; 10291 Entry.IsZExt = false; 10292 Entry.IsInReg = false; 10293 Entry.IsSRet = true; 10294 Entry.IsNest = false; 10295 Entry.IsByVal = false; 10296 Entry.IsByRef = false; 10297 Entry.IsReturned = false; 10298 Entry.IsSwiftSelf = false; 10299 Entry.IsSwiftAsync = false; 10300 Entry.IsSwiftError = false; 10301 Entry.IsCFGuardTarget = false; 10302 Entry.Alignment = Alignment; 10303 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 10304 CLI.NumFixedArgs += 1; 10305 CLI.getArgs()[0].IndirectType = CLI.RetTy; 10306 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 10307 10308 // sret demotion isn't compatible with tail-calls, since the sret argument 10309 // points into the callers stack frame. 10310 CLI.IsTailCall = false; 10311 } else { 10312 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10313 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL); 10314 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 10315 ISD::ArgFlagsTy Flags; 10316 if (NeedsRegBlock) { 10317 Flags.setInConsecutiveRegs(); 10318 if (I == RetTys.size() - 1) 10319 Flags.setInConsecutiveRegsLast(); 10320 } 10321 EVT VT = RetTys[I]; 10322 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10323 CLI.CallConv, VT); 10324 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10325 CLI.CallConv, VT); 10326 for (unsigned i = 0; i != NumRegs; ++i) { 10327 ISD::InputArg MyFlags; 10328 MyFlags.Flags = Flags; 10329 MyFlags.VT = RegisterVT; 10330 MyFlags.ArgVT = VT; 10331 MyFlags.Used = CLI.IsReturnValueUsed; 10332 if (CLI.RetTy->isPointerTy()) { 10333 MyFlags.Flags.setPointer(); 10334 MyFlags.Flags.setPointerAddrSpace( 10335 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 10336 } 10337 if (CLI.RetSExt) 10338 MyFlags.Flags.setSExt(); 10339 if (CLI.RetZExt) 10340 MyFlags.Flags.setZExt(); 10341 if (CLI.IsInReg) 10342 MyFlags.Flags.setInReg(); 10343 CLI.Ins.push_back(MyFlags); 10344 } 10345 } 10346 } 10347 10348 // We push in swifterror return as the last element of CLI.Ins. 10349 ArgListTy &Args = CLI.getArgs(); 10350 if (supportSwiftError()) { 10351 for (const ArgListEntry &Arg : Args) { 10352 if (Arg.IsSwiftError) { 10353 ISD::InputArg MyFlags; 10354 MyFlags.VT = getPointerTy(DL); 10355 MyFlags.ArgVT = EVT(getPointerTy(DL)); 10356 MyFlags.Flags.setSwiftError(); 10357 CLI.Ins.push_back(MyFlags); 10358 } 10359 } 10360 } 10361 10362 // Handle all of the outgoing arguments. 10363 CLI.Outs.clear(); 10364 CLI.OutVals.clear(); 10365 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 10366 SmallVector<EVT, 4> ValueVTs; 10367 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 10368 // FIXME: Split arguments if CLI.IsPostTypeLegalization 10369 Type *FinalType = Args[i].Ty; 10370 if (Args[i].IsByVal) 10371 FinalType = Args[i].IndirectType; 10372 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10373 FinalType, CLI.CallConv, CLI.IsVarArg, DL); 10374 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 10375 ++Value) { 10376 EVT VT = ValueVTs[Value]; 10377 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 10378 SDValue Op = SDValue(Args[i].Node.getNode(), 10379 Args[i].Node.getResNo() + Value); 10380 ISD::ArgFlagsTy Flags; 10381 10382 // Certain targets (such as MIPS), may have a different ABI alignment 10383 // for a type depending on the context. Give the target a chance to 10384 // specify the alignment it wants. 10385 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 10386 Flags.setOrigAlign(OriginalAlignment); 10387 10388 if (Args[i].Ty->isPointerTy()) { 10389 Flags.setPointer(); 10390 Flags.setPointerAddrSpace( 10391 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 10392 } 10393 if (Args[i].IsZExt) 10394 Flags.setZExt(); 10395 if (Args[i].IsSExt) 10396 Flags.setSExt(); 10397 if (Args[i].IsInReg) { 10398 // If we are using vectorcall calling convention, a structure that is 10399 // passed InReg - is surely an HVA 10400 if (CLI.CallConv == CallingConv::X86_VectorCall && 10401 isa<StructType>(FinalType)) { 10402 // The first value of a structure is marked 10403 if (0 == Value) 10404 Flags.setHvaStart(); 10405 Flags.setHva(); 10406 } 10407 // Set InReg Flag 10408 Flags.setInReg(); 10409 } 10410 if (Args[i].IsSRet) 10411 Flags.setSRet(); 10412 if (Args[i].IsSwiftSelf) 10413 Flags.setSwiftSelf(); 10414 if (Args[i].IsSwiftAsync) 10415 Flags.setSwiftAsync(); 10416 if (Args[i].IsSwiftError) 10417 Flags.setSwiftError(); 10418 if (Args[i].IsCFGuardTarget) 10419 Flags.setCFGuardTarget(); 10420 if (Args[i].IsByVal) 10421 Flags.setByVal(); 10422 if (Args[i].IsByRef) 10423 Flags.setByRef(); 10424 if (Args[i].IsPreallocated) { 10425 Flags.setPreallocated(); 10426 // Set the byval flag for CCAssignFn callbacks that don't know about 10427 // preallocated. This way we can know how many bytes we should've 10428 // allocated and how many bytes a callee cleanup function will pop. If 10429 // we port preallocated to more targets, we'll have to add custom 10430 // preallocated handling in the various CC lowering callbacks. 10431 Flags.setByVal(); 10432 } 10433 if (Args[i].IsInAlloca) { 10434 Flags.setInAlloca(); 10435 // Set the byval flag for CCAssignFn callbacks that don't know about 10436 // inalloca. This way we can know how many bytes we should've allocated 10437 // and how many bytes a callee cleanup function will pop. If we port 10438 // inalloca to more targets, we'll have to add custom inalloca handling 10439 // in the various CC lowering callbacks. 10440 Flags.setByVal(); 10441 } 10442 Align MemAlign; 10443 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 10444 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType); 10445 Flags.setByValSize(FrameSize); 10446 10447 // info is not there but there are cases it cannot get right. 10448 if (auto MA = Args[i].Alignment) 10449 MemAlign = *MA; 10450 else 10451 MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL)); 10452 } else if (auto MA = Args[i].Alignment) { 10453 MemAlign = *MA; 10454 } else { 10455 MemAlign = OriginalAlignment; 10456 } 10457 Flags.setMemAlign(MemAlign); 10458 if (Args[i].IsNest) 10459 Flags.setNest(); 10460 if (NeedsRegBlock) 10461 Flags.setInConsecutiveRegs(); 10462 10463 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10464 CLI.CallConv, VT); 10465 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10466 CLI.CallConv, VT); 10467 SmallVector<SDValue, 4> Parts(NumParts); 10468 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 10469 10470 if (Args[i].IsSExt) 10471 ExtendKind = ISD::SIGN_EXTEND; 10472 else if (Args[i].IsZExt) 10473 ExtendKind = ISD::ZERO_EXTEND; 10474 10475 // Conservatively only handle 'returned' on non-vectors that can be lowered, 10476 // for now. 10477 if (Args[i].IsReturned && !Op.getValueType().isVector() && 10478 CanLowerReturn) { 10479 assert((CLI.RetTy == Args[i].Ty || 10480 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 10481 CLI.RetTy->getPointerAddressSpace() == 10482 Args[i].Ty->getPointerAddressSpace())) && 10483 RetTys.size() == NumValues && "unexpected use of 'returned'"); 10484 // Before passing 'returned' to the target lowering code, ensure that 10485 // either the register MVT and the actual EVT are the same size or that 10486 // the return value and argument are extended in the same way; in these 10487 // cases it's safe to pass the argument register value unchanged as the 10488 // return register value (although it's at the target's option whether 10489 // to do so) 10490 // TODO: allow code generation to take advantage of partially preserved 10491 // registers rather than clobbering the entire register when the 10492 // parameter extension method is not compatible with the return 10493 // extension method 10494 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 10495 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 10496 CLI.RetZExt == Args[i].IsZExt)) 10497 Flags.setReturned(); 10498 } 10499 10500 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 10501 CLI.CallConv, ExtendKind); 10502 10503 for (unsigned j = 0; j != NumParts; ++j) { 10504 // if it isn't first piece, alignment must be 1 10505 // For scalable vectors the scalable part is currently handled 10506 // by individual targets, so we just use the known minimum size here. 10507 ISD::OutputArg MyFlags( 10508 Flags, Parts[j].getValueType().getSimpleVT(), VT, 10509 i < CLI.NumFixedArgs, i, 10510 j * Parts[j].getValueType().getStoreSize().getKnownMinValue()); 10511 if (NumParts > 1 && j == 0) 10512 MyFlags.Flags.setSplit(); 10513 else if (j != 0) { 10514 MyFlags.Flags.setOrigAlign(Align(1)); 10515 if (j == NumParts - 1) 10516 MyFlags.Flags.setSplitEnd(); 10517 } 10518 10519 CLI.Outs.push_back(MyFlags); 10520 CLI.OutVals.push_back(Parts[j]); 10521 } 10522 10523 if (NeedsRegBlock && Value == NumValues - 1) 10524 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 10525 } 10526 } 10527 10528 SmallVector<SDValue, 4> InVals; 10529 CLI.Chain = LowerCall(CLI, InVals); 10530 10531 // Update CLI.InVals to use outside of this function. 10532 CLI.InVals = InVals; 10533 10534 // Verify that the target's LowerCall behaved as expected. 10535 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 10536 "LowerCall didn't return a valid chain!"); 10537 assert((!CLI.IsTailCall || InVals.empty()) && 10538 "LowerCall emitted a return value for a tail call!"); 10539 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 10540 "LowerCall didn't emit the correct number of values!"); 10541 10542 // For a tail call, the return value is merely live-out and there aren't 10543 // any nodes in the DAG representing it. Return a special value to 10544 // indicate that a tail call has been emitted and no more Instructions 10545 // should be processed in the current block. 10546 if (CLI.IsTailCall) { 10547 CLI.DAG.setRoot(CLI.Chain); 10548 return std::make_pair(SDValue(), SDValue()); 10549 } 10550 10551 #ifndef NDEBUG 10552 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 10553 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 10554 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 10555 "LowerCall emitted a value with the wrong type!"); 10556 } 10557 #endif 10558 10559 SmallVector<SDValue, 4> ReturnValues; 10560 if (!CanLowerReturn) { 10561 // The instruction result is the result of loading from the 10562 // hidden sret parameter. 10563 SmallVector<EVT, 1> PVTs; 10564 Type *PtrRetTy = 10565 PointerType::get(OrigRetTy->getContext(), DL.getAllocaAddrSpace()); 10566 10567 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 10568 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 10569 EVT PtrVT = PVTs[0]; 10570 10571 unsigned NumValues = RetTys.size(); 10572 ReturnValues.resize(NumValues); 10573 SmallVector<SDValue, 4> Chains(NumValues); 10574 10575 // An aggregate return value cannot wrap around the address space, so 10576 // offsets to its parts don't wrap either. 10577 SDNodeFlags Flags; 10578 Flags.setNoUnsignedWrap(true); 10579 10580 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10581 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 10582 for (unsigned i = 0; i < NumValues; ++i) { 10583 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 10584 CLI.DAG.getConstant(Offsets[i], CLI.DL, 10585 PtrVT), Flags); 10586 SDValue L = CLI.DAG.getLoad( 10587 RetTys[i], CLI.DL, CLI.Chain, Add, 10588 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 10589 DemoteStackIdx, Offsets[i]), 10590 HiddenSRetAlign); 10591 ReturnValues[i] = L; 10592 Chains[i] = L.getValue(1); 10593 } 10594 10595 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 10596 } else { 10597 // Collect the legal value parts into potentially illegal values 10598 // that correspond to the original function's return values. 10599 std::optional<ISD::NodeType> AssertOp; 10600 if (CLI.RetSExt) 10601 AssertOp = ISD::AssertSext; 10602 else if (CLI.RetZExt) 10603 AssertOp = ISD::AssertZext; 10604 unsigned CurReg = 0; 10605 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 10606 EVT VT = RetTys[I]; 10607 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10608 CLI.CallConv, VT); 10609 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10610 CLI.CallConv, VT); 10611 10612 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 10613 NumRegs, RegisterVT, VT, nullptr, 10614 CLI.CallConv, AssertOp)); 10615 CurReg += NumRegs; 10616 } 10617 10618 // For a function returning void, there is no return value. We can't create 10619 // such a node, so we just return a null return value in that case. In 10620 // that case, nothing will actually look at the value. 10621 if (ReturnValues.empty()) 10622 return std::make_pair(SDValue(), CLI.Chain); 10623 } 10624 10625 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 10626 CLI.DAG.getVTList(RetTys), ReturnValues); 10627 return std::make_pair(Res, CLI.Chain); 10628 } 10629 10630 /// Places new result values for the node in Results (their number 10631 /// and types must exactly match those of the original return values of 10632 /// the node), or leaves Results empty, which indicates that the node is not 10633 /// to be custom lowered after all. 10634 void TargetLowering::LowerOperationWrapper(SDNode *N, 10635 SmallVectorImpl<SDValue> &Results, 10636 SelectionDAG &DAG) const { 10637 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 10638 10639 if (!Res.getNode()) 10640 return; 10641 10642 // If the original node has one result, take the return value from 10643 // LowerOperation as is. It might not be result number 0. 10644 if (N->getNumValues() == 1) { 10645 Results.push_back(Res); 10646 return; 10647 } 10648 10649 // If the original node has multiple results, then the return node should 10650 // have the same number of results. 10651 assert((N->getNumValues() == Res->getNumValues()) && 10652 "Lowering returned the wrong number of results!"); 10653 10654 // Places new result values base on N result number. 10655 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 10656 Results.push_back(Res.getValue(I)); 10657 } 10658 10659 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10660 llvm_unreachable("LowerOperation not implemented for this target!"); 10661 } 10662 10663 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, 10664 unsigned Reg, 10665 ISD::NodeType ExtendType) { 10666 SDValue Op = getNonRegisterValue(V); 10667 assert((Op.getOpcode() != ISD::CopyFromReg || 10668 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 10669 "Copy from a reg to the same reg!"); 10670 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 10671 10672 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10673 // If this is an InlineAsm we have to match the registers required, not the 10674 // notional registers required by the type. 10675 10676 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 10677 std::nullopt); // This is not an ABI copy. 10678 SDValue Chain = DAG.getEntryNode(); 10679 10680 if (ExtendType == ISD::ANY_EXTEND) { 10681 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V); 10682 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end()) 10683 ExtendType = PreferredExtendIt->second; 10684 } 10685 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 10686 PendingExports.push_back(Chain); 10687 } 10688 10689 #include "llvm/CodeGen/SelectionDAGISel.h" 10690 10691 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 10692 /// entry block, return true. This includes arguments used by switches, since 10693 /// the switch may expand into multiple basic blocks. 10694 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 10695 // With FastISel active, we may be splitting blocks, so force creation 10696 // of virtual registers for all non-dead arguments. 10697 if (FastISel) 10698 return A->use_empty(); 10699 10700 const BasicBlock &Entry = A->getParent()->front(); 10701 for (const User *U : A->users()) 10702 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 10703 return false; // Use not in entry block. 10704 10705 return true; 10706 } 10707 10708 using ArgCopyElisionMapTy = 10709 DenseMap<const Argument *, 10710 std::pair<const AllocaInst *, const StoreInst *>>; 10711 10712 /// Scan the entry block of the function in FuncInfo for arguments that look 10713 /// like copies into a local alloca. Record any copied arguments in 10714 /// ArgCopyElisionCandidates. 10715 static void 10716 findArgumentCopyElisionCandidates(const DataLayout &DL, 10717 FunctionLoweringInfo *FuncInfo, 10718 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 10719 // Record the state of every static alloca used in the entry block. Argument 10720 // allocas are all used in the entry block, so we need approximately as many 10721 // entries as we have arguments. 10722 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 10723 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 10724 unsigned NumArgs = FuncInfo->Fn->arg_size(); 10725 StaticAllocas.reserve(NumArgs * 2); 10726 10727 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 10728 if (!V) 10729 return nullptr; 10730 V = V->stripPointerCasts(); 10731 const auto *AI = dyn_cast<AllocaInst>(V); 10732 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 10733 return nullptr; 10734 auto Iter = StaticAllocas.insert({AI, Unknown}); 10735 return &Iter.first->second; 10736 }; 10737 10738 // Look for stores of arguments to static allocas. Look through bitcasts and 10739 // GEPs to handle type coercions, as long as the alloca is fully initialized 10740 // by the store. Any non-store use of an alloca escapes it and any subsequent 10741 // unanalyzed store might write it. 10742 // FIXME: Handle structs initialized with multiple stores. 10743 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 10744 // Look for stores, and handle non-store uses conservatively. 10745 const auto *SI = dyn_cast<StoreInst>(&I); 10746 if (!SI) { 10747 // We will look through cast uses, so ignore them completely. 10748 if (I.isCast()) 10749 continue; 10750 // Ignore debug info and pseudo op intrinsics, they don't escape or store 10751 // to allocas. 10752 if (I.isDebugOrPseudoInst()) 10753 continue; 10754 // This is an unknown instruction. Assume it escapes or writes to all 10755 // static alloca operands. 10756 for (const Use &U : I.operands()) { 10757 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 10758 *Info = StaticAllocaInfo::Clobbered; 10759 } 10760 continue; 10761 } 10762 10763 // If the stored value is a static alloca, mark it as escaped. 10764 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 10765 *Info = StaticAllocaInfo::Clobbered; 10766 10767 // Check if the destination is a static alloca. 10768 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 10769 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 10770 if (!Info) 10771 continue; 10772 const AllocaInst *AI = cast<AllocaInst>(Dst); 10773 10774 // Skip allocas that have been initialized or clobbered. 10775 if (*Info != StaticAllocaInfo::Unknown) 10776 continue; 10777 10778 // Check if the stored value is an argument, and that this store fully 10779 // initializes the alloca. 10780 // If the argument type has padding bits we can't directly forward a pointer 10781 // as the upper bits may contain garbage. 10782 // Don't elide copies from the same argument twice. 10783 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 10784 const auto *Arg = dyn_cast<Argument>(Val); 10785 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 10786 Arg->getType()->isEmptyTy() || 10787 DL.getTypeStoreSize(Arg->getType()) != 10788 DL.getTypeAllocSize(AI->getAllocatedType()) || 10789 !DL.typeSizeEqualsStoreSize(Arg->getType()) || 10790 ArgCopyElisionCandidates.count(Arg)) { 10791 *Info = StaticAllocaInfo::Clobbered; 10792 continue; 10793 } 10794 10795 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 10796 << '\n'); 10797 10798 // Mark this alloca and store for argument copy elision. 10799 *Info = StaticAllocaInfo::Elidable; 10800 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 10801 10802 // Stop scanning if we've seen all arguments. This will happen early in -O0 10803 // builds, which is useful, because -O0 builds have large entry blocks and 10804 // many allocas. 10805 if (ArgCopyElisionCandidates.size() == NumArgs) 10806 break; 10807 } 10808 } 10809 10810 /// Try to elide argument copies from memory into a local alloca. Succeeds if 10811 /// ArgVal is a load from a suitable fixed stack object. 10812 static void tryToElideArgumentCopy( 10813 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 10814 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 10815 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 10816 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 10817 ArrayRef<SDValue> ArgVals, bool &ArgHasUses) { 10818 // Check if this is a load from a fixed stack object. 10819 auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]); 10820 if (!LNode) 10821 return; 10822 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 10823 if (!FINode) 10824 return; 10825 10826 // Check that the fixed stack object is the right size and alignment. 10827 // Look at the alignment that the user wrote on the alloca instead of looking 10828 // at the stack object. 10829 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 10830 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 10831 const AllocaInst *AI = ArgCopyIter->second.first; 10832 int FixedIndex = FINode->getIndex(); 10833 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 10834 int OldIndex = AllocaIndex; 10835 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 10836 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 10837 LLVM_DEBUG( 10838 dbgs() << " argument copy elision failed due to bad fixed stack " 10839 "object size\n"); 10840 return; 10841 } 10842 Align RequiredAlignment = AI->getAlign(); 10843 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 10844 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 10845 "greater than stack argument alignment (" 10846 << DebugStr(RequiredAlignment) << " vs " 10847 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 10848 return; 10849 } 10850 10851 // Perform the elision. Delete the old stack object and replace its only use 10852 // in the variable info map. Mark the stack object as mutable. 10853 LLVM_DEBUG({ 10854 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 10855 << " Replacing frame index " << OldIndex << " with " << FixedIndex 10856 << '\n'; 10857 }); 10858 MFI.RemoveStackObject(OldIndex); 10859 MFI.setIsImmutableObjectIndex(FixedIndex, false); 10860 AllocaIndex = FixedIndex; 10861 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 10862 for (SDValue ArgVal : ArgVals) 10863 Chains.push_back(ArgVal.getValue(1)); 10864 10865 // Avoid emitting code for the store implementing the copy. 10866 const StoreInst *SI = ArgCopyIter->second.second; 10867 ElidedArgCopyInstrs.insert(SI); 10868 10869 // Check for uses of the argument again so that we can avoid exporting ArgVal 10870 // if it is't used by anything other than the store. 10871 for (const Value *U : Arg.users()) { 10872 if (U != SI) { 10873 ArgHasUses = true; 10874 break; 10875 } 10876 } 10877 } 10878 10879 void SelectionDAGISel::LowerArguments(const Function &F) { 10880 SelectionDAG &DAG = SDB->DAG; 10881 SDLoc dl = SDB->getCurSDLoc(); 10882 const DataLayout &DL = DAG.getDataLayout(); 10883 SmallVector<ISD::InputArg, 16> Ins; 10884 10885 // In Naked functions we aren't going to save any registers. 10886 if (F.hasFnAttribute(Attribute::Naked)) 10887 return; 10888 10889 if (!FuncInfo->CanLowerReturn) { 10890 // Put in an sret pointer parameter before all the other parameters. 10891 SmallVector<EVT, 1> ValueVTs; 10892 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10893 PointerType::get(F.getContext(), 10894 DAG.getDataLayout().getAllocaAddrSpace()), 10895 ValueVTs); 10896 10897 // NOTE: Assuming that a pointer will never break down to more than one VT 10898 // or one register. 10899 ISD::ArgFlagsTy Flags; 10900 Flags.setSRet(); 10901 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 10902 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 10903 ISD::InputArg::NoArgIndex, 0); 10904 Ins.push_back(RetArg); 10905 } 10906 10907 // Look for stores of arguments to static allocas. Mark such arguments with a 10908 // flag to ask the target to give us the memory location of that argument if 10909 // available. 10910 ArgCopyElisionMapTy ArgCopyElisionCandidates; 10911 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 10912 ArgCopyElisionCandidates); 10913 10914 // Set up the incoming argument description vector. 10915 for (const Argument &Arg : F.args()) { 10916 unsigned ArgNo = Arg.getArgNo(); 10917 SmallVector<EVT, 4> ValueVTs; 10918 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10919 bool isArgValueUsed = !Arg.use_empty(); 10920 unsigned PartBase = 0; 10921 Type *FinalType = Arg.getType(); 10922 if (Arg.hasAttribute(Attribute::ByVal)) 10923 FinalType = Arg.getParamByValType(); 10924 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 10925 FinalType, F.getCallingConv(), F.isVarArg(), DL); 10926 for (unsigned Value = 0, NumValues = ValueVTs.size(); 10927 Value != NumValues; ++Value) { 10928 EVT VT = ValueVTs[Value]; 10929 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 10930 ISD::ArgFlagsTy Flags; 10931 10932 10933 if (Arg.getType()->isPointerTy()) { 10934 Flags.setPointer(); 10935 Flags.setPointerAddrSpace( 10936 cast<PointerType>(Arg.getType())->getAddressSpace()); 10937 } 10938 if (Arg.hasAttribute(Attribute::ZExt)) 10939 Flags.setZExt(); 10940 if (Arg.hasAttribute(Attribute::SExt)) 10941 Flags.setSExt(); 10942 if (Arg.hasAttribute(Attribute::InReg)) { 10943 // If we are using vectorcall calling convention, a structure that is 10944 // passed InReg - is surely an HVA 10945 if (F.getCallingConv() == CallingConv::X86_VectorCall && 10946 isa<StructType>(Arg.getType())) { 10947 // The first value of a structure is marked 10948 if (0 == Value) 10949 Flags.setHvaStart(); 10950 Flags.setHva(); 10951 } 10952 // Set InReg Flag 10953 Flags.setInReg(); 10954 } 10955 if (Arg.hasAttribute(Attribute::StructRet)) 10956 Flags.setSRet(); 10957 if (Arg.hasAttribute(Attribute::SwiftSelf)) 10958 Flags.setSwiftSelf(); 10959 if (Arg.hasAttribute(Attribute::SwiftAsync)) 10960 Flags.setSwiftAsync(); 10961 if (Arg.hasAttribute(Attribute::SwiftError)) 10962 Flags.setSwiftError(); 10963 if (Arg.hasAttribute(Attribute::ByVal)) 10964 Flags.setByVal(); 10965 if (Arg.hasAttribute(Attribute::ByRef)) 10966 Flags.setByRef(); 10967 if (Arg.hasAttribute(Attribute::InAlloca)) { 10968 Flags.setInAlloca(); 10969 // Set the byval flag for CCAssignFn callbacks that don't know about 10970 // inalloca. This way we can know how many bytes we should've allocated 10971 // and how many bytes a callee cleanup function will pop. If we port 10972 // inalloca to more targets, we'll have to add custom inalloca handling 10973 // in the various CC lowering callbacks. 10974 Flags.setByVal(); 10975 } 10976 if (Arg.hasAttribute(Attribute::Preallocated)) { 10977 Flags.setPreallocated(); 10978 // Set the byval flag for CCAssignFn callbacks that don't know about 10979 // preallocated. This way we can know how many bytes we should've 10980 // allocated and how many bytes a callee cleanup function will pop. If 10981 // we port preallocated to more targets, we'll have to add custom 10982 // preallocated handling in the various CC lowering callbacks. 10983 Flags.setByVal(); 10984 } 10985 10986 // Certain targets (such as MIPS), may have a different ABI alignment 10987 // for a type depending on the context. Give the target a chance to 10988 // specify the alignment it wants. 10989 const Align OriginalAlignment( 10990 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 10991 Flags.setOrigAlign(OriginalAlignment); 10992 10993 Align MemAlign; 10994 Type *ArgMemTy = nullptr; 10995 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 10996 Flags.isByRef()) { 10997 if (!ArgMemTy) 10998 ArgMemTy = Arg.getPointeeInMemoryValueType(); 10999 11000 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 11001 11002 // For in-memory arguments, size and alignment should be passed from FE. 11003 // BE will guess if this info is not there but there are cases it cannot 11004 // get right. 11005 if (auto ParamAlign = Arg.getParamStackAlign()) 11006 MemAlign = *ParamAlign; 11007 else if ((ParamAlign = Arg.getParamAlign())) 11008 MemAlign = *ParamAlign; 11009 else 11010 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 11011 if (Flags.isByRef()) 11012 Flags.setByRefSize(MemSize); 11013 else 11014 Flags.setByValSize(MemSize); 11015 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 11016 MemAlign = *ParamAlign; 11017 } else { 11018 MemAlign = OriginalAlignment; 11019 } 11020 Flags.setMemAlign(MemAlign); 11021 11022 if (Arg.hasAttribute(Attribute::Nest)) 11023 Flags.setNest(); 11024 if (NeedsRegBlock) 11025 Flags.setInConsecutiveRegs(); 11026 if (ArgCopyElisionCandidates.count(&Arg)) 11027 Flags.setCopyElisionCandidate(); 11028 if (Arg.hasAttribute(Attribute::Returned)) 11029 Flags.setReturned(); 11030 11031 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 11032 *CurDAG->getContext(), F.getCallingConv(), VT); 11033 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 11034 *CurDAG->getContext(), F.getCallingConv(), VT); 11035 for (unsigned i = 0; i != NumRegs; ++i) { 11036 // For scalable vectors, use the minimum size; individual targets 11037 // are responsible for handling scalable vector arguments and 11038 // return values. 11039 ISD::InputArg MyFlags( 11040 Flags, RegisterVT, VT, isArgValueUsed, ArgNo, 11041 PartBase + i * RegisterVT.getStoreSize().getKnownMinValue()); 11042 if (NumRegs > 1 && i == 0) 11043 MyFlags.Flags.setSplit(); 11044 // if it isn't first piece, alignment must be 1 11045 else if (i > 0) { 11046 MyFlags.Flags.setOrigAlign(Align(1)); 11047 if (i == NumRegs - 1) 11048 MyFlags.Flags.setSplitEnd(); 11049 } 11050 Ins.push_back(MyFlags); 11051 } 11052 if (NeedsRegBlock && Value == NumValues - 1) 11053 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 11054 PartBase += VT.getStoreSize().getKnownMinValue(); 11055 } 11056 } 11057 11058 // Call the target to set up the argument values. 11059 SmallVector<SDValue, 8> InVals; 11060 SDValue NewRoot = TLI->LowerFormalArguments( 11061 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 11062 11063 // Verify that the target's LowerFormalArguments behaved as expected. 11064 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 11065 "LowerFormalArguments didn't return a valid chain!"); 11066 assert(InVals.size() == Ins.size() && 11067 "LowerFormalArguments didn't emit the correct number of values!"); 11068 LLVM_DEBUG({ 11069 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 11070 assert(InVals[i].getNode() && 11071 "LowerFormalArguments emitted a null value!"); 11072 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 11073 "LowerFormalArguments emitted a value with the wrong type!"); 11074 } 11075 }); 11076 11077 // Update the DAG with the new chain value resulting from argument lowering. 11078 DAG.setRoot(NewRoot); 11079 11080 // Set up the argument values. 11081 unsigned i = 0; 11082 if (!FuncInfo->CanLowerReturn) { 11083 // Create a virtual register for the sret pointer, and put in a copy 11084 // from the sret argument into it. 11085 SmallVector<EVT, 1> ValueVTs; 11086 ComputeValueVTs(*TLI, DAG.getDataLayout(), 11087 PointerType::get(F.getContext(), 11088 DAG.getDataLayout().getAllocaAddrSpace()), 11089 ValueVTs); 11090 MVT VT = ValueVTs[0].getSimpleVT(); 11091 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 11092 std::optional<ISD::NodeType> AssertOp; 11093 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 11094 nullptr, F.getCallingConv(), AssertOp); 11095 11096 MachineFunction& MF = SDB->DAG.getMachineFunction(); 11097 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 11098 Register SRetReg = 11099 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 11100 FuncInfo->DemoteRegister = SRetReg; 11101 NewRoot = 11102 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 11103 DAG.setRoot(NewRoot); 11104 11105 // i indexes lowered arguments. Bump it past the hidden sret argument. 11106 ++i; 11107 } 11108 11109 SmallVector<SDValue, 4> Chains; 11110 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 11111 for (const Argument &Arg : F.args()) { 11112 SmallVector<SDValue, 4> ArgValues; 11113 SmallVector<EVT, 4> ValueVTs; 11114 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 11115 unsigned NumValues = ValueVTs.size(); 11116 if (NumValues == 0) 11117 continue; 11118 11119 bool ArgHasUses = !Arg.use_empty(); 11120 11121 // Elide the copying store if the target loaded this argument from a 11122 // suitable fixed stack object. 11123 if (Ins[i].Flags.isCopyElisionCandidate()) { 11124 unsigned NumParts = 0; 11125 for (EVT VT : ValueVTs) 11126 NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), 11127 F.getCallingConv(), VT); 11128 11129 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 11130 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 11131 ArrayRef(&InVals[i], NumParts), ArgHasUses); 11132 } 11133 11134 // If this argument is unused then remember its value. It is used to generate 11135 // debugging information. 11136 bool isSwiftErrorArg = 11137 TLI->supportSwiftError() && 11138 Arg.hasAttribute(Attribute::SwiftError); 11139 if (!ArgHasUses && !isSwiftErrorArg) { 11140 SDB->setUnusedArgValue(&Arg, InVals[i]); 11141 11142 // Also remember any frame index for use in FastISel. 11143 if (FrameIndexSDNode *FI = 11144 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 11145 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11146 } 11147 11148 for (unsigned Val = 0; Val != NumValues; ++Val) { 11149 EVT VT = ValueVTs[Val]; 11150 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 11151 F.getCallingConv(), VT); 11152 unsigned NumParts = TLI->getNumRegistersForCallingConv( 11153 *CurDAG->getContext(), F.getCallingConv(), VT); 11154 11155 // Even an apparent 'unused' swifterror argument needs to be returned. So 11156 // we do generate a copy for it that can be used on return from the 11157 // function. 11158 if (ArgHasUses || isSwiftErrorArg) { 11159 std::optional<ISD::NodeType> AssertOp; 11160 if (Arg.hasAttribute(Attribute::SExt)) 11161 AssertOp = ISD::AssertSext; 11162 else if (Arg.hasAttribute(Attribute::ZExt)) 11163 AssertOp = ISD::AssertZext; 11164 11165 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 11166 PartVT, VT, nullptr, 11167 F.getCallingConv(), AssertOp)); 11168 } 11169 11170 i += NumParts; 11171 } 11172 11173 // We don't need to do anything else for unused arguments. 11174 if (ArgValues.empty()) 11175 continue; 11176 11177 // Note down frame index. 11178 if (FrameIndexSDNode *FI = 11179 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 11180 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11181 11182 SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues), 11183 SDB->getCurSDLoc()); 11184 11185 SDB->setValue(&Arg, Res); 11186 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 11187 // We want to associate the argument with the frame index, among 11188 // involved operands, that correspond to the lowest address. The 11189 // getCopyFromParts function, called earlier, is swapping the order of 11190 // the operands to BUILD_PAIR depending on endianness. The result of 11191 // that swapping is that the least significant bits of the argument will 11192 // be in the first operand of the BUILD_PAIR node, and the most 11193 // significant bits will be in the second operand. 11194 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 11195 if (LoadSDNode *LNode = 11196 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 11197 if (FrameIndexSDNode *FI = 11198 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 11199 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11200 } 11201 11202 // Analyses past this point are naive and don't expect an assertion. 11203 if (Res.getOpcode() == ISD::AssertZext) 11204 Res = Res.getOperand(0); 11205 11206 // Update the SwiftErrorVRegDefMap. 11207 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 11208 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 11209 if (Register::isVirtualRegister(Reg)) 11210 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 11211 Reg); 11212 } 11213 11214 // If this argument is live outside of the entry block, insert a copy from 11215 // wherever we got it to the vreg that other BB's will reference it as. 11216 if (Res.getOpcode() == ISD::CopyFromReg) { 11217 // If we can, though, try to skip creating an unnecessary vreg. 11218 // FIXME: This isn't very clean... it would be nice to make this more 11219 // general. 11220 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 11221 if (Register::isVirtualRegister(Reg)) { 11222 FuncInfo->ValueMap[&Arg] = Reg; 11223 continue; 11224 } 11225 } 11226 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 11227 FuncInfo->InitializeRegForValue(&Arg); 11228 SDB->CopyToExportRegsIfNeeded(&Arg); 11229 } 11230 } 11231 11232 if (!Chains.empty()) { 11233 Chains.push_back(NewRoot); 11234 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 11235 } 11236 11237 DAG.setRoot(NewRoot); 11238 11239 assert(i == InVals.size() && "Argument register count mismatch!"); 11240 11241 // If any argument copy elisions occurred and we have debug info, update the 11242 // stale frame indices used in the dbg.declare variable info table. 11243 if (!ArgCopyElisionFrameIndexMap.empty()) { 11244 for (MachineFunction::VariableDbgInfo &VI : 11245 MF->getInStackSlotVariableDbgInfo()) { 11246 auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot()); 11247 if (I != ArgCopyElisionFrameIndexMap.end()) 11248 VI.updateStackSlot(I->second); 11249 } 11250 } 11251 11252 // Finally, if the target has anything special to do, allow it to do so. 11253 emitFunctionEntryCode(); 11254 } 11255 11256 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 11257 /// ensure constants are generated when needed. Remember the virtual registers 11258 /// that need to be added to the Machine PHI nodes as input. We cannot just 11259 /// directly add them, because expansion might result in multiple MBB's for one 11260 /// BB. As such, the start of the BB might correspond to a different MBB than 11261 /// the end. 11262 void 11263 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 11264 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11265 11266 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 11267 11268 // Check PHI nodes in successors that expect a value to be available from this 11269 // block. 11270 for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) { 11271 if (!isa<PHINode>(SuccBB->begin())) continue; 11272 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 11273 11274 // If this terminator has multiple identical successors (common for 11275 // switches), only handle each succ once. 11276 if (!SuccsHandled.insert(SuccMBB).second) 11277 continue; 11278 11279 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 11280 11281 // At this point we know that there is a 1-1 correspondence between LLVM PHI 11282 // nodes and Machine PHI nodes, but the incoming operands have not been 11283 // emitted yet. 11284 for (const PHINode &PN : SuccBB->phis()) { 11285 // Ignore dead phi's. 11286 if (PN.use_empty()) 11287 continue; 11288 11289 // Skip empty types 11290 if (PN.getType()->isEmptyTy()) 11291 continue; 11292 11293 unsigned Reg; 11294 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 11295 11296 if (const auto *C = dyn_cast<Constant>(PHIOp)) { 11297 unsigned &RegOut = ConstantsOut[C]; 11298 if (RegOut == 0) { 11299 RegOut = FuncInfo.CreateRegs(C); 11300 // We need to zero/sign extend ConstantInt phi operands to match 11301 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo. 11302 ISD::NodeType ExtendType = ISD::ANY_EXTEND; 11303 if (auto *CI = dyn_cast<ConstantInt>(C)) 11304 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND 11305 : ISD::ZERO_EXTEND; 11306 CopyValueToVirtualRegister(C, RegOut, ExtendType); 11307 } 11308 Reg = RegOut; 11309 } else { 11310 DenseMap<const Value *, Register>::iterator I = 11311 FuncInfo.ValueMap.find(PHIOp); 11312 if (I != FuncInfo.ValueMap.end()) 11313 Reg = I->second; 11314 else { 11315 assert(isa<AllocaInst>(PHIOp) && 11316 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 11317 "Didn't codegen value into a register!??"); 11318 Reg = FuncInfo.CreateRegs(PHIOp); 11319 CopyValueToVirtualRegister(PHIOp, Reg); 11320 } 11321 } 11322 11323 // Remember that this register needs to added to the machine PHI node as 11324 // the input for this MBB. 11325 SmallVector<EVT, 4> ValueVTs; 11326 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 11327 for (EVT VT : ValueVTs) { 11328 const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 11329 for (unsigned i = 0; i != NumRegisters; ++i) 11330 FuncInfo.PHINodesToUpdate.push_back( 11331 std::make_pair(&*MBBI++, Reg + i)); 11332 Reg += NumRegisters; 11333 } 11334 } 11335 } 11336 11337 ConstantsOut.clear(); 11338 } 11339 11340 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 11341 MachineFunction::iterator I(MBB); 11342 if (++I == FuncInfo.MF->end()) 11343 return nullptr; 11344 return &*I; 11345 } 11346 11347 /// During lowering new call nodes can be created (such as memset, etc.). 11348 /// Those will become new roots of the current DAG, but complications arise 11349 /// when they are tail calls. In such cases, the call lowering will update 11350 /// the root, but the builder still needs to know that a tail call has been 11351 /// lowered in order to avoid generating an additional return. 11352 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 11353 // If the node is null, we do have a tail call. 11354 if (MaybeTC.getNode() != nullptr) 11355 DAG.setRoot(MaybeTC); 11356 else 11357 HasTailCall = true; 11358 } 11359 11360 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 11361 MachineBasicBlock *SwitchMBB, 11362 MachineBasicBlock *DefaultMBB) { 11363 MachineFunction *CurMF = FuncInfo.MF; 11364 MachineBasicBlock *NextMBB = nullptr; 11365 MachineFunction::iterator BBI(W.MBB); 11366 if (++BBI != FuncInfo.MF->end()) 11367 NextMBB = &*BBI; 11368 11369 unsigned Size = W.LastCluster - W.FirstCluster + 1; 11370 11371 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11372 11373 if (Size == 2 && W.MBB == SwitchMBB) { 11374 // If any two of the cases has the same destination, and if one value 11375 // is the same as the other, but has one bit unset that the other has set, 11376 // use bit manipulation to do two compares at once. For example: 11377 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 11378 // TODO: This could be extended to merge any 2 cases in switches with 3 11379 // cases. 11380 // TODO: Handle cases where W.CaseBB != SwitchBB. 11381 CaseCluster &Small = *W.FirstCluster; 11382 CaseCluster &Big = *W.LastCluster; 11383 11384 if (Small.Low == Small.High && Big.Low == Big.High && 11385 Small.MBB == Big.MBB) { 11386 const APInt &SmallValue = Small.Low->getValue(); 11387 const APInt &BigValue = Big.Low->getValue(); 11388 11389 // Check that there is only one bit different. 11390 APInt CommonBit = BigValue ^ SmallValue; 11391 if (CommonBit.isPowerOf2()) { 11392 SDValue CondLHS = getValue(Cond); 11393 EVT VT = CondLHS.getValueType(); 11394 SDLoc DL = getCurSDLoc(); 11395 11396 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 11397 DAG.getConstant(CommonBit, DL, VT)); 11398 SDValue Cond = DAG.getSetCC( 11399 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 11400 ISD::SETEQ); 11401 11402 // Update successor info. 11403 // Both Small and Big will jump to Small.BB, so we sum up the 11404 // probabilities. 11405 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 11406 if (BPI) 11407 addSuccessorWithProb( 11408 SwitchMBB, DefaultMBB, 11409 // The default destination is the first successor in IR. 11410 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 11411 else 11412 addSuccessorWithProb(SwitchMBB, DefaultMBB); 11413 11414 // Insert the true branch. 11415 SDValue BrCond = 11416 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 11417 DAG.getBasicBlock(Small.MBB)); 11418 // Insert the false branch. 11419 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 11420 DAG.getBasicBlock(DefaultMBB)); 11421 11422 DAG.setRoot(BrCond); 11423 return; 11424 } 11425 } 11426 } 11427 11428 if (TM.getOptLevel() != CodeGenOptLevel::None) { 11429 // Here, we order cases by probability so the most likely case will be 11430 // checked first. However, two clusters can have the same probability in 11431 // which case their relative ordering is non-deterministic. So we use Low 11432 // as a tie-breaker as clusters are guaranteed to never overlap. 11433 llvm::sort(W.FirstCluster, W.LastCluster + 1, 11434 [](const CaseCluster &a, const CaseCluster &b) { 11435 return a.Prob != b.Prob ? 11436 a.Prob > b.Prob : 11437 a.Low->getValue().slt(b.Low->getValue()); 11438 }); 11439 11440 // Rearrange the case blocks so that the last one falls through if possible 11441 // without changing the order of probabilities. 11442 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 11443 --I; 11444 if (I->Prob > W.LastCluster->Prob) 11445 break; 11446 if (I->Kind == CC_Range && I->MBB == NextMBB) { 11447 std::swap(*I, *W.LastCluster); 11448 break; 11449 } 11450 } 11451 } 11452 11453 // Compute total probability. 11454 BranchProbability DefaultProb = W.DefaultProb; 11455 BranchProbability UnhandledProbs = DefaultProb; 11456 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 11457 UnhandledProbs += I->Prob; 11458 11459 MachineBasicBlock *CurMBB = W.MBB; 11460 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 11461 bool FallthroughUnreachable = false; 11462 MachineBasicBlock *Fallthrough; 11463 if (I == W.LastCluster) { 11464 // For the last cluster, fall through to the default destination. 11465 Fallthrough = DefaultMBB; 11466 FallthroughUnreachable = isa<UnreachableInst>( 11467 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 11468 } else { 11469 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 11470 CurMF->insert(BBI, Fallthrough); 11471 // Put Cond in a virtual register to make it available from the new blocks. 11472 ExportFromCurrentBlock(Cond); 11473 } 11474 UnhandledProbs -= I->Prob; 11475 11476 switch (I->Kind) { 11477 case CC_JumpTable: { 11478 // FIXME: Optimize away range check based on pivot comparisons. 11479 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 11480 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 11481 11482 // The jump block hasn't been inserted yet; insert it here. 11483 MachineBasicBlock *JumpMBB = JT->MBB; 11484 CurMF->insert(BBI, JumpMBB); 11485 11486 auto JumpProb = I->Prob; 11487 auto FallthroughProb = UnhandledProbs; 11488 11489 // If the default statement is a target of the jump table, we evenly 11490 // distribute the default probability to successors of CurMBB. Also 11491 // update the probability on the edge from JumpMBB to Fallthrough. 11492 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 11493 SE = JumpMBB->succ_end(); 11494 SI != SE; ++SI) { 11495 if (*SI == DefaultMBB) { 11496 JumpProb += DefaultProb / 2; 11497 FallthroughProb -= DefaultProb / 2; 11498 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 11499 JumpMBB->normalizeSuccProbs(); 11500 break; 11501 } 11502 } 11503 11504 // If the default clause is unreachable, propagate that knowledge into 11505 // JTH->FallthroughUnreachable which will use it to suppress the range 11506 // check. 11507 // 11508 // However, don't do this if we're doing branch target enforcement, 11509 // because a table branch _without_ a range check can be a tempting JOP 11510 // gadget - out-of-bounds inputs that are impossible in correct 11511 // execution become possible again if an attacker can influence the 11512 // control flow. So if an attacker doesn't already have a BTI bypass 11513 // available, we don't want them to be able to get one out of this 11514 // table branch. 11515 if (FallthroughUnreachable) { 11516 Function &CurFunc = CurMF->getFunction(); 11517 bool HasBranchTargetEnforcement = false; 11518 if (CurFunc.hasFnAttribute("branch-target-enforcement")) { 11519 HasBranchTargetEnforcement = 11520 CurFunc.getFnAttribute("branch-target-enforcement") 11521 .getValueAsBool(); 11522 } else { 11523 HasBranchTargetEnforcement = 11524 CurMF->getMMI().getModule()->getModuleFlag( 11525 "branch-target-enforcement"); 11526 } 11527 if (!HasBranchTargetEnforcement) 11528 JTH->FallthroughUnreachable = true; 11529 } 11530 11531 if (!JTH->FallthroughUnreachable) 11532 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 11533 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 11534 CurMBB->normalizeSuccProbs(); 11535 11536 // The jump table header will be inserted in our current block, do the 11537 // range check, and fall through to our fallthrough block. 11538 JTH->HeaderBB = CurMBB; 11539 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 11540 11541 // If we're in the right place, emit the jump table header right now. 11542 if (CurMBB == SwitchMBB) { 11543 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 11544 JTH->Emitted = true; 11545 } 11546 break; 11547 } 11548 case CC_BitTests: { 11549 // FIXME: Optimize away range check based on pivot comparisons. 11550 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 11551 11552 // The bit test blocks haven't been inserted yet; insert them here. 11553 for (BitTestCase &BTC : BTB->Cases) 11554 CurMF->insert(BBI, BTC.ThisBB); 11555 11556 // Fill in fields of the BitTestBlock. 11557 BTB->Parent = CurMBB; 11558 BTB->Default = Fallthrough; 11559 11560 BTB->DefaultProb = UnhandledProbs; 11561 // If the cases in bit test don't form a contiguous range, we evenly 11562 // distribute the probability on the edge to Fallthrough to two 11563 // successors of CurMBB. 11564 if (!BTB->ContiguousRange) { 11565 BTB->Prob += DefaultProb / 2; 11566 BTB->DefaultProb -= DefaultProb / 2; 11567 } 11568 11569 if (FallthroughUnreachable) 11570 BTB->FallthroughUnreachable = true; 11571 11572 // If we're in the right place, emit the bit test header right now. 11573 if (CurMBB == SwitchMBB) { 11574 visitBitTestHeader(*BTB, SwitchMBB); 11575 BTB->Emitted = true; 11576 } 11577 break; 11578 } 11579 case CC_Range: { 11580 const Value *RHS, *LHS, *MHS; 11581 ISD::CondCode CC; 11582 if (I->Low == I->High) { 11583 // Check Cond == I->Low. 11584 CC = ISD::SETEQ; 11585 LHS = Cond; 11586 RHS=I->Low; 11587 MHS = nullptr; 11588 } else { 11589 // Check I->Low <= Cond <= I->High. 11590 CC = ISD::SETLE; 11591 LHS = I->Low; 11592 MHS = Cond; 11593 RHS = I->High; 11594 } 11595 11596 // If Fallthrough is unreachable, fold away the comparison. 11597 if (FallthroughUnreachable) 11598 CC = ISD::SETTRUE; 11599 11600 // The false probability is the sum of all unhandled cases. 11601 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 11602 getCurSDLoc(), I->Prob, UnhandledProbs); 11603 11604 if (CurMBB == SwitchMBB) 11605 visitSwitchCase(CB, SwitchMBB); 11606 else 11607 SL->SwitchCases.push_back(CB); 11608 11609 break; 11610 } 11611 } 11612 CurMBB = Fallthrough; 11613 } 11614 } 11615 11616 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 11617 CaseClusterIt First, 11618 CaseClusterIt Last) { 11619 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 11620 if (X.Prob != CC.Prob) 11621 return X.Prob > CC.Prob; 11622 11623 // Ties are broken by comparing the case value. 11624 return X.Low->getValue().slt(CC.Low->getValue()); 11625 }); 11626 } 11627 11628 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 11629 const SwitchWorkListItem &W, 11630 Value *Cond, 11631 MachineBasicBlock *SwitchMBB) { 11632 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 11633 "Clusters not sorted?"); 11634 11635 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 11636 11637 // Balance the tree based on branch probabilities to create a near-optimal (in 11638 // terms of search time given key frequency) binary search tree. See e.g. Kurt 11639 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 11640 CaseClusterIt LastLeft = W.FirstCluster; 11641 CaseClusterIt FirstRight = W.LastCluster; 11642 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 11643 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 11644 11645 // Move LastLeft and FirstRight towards each other from opposite directions to 11646 // find a partitioning of the clusters which balances the probability on both 11647 // sides. If LeftProb and RightProb are equal, alternate which side is 11648 // taken to ensure 0-probability nodes are distributed evenly. 11649 unsigned I = 0; 11650 while (LastLeft + 1 < FirstRight) { 11651 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 11652 LeftProb += (++LastLeft)->Prob; 11653 else 11654 RightProb += (--FirstRight)->Prob; 11655 I++; 11656 } 11657 11658 while (true) { 11659 // Our binary search tree differs from a typical BST in that ours can have up 11660 // to three values in each leaf. The pivot selection above doesn't take that 11661 // into account, which means the tree might require more nodes and be less 11662 // efficient. We compensate for this here. 11663 11664 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 11665 unsigned NumRight = W.LastCluster - FirstRight + 1; 11666 11667 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 11668 // If one side has less than 3 clusters, and the other has more than 3, 11669 // consider taking a cluster from the other side. 11670 11671 if (NumLeft < NumRight) { 11672 // Consider moving the first cluster on the right to the left side. 11673 CaseCluster &CC = *FirstRight; 11674 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11675 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11676 if (LeftSideRank <= RightSideRank) { 11677 // Moving the cluster to the left does not demote it. 11678 ++LastLeft; 11679 ++FirstRight; 11680 continue; 11681 } 11682 } else { 11683 assert(NumRight < NumLeft); 11684 // Consider moving the last element on the left to the right side. 11685 CaseCluster &CC = *LastLeft; 11686 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11687 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11688 if (RightSideRank <= LeftSideRank) { 11689 // Moving the cluster to the right does not demot it. 11690 --LastLeft; 11691 --FirstRight; 11692 continue; 11693 } 11694 } 11695 } 11696 break; 11697 } 11698 11699 assert(LastLeft + 1 == FirstRight); 11700 assert(LastLeft >= W.FirstCluster); 11701 assert(FirstRight <= W.LastCluster); 11702 11703 // Use the first element on the right as pivot since we will make less-than 11704 // comparisons against it. 11705 CaseClusterIt PivotCluster = FirstRight; 11706 assert(PivotCluster > W.FirstCluster); 11707 assert(PivotCluster <= W.LastCluster); 11708 11709 CaseClusterIt FirstLeft = W.FirstCluster; 11710 CaseClusterIt LastRight = W.LastCluster; 11711 11712 const ConstantInt *Pivot = PivotCluster->Low; 11713 11714 // New blocks will be inserted immediately after the current one. 11715 MachineFunction::iterator BBI(W.MBB); 11716 ++BBI; 11717 11718 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 11719 // we can branch to its destination directly if it's squeezed exactly in 11720 // between the known lower bound and Pivot - 1. 11721 MachineBasicBlock *LeftMBB; 11722 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 11723 FirstLeft->Low == W.GE && 11724 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 11725 LeftMBB = FirstLeft->MBB; 11726 } else { 11727 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11728 FuncInfo.MF->insert(BBI, LeftMBB); 11729 WorkList.push_back( 11730 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 11731 // Put Cond in a virtual register to make it available from the new blocks. 11732 ExportFromCurrentBlock(Cond); 11733 } 11734 11735 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 11736 // single cluster, RHS.Low == Pivot, and we can branch to its destination 11737 // directly if RHS.High equals the current upper bound. 11738 MachineBasicBlock *RightMBB; 11739 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 11740 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 11741 RightMBB = FirstRight->MBB; 11742 } else { 11743 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11744 FuncInfo.MF->insert(BBI, RightMBB); 11745 WorkList.push_back( 11746 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 11747 // Put Cond in a virtual register to make it available from the new blocks. 11748 ExportFromCurrentBlock(Cond); 11749 } 11750 11751 // Create the CaseBlock record that will be used to lower the branch. 11752 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 11753 getCurSDLoc(), LeftProb, RightProb); 11754 11755 if (W.MBB == SwitchMBB) 11756 visitSwitchCase(CB, SwitchMBB); 11757 else 11758 SL->SwitchCases.push_back(CB); 11759 } 11760 11761 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 11762 // from the swith statement. 11763 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 11764 BranchProbability PeeledCaseProb) { 11765 if (PeeledCaseProb == BranchProbability::getOne()) 11766 return BranchProbability::getZero(); 11767 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 11768 11769 uint32_t Numerator = CaseProb.getNumerator(); 11770 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 11771 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 11772 } 11773 11774 // Try to peel the top probability case if it exceeds the threshold. 11775 // Return current MachineBasicBlock for the switch statement if the peeling 11776 // does not occur. 11777 // If the peeling is performed, return the newly created MachineBasicBlock 11778 // for the peeled switch statement. Also update Clusters to remove the peeled 11779 // case. PeeledCaseProb is the BranchProbability for the peeled case. 11780 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 11781 const SwitchInst &SI, CaseClusterVector &Clusters, 11782 BranchProbability &PeeledCaseProb) { 11783 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11784 // Don't perform if there is only one cluster or optimizing for size. 11785 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 11786 TM.getOptLevel() == CodeGenOptLevel::None || 11787 SwitchMBB->getParent()->getFunction().hasMinSize()) 11788 return SwitchMBB; 11789 11790 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 11791 unsigned PeeledCaseIndex = 0; 11792 bool SwitchPeeled = false; 11793 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 11794 CaseCluster &CC = Clusters[Index]; 11795 if (CC.Prob < TopCaseProb) 11796 continue; 11797 TopCaseProb = CC.Prob; 11798 PeeledCaseIndex = Index; 11799 SwitchPeeled = true; 11800 } 11801 if (!SwitchPeeled) 11802 return SwitchMBB; 11803 11804 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 11805 << TopCaseProb << "\n"); 11806 11807 // Record the MBB for the peeled switch statement. 11808 MachineFunction::iterator BBI(SwitchMBB); 11809 ++BBI; 11810 MachineBasicBlock *PeeledSwitchMBB = 11811 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 11812 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 11813 11814 ExportFromCurrentBlock(SI.getCondition()); 11815 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 11816 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 11817 nullptr, nullptr, TopCaseProb.getCompl()}; 11818 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 11819 11820 Clusters.erase(PeeledCaseIt); 11821 for (CaseCluster &CC : Clusters) { 11822 LLVM_DEBUG( 11823 dbgs() << "Scale the probablity for one cluster, before scaling: " 11824 << CC.Prob << "\n"); 11825 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 11826 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 11827 } 11828 PeeledCaseProb = TopCaseProb; 11829 return PeeledSwitchMBB; 11830 } 11831 11832 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 11833 // Extract cases from the switch. 11834 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11835 CaseClusterVector Clusters; 11836 Clusters.reserve(SI.getNumCases()); 11837 for (auto I : SI.cases()) { 11838 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 11839 const ConstantInt *CaseVal = I.getCaseValue(); 11840 BranchProbability Prob = 11841 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 11842 : BranchProbability(1, SI.getNumCases() + 1); 11843 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 11844 } 11845 11846 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 11847 11848 // Cluster adjacent cases with the same destination. We do this at all 11849 // optimization levels because it's cheap to do and will make codegen faster 11850 // if there are many clusters. 11851 sortAndRangeify(Clusters); 11852 11853 // The branch probablity of the peeled case. 11854 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 11855 MachineBasicBlock *PeeledSwitchMBB = 11856 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 11857 11858 // If there is only the default destination, jump there directly. 11859 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11860 if (Clusters.empty()) { 11861 assert(PeeledSwitchMBB == SwitchMBB); 11862 SwitchMBB->addSuccessor(DefaultMBB); 11863 if (DefaultMBB != NextBlock(SwitchMBB)) { 11864 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 11865 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 11866 } 11867 return; 11868 } 11869 11870 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 11871 SL->findBitTestClusters(Clusters, &SI); 11872 11873 LLVM_DEBUG({ 11874 dbgs() << "Case clusters: "; 11875 for (const CaseCluster &C : Clusters) { 11876 if (C.Kind == CC_JumpTable) 11877 dbgs() << "JT:"; 11878 if (C.Kind == CC_BitTests) 11879 dbgs() << "BT:"; 11880 11881 C.Low->getValue().print(dbgs(), true); 11882 if (C.Low != C.High) { 11883 dbgs() << '-'; 11884 C.High->getValue().print(dbgs(), true); 11885 } 11886 dbgs() << ' '; 11887 } 11888 dbgs() << '\n'; 11889 }); 11890 11891 assert(!Clusters.empty()); 11892 SwitchWorkList WorkList; 11893 CaseClusterIt First = Clusters.begin(); 11894 CaseClusterIt Last = Clusters.end() - 1; 11895 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 11896 // Scale the branchprobability for DefaultMBB if the peel occurs and 11897 // DefaultMBB is not replaced. 11898 if (PeeledCaseProb != BranchProbability::getZero() && 11899 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 11900 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 11901 WorkList.push_back( 11902 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 11903 11904 while (!WorkList.empty()) { 11905 SwitchWorkListItem W = WorkList.pop_back_val(); 11906 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 11907 11908 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None && 11909 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 11910 // For optimized builds, lower large range as a balanced binary tree. 11911 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 11912 continue; 11913 } 11914 11915 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 11916 } 11917 } 11918 11919 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 11920 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11921 auto DL = getCurSDLoc(); 11922 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11923 setValue(&I, DAG.getStepVector(DL, ResultVT)); 11924 } 11925 11926 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 11927 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11928 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11929 11930 SDLoc DL = getCurSDLoc(); 11931 SDValue V = getValue(I.getOperand(0)); 11932 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 11933 11934 if (VT.isScalableVector()) { 11935 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 11936 return; 11937 } 11938 11939 // Use VECTOR_SHUFFLE for the fixed-length vector 11940 // to maintain existing behavior. 11941 SmallVector<int, 8> Mask; 11942 unsigned NumElts = VT.getVectorMinNumElements(); 11943 for (unsigned i = 0; i != NumElts; ++i) 11944 Mask.push_back(NumElts - 1 - i); 11945 11946 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 11947 } 11948 11949 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) { 11950 auto DL = getCurSDLoc(); 11951 SDValue InVec = getValue(I.getOperand(0)); 11952 EVT OutVT = 11953 InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 11954 11955 unsigned OutNumElts = OutVT.getVectorMinNumElements(); 11956 11957 // ISD Node needs the input vectors split into two equal parts 11958 SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 11959 DAG.getVectorIdxConstant(0, DL)); 11960 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 11961 DAG.getVectorIdxConstant(OutNumElts, DL)); 11962 11963 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 11964 // legalisation and combines. 11965 if (OutVT.isFixedLengthVector()) { 11966 SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 11967 createStrideMask(0, 2, OutNumElts)); 11968 SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 11969 createStrideMask(1, 2, OutNumElts)); 11970 SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc()); 11971 setValue(&I, Res); 11972 return; 11973 } 11974 11975 SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL, 11976 DAG.getVTList(OutVT, OutVT), Lo, Hi); 11977 setValue(&I, Res); 11978 } 11979 11980 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) { 11981 auto DL = getCurSDLoc(); 11982 EVT InVT = getValue(I.getOperand(0)).getValueType(); 11983 SDValue InVec0 = getValue(I.getOperand(0)); 11984 SDValue InVec1 = getValue(I.getOperand(1)); 11985 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11986 EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11987 11988 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 11989 // legalisation and combines. 11990 if (OutVT.isFixedLengthVector()) { 11991 unsigned NumElts = InVT.getVectorMinNumElements(); 11992 SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1); 11993 setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT), 11994 createInterleaveMask(NumElts, 2))); 11995 return; 11996 } 11997 11998 SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, 11999 DAG.getVTList(InVT, InVT), InVec0, InVec1); 12000 Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0), 12001 Res.getValue(1)); 12002 setValue(&I, Res); 12003 } 12004 12005 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 12006 SmallVector<EVT, 4> ValueVTs; 12007 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 12008 ValueVTs); 12009 unsigned NumValues = ValueVTs.size(); 12010 if (NumValues == 0) return; 12011 12012 SmallVector<SDValue, 4> Values(NumValues); 12013 SDValue Op = getValue(I.getOperand(0)); 12014 12015 for (unsigned i = 0; i != NumValues; ++i) 12016 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 12017 SDValue(Op.getNode(), Op.getResNo() + i)); 12018 12019 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 12020 DAG.getVTList(ValueVTs), Values)); 12021 } 12022 12023 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 12024 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12025 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12026 12027 SDLoc DL = getCurSDLoc(); 12028 SDValue V1 = getValue(I.getOperand(0)); 12029 SDValue V2 = getValue(I.getOperand(1)); 12030 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 12031 12032 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 12033 if (VT.isScalableVector()) { 12034 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 12035 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 12036 DAG.getConstant(Imm, DL, IdxVT))); 12037 return; 12038 } 12039 12040 unsigned NumElts = VT.getVectorNumElements(); 12041 12042 uint64_t Idx = (NumElts + Imm) % NumElts; 12043 12044 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 12045 SmallVector<int, 8> Mask; 12046 for (unsigned i = 0; i < NumElts; ++i) 12047 Mask.push_back(Idx + i); 12048 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 12049 } 12050 12051 // Consider the following MIR after SelectionDAG, which produces output in 12052 // phyregs in the first case or virtregs in the second case. 12053 // 12054 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx 12055 // %5:gr32 = COPY $ebx 12056 // %6:gr32 = COPY $edx 12057 // %1:gr32 = COPY %6:gr32 12058 // %0:gr32 = COPY %5:gr32 12059 // 12060 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32 12061 // %1:gr32 = COPY %6:gr32 12062 // %0:gr32 = COPY %5:gr32 12063 // 12064 // Given %0, we'd like to return $ebx in the first case and %5 in the second. 12065 // Given %1, we'd like to return $edx in the first case and %6 in the second. 12066 // 12067 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap 12068 // to a single virtreg (such as %0). The remaining outputs monotonically 12069 // increase in virtreg number from there. If a callbr has no outputs, then it 12070 // should not have a corresponding callbr landingpad; in fact, the callbr 12071 // landingpad would not even be able to refer to such a callbr. 12072 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) { 12073 MachineInstr *MI = MRI.def_begin(Reg)->getParent(); 12074 // There is definitely at least one copy. 12075 assert(MI->getOpcode() == TargetOpcode::COPY && 12076 "start of copy chain MUST be COPY"); 12077 Reg = MI->getOperand(1).getReg(); 12078 MI = MRI.def_begin(Reg)->getParent(); 12079 // There may be an optional second copy. 12080 if (MI->getOpcode() == TargetOpcode::COPY) { 12081 assert(Reg.isVirtual() && "expected COPY of virtual register"); 12082 Reg = MI->getOperand(1).getReg(); 12083 assert(Reg.isPhysical() && "expected COPY of physical register"); 12084 MI = MRI.def_begin(Reg)->getParent(); 12085 } 12086 // The start of the chain must be an INLINEASM_BR. 12087 assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR && 12088 "end of copy chain MUST be INLINEASM_BR"); 12089 return Reg; 12090 } 12091 12092 // We must do this walk rather than the simpler 12093 // setValue(&I, getCopyFromRegs(CBR, CBR->getType())); 12094 // otherwise we will end up with copies of virtregs only valid along direct 12095 // edges. 12096 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) { 12097 SmallVector<EVT, 8> ResultVTs; 12098 SmallVector<SDValue, 8> ResultValues; 12099 const auto *CBR = 12100 cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator()); 12101 12102 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12103 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 12104 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 12105 12106 unsigned InitialDef = FuncInfo.ValueMap[CBR]; 12107 SDValue Chain = DAG.getRoot(); 12108 12109 // Re-parse the asm constraints string. 12110 TargetLowering::AsmOperandInfoVector TargetConstraints = 12111 TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR); 12112 for (auto &T : TargetConstraints) { 12113 SDISelAsmOperandInfo OpInfo(T); 12114 if (OpInfo.Type != InlineAsm::isOutput) 12115 continue; 12116 12117 // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the 12118 // individual constraint. 12119 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 12120 12121 switch (OpInfo.ConstraintType) { 12122 case TargetLowering::C_Register: 12123 case TargetLowering::C_RegisterClass: { 12124 // Fill in OpInfo.AssignedRegs.Regs. 12125 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo); 12126 12127 // getRegistersForValue may produce 1 to many registers based on whether 12128 // the OpInfo.ConstraintVT is legal on the target or not. 12129 for (size_t i = 0, e = OpInfo.AssignedRegs.Regs.size(); i != e; ++i) { 12130 Register OriginalDef = FollowCopyChain(MRI, InitialDef++); 12131 if (Register::isPhysicalRegister(OriginalDef)) 12132 FuncInfo.MBB->addLiveIn(OriginalDef); 12133 // Update the assigned registers to use the original defs. 12134 OpInfo.AssignedRegs.Regs[i] = OriginalDef; 12135 } 12136 12137 SDValue V = OpInfo.AssignedRegs.getCopyFromRegs( 12138 DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR); 12139 ResultValues.push_back(V); 12140 ResultVTs.push_back(OpInfo.ConstraintVT); 12141 break; 12142 } 12143 case TargetLowering::C_Other: { 12144 SDValue Flag; 12145 SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 12146 OpInfo, DAG); 12147 ++InitialDef; 12148 ResultValues.push_back(V); 12149 ResultVTs.push_back(OpInfo.ConstraintVT); 12150 break; 12151 } 12152 default: 12153 break; 12154 } 12155 } 12156 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 12157 DAG.getVTList(ResultVTs), ResultValues); 12158 setValue(&I, V); 12159 } 12160