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/MachineBasicBlock.h" 37 #include "llvm/CodeGen/MachineFrameInfo.h" 38 #include "llvm/CodeGen/MachineFunction.h" 39 #include "llvm/CodeGen/MachineInstrBuilder.h" 40 #include "llvm/CodeGen/MachineInstrBundleIterator.h" 41 #include "llvm/CodeGen/MachineMemOperand.h" 42 #include "llvm/CodeGen/MachineModuleInfo.h" 43 #include "llvm/CodeGen/MachineOperand.h" 44 #include "llvm/CodeGen/MachineRegisterInfo.h" 45 #include "llvm/CodeGen/RuntimeLibcalls.h" 46 #include "llvm/CodeGen/SelectionDAG.h" 47 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 48 #include "llvm/CodeGen/StackMaps.h" 49 #include "llvm/CodeGen/SwiftErrorValueTracking.h" 50 #include "llvm/CodeGen/TargetFrameLowering.h" 51 #include "llvm/CodeGen/TargetInstrInfo.h" 52 #include "llvm/CodeGen/TargetOpcodes.h" 53 #include "llvm/CodeGen/TargetRegisterInfo.h" 54 #include "llvm/CodeGen/TargetSubtargetInfo.h" 55 #include "llvm/CodeGen/WinEHFuncInfo.h" 56 #include "llvm/IR/Argument.h" 57 #include "llvm/IR/Attributes.h" 58 #include "llvm/IR/BasicBlock.h" 59 #include "llvm/IR/CFG.h" 60 #include "llvm/IR/CallingConv.h" 61 #include "llvm/IR/Constant.h" 62 #include "llvm/IR/ConstantRange.h" 63 #include "llvm/IR/Constants.h" 64 #include "llvm/IR/DataLayout.h" 65 #include "llvm/IR/DebugInfo.h" 66 #include "llvm/IR/DebugInfoMetadata.h" 67 #include "llvm/IR/DerivedTypes.h" 68 #include "llvm/IR/DiagnosticInfo.h" 69 #include "llvm/IR/EHPersonalities.h" 70 #include "llvm/IR/Function.h" 71 #include "llvm/IR/GetElementPtrTypeIterator.h" 72 #include "llvm/IR/InlineAsm.h" 73 #include "llvm/IR/InstrTypes.h" 74 #include "llvm/IR/Instructions.h" 75 #include "llvm/IR/IntrinsicInst.h" 76 #include "llvm/IR/Intrinsics.h" 77 #include "llvm/IR/IntrinsicsAArch64.h" 78 #include "llvm/IR/IntrinsicsWebAssembly.h" 79 #include "llvm/IR/LLVMContext.h" 80 #include "llvm/IR/Metadata.h" 81 #include "llvm/IR/Module.h" 82 #include "llvm/IR/Operator.h" 83 #include "llvm/IR/PatternMatch.h" 84 #include "llvm/IR/Statepoint.h" 85 #include "llvm/IR/Type.h" 86 #include "llvm/IR/User.h" 87 #include "llvm/IR/Value.h" 88 #include "llvm/MC/MCContext.h" 89 #include "llvm/Support/AtomicOrdering.h" 90 #include "llvm/Support/Casting.h" 91 #include "llvm/Support/CommandLine.h" 92 #include "llvm/Support/Compiler.h" 93 #include "llvm/Support/Debug.h" 94 #include "llvm/Support/MathExtras.h" 95 #include "llvm/Support/raw_ostream.h" 96 #include "llvm/Target/TargetIntrinsicInfo.h" 97 #include "llvm/Target/TargetMachine.h" 98 #include "llvm/Target/TargetOptions.h" 99 #include "llvm/TargetParser/Triple.h" 100 #include "llvm/Transforms/Utils/Local.h" 101 #include <cstddef> 102 #include <iterator> 103 #include <limits> 104 #include <optional> 105 #include <tuple> 106 107 using namespace llvm; 108 using namespace PatternMatch; 109 using namespace SwitchCG; 110 111 #define DEBUG_TYPE "isel" 112 113 /// LimitFloatPrecision - Generate low-precision inline sequences for 114 /// some float libcalls (6, 8 or 12 bits). 115 static unsigned LimitFloatPrecision; 116 117 static cl::opt<bool> 118 InsertAssertAlign("insert-assert-align", cl::init(true), 119 cl::desc("Insert the experimental `assertalign` node."), 120 cl::ReallyHidden); 121 122 static cl::opt<unsigned, true> 123 LimitFPPrecision("limit-float-precision", 124 cl::desc("Generate low-precision inline sequences " 125 "for some float libcalls"), 126 cl::location(LimitFloatPrecision), cl::Hidden, 127 cl::init(0)); 128 129 static cl::opt<unsigned> SwitchPeelThreshold( 130 "switch-peel-threshold", cl::Hidden, cl::init(66), 131 cl::desc("Set the case probability threshold for peeling the case from a " 132 "switch statement. A value greater than 100 will void this " 133 "optimization")); 134 135 // Limit the width of DAG chains. This is important in general to prevent 136 // DAG-based analysis from blowing up. For example, alias analysis and 137 // load clustering may not complete in reasonable time. It is difficult to 138 // recognize and avoid this situation within each individual analysis, and 139 // future analyses are likely to have the same behavior. Limiting DAG width is 140 // the safe approach and will be especially important with global DAGs. 141 // 142 // MaxParallelChains default is arbitrarily high to avoid affecting 143 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 144 // sequence over this should have been converted to llvm.memcpy by the 145 // frontend. It is easy to induce this behavior with .ll code such as: 146 // %buffer = alloca [4096 x i8] 147 // %data = load [4096 x i8]* %argPtr 148 // store [4096 x i8] %data, [4096 x i8]* %buffer 149 static const unsigned MaxParallelChains = 64; 150 151 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 152 const SDValue *Parts, unsigned NumParts, 153 MVT PartVT, EVT ValueVT, const Value *V, 154 std::optional<CallingConv::ID> CC); 155 156 /// getCopyFromParts - Create a value that contains the specified legal parts 157 /// combined into the value they represent. If the parts combine to a type 158 /// larger than ValueVT then AssertOp can be used to specify whether the extra 159 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 160 /// (ISD::AssertSext). 161 static SDValue 162 getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, 163 unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V, 164 std::optional<CallingConv::ID> CC = std::nullopt, 165 std::optional<ISD::NodeType> AssertOp = std::nullopt) { 166 // Let the target assemble the parts if it wants to 167 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 168 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts, 169 PartVT, ValueVT, CC)) 170 return Val; 171 172 if (ValueVT.isVector()) 173 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 174 CC); 175 176 assert(NumParts > 0 && "No parts to assemble!"); 177 SDValue Val = Parts[0]; 178 179 if (NumParts > 1) { 180 // Assemble the value from multiple parts. 181 if (ValueVT.isInteger()) { 182 unsigned PartBits = PartVT.getSizeInBits(); 183 unsigned ValueBits = ValueVT.getSizeInBits(); 184 185 // Assemble the power of 2 part. 186 unsigned RoundParts = llvm::bit_floor(NumParts); 187 unsigned RoundBits = PartBits * RoundParts; 188 EVT RoundVT = RoundBits == ValueBits ? 189 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 190 SDValue Lo, Hi; 191 192 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 193 194 if (RoundParts > 2) { 195 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 196 PartVT, HalfVT, V); 197 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 198 RoundParts / 2, PartVT, HalfVT, V); 199 } else { 200 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 201 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 202 } 203 204 if (DAG.getDataLayout().isBigEndian()) 205 std::swap(Lo, Hi); 206 207 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 208 209 if (RoundParts < NumParts) { 210 // Assemble the trailing non-power-of-2 part. 211 unsigned OddParts = NumParts - RoundParts; 212 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 213 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 214 OddVT, V, CC); 215 216 // Combine the round and odd parts. 217 Lo = Val; 218 if (DAG.getDataLayout().isBigEndian()) 219 std::swap(Lo, Hi); 220 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 221 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 222 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 223 DAG.getConstant(Lo.getValueSizeInBits(), DL, 224 TLI.getShiftAmountTy( 225 TotalVT, DAG.getDataLayout()))); 226 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 227 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 228 } 229 } else if (PartVT.isFloatingPoint()) { 230 // FP split into multiple FP parts (for ppcf128) 231 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 232 "Unexpected split"); 233 SDValue Lo, Hi; 234 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 235 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 236 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 237 std::swap(Lo, Hi); 238 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 239 } else { 240 // FP split into integer parts (soft fp) 241 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 242 !PartVT.isVector() && "Unexpected split"); 243 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 244 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 245 } 246 } 247 248 // There is now one part, held in Val. Correct it to match ValueVT. 249 // PartEVT is the type of the register class that holds the value. 250 // ValueVT is the type of the inline asm operation. 251 EVT PartEVT = Val.getValueType(); 252 253 if (PartEVT == ValueVT) 254 return Val; 255 256 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 257 ValueVT.bitsLT(PartEVT)) { 258 // For an FP value in an integer part, we need to truncate to the right 259 // width first. 260 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 261 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 262 } 263 264 // Handle types that have the same size. 265 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 266 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 267 268 // Handle types with different sizes. 269 if (PartEVT.isInteger() && ValueVT.isInteger()) { 270 if (ValueVT.bitsLT(PartEVT)) { 271 // For a truncate, see if we have any information to 272 // indicate whether the truncated bits will always be 273 // zero or sign-extension. 274 if (AssertOp) 275 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 276 DAG.getValueType(ValueVT)); 277 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 278 } 279 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 280 } 281 282 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 283 // FP_ROUND's are always exact here. 284 if (ValueVT.bitsLT(Val.getValueType())) 285 return DAG.getNode( 286 ISD::FP_ROUND, DL, ValueVT, Val, 287 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 288 289 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 290 } 291 292 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 293 // then truncating. 294 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 295 ValueVT.bitsLT(PartEVT)) { 296 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 297 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 298 } 299 300 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 301 } 302 303 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 304 const Twine &ErrMsg) { 305 const Instruction *I = dyn_cast_or_null<Instruction>(V); 306 if (!V) 307 return Ctx.emitError(ErrMsg); 308 309 const char *AsmError = ", possible invalid constraint for vector type"; 310 if (const CallInst *CI = dyn_cast<CallInst>(I)) 311 if (CI->isInlineAsm()) 312 return Ctx.emitError(I, ErrMsg + AsmError); 313 314 return Ctx.emitError(I, ErrMsg); 315 } 316 317 /// getCopyFromPartsVector - Create a value that contains the specified legal 318 /// parts combined into the value they represent. If the parts combine to a 319 /// type larger than ValueVT then AssertOp can be used to specify whether the 320 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 321 /// ValueVT (ISD::AssertSext). 322 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 323 const SDValue *Parts, unsigned NumParts, 324 MVT PartVT, EVT ValueVT, const Value *V, 325 std::optional<CallingConv::ID> CallConv) { 326 assert(ValueVT.isVector() && "Not a vector value"); 327 assert(NumParts > 0 && "No parts to assemble!"); 328 const bool IsABIRegCopy = CallConv.has_value(); 329 330 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 331 SDValue Val = Parts[0]; 332 333 // Handle a multi-element vector. 334 if (NumParts > 1) { 335 EVT IntermediateVT; 336 MVT RegisterVT; 337 unsigned NumIntermediates; 338 unsigned NumRegs; 339 340 if (IsABIRegCopy) { 341 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 342 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, 343 NumIntermediates, RegisterVT); 344 } else { 345 NumRegs = 346 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 347 NumIntermediates, RegisterVT); 348 } 349 350 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 351 NumParts = NumRegs; // Silence a compiler warning. 352 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 353 assert(RegisterVT.getSizeInBits() == 354 Parts[0].getSimpleValueType().getSizeInBits() && 355 "Part type sizes don't match!"); 356 357 // Assemble the parts into intermediate operands. 358 SmallVector<SDValue, 8> Ops(NumIntermediates); 359 if (NumIntermediates == NumParts) { 360 // If the register was not expanded, truncate or copy the value, 361 // as appropriate. 362 for (unsigned i = 0; i != NumParts; ++i) 363 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 364 PartVT, IntermediateVT, V, CallConv); 365 } else if (NumParts > 0) { 366 // If the intermediate type was expanded, build the intermediate 367 // operands from the parts. 368 assert(NumParts % NumIntermediates == 0 && 369 "Must expand into a divisible number of parts!"); 370 unsigned Factor = NumParts / NumIntermediates; 371 for (unsigned i = 0; i != NumIntermediates; ++i) 372 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 373 PartVT, IntermediateVT, V, CallConv); 374 } 375 376 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 377 // intermediate operands. 378 EVT BuiltVectorTy = 379 IntermediateVT.isVector() 380 ? EVT::getVectorVT( 381 *DAG.getContext(), IntermediateVT.getScalarType(), 382 IntermediateVT.getVectorElementCount() * NumParts) 383 : EVT::getVectorVT(*DAG.getContext(), 384 IntermediateVT.getScalarType(), 385 NumIntermediates); 386 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 387 : ISD::BUILD_VECTOR, 388 DL, BuiltVectorTy, Ops); 389 } 390 391 // There is now one part, held in Val. Correct it to match ValueVT. 392 EVT PartEVT = Val.getValueType(); 393 394 if (PartEVT == ValueVT) 395 return Val; 396 397 if (PartEVT.isVector()) { 398 // Vector/Vector bitcast. 399 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 400 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 401 402 // If the parts vector has more elements than the value vector, then we 403 // have a vector widening case (e.g. <2 x float> -> <4 x float>). 404 // Extract the elements we want. 405 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) { 406 assert((PartEVT.getVectorElementCount().getKnownMinValue() > 407 ValueVT.getVectorElementCount().getKnownMinValue()) && 408 (PartEVT.getVectorElementCount().isScalable() == 409 ValueVT.getVectorElementCount().isScalable()) && 410 "Cannot narrow, it would be a lossy transformation"); 411 PartEVT = 412 EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(), 413 ValueVT.getVectorElementCount()); 414 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val, 415 DAG.getVectorIdxConstant(0, DL)); 416 if (PartEVT == ValueVT) 417 return Val; 418 if (PartEVT.isInteger() && ValueVT.isFloatingPoint()) 419 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 420 } 421 422 // Promoted vector extract 423 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 424 } 425 426 // Trivial bitcast if the types are the same size and the destination 427 // vector type is legal. 428 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 429 TLI.isTypeLegal(ValueVT)) 430 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 431 432 if (ValueVT.getVectorNumElements() != 1) { 433 // Certain ABIs require that vectors are passed as integers. For vectors 434 // are the same size, this is an obvious bitcast. 435 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 436 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 437 } else if (ValueVT.bitsLT(PartEVT)) { 438 const uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 439 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 440 // Drop the extra bits. 441 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 442 return DAG.getBitcast(ValueVT, Val); 443 } 444 445 diagnosePossiblyInvalidConstraint( 446 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 447 return DAG.getUNDEF(ValueVT); 448 } 449 450 // Handle cases such as i8 -> <1 x i1> 451 EVT ValueSVT = ValueVT.getVectorElementType(); 452 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 453 unsigned ValueSize = ValueSVT.getSizeInBits(); 454 if (ValueSize == PartEVT.getSizeInBits()) { 455 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 456 } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) { 457 // It's possible a scalar floating point type gets softened to integer and 458 // then promoted to a larger integer. If PartEVT is the larger integer 459 // we need to truncate it and then bitcast to the FP type. 460 assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types"); 461 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 462 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 463 Val = DAG.getBitcast(ValueSVT, Val); 464 } else { 465 Val = ValueVT.isFloatingPoint() 466 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 467 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 468 } 469 } 470 471 return DAG.getBuildVector(ValueVT, DL, Val); 472 } 473 474 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 475 SDValue Val, SDValue *Parts, unsigned NumParts, 476 MVT PartVT, const Value *V, 477 std::optional<CallingConv::ID> CallConv); 478 479 /// getCopyToParts - Create a series of nodes that contain the specified value 480 /// split into legal parts. If the parts contain more bits than Val, then, for 481 /// integers, ExtendKind can be used to specify how to generate the extra bits. 482 static void 483 getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 484 unsigned NumParts, MVT PartVT, const Value *V, 485 std::optional<CallingConv::ID> CallConv = std::nullopt, 486 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 487 // Let the target split the parts if it wants to 488 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 489 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 490 CallConv)) 491 return; 492 EVT ValueVT = Val.getValueType(); 493 494 // Handle the vector case separately. 495 if (ValueVT.isVector()) 496 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 497 CallConv); 498 499 unsigned OrigNumParts = NumParts; 500 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 501 "Copying to an illegal type!"); 502 503 if (NumParts == 0) 504 return; 505 506 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 507 EVT PartEVT = PartVT; 508 if (PartEVT == ValueVT) { 509 assert(NumParts == 1 && "No-op copy with multiple parts!"); 510 Parts[0] = Val; 511 return; 512 } 513 514 unsigned PartBits = PartVT.getSizeInBits(); 515 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 516 // If the parts cover more bits than the value has, promote the value. 517 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 518 assert(NumParts == 1 && "Do not know what to promote to!"); 519 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 520 } else { 521 if (ValueVT.isFloatingPoint()) { 522 // FP values need to be bitcast, then extended if they are being put 523 // into a larger container. 524 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 525 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 526 } 527 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 528 ValueVT.isInteger() && 529 "Unknown mismatch!"); 530 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 531 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 532 if (PartVT == MVT::x86mmx) 533 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 534 } 535 } else if (PartBits == ValueVT.getSizeInBits()) { 536 // Different types of the same size. 537 assert(NumParts == 1 && PartEVT != ValueVT); 538 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 539 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 540 // If the parts cover less bits than value has, truncate the value. 541 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 542 ValueVT.isInteger() && 543 "Unknown mismatch!"); 544 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 545 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 546 if (PartVT == MVT::x86mmx) 547 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 548 } 549 550 // The value may have changed - recompute ValueVT. 551 ValueVT = Val.getValueType(); 552 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 553 "Failed to tile the value with PartVT!"); 554 555 if (NumParts == 1) { 556 if (PartEVT != ValueVT) { 557 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 558 "scalar-to-vector conversion failed"); 559 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 560 } 561 562 Parts[0] = Val; 563 return; 564 } 565 566 // Expand the value into multiple parts. 567 if (NumParts & (NumParts - 1)) { 568 // The number of parts is not a power of 2. Split off and copy the tail. 569 assert(PartVT.isInteger() && ValueVT.isInteger() && 570 "Do not know what to expand to!"); 571 unsigned RoundParts = llvm::bit_floor(NumParts); 572 unsigned RoundBits = RoundParts * PartBits; 573 unsigned OddParts = NumParts - RoundParts; 574 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 575 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL)); 576 577 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 578 CallConv); 579 580 if (DAG.getDataLayout().isBigEndian()) 581 // The odd parts were reversed by getCopyToParts - unreverse them. 582 std::reverse(Parts + RoundParts, Parts + NumParts); 583 584 NumParts = RoundParts; 585 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 586 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 587 } 588 589 // The number of parts is a power of 2. Repeatedly bisect the value using 590 // EXTRACT_ELEMENT. 591 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 592 EVT::getIntegerVT(*DAG.getContext(), 593 ValueVT.getSizeInBits()), 594 Val); 595 596 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 597 for (unsigned i = 0; i < NumParts; i += StepSize) { 598 unsigned ThisBits = StepSize * PartBits / 2; 599 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 600 SDValue &Part0 = Parts[i]; 601 SDValue &Part1 = Parts[i+StepSize/2]; 602 603 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 604 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 605 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 606 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 607 608 if (ThisBits == PartBits && ThisVT != PartVT) { 609 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 610 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 611 } 612 } 613 } 614 615 if (DAG.getDataLayout().isBigEndian()) 616 std::reverse(Parts, Parts + OrigNumParts); 617 } 618 619 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val, 620 const SDLoc &DL, EVT PartVT) { 621 if (!PartVT.isVector()) 622 return SDValue(); 623 624 EVT ValueVT = Val.getValueType(); 625 ElementCount PartNumElts = PartVT.getVectorElementCount(); 626 ElementCount ValueNumElts = ValueVT.getVectorElementCount(); 627 628 // We only support widening vectors with equivalent element types and 629 // fixed/scalable properties. If a target needs to widen a fixed-length type 630 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below. 631 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) || 632 PartNumElts.isScalable() != ValueNumElts.isScalable() || 633 PartVT.getVectorElementType() != ValueVT.getVectorElementType()) 634 return SDValue(); 635 636 // Widening a scalable vector to another scalable vector is done by inserting 637 // the vector into a larger undef one. 638 if (PartNumElts.isScalable()) 639 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 640 Val, DAG.getVectorIdxConstant(0, DL)); 641 642 EVT ElementVT = PartVT.getVectorElementType(); 643 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 644 // undef elements. 645 SmallVector<SDValue, 16> Ops; 646 DAG.ExtractVectorElements(Val, Ops); 647 SDValue EltUndef = DAG.getUNDEF(ElementVT); 648 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef); 649 650 // FIXME: Use CONCAT for 2x -> 4x. 651 return DAG.getBuildVector(PartVT, DL, Ops); 652 } 653 654 /// getCopyToPartsVector - Create a series of nodes that contain the specified 655 /// value split into legal parts. 656 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 657 SDValue Val, SDValue *Parts, unsigned NumParts, 658 MVT PartVT, const Value *V, 659 std::optional<CallingConv::ID> CallConv) { 660 EVT ValueVT = Val.getValueType(); 661 assert(ValueVT.isVector() && "Not a vector"); 662 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 663 const bool IsABIRegCopy = CallConv.has_value(); 664 665 if (NumParts == 1) { 666 EVT PartEVT = PartVT; 667 if (PartEVT == ValueVT) { 668 // Nothing to do. 669 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 670 // Bitconvert vector->vector case. 671 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 672 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 673 Val = Widened; 674 } else if (PartVT.isVector() && 675 PartEVT.getVectorElementType().bitsGE( 676 ValueVT.getVectorElementType()) && 677 PartEVT.getVectorElementCount() == 678 ValueVT.getVectorElementCount()) { 679 680 // Promoted vector extract 681 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 682 } else if (PartEVT.isVector() && 683 PartEVT.getVectorElementType() != 684 ValueVT.getVectorElementType() && 685 TLI.getTypeAction(*DAG.getContext(), ValueVT) == 686 TargetLowering::TypeWidenVector) { 687 // Combination of widening and promotion. 688 EVT WidenVT = 689 EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(), 690 PartVT.getVectorElementCount()); 691 SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT); 692 Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT); 693 } else { 694 // Don't extract an integer from a float vector. This can happen if the 695 // FP type gets softened to integer and then promoted. The promotion 696 // prevents it from being picked up by the earlier bitcast case. 697 if (ValueVT.getVectorElementCount().isScalar() && 698 (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) { 699 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 700 DAG.getVectorIdxConstant(0, DL)); 701 } else { 702 uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 703 assert(PartVT.getFixedSizeInBits() > ValueSize && 704 "lossy conversion of vector to scalar type"); 705 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 706 Val = DAG.getBitcast(IntermediateType, Val); 707 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 708 } 709 } 710 711 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 712 Parts[0] = Val; 713 return; 714 } 715 716 // Handle a multi-element vector. 717 EVT IntermediateVT; 718 MVT RegisterVT; 719 unsigned NumIntermediates; 720 unsigned NumRegs; 721 if (IsABIRegCopy) { 722 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 723 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates, 724 RegisterVT); 725 } else { 726 NumRegs = 727 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 728 NumIntermediates, RegisterVT); 729 } 730 731 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 732 NumParts = NumRegs; // Silence a compiler warning. 733 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 734 735 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 736 "Mixing scalable and fixed vectors when copying in parts"); 737 738 std::optional<ElementCount> DestEltCnt; 739 740 if (IntermediateVT.isVector()) 741 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 742 else 743 DestEltCnt = ElementCount::getFixed(NumIntermediates); 744 745 EVT BuiltVectorTy = EVT::getVectorVT( 746 *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt); 747 748 if (ValueVT == BuiltVectorTy) { 749 // Nothing to do. 750 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) { 751 // Bitconvert vector->vector case. 752 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 753 } else { 754 if (BuiltVectorTy.getVectorElementType().bitsGT( 755 ValueVT.getVectorElementType())) { 756 // Integer promotion. 757 ValueVT = EVT::getVectorVT(*DAG.getContext(), 758 BuiltVectorTy.getVectorElementType(), 759 ValueVT.getVectorElementCount()); 760 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 761 } 762 763 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) { 764 Val = Widened; 765 } 766 } 767 768 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type"); 769 770 // Split the vector into intermediate operands. 771 SmallVector<SDValue, 8> Ops(NumIntermediates); 772 for (unsigned i = 0; i != NumIntermediates; ++i) { 773 if (IntermediateVT.isVector()) { 774 // This does something sensible for scalable vectors - see the 775 // definition of EXTRACT_SUBVECTOR for further details. 776 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 777 Ops[i] = 778 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 779 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 780 } else { 781 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 782 DAG.getVectorIdxConstant(i, DL)); 783 } 784 } 785 786 // Split the intermediate operands into legal parts. 787 if (NumParts == NumIntermediates) { 788 // If the register was not expanded, promote or copy the value, 789 // as appropriate. 790 for (unsigned i = 0; i != NumParts; ++i) 791 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 792 } else if (NumParts > 0) { 793 // If the intermediate type was expanded, split each the value into 794 // legal parts. 795 assert(NumIntermediates != 0 && "division by zero"); 796 assert(NumParts % NumIntermediates == 0 && 797 "Must expand into a divisible number of parts!"); 798 unsigned Factor = NumParts / NumIntermediates; 799 for (unsigned i = 0; i != NumIntermediates; ++i) 800 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 801 CallConv); 802 } 803 } 804 805 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 806 EVT valuevt, std::optional<CallingConv::ID> CC) 807 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 808 RegCount(1, regs.size()), CallConv(CC) {} 809 810 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 811 const DataLayout &DL, unsigned Reg, Type *Ty, 812 std::optional<CallingConv::ID> CC) { 813 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 814 815 CallConv = CC; 816 817 for (EVT ValueVT : ValueVTs) { 818 unsigned NumRegs = 819 isABIMangled() 820 ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT) 821 : TLI.getNumRegisters(Context, ValueVT); 822 MVT RegisterVT = 823 isABIMangled() 824 ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT) 825 : TLI.getRegisterType(Context, ValueVT); 826 for (unsigned i = 0; i != NumRegs; ++i) 827 Regs.push_back(Reg + i); 828 RegVTs.push_back(RegisterVT); 829 RegCount.push_back(NumRegs); 830 Reg += NumRegs; 831 } 832 } 833 834 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 835 FunctionLoweringInfo &FuncInfo, 836 const SDLoc &dl, SDValue &Chain, 837 SDValue *Glue, const Value *V) const { 838 // A Value with type {} or [0 x %t] needs no registers. 839 if (ValueVTs.empty()) 840 return SDValue(); 841 842 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 843 844 // Assemble the legal parts into the final values. 845 SmallVector<SDValue, 4> Values(ValueVTs.size()); 846 SmallVector<SDValue, 8> Parts; 847 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 848 // Copy the legal parts from the registers. 849 EVT ValueVT = ValueVTs[Value]; 850 unsigned NumRegs = RegCount[Value]; 851 MVT RegisterVT = isABIMangled() 852 ? TLI.getRegisterTypeForCallingConv( 853 *DAG.getContext(), *CallConv, RegVTs[Value]) 854 : RegVTs[Value]; 855 856 Parts.resize(NumRegs); 857 for (unsigned i = 0; i != NumRegs; ++i) { 858 SDValue P; 859 if (!Glue) { 860 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 861 } else { 862 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue); 863 *Glue = P.getValue(2); 864 } 865 866 Chain = P.getValue(1); 867 Parts[i] = P; 868 869 // If the source register was virtual and if we know something about it, 870 // add an assert node. 871 if (!Register::isVirtualRegister(Regs[Part + i]) || 872 !RegisterVT.isInteger()) 873 continue; 874 875 const FunctionLoweringInfo::LiveOutInfo *LOI = 876 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 877 if (!LOI) 878 continue; 879 880 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 881 unsigned NumSignBits = LOI->NumSignBits; 882 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 883 884 if (NumZeroBits == RegSize) { 885 // The current value is a zero. 886 // Explicitly express that as it would be easier for 887 // optimizations to kick in. 888 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 889 continue; 890 } 891 892 // FIXME: We capture more information than the dag can represent. For 893 // now, just use the tightest assertzext/assertsext possible. 894 bool isSExt; 895 EVT FromVT(MVT::Other); 896 if (NumZeroBits) { 897 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 898 isSExt = false; 899 } else if (NumSignBits > 1) { 900 FromVT = 901 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 902 isSExt = true; 903 } else { 904 continue; 905 } 906 // Add an assertion node. 907 assert(FromVT != MVT::Other); 908 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 909 RegisterVT, P, DAG.getValueType(FromVT)); 910 } 911 912 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 913 RegisterVT, ValueVT, V, CallConv); 914 Part += NumRegs; 915 Parts.clear(); 916 } 917 918 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 919 } 920 921 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 922 const SDLoc &dl, SDValue &Chain, SDValue *Glue, 923 const Value *V, 924 ISD::NodeType PreferredExtendType) const { 925 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 926 ISD::NodeType ExtendKind = PreferredExtendType; 927 928 // Get the list of the values's legal parts. 929 unsigned NumRegs = Regs.size(); 930 SmallVector<SDValue, 8> Parts(NumRegs); 931 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 932 unsigned NumParts = RegCount[Value]; 933 934 MVT RegisterVT = isABIMangled() 935 ? TLI.getRegisterTypeForCallingConv( 936 *DAG.getContext(), *CallConv, RegVTs[Value]) 937 : RegVTs[Value]; 938 939 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 940 ExtendKind = ISD::ZERO_EXTEND; 941 942 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 943 NumParts, RegisterVT, V, CallConv, ExtendKind); 944 Part += NumParts; 945 } 946 947 // Copy the parts into the registers. 948 SmallVector<SDValue, 8> Chains(NumRegs); 949 for (unsigned i = 0; i != NumRegs; ++i) { 950 SDValue Part; 951 if (!Glue) { 952 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 953 } else { 954 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue); 955 *Glue = Part.getValue(1); 956 } 957 958 Chains[i] = Part.getValue(0); 959 } 960 961 if (NumRegs == 1 || Glue) 962 // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is 963 // flagged to it. That is the CopyToReg nodes and the user are considered 964 // a single scheduling unit. If we create a TokenFactor and return it as 965 // chain, then the TokenFactor is both a predecessor (operand) of the 966 // user as well as a successor (the TF operands are flagged to the user). 967 // c1, f1 = CopyToReg 968 // c2, f2 = CopyToReg 969 // c3 = TokenFactor c1, c2 970 // ... 971 // = op c3, ..., f2 972 Chain = Chains[NumRegs-1]; 973 else 974 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 975 } 976 977 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 978 unsigned MatchingIdx, const SDLoc &dl, 979 SelectionDAG &DAG, 980 std::vector<SDValue> &Ops) const { 981 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 982 983 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 984 if (HasMatching) 985 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 986 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 987 // Put the register class of the virtual registers in the flag word. That 988 // way, later passes can recompute register class constraints for inline 989 // assembly as well as normal instructions. 990 // Don't do this for tied operands that can use the regclass information 991 // from the def. 992 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 993 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 994 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 995 } 996 997 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 998 Ops.push_back(Res); 999 1000 if (Code == InlineAsm::Kind_Clobber) { 1001 // Clobbers should always have a 1:1 mapping with registers, and may 1002 // reference registers that have illegal (e.g. vector) types. Hence, we 1003 // shouldn't try to apply any sort of splitting logic to them. 1004 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 1005 "No 1:1 mapping from clobbers to regs?"); 1006 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 1007 (void)SP; 1008 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 1009 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 1010 assert( 1011 (Regs[I] != SP || 1012 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 1013 "If we clobbered the stack pointer, MFI should know about it."); 1014 } 1015 return; 1016 } 1017 1018 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 1019 MVT RegisterVT = RegVTs[Value]; 1020 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value], 1021 RegisterVT); 1022 for (unsigned i = 0; i != NumRegs; ++i) { 1023 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 1024 unsigned TheReg = Regs[Reg++]; 1025 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 1026 } 1027 } 1028 } 1029 1030 SmallVector<std::pair<unsigned, TypeSize>, 4> 1031 RegsForValue::getRegsAndSizes() const { 1032 SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec; 1033 unsigned I = 0; 1034 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1035 unsigned RegCount = std::get<0>(CountAndVT); 1036 MVT RegisterVT = std::get<1>(CountAndVT); 1037 TypeSize RegisterSize = RegisterVT.getSizeInBits(); 1038 for (unsigned E = I + RegCount; I != E; ++I) 1039 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1040 } 1041 return OutVec; 1042 } 1043 1044 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1045 AssumptionCache *ac, 1046 const TargetLibraryInfo *li) { 1047 AA = aa; 1048 AC = ac; 1049 GFI = gfi; 1050 LibInfo = li; 1051 Context = DAG.getContext(); 1052 LPadToCallSiteMap.clear(); 1053 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1054 AssignmentTrackingEnabled = isAssignmentTrackingEnabled( 1055 *DAG.getMachineFunction().getFunction().getParent()); 1056 } 1057 1058 void SelectionDAGBuilder::clear() { 1059 NodeMap.clear(); 1060 UnusedArgNodeMap.clear(); 1061 PendingLoads.clear(); 1062 PendingExports.clear(); 1063 PendingConstrainedFP.clear(); 1064 PendingConstrainedFPStrict.clear(); 1065 CurInst = nullptr; 1066 HasTailCall = false; 1067 SDNodeOrder = LowestSDNodeOrder; 1068 StatepointLowering.clear(); 1069 } 1070 1071 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1072 DanglingDebugInfoMap.clear(); 1073 } 1074 1075 // Update DAG root to include dependencies on Pending chains. 1076 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1077 SDValue Root = DAG.getRoot(); 1078 1079 if (Pending.empty()) 1080 return Root; 1081 1082 // Add current root to PendingChains, unless we already indirectly 1083 // depend on it. 1084 if (Root.getOpcode() != ISD::EntryToken) { 1085 unsigned i = 0, e = Pending.size(); 1086 for (; i != e; ++i) { 1087 assert(Pending[i].getNode()->getNumOperands() > 1); 1088 if (Pending[i].getNode()->getOperand(0) == Root) 1089 break; // Don't add the root if we already indirectly depend on it. 1090 } 1091 1092 if (i == e) 1093 Pending.push_back(Root); 1094 } 1095 1096 if (Pending.size() == 1) 1097 Root = Pending[0]; 1098 else 1099 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1100 1101 DAG.setRoot(Root); 1102 Pending.clear(); 1103 return Root; 1104 } 1105 1106 SDValue SelectionDAGBuilder::getMemoryRoot() { 1107 return updateRoot(PendingLoads); 1108 } 1109 1110 SDValue SelectionDAGBuilder::getRoot() { 1111 // Chain up all pending constrained intrinsics together with all 1112 // pending loads, by simply appending them to PendingLoads and 1113 // then calling getMemoryRoot(). 1114 PendingLoads.reserve(PendingLoads.size() + 1115 PendingConstrainedFP.size() + 1116 PendingConstrainedFPStrict.size()); 1117 PendingLoads.append(PendingConstrainedFP.begin(), 1118 PendingConstrainedFP.end()); 1119 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1120 PendingConstrainedFPStrict.end()); 1121 PendingConstrainedFP.clear(); 1122 PendingConstrainedFPStrict.clear(); 1123 return getMemoryRoot(); 1124 } 1125 1126 SDValue SelectionDAGBuilder::getControlRoot() { 1127 // We need to emit pending fpexcept.strict constrained intrinsics, 1128 // so append them to the PendingExports list. 1129 PendingExports.append(PendingConstrainedFPStrict.begin(), 1130 PendingConstrainedFPStrict.end()); 1131 PendingConstrainedFPStrict.clear(); 1132 return updateRoot(PendingExports); 1133 } 1134 1135 void SelectionDAGBuilder::visit(const Instruction &I) { 1136 // Set up outgoing PHI node register values before emitting the terminator. 1137 if (I.isTerminator()) { 1138 HandlePHINodesInSuccessorBlocks(I.getParent()); 1139 } 1140 1141 // Add SDDbgValue nodes for any var locs here. Do so before updating 1142 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1143 if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) { 1144 // Add SDDbgValue nodes for any var locs here. Do so before updating 1145 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1146 for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I); 1147 It != End; ++It) { 1148 auto *Var = FnVarLocs->getDILocalVariable(It->VariableID); 1149 dropDanglingDebugInfo(Var, It->Expr); 1150 if (It->Values.isKillLocation(It->Expr)) { 1151 handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder); 1152 continue; 1153 } 1154 SmallVector<Value *> Values(It->Values.location_ops()); 1155 if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder, 1156 It->Values.hasArgList())) 1157 addDanglingDebugInfo(It, SDNodeOrder); 1158 } 1159 } 1160 1161 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1162 if (!isa<DbgInfoIntrinsic>(I)) 1163 ++SDNodeOrder; 1164 1165 CurInst = &I; 1166 1167 // Set inserted listener only if required. 1168 bool NodeInserted = false; 1169 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener; 1170 MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections); 1171 if (PCSectionsMD) { 1172 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>( 1173 DAG, [&](SDNode *) { NodeInserted = true; }); 1174 } 1175 1176 visit(I.getOpcode(), I); 1177 1178 if (!I.isTerminator() && !HasTailCall && 1179 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1180 CopyToExportRegsIfNeeded(&I); 1181 1182 // Handle metadata. 1183 if (PCSectionsMD) { 1184 auto It = NodeMap.find(&I); 1185 if (It != NodeMap.end()) { 1186 DAG.addPCSections(It->second.getNode(), PCSectionsMD); 1187 } else if (NodeInserted) { 1188 // This should not happen; if it does, don't let it go unnoticed so we can 1189 // fix it. Relevant visit*() function is probably missing a setValue(). 1190 errs() << "warning: loosing !pcsections metadata [" 1191 << I.getModule()->getName() << "]\n"; 1192 LLVM_DEBUG(I.dump()); 1193 assert(false); 1194 } 1195 } 1196 1197 CurInst = nullptr; 1198 } 1199 1200 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1201 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1202 } 1203 1204 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1205 // Note: this doesn't use InstVisitor, because it has to work with 1206 // ConstantExpr's in addition to instructions. 1207 switch (Opcode) { 1208 default: llvm_unreachable("Unknown instruction type encountered!"); 1209 // Build the switch statement using the Instruction.def file. 1210 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1211 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1212 #include "llvm/IR/Instruction.def" 1213 } 1214 } 1215 1216 static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG, 1217 DILocalVariable *Variable, 1218 DebugLoc DL, unsigned Order, 1219 RawLocationWrapper Values, 1220 DIExpression *Expression) { 1221 if (!Values.hasArgList()) 1222 return false; 1223 // For variadic dbg_values we will now insert an undef. 1224 // FIXME: We can potentially recover these! 1225 SmallVector<SDDbgOperand, 2> Locs; 1226 for (const Value *V : Values.location_ops()) { 1227 auto *Undef = UndefValue::get(V->getType()); 1228 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1229 } 1230 SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {}, 1231 /*IsIndirect=*/false, DL, Order, 1232 /*IsVariadic=*/true); 1233 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1234 return true; 1235 } 1236 1237 void SelectionDAGBuilder::addDanglingDebugInfo(const VarLocInfo *VarLoc, 1238 unsigned Order) { 1239 if (!handleDanglingVariadicDebugInfo( 1240 DAG, 1241 const_cast<DILocalVariable *>(DAG.getFunctionVarLocs() 1242 ->getVariable(VarLoc->VariableID) 1243 .getVariable()), 1244 VarLoc->DL, Order, VarLoc->Values, VarLoc->Expr)) { 1245 DanglingDebugInfoMap[VarLoc->Values.getVariableLocationOp(0)].emplace_back( 1246 VarLoc, Order); 1247 } 1248 } 1249 1250 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI, 1251 unsigned Order) { 1252 // We treat variadic dbg_values differently at this stage. 1253 if (!handleDanglingVariadicDebugInfo( 1254 DAG, DI->getVariable(), DI->getDebugLoc(), Order, 1255 DI->getWrappedLocation(), DI->getExpression())) { 1256 // TODO: Dangling debug info will eventually either be resolved or produce 1257 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1258 // between the original dbg.value location and its resolved DBG_VALUE, 1259 // which we should ideally fill with an extra Undef DBG_VALUE. 1260 assert(DI->getNumVariableLocationOps() == 1 && 1261 "DbgValueInst without an ArgList should have a single location " 1262 "operand."); 1263 DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, Order); 1264 } 1265 } 1266 1267 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1268 const DIExpression *Expr) { 1269 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1270 DIVariable *DanglingVariable = DDI.getVariable(DAG.getFunctionVarLocs()); 1271 DIExpression *DanglingExpr = DDI.getExpression(); 1272 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1273 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << printDDI(DDI) 1274 << "\n"); 1275 return true; 1276 } 1277 return false; 1278 }; 1279 1280 for (auto &DDIMI : DanglingDebugInfoMap) { 1281 DanglingDebugInfoVector &DDIV = DDIMI.second; 1282 1283 // If debug info is to be dropped, run it through final checks to see 1284 // whether it can be salvaged. 1285 for (auto &DDI : DDIV) 1286 if (isMatchingDbgValue(DDI)) 1287 salvageUnresolvedDbgValue(DDI); 1288 1289 erase_if(DDIV, isMatchingDbgValue); 1290 } 1291 } 1292 1293 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1294 // generate the debug data structures now that we've seen its definition. 1295 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1296 SDValue Val) { 1297 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1298 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1299 return; 1300 1301 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1302 for (auto &DDI : DDIV) { 1303 DebugLoc DL = DDI.getDebugLoc(); 1304 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1305 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1306 DILocalVariable *Variable = DDI.getVariable(DAG.getFunctionVarLocs()); 1307 DIExpression *Expr = DDI.getExpression(); 1308 assert(Variable->isValidLocationForIntrinsic(DL) && 1309 "Expected inlined-at fields to agree"); 1310 SDDbgValue *SDV; 1311 if (Val.getNode()) { 1312 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1313 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1314 // we couldn't resolve it directly when examining the DbgValue intrinsic 1315 // in the first place we should not be more successful here). Unless we 1316 // have some test case that prove this to be correct we should avoid 1317 // calling EmitFuncArgumentDbgValue here. 1318 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL, 1319 FuncArgumentDbgValueKind::Value, Val)) { 1320 LLVM_DEBUG(dbgs() << "Resolve dangling debug info for " << printDDI(DDI) 1321 << "\n"); 1322 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1323 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1324 // inserted after the definition of Val when emitting the instructions 1325 // after ISel. An alternative could be to teach 1326 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1327 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1328 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1329 << ValSDNodeOrder << "\n"); 1330 SDV = getDbgValue(Val, Variable, Expr, DL, 1331 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1332 DAG.AddDbgValue(SDV, false); 1333 } else 1334 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " 1335 << printDDI(DDI) << " in EmitFuncArgumentDbgValue\n"); 1336 } else { 1337 LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(DDI) << "\n"); 1338 auto Undef = UndefValue::get(V->getType()); 1339 auto SDV = 1340 DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder); 1341 DAG.AddDbgValue(SDV, false); 1342 } 1343 } 1344 DDIV.clear(); 1345 } 1346 1347 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1348 // TODO: For the variadic implementation, instead of only checking the fail 1349 // state of `handleDebugValue`, we need know specifically which values were 1350 // invalid, so that we attempt to salvage only those values when processing 1351 // a DIArgList. 1352 Value *V = DDI.getVariableLocationOp(0); 1353 Value *OrigV = V; 1354 DILocalVariable *Var = DDI.getVariable(DAG.getFunctionVarLocs()); 1355 DIExpression *Expr = DDI.getExpression(); 1356 DebugLoc DL = DDI.getDebugLoc(); 1357 unsigned SDOrder = DDI.getSDNodeOrder(); 1358 1359 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1360 // that DW_OP_stack_value is desired. 1361 bool StackValue = true; 1362 1363 // Can this Value can be encoded without any further work? 1364 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) 1365 return; 1366 1367 // Attempt to salvage back through as many instructions as possible. Bail if 1368 // a non-instruction is seen, such as a constant expression or global 1369 // variable. FIXME: Further work could recover those too. 1370 while (isa<Instruction>(V)) { 1371 Instruction &VAsInst = *cast<Instruction>(V); 1372 // Temporary "0", awaiting real implementation. 1373 SmallVector<uint64_t, 16> Ops; 1374 SmallVector<Value *, 4> AdditionalValues; 1375 V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops, 1376 AdditionalValues); 1377 // If we cannot salvage any further, and haven't yet found a suitable debug 1378 // expression, bail out. 1379 if (!V) 1380 break; 1381 1382 // TODO: If AdditionalValues isn't empty, then the salvage can only be 1383 // represented with a DBG_VALUE_LIST, so we give up. When we have support 1384 // here for variadic dbg_values, remove that condition. 1385 if (!AdditionalValues.empty()) 1386 break; 1387 1388 // New value and expr now represent this debuginfo. 1389 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue); 1390 1391 // Some kind of simplification occurred: check whether the operand of the 1392 // salvaged debug expression can be encoded in this DAG. 1393 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) { 1394 LLVM_DEBUG( 1395 dbgs() << "Salvaged debug location info for:\n " << *Var << "\n" 1396 << *OrigV << "\nBy stripping back to:\n " << *V << "\n"); 1397 return; 1398 } 1399 } 1400 1401 // This was the final opportunity to salvage this debug information, and it 1402 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1403 // any earlier variable location. 1404 assert(OrigV && "V shouldn't be null"); 1405 auto *Undef = UndefValue::get(OrigV->getType()); 1406 auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1407 DAG.AddDbgValue(SDV, false); 1408 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << printDDI(DDI) 1409 << "\n"); 1410 } 1411 1412 void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var, 1413 DIExpression *Expr, 1414 DebugLoc DbgLoc, 1415 unsigned Order) { 1416 Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context)); 1417 DIExpression *NewExpr = 1418 const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr)); 1419 handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order, 1420 /*IsVariadic*/ false); 1421 } 1422 1423 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1424 DILocalVariable *Var, 1425 DIExpression *Expr, DebugLoc DbgLoc, 1426 unsigned Order, bool IsVariadic) { 1427 if (Values.empty()) 1428 return true; 1429 SmallVector<SDDbgOperand> LocationOps; 1430 SmallVector<SDNode *> Dependencies; 1431 for (const Value *V : Values) { 1432 // Constant value. 1433 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1434 isa<ConstantPointerNull>(V)) { 1435 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1436 continue; 1437 } 1438 1439 // Look through IntToPtr constants. 1440 if (auto *CE = dyn_cast<ConstantExpr>(V)) 1441 if (CE->getOpcode() == Instruction::IntToPtr) { 1442 LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0))); 1443 continue; 1444 } 1445 1446 // If the Value is a frame index, we can create a FrameIndex debug value 1447 // without relying on the DAG at all. 1448 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1449 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1450 if (SI != FuncInfo.StaticAllocaMap.end()) { 1451 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1452 continue; 1453 } 1454 } 1455 1456 // Do not use getValue() in here; we don't want to generate code at 1457 // this point if it hasn't been done yet. 1458 SDValue N = NodeMap[V]; 1459 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1460 N = UnusedArgNodeMap[V]; 1461 if (N.getNode()) { 1462 // Only emit func arg dbg value for non-variadic dbg.values for now. 1463 if (!IsVariadic && 1464 EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc, 1465 FuncArgumentDbgValueKind::Value, N)) 1466 return true; 1467 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1468 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1469 // describe stack slot locations. 1470 // 1471 // Consider "int x = 0; int *px = &x;". There are two kinds of 1472 // interesting debug values here after optimization: 1473 // 1474 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1475 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1476 // 1477 // Both describe the direct values of their associated variables. 1478 Dependencies.push_back(N.getNode()); 1479 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1480 continue; 1481 } 1482 LocationOps.emplace_back( 1483 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1484 continue; 1485 } 1486 1487 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1488 // Special rules apply for the first dbg.values of parameter variables in a 1489 // function. Identify them by the fact they reference Argument Values, that 1490 // they're parameters, and they are parameters of the current function. We 1491 // need to let them dangle until they get an SDNode. 1492 bool IsParamOfFunc = 1493 isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt(); 1494 if (IsParamOfFunc) 1495 return false; 1496 1497 // The value is not used in this block yet (or it would have an SDNode). 1498 // We still want the value to appear for the user if possible -- if it has 1499 // an associated VReg, we can refer to that instead. 1500 auto VMI = FuncInfo.ValueMap.find(V); 1501 if (VMI != FuncInfo.ValueMap.end()) { 1502 unsigned Reg = VMI->second; 1503 // If this is a PHI node, it may be split up into several MI PHI nodes 1504 // (in FunctionLoweringInfo::set). 1505 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1506 V->getType(), std::nullopt); 1507 if (RFV.occupiesMultipleRegs()) { 1508 // FIXME: We could potentially support variadic dbg_values here. 1509 if (IsVariadic) 1510 return false; 1511 unsigned Offset = 0; 1512 unsigned BitsToDescribe = 0; 1513 if (auto VarSize = Var->getSizeInBits()) 1514 BitsToDescribe = *VarSize; 1515 if (auto Fragment = Expr->getFragmentInfo()) 1516 BitsToDescribe = Fragment->SizeInBits; 1517 for (const auto &RegAndSize : RFV.getRegsAndSizes()) { 1518 // Bail out if all bits are described already. 1519 if (Offset >= BitsToDescribe) 1520 break; 1521 // TODO: handle scalable vectors. 1522 unsigned RegisterSize = RegAndSize.second; 1523 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1524 ? BitsToDescribe - Offset 1525 : RegisterSize; 1526 auto FragmentExpr = DIExpression::createFragmentExpression( 1527 Expr, Offset, FragmentSize); 1528 if (!FragmentExpr) 1529 continue; 1530 SDDbgValue *SDV = DAG.getVRegDbgValue( 1531 Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, SDNodeOrder); 1532 DAG.AddDbgValue(SDV, false); 1533 Offset += RegisterSize; 1534 } 1535 return true; 1536 } 1537 // We can use simple vreg locations for variadic dbg_values as well. 1538 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1539 continue; 1540 } 1541 // We failed to create a SDDbgOperand for V. 1542 return false; 1543 } 1544 1545 // We have created a SDDbgOperand for each Value in Values. 1546 // Should use Order instead of SDNodeOrder? 1547 assert(!LocationOps.empty()); 1548 SDDbgValue *SDV = DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1549 /*IsIndirect=*/false, DbgLoc, 1550 SDNodeOrder, IsVariadic); 1551 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1552 return true; 1553 } 1554 1555 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1556 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1557 for (auto &Pair : DanglingDebugInfoMap) 1558 for (auto &DDI : Pair.second) 1559 salvageUnresolvedDbgValue(DDI); 1560 clearDanglingDebugInfo(); 1561 } 1562 1563 /// getCopyFromRegs - If there was virtual register allocated for the value V 1564 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1565 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1566 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1567 SDValue Result; 1568 1569 if (It != FuncInfo.ValueMap.end()) { 1570 Register InReg = It->second; 1571 1572 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1573 DAG.getDataLayout(), InReg, Ty, 1574 std::nullopt); // This is not an ABI copy. 1575 SDValue Chain = DAG.getEntryNode(); 1576 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1577 V); 1578 resolveDanglingDebugInfo(V, Result); 1579 } 1580 1581 return Result; 1582 } 1583 1584 /// getValue - Return an SDValue for the given Value. 1585 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1586 // If we already have an SDValue for this value, use it. It's important 1587 // to do this first, so that we don't create a CopyFromReg if we already 1588 // have a regular SDValue. 1589 SDValue &N = NodeMap[V]; 1590 if (N.getNode()) return N; 1591 1592 // If there's a virtual register allocated and initialized for this 1593 // value, use it. 1594 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1595 return copyFromReg; 1596 1597 // Otherwise create a new SDValue and remember it. 1598 SDValue Val = getValueImpl(V); 1599 NodeMap[V] = Val; 1600 resolveDanglingDebugInfo(V, Val); 1601 return Val; 1602 } 1603 1604 /// getNonRegisterValue - Return an SDValue for the given Value, but 1605 /// don't look in FuncInfo.ValueMap for a virtual register. 1606 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1607 // If we already have an SDValue for this value, use it. 1608 SDValue &N = NodeMap[V]; 1609 if (N.getNode()) { 1610 if (isIntOrFPConstant(N)) { 1611 // Remove the debug location from the node as the node is about to be used 1612 // in a location which may differ from the original debug location. This 1613 // is relevant to Constant and ConstantFP nodes because they can appear 1614 // as constant expressions inside PHI nodes. 1615 N->setDebugLoc(DebugLoc()); 1616 } 1617 return N; 1618 } 1619 1620 // Otherwise create a new SDValue and remember it. 1621 SDValue Val = getValueImpl(V); 1622 NodeMap[V] = Val; 1623 resolveDanglingDebugInfo(V, Val); 1624 return Val; 1625 } 1626 1627 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1628 /// Create an SDValue for the given value. 1629 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1630 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1631 1632 if (const Constant *C = dyn_cast<Constant>(V)) { 1633 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1634 1635 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1636 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1637 1638 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1639 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1640 1641 if (isa<ConstantPointerNull>(C)) { 1642 unsigned AS = V->getType()->getPointerAddressSpace(); 1643 return DAG.getConstant(0, getCurSDLoc(), 1644 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1645 } 1646 1647 if (match(C, m_VScale())) 1648 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1649 1650 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1651 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1652 1653 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1654 return DAG.getUNDEF(VT); 1655 1656 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1657 visit(CE->getOpcode(), *CE); 1658 SDValue N1 = NodeMap[V]; 1659 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1660 return N1; 1661 } 1662 1663 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1664 SmallVector<SDValue, 4> Constants; 1665 for (const Use &U : C->operands()) { 1666 SDNode *Val = getValue(U).getNode(); 1667 // If the operand is an empty aggregate, there are no values. 1668 if (!Val) continue; 1669 // Add each leaf value from the operand to the Constants list 1670 // to form a flattened list of all the values. 1671 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1672 Constants.push_back(SDValue(Val, i)); 1673 } 1674 1675 return DAG.getMergeValues(Constants, getCurSDLoc()); 1676 } 1677 1678 if (const ConstantDataSequential *CDS = 1679 dyn_cast<ConstantDataSequential>(C)) { 1680 SmallVector<SDValue, 4> Ops; 1681 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1682 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1683 // Add each leaf value from the operand to the Constants list 1684 // to form a flattened list of all the values. 1685 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1686 Ops.push_back(SDValue(Val, i)); 1687 } 1688 1689 if (isa<ArrayType>(CDS->getType())) 1690 return DAG.getMergeValues(Ops, getCurSDLoc()); 1691 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1692 } 1693 1694 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1695 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1696 "Unknown struct or array constant!"); 1697 1698 SmallVector<EVT, 4> ValueVTs; 1699 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1700 unsigned NumElts = ValueVTs.size(); 1701 if (NumElts == 0) 1702 return SDValue(); // empty struct 1703 SmallVector<SDValue, 4> Constants(NumElts); 1704 for (unsigned i = 0; i != NumElts; ++i) { 1705 EVT EltVT = ValueVTs[i]; 1706 if (isa<UndefValue>(C)) 1707 Constants[i] = DAG.getUNDEF(EltVT); 1708 else if (EltVT.isFloatingPoint()) 1709 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1710 else 1711 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1712 } 1713 1714 return DAG.getMergeValues(Constants, getCurSDLoc()); 1715 } 1716 1717 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1718 return DAG.getBlockAddress(BA, VT); 1719 1720 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1721 return getValue(Equiv->getGlobalValue()); 1722 1723 if (const auto *NC = dyn_cast<NoCFIValue>(C)) 1724 return getValue(NC->getGlobalValue()); 1725 1726 VectorType *VecTy = cast<VectorType>(V->getType()); 1727 1728 // Now that we know the number and type of the elements, get that number of 1729 // elements into the Ops array based on what kind of constant it is. 1730 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1731 SmallVector<SDValue, 16> Ops; 1732 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1733 for (unsigned i = 0; i != NumElements; ++i) 1734 Ops.push_back(getValue(CV->getOperand(i))); 1735 1736 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1737 } 1738 1739 if (isa<ConstantAggregateZero>(C)) { 1740 EVT EltVT = 1741 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1742 1743 SDValue Op; 1744 if (EltVT.isFloatingPoint()) 1745 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1746 else 1747 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1748 1749 return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op); 1750 } 1751 1752 llvm_unreachable("Unknown vector constant"); 1753 } 1754 1755 // If this is a static alloca, generate it as the frameindex instead of 1756 // computation. 1757 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1758 DenseMap<const AllocaInst*, int>::iterator SI = 1759 FuncInfo.StaticAllocaMap.find(AI); 1760 if (SI != FuncInfo.StaticAllocaMap.end()) 1761 return DAG.getFrameIndex( 1762 SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType())); 1763 } 1764 1765 // If this is an instruction which fast-isel has deferred, select it now. 1766 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1767 Register InReg = FuncInfo.InitializeRegForValue(Inst); 1768 1769 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1770 Inst->getType(), std::nullopt); 1771 SDValue Chain = DAG.getEntryNode(); 1772 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1773 } 1774 1775 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) 1776 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1777 1778 if (const auto *BB = dyn_cast<BasicBlock>(V)) 1779 return DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 1780 1781 llvm_unreachable("Can't get register for value!"); 1782 } 1783 1784 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1785 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1786 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1787 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1788 bool IsSEH = isAsynchronousEHPersonality(Pers); 1789 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1790 if (!IsSEH) 1791 CatchPadMBB->setIsEHScopeEntry(); 1792 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1793 if (IsMSVCCXX || IsCoreCLR) 1794 CatchPadMBB->setIsEHFuncletEntry(); 1795 } 1796 1797 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1798 // Update machine-CFG edge. 1799 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1800 FuncInfo.MBB->addSuccessor(TargetMBB); 1801 TargetMBB->setIsEHCatchretTarget(true); 1802 DAG.getMachineFunction().setHasEHCatchret(true); 1803 1804 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1805 bool IsSEH = isAsynchronousEHPersonality(Pers); 1806 if (IsSEH) { 1807 // If this is not a fall-through branch or optimizations are switched off, 1808 // emit the branch. 1809 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1810 TM.getOptLevel() == CodeGenOpt::None) 1811 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1812 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1813 return; 1814 } 1815 1816 // Figure out the funclet membership for the catchret's successor. 1817 // This will be used by the FuncletLayout pass to determine how to order the 1818 // BB's. 1819 // A 'catchret' returns to the outer scope's color. 1820 Value *ParentPad = I.getCatchSwitchParentPad(); 1821 const BasicBlock *SuccessorColor; 1822 if (isa<ConstantTokenNone>(ParentPad)) 1823 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1824 else 1825 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1826 assert(SuccessorColor && "No parent funclet for catchret!"); 1827 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1828 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1829 1830 // Create the terminator node. 1831 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1832 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1833 DAG.getBasicBlock(SuccessorColorMBB)); 1834 DAG.setRoot(Ret); 1835 } 1836 1837 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1838 // Don't emit any special code for the cleanuppad instruction. It just marks 1839 // the start of an EH scope/funclet. 1840 FuncInfo.MBB->setIsEHScopeEntry(); 1841 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1842 if (Pers != EHPersonality::Wasm_CXX) { 1843 FuncInfo.MBB->setIsEHFuncletEntry(); 1844 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1845 } 1846 } 1847 1848 // In wasm EH, even though a catchpad may not catch an exception if a tag does 1849 // not match, it is OK to add only the first unwind destination catchpad to the 1850 // successors, because there will be at least one invoke instruction within the 1851 // catch scope that points to the next unwind destination, if one exists, so 1852 // CFGSort cannot mess up with BB sorting order. 1853 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 1854 // call within them, and catchpads only consisting of 'catch (...)' have a 1855 // '__cxa_end_catch' call within them, both of which generate invokes in case 1856 // the next unwind destination exists, i.e., the next unwind destination is not 1857 // the caller.) 1858 // 1859 // Having at most one EH pad successor is also simpler and helps later 1860 // transformations. 1861 // 1862 // For example, 1863 // current: 1864 // invoke void @foo to ... unwind label %catch.dispatch 1865 // catch.dispatch: 1866 // %0 = catchswitch within ... [label %catch.start] unwind label %next 1867 // catch.start: 1868 // ... 1869 // ... in this BB or some other child BB dominated by this BB there will be an 1870 // invoke that points to 'next' BB as an unwind destination 1871 // 1872 // next: ; We don't need to add this to 'current' BB's successor 1873 // ... 1874 static void findWasmUnwindDestinations( 1875 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1876 BranchProbability Prob, 1877 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1878 &UnwindDests) { 1879 while (EHPadBB) { 1880 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1881 if (isa<CleanupPadInst>(Pad)) { 1882 // Stop on cleanup pads. 1883 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1884 UnwindDests.back().first->setIsEHScopeEntry(); 1885 break; 1886 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1887 // Add the catchpad handlers to the possible destinations. We don't 1888 // continue to the unwind destination of the catchswitch for wasm. 1889 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1890 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1891 UnwindDests.back().first->setIsEHScopeEntry(); 1892 } 1893 break; 1894 } else { 1895 continue; 1896 } 1897 } 1898 } 1899 1900 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1901 /// many places it could ultimately go. In the IR, we have a single unwind 1902 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1903 /// This function skips over imaginary basic blocks that hold catchswitch 1904 /// instructions, and finds all the "real" machine 1905 /// basic block destinations. As those destinations may not be successors of 1906 /// EHPadBB, here we also calculate the edge probability to those destinations. 1907 /// The passed-in Prob is the edge probability to EHPadBB. 1908 static void findUnwindDestinations( 1909 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1910 BranchProbability Prob, 1911 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1912 &UnwindDests) { 1913 EHPersonality Personality = 1914 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1915 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1916 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1917 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1918 bool IsSEH = isAsynchronousEHPersonality(Personality); 1919 1920 if (IsWasmCXX) { 1921 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1922 assert(UnwindDests.size() <= 1 && 1923 "There should be at most one unwind destination for wasm"); 1924 return; 1925 } 1926 1927 while (EHPadBB) { 1928 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1929 BasicBlock *NewEHPadBB = nullptr; 1930 if (isa<LandingPadInst>(Pad)) { 1931 // Stop on landingpads. They are not funclets. 1932 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1933 break; 1934 } else if (isa<CleanupPadInst>(Pad)) { 1935 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1936 // personalities. 1937 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1938 UnwindDests.back().first->setIsEHScopeEntry(); 1939 UnwindDests.back().first->setIsEHFuncletEntry(); 1940 break; 1941 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1942 // Add the catchpad handlers to the possible destinations. 1943 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1944 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1945 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1946 if (IsMSVCCXX || IsCoreCLR) 1947 UnwindDests.back().first->setIsEHFuncletEntry(); 1948 if (!IsSEH) 1949 UnwindDests.back().first->setIsEHScopeEntry(); 1950 } 1951 NewEHPadBB = CatchSwitch->getUnwindDest(); 1952 } else { 1953 continue; 1954 } 1955 1956 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1957 if (BPI && NewEHPadBB) 1958 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1959 EHPadBB = NewEHPadBB; 1960 } 1961 } 1962 1963 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1964 // Update successor info. 1965 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1966 auto UnwindDest = I.getUnwindDest(); 1967 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1968 BranchProbability UnwindDestProb = 1969 (BPI && UnwindDest) 1970 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1971 : BranchProbability::getZero(); 1972 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1973 for (auto &UnwindDest : UnwindDests) { 1974 UnwindDest.first->setIsEHPad(); 1975 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1976 } 1977 FuncInfo.MBB->normalizeSuccProbs(); 1978 1979 // Create the terminator node. 1980 SDValue Ret = 1981 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1982 DAG.setRoot(Ret); 1983 } 1984 1985 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1986 report_fatal_error("visitCatchSwitch not yet implemented!"); 1987 } 1988 1989 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1990 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1991 auto &DL = DAG.getDataLayout(); 1992 SDValue Chain = getControlRoot(); 1993 SmallVector<ISD::OutputArg, 8> Outs; 1994 SmallVector<SDValue, 8> OutVals; 1995 1996 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1997 // lower 1998 // 1999 // %val = call <ty> @llvm.experimental.deoptimize() 2000 // ret <ty> %val 2001 // 2002 // differently. 2003 if (I.getParent()->getTerminatingDeoptimizeCall()) { 2004 LowerDeoptimizingReturn(); 2005 return; 2006 } 2007 2008 if (!FuncInfo.CanLowerReturn) { 2009 unsigned DemoteReg = FuncInfo.DemoteRegister; 2010 const Function *F = I.getParent()->getParent(); 2011 2012 // Emit a store of the return value through the virtual register. 2013 // Leave Outs empty so that LowerReturn won't try to load return 2014 // registers the usual way. 2015 SmallVector<EVT, 1> PtrValueVTs; 2016 ComputeValueVTs(TLI, DL, 2017 F->getReturnType()->getPointerTo( 2018 DAG.getDataLayout().getAllocaAddrSpace()), 2019 PtrValueVTs); 2020 2021 SDValue RetPtr = 2022 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]); 2023 SDValue RetOp = getValue(I.getOperand(0)); 2024 2025 SmallVector<EVT, 4> ValueVTs, MemVTs; 2026 SmallVector<uint64_t, 4> Offsets; 2027 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 2028 &Offsets, 0); 2029 unsigned NumValues = ValueVTs.size(); 2030 2031 SmallVector<SDValue, 4> Chains(NumValues); 2032 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 2033 for (unsigned i = 0; i != NumValues; ++i) { 2034 // An aggregate return value cannot wrap around the address space, so 2035 // offsets to its parts don't wrap either. 2036 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 2037 TypeSize::Fixed(Offsets[i])); 2038 2039 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 2040 if (MemVTs[i] != ValueVTs[i]) 2041 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 2042 Chains[i] = DAG.getStore( 2043 Chain, getCurSDLoc(), Val, 2044 // FIXME: better loc info would be nice. 2045 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 2046 commonAlignment(BaseAlign, Offsets[i])); 2047 } 2048 2049 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 2050 MVT::Other, Chains); 2051 } else if (I.getNumOperands() != 0) { 2052 SmallVector<EVT, 4> ValueVTs; 2053 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 2054 unsigned NumValues = ValueVTs.size(); 2055 if (NumValues) { 2056 SDValue RetOp = getValue(I.getOperand(0)); 2057 2058 const Function *F = I.getParent()->getParent(); 2059 2060 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 2061 I.getOperand(0)->getType(), F->getCallingConv(), 2062 /*IsVarArg*/ false, DL); 2063 2064 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 2065 if (F->getAttributes().hasRetAttr(Attribute::SExt)) 2066 ExtendKind = ISD::SIGN_EXTEND; 2067 else if (F->getAttributes().hasRetAttr(Attribute::ZExt)) 2068 ExtendKind = ISD::ZERO_EXTEND; 2069 2070 LLVMContext &Context = F->getContext(); 2071 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg); 2072 2073 for (unsigned j = 0; j != NumValues; ++j) { 2074 EVT VT = ValueVTs[j]; 2075 2076 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 2077 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 2078 2079 CallingConv::ID CC = F->getCallingConv(); 2080 2081 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 2082 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 2083 SmallVector<SDValue, 4> Parts(NumParts); 2084 getCopyToParts(DAG, getCurSDLoc(), 2085 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 2086 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 2087 2088 // 'inreg' on function refers to return value 2089 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2090 if (RetInReg) 2091 Flags.setInReg(); 2092 2093 if (I.getOperand(0)->getType()->isPointerTy()) { 2094 Flags.setPointer(); 2095 Flags.setPointerAddrSpace( 2096 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 2097 } 2098 2099 if (NeedsRegBlock) { 2100 Flags.setInConsecutiveRegs(); 2101 if (j == NumValues - 1) 2102 Flags.setInConsecutiveRegsLast(); 2103 } 2104 2105 // Propagate extension type if any 2106 if (ExtendKind == ISD::SIGN_EXTEND) 2107 Flags.setSExt(); 2108 else if (ExtendKind == ISD::ZERO_EXTEND) 2109 Flags.setZExt(); 2110 2111 for (unsigned i = 0; i < NumParts; ++i) { 2112 Outs.push_back(ISD::OutputArg(Flags, 2113 Parts[i].getValueType().getSimpleVT(), 2114 VT, /*isfixed=*/true, 0, 0)); 2115 OutVals.push_back(Parts[i]); 2116 } 2117 } 2118 } 2119 } 2120 2121 // Push in swifterror virtual register as the last element of Outs. This makes 2122 // sure swifterror virtual register will be returned in the swifterror 2123 // physical register. 2124 const Function *F = I.getParent()->getParent(); 2125 if (TLI.supportSwiftError() && 2126 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2127 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2128 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2129 Flags.setSwiftError(); 2130 Outs.push_back(ISD::OutputArg( 2131 Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)), 2132 /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0)); 2133 // Create SDNode for the swifterror virtual register. 2134 OutVals.push_back( 2135 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2136 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2137 EVT(TLI.getPointerTy(DL)))); 2138 } 2139 2140 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2141 CallingConv::ID CallConv = 2142 DAG.getMachineFunction().getFunction().getCallingConv(); 2143 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2144 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2145 2146 // Verify that the target's LowerReturn behaved as expected. 2147 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2148 "LowerReturn didn't return a valid chain!"); 2149 2150 // Update the DAG with the new chain value resulting from return lowering. 2151 DAG.setRoot(Chain); 2152 } 2153 2154 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2155 /// created for it, emit nodes to copy the value into the virtual 2156 /// registers. 2157 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2158 // Skip empty types 2159 if (V->getType()->isEmptyTy()) 2160 return; 2161 2162 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2163 if (VMI != FuncInfo.ValueMap.end()) { 2164 assert((!V->use_empty() || isa<CallBrInst>(V)) && 2165 "Unused value assigned virtual registers!"); 2166 CopyValueToVirtualRegister(V, VMI->second); 2167 } 2168 } 2169 2170 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2171 /// the current basic block, add it to ValueMap now so that we'll get a 2172 /// CopyTo/FromReg. 2173 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2174 // No need to export constants. 2175 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2176 2177 // Already exported? 2178 if (FuncInfo.isExportedInst(V)) return; 2179 2180 Register Reg = FuncInfo.InitializeRegForValue(V); 2181 CopyValueToVirtualRegister(V, Reg); 2182 } 2183 2184 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2185 const BasicBlock *FromBB) { 2186 // The operands of the setcc have to be in this block. We don't know 2187 // how to export them from some other block. 2188 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2189 // Can export from current BB. 2190 if (VI->getParent() == FromBB) 2191 return true; 2192 2193 // Is already exported, noop. 2194 return FuncInfo.isExportedInst(V); 2195 } 2196 2197 // If this is an argument, we can export it if the BB is the entry block or 2198 // if it is already exported. 2199 if (isa<Argument>(V)) { 2200 if (FromBB->isEntryBlock()) 2201 return true; 2202 2203 // Otherwise, can only export this if it is already exported. 2204 return FuncInfo.isExportedInst(V); 2205 } 2206 2207 // Otherwise, constants can always be exported. 2208 return true; 2209 } 2210 2211 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2212 BranchProbability 2213 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2214 const MachineBasicBlock *Dst) const { 2215 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2216 const BasicBlock *SrcBB = Src->getBasicBlock(); 2217 const BasicBlock *DstBB = Dst->getBasicBlock(); 2218 if (!BPI) { 2219 // If BPI is not available, set the default probability as 1 / N, where N is 2220 // the number of successors. 2221 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2222 return BranchProbability(1, SuccSize); 2223 } 2224 return BPI->getEdgeProbability(SrcBB, DstBB); 2225 } 2226 2227 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2228 MachineBasicBlock *Dst, 2229 BranchProbability Prob) { 2230 if (!FuncInfo.BPI) 2231 Src->addSuccessorWithoutProb(Dst); 2232 else { 2233 if (Prob.isUnknown()) 2234 Prob = getEdgeProbability(Src, Dst); 2235 Src->addSuccessor(Dst, Prob); 2236 } 2237 } 2238 2239 static bool InBlock(const Value *V, const BasicBlock *BB) { 2240 if (const Instruction *I = dyn_cast<Instruction>(V)) 2241 return I->getParent() == BB; 2242 return true; 2243 } 2244 2245 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2246 /// This function emits a branch and is used at the leaves of an OR or an 2247 /// AND operator tree. 2248 void 2249 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2250 MachineBasicBlock *TBB, 2251 MachineBasicBlock *FBB, 2252 MachineBasicBlock *CurBB, 2253 MachineBasicBlock *SwitchBB, 2254 BranchProbability TProb, 2255 BranchProbability FProb, 2256 bool InvertCond) { 2257 const BasicBlock *BB = CurBB->getBasicBlock(); 2258 2259 // If the leaf of the tree is a comparison, merge the condition into 2260 // the caseblock. 2261 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2262 // The operands of the cmp have to be in this block. We don't know 2263 // how to export them from some other block. If this is the first block 2264 // of the sequence, no exporting is needed. 2265 if (CurBB == SwitchBB || 2266 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2267 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2268 ISD::CondCode Condition; 2269 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2270 ICmpInst::Predicate Pred = 2271 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2272 Condition = getICmpCondCode(Pred); 2273 } else { 2274 const FCmpInst *FC = cast<FCmpInst>(Cond); 2275 FCmpInst::Predicate Pred = 2276 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2277 Condition = getFCmpCondCode(Pred); 2278 if (TM.Options.NoNaNsFPMath) 2279 Condition = getFCmpCodeWithoutNaN(Condition); 2280 } 2281 2282 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2283 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2284 SL->SwitchCases.push_back(CB); 2285 return; 2286 } 2287 } 2288 2289 // Create a CaseBlock record representing this branch. 2290 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2291 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2292 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2293 SL->SwitchCases.push_back(CB); 2294 } 2295 2296 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2297 MachineBasicBlock *TBB, 2298 MachineBasicBlock *FBB, 2299 MachineBasicBlock *CurBB, 2300 MachineBasicBlock *SwitchBB, 2301 Instruction::BinaryOps Opc, 2302 BranchProbability TProb, 2303 BranchProbability FProb, 2304 bool InvertCond) { 2305 // Skip over not part of the tree and remember to invert op and operands at 2306 // next level. 2307 Value *NotCond; 2308 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2309 InBlock(NotCond, CurBB->getBasicBlock())) { 2310 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2311 !InvertCond); 2312 return; 2313 } 2314 2315 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2316 const Value *BOpOp0, *BOpOp1; 2317 // Compute the effective opcode for Cond, taking into account whether it needs 2318 // to be inverted, e.g. 2319 // and (not (or A, B)), C 2320 // gets lowered as 2321 // and (and (not A, not B), C) 2322 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2323 if (BOp) { 2324 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2325 ? Instruction::And 2326 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2327 ? Instruction::Or 2328 : (Instruction::BinaryOps)0); 2329 if (InvertCond) { 2330 if (BOpc == Instruction::And) 2331 BOpc = Instruction::Or; 2332 else if (BOpc == Instruction::Or) 2333 BOpc = Instruction::And; 2334 } 2335 } 2336 2337 // If this node is not part of the or/and tree, emit it as a branch. 2338 // Note that all nodes in the tree should have same opcode. 2339 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2340 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2341 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2342 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2343 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2344 TProb, FProb, InvertCond); 2345 return; 2346 } 2347 2348 // Create TmpBB after CurBB. 2349 MachineFunction::iterator BBI(CurBB); 2350 MachineFunction &MF = DAG.getMachineFunction(); 2351 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2352 CurBB->getParent()->insert(++BBI, TmpBB); 2353 2354 if (Opc == Instruction::Or) { 2355 // Codegen X | Y as: 2356 // BB1: 2357 // jmp_if_X TBB 2358 // jmp TmpBB 2359 // TmpBB: 2360 // jmp_if_Y TBB 2361 // jmp FBB 2362 // 2363 2364 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2365 // The requirement is that 2366 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2367 // = TrueProb for original BB. 2368 // Assuming the original probabilities are A and B, one choice is to set 2369 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2370 // A/(1+B) and 2B/(1+B). This choice assumes that 2371 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2372 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2373 // TmpBB, but the math is more complicated. 2374 2375 auto NewTrueProb = TProb / 2; 2376 auto NewFalseProb = TProb / 2 + FProb; 2377 // Emit the LHS condition. 2378 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2379 NewFalseProb, InvertCond); 2380 2381 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2382 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2383 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2384 // Emit the RHS condition into TmpBB. 2385 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2386 Probs[1], InvertCond); 2387 } else { 2388 assert(Opc == Instruction::And && "Unknown merge op!"); 2389 // Codegen X & Y as: 2390 // BB1: 2391 // jmp_if_X TmpBB 2392 // jmp FBB 2393 // TmpBB: 2394 // jmp_if_Y TBB 2395 // jmp FBB 2396 // 2397 // This requires creation of TmpBB after CurBB. 2398 2399 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2400 // The requirement is that 2401 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2402 // = FalseProb for original BB. 2403 // Assuming the original probabilities are A and B, one choice is to set 2404 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2405 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2406 // TrueProb for BB1 * FalseProb for TmpBB. 2407 2408 auto NewTrueProb = TProb + FProb / 2; 2409 auto NewFalseProb = FProb / 2; 2410 // Emit the LHS condition. 2411 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2412 NewFalseProb, InvertCond); 2413 2414 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2415 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2416 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2417 // Emit the RHS condition into TmpBB. 2418 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2419 Probs[1], InvertCond); 2420 } 2421 } 2422 2423 /// If the set of cases should be emitted as a series of branches, return true. 2424 /// If we should emit this as a bunch of and/or'd together conditions, return 2425 /// false. 2426 bool 2427 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2428 if (Cases.size() != 2) return true; 2429 2430 // If this is two comparisons of the same values or'd or and'd together, they 2431 // will get folded into a single comparison, so don't emit two blocks. 2432 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2433 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2434 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2435 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2436 return false; 2437 } 2438 2439 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2440 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2441 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2442 Cases[0].CC == Cases[1].CC && 2443 isa<Constant>(Cases[0].CmpRHS) && 2444 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2445 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2446 return false; 2447 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2448 return false; 2449 } 2450 2451 return true; 2452 } 2453 2454 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2455 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2456 2457 // Update machine-CFG edges. 2458 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2459 2460 if (I.isUnconditional()) { 2461 // Update machine-CFG edges. 2462 BrMBB->addSuccessor(Succ0MBB); 2463 2464 // If this is not a fall-through branch or optimizations are switched off, 2465 // emit the branch. 2466 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2467 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2468 MVT::Other, getControlRoot(), 2469 DAG.getBasicBlock(Succ0MBB))); 2470 2471 return; 2472 } 2473 2474 // If this condition is one of the special cases we handle, do special stuff 2475 // now. 2476 const Value *CondVal = I.getCondition(); 2477 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2478 2479 // If this is a series of conditions that are or'd or and'd together, emit 2480 // this as a sequence of branches instead of setcc's with and/or operations. 2481 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2482 // unpredictable branches, and vector extracts because those jumps are likely 2483 // expensive for any target), this should improve performance. 2484 // For example, instead of something like: 2485 // cmp A, B 2486 // C = seteq 2487 // cmp D, E 2488 // F = setle 2489 // or C, F 2490 // jnz foo 2491 // Emit: 2492 // cmp A, B 2493 // je foo 2494 // cmp D, E 2495 // jle foo 2496 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2497 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2498 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2499 Value *Vec; 2500 const Value *BOp0, *BOp1; 2501 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2502 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2503 Opcode = Instruction::And; 2504 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2505 Opcode = Instruction::Or; 2506 2507 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2508 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2509 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2510 getEdgeProbability(BrMBB, Succ0MBB), 2511 getEdgeProbability(BrMBB, Succ1MBB), 2512 /*InvertCond=*/false); 2513 // If the compares in later blocks need to use values not currently 2514 // exported from this block, export them now. This block should always 2515 // be the first entry. 2516 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2517 2518 // Allow some cases to be rejected. 2519 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2520 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2521 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2522 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2523 } 2524 2525 // Emit the branch for this block. 2526 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2527 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2528 return; 2529 } 2530 2531 // Okay, we decided not to do this, remove any inserted MBB's and clear 2532 // SwitchCases. 2533 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2534 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2535 2536 SL->SwitchCases.clear(); 2537 } 2538 } 2539 2540 // Create a CaseBlock record representing this branch. 2541 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2542 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2543 2544 // Use visitSwitchCase to actually insert the fast branch sequence for this 2545 // cond branch. 2546 visitSwitchCase(CB, BrMBB); 2547 } 2548 2549 /// visitSwitchCase - Emits the necessary code to represent a single node in 2550 /// the binary search tree resulting from lowering a switch instruction. 2551 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2552 MachineBasicBlock *SwitchBB) { 2553 SDValue Cond; 2554 SDValue CondLHS = getValue(CB.CmpLHS); 2555 SDLoc dl = CB.DL; 2556 2557 if (CB.CC == ISD::SETTRUE) { 2558 // Branch or fall through to TrueBB. 2559 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2560 SwitchBB->normalizeSuccProbs(); 2561 if (CB.TrueBB != NextBlock(SwitchBB)) { 2562 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2563 DAG.getBasicBlock(CB.TrueBB))); 2564 } 2565 return; 2566 } 2567 2568 auto &TLI = DAG.getTargetLoweringInfo(); 2569 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2570 2571 // Build the setcc now. 2572 if (!CB.CmpMHS) { 2573 // Fold "(X == true)" to X and "(X == false)" to !X to 2574 // handle common cases produced by branch lowering. 2575 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2576 CB.CC == ISD::SETEQ) 2577 Cond = CondLHS; 2578 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2579 CB.CC == ISD::SETEQ) { 2580 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2581 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2582 } else { 2583 SDValue CondRHS = getValue(CB.CmpRHS); 2584 2585 // If a pointer's DAG type is larger than its memory type then the DAG 2586 // values are zero-extended. This breaks signed comparisons so truncate 2587 // back to the underlying type before doing the compare. 2588 if (CondLHS.getValueType() != MemVT) { 2589 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2590 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2591 } 2592 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2593 } 2594 } else { 2595 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2596 2597 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2598 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2599 2600 SDValue CmpOp = getValue(CB.CmpMHS); 2601 EVT VT = CmpOp.getValueType(); 2602 2603 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2604 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2605 ISD::SETLE); 2606 } else { 2607 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2608 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2609 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2610 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2611 } 2612 } 2613 2614 // Update successor info 2615 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2616 // TrueBB and FalseBB are always different unless the incoming IR is 2617 // degenerate. This only happens when running llc on weird IR. 2618 if (CB.TrueBB != CB.FalseBB) 2619 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2620 SwitchBB->normalizeSuccProbs(); 2621 2622 // If the lhs block is the next block, invert the condition so that we can 2623 // fall through to the lhs instead of the rhs block. 2624 if (CB.TrueBB == NextBlock(SwitchBB)) { 2625 std::swap(CB.TrueBB, CB.FalseBB); 2626 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2627 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2628 } 2629 2630 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2631 MVT::Other, getControlRoot(), Cond, 2632 DAG.getBasicBlock(CB.TrueBB)); 2633 2634 setValue(CurInst, BrCond); 2635 2636 // Insert the false branch. Do this even if it's a fall through branch, 2637 // this makes it easier to do DAG optimizations which require inverting 2638 // the branch condition. 2639 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2640 DAG.getBasicBlock(CB.FalseBB)); 2641 2642 DAG.setRoot(BrCond); 2643 } 2644 2645 /// visitJumpTable - Emit JumpTable node in the current MBB 2646 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2647 // Emit the code for the jump table 2648 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2649 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2650 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2651 JT.Reg, PTy); 2652 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2653 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2654 MVT::Other, Index.getValue(1), 2655 Table, Index); 2656 DAG.setRoot(BrJumpTable); 2657 } 2658 2659 /// visitJumpTableHeader - This function emits necessary code to produce index 2660 /// in the JumpTable from switch case. 2661 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2662 JumpTableHeader &JTH, 2663 MachineBasicBlock *SwitchBB) { 2664 SDLoc dl = getCurSDLoc(); 2665 2666 // Subtract the lowest switch case value from the value being switched on. 2667 SDValue SwitchOp = getValue(JTH.SValue); 2668 EVT VT = SwitchOp.getValueType(); 2669 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2670 DAG.getConstant(JTH.First, dl, VT)); 2671 2672 // The SDNode we just created, which holds the value being switched on minus 2673 // the smallest case value, needs to be copied to a virtual register so it 2674 // can be used as an index into the jump table in a subsequent basic block. 2675 // This value may be smaller or larger than the target's pointer type, and 2676 // therefore require extension or truncating. 2677 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2678 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2679 2680 unsigned JumpTableReg = 2681 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2682 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2683 JumpTableReg, SwitchOp); 2684 JT.Reg = JumpTableReg; 2685 2686 if (!JTH.FallthroughUnreachable) { 2687 // Emit the range check for the jump table, and branch to the default block 2688 // for the switch statement if the value being switched on exceeds the 2689 // largest case in the switch. 2690 SDValue CMP = DAG.getSetCC( 2691 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2692 Sub.getValueType()), 2693 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2694 2695 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2696 MVT::Other, CopyTo, CMP, 2697 DAG.getBasicBlock(JT.Default)); 2698 2699 // Avoid emitting unnecessary branches to the next block. 2700 if (JT.MBB != NextBlock(SwitchBB)) 2701 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2702 DAG.getBasicBlock(JT.MBB)); 2703 2704 DAG.setRoot(BrCond); 2705 } else { 2706 // Avoid emitting unnecessary branches to the next block. 2707 if (JT.MBB != NextBlock(SwitchBB)) 2708 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2709 DAG.getBasicBlock(JT.MBB))); 2710 else 2711 DAG.setRoot(CopyTo); 2712 } 2713 } 2714 2715 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2716 /// variable if there exists one. 2717 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2718 SDValue &Chain) { 2719 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2720 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2721 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2722 MachineFunction &MF = DAG.getMachineFunction(); 2723 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2724 MachineSDNode *Node = 2725 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2726 if (Global) { 2727 MachinePointerInfo MPInfo(Global); 2728 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2729 MachineMemOperand::MODereferenceable; 2730 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2731 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2732 DAG.setNodeMemRefs(Node, {MemRef}); 2733 } 2734 if (PtrTy != PtrMemTy) 2735 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2736 return SDValue(Node, 0); 2737 } 2738 2739 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2740 /// tail spliced into a stack protector check success bb. 2741 /// 2742 /// For a high level explanation of how this fits into the stack protector 2743 /// generation see the comment on the declaration of class 2744 /// StackProtectorDescriptor. 2745 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2746 MachineBasicBlock *ParentBB) { 2747 2748 // First create the loads to the guard/stack slot for the comparison. 2749 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2750 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2751 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2752 2753 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2754 int FI = MFI.getStackProtectorIndex(); 2755 2756 SDValue Guard; 2757 SDLoc dl = getCurSDLoc(); 2758 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2759 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2760 Align Align = 2761 DAG.getDataLayout().getPrefTypeAlign(Type::getInt8PtrTy(M.getContext())); 2762 2763 // Generate code to load the content of the guard slot. 2764 SDValue GuardVal = DAG.getLoad( 2765 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2766 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2767 MachineMemOperand::MOVolatile); 2768 2769 if (TLI.useStackGuardXorFP()) 2770 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2771 2772 // Retrieve guard check function, nullptr if instrumentation is inlined. 2773 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2774 // The target provides a guard check function to validate the guard value. 2775 // Generate a call to that function with the content of the guard slot as 2776 // argument. 2777 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2778 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2779 2780 TargetLowering::ArgListTy Args; 2781 TargetLowering::ArgListEntry Entry; 2782 Entry.Node = GuardVal; 2783 Entry.Ty = FnTy->getParamType(0); 2784 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg)) 2785 Entry.IsInReg = true; 2786 Args.push_back(Entry); 2787 2788 TargetLowering::CallLoweringInfo CLI(DAG); 2789 CLI.setDebugLoc(getCurSDLoc()) 2790 .setChain(DAG.getEntryNode()) 2791 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2792 getValue(GuardCheckFn), std::move(Args)); 2793 2794 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2795 DAG.setRoot(Result.second); 2796 return; 2797 } 2798 2799 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2800 // Otherwise, emit a volatile load to retrieve the stack guard value. 2801 SDValue Chain = DAG.getEntryNode(); 2802 if (TLI.useLoadStackGuardNode()) { 2803 Guard = getLoadStackGuard(DAG, dl, Chain); 2804 } else { 2805 const Value *IRGuard = TLI.getSDagStackGuard(M); 2806 SDValue GuardPtr = getValue(IRGuard); 2807 2808 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2809 MachinePointerInfo(IRGuard, 0), Align, 2810 MachineMemOperand::MOVolatile); 2811 } 2812 2813 // Perform the comparison via a getsetcc. 2814 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2815 *DAG.getContext(), 2816 Guard.getValueType()), 2817 Guard, GuardVal, ISD::SETNE); 2818 2819 // If the guard/stackslot do not equal, branch to failure MBB. 2820 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2821 MVT::Other, GuardVal.getOperand(0), 2822 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2823 // Otherwise branch to success MBB. 2824 SDValue Br = DAG.getNode(ISD::BR, dl, 2825 MVT::Other, BrCond, 2826 DAG.getBasicBlock(SPD.getSuccessMBB())); 2827 2828 DAG.setRoot(Br); 2829 } 2830 2831 /// Codegen the failure basic block for a stack protector check. 2832 /// 2833 /// A failure stack protector machine basic block consists simply of a call to 2834 /// __stack_chk_fail(). 2835 /// 2836 /// For a high level explanation of how this fits into the stack protector 2837 /// generation see the comment on the declaration of class 2838 /// StackProtectorDescriptor. 2839 void 2840 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2841 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2842 TargetLowering::MakeLibCallOptions CallOptions; 2843 CallOptions.setDiscardResult(true); 2844 SDValue Chain = 2845 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2846 std::nullopt, CallOptions, getCurSDLoc()) 2847 .second; 2848 // On PS4/PS5, the "return address" must still be within the calling 2849 // function, even if it's at the very end, so emit an explicit TRAP here. 2850 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2851 if (TM.getTargetTriple().isPS()) 2852 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2853 // WebAssembly needs an unreachable instruction after a non-returning call, 2854 // because the function return type can be different from __stack_chk_fail's 2855 // return type (void). 2856 if (TM.getTargetTriple().isWasm()) 2857 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2858 2859 DAG.setRoot(Chain); 2860 } 2861 2862 /// visitBitTestHeader - This function emits necessary code to produce value 2863 /// suitable for "bit tests" 2864 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2865 MachineBasicBlock *SwitchBB) { 2866 SDLoc dl = getCurSDLoc(); 2867 2868 // Subtract the minimum value. 2869 SDValue SwitchOp = getValue(B.SValue); 2870 EVT VT = SwitchOp.getValueType(); 2871 SDValue RangeSub = 2872 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2873 2874 // Determine the type of the test operands. 2875 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2876 bool UsePtrType = false; 2877 if (!TLI.isTypeLegal(VT)) { 2878 UsePtrType = true; 2879 } else { 2880 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2881 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2882 // Switch table case range are encoded into series of masks. 2883 // Just use pointer type, it's guaranteed to fit. 2884 UsePtrType = true; 2885 break; 2886 } 2887 } 2888 SDValue Sub = RangeSub; 2889 if (UsePtrType) { 2890 VT = TLI.getPointerTy(DAG.getDataLayout()); 2891 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2892 } 2893 2894 B.RegVT = VT.getSimpleVT(); 2895 B.Reg = FuncInfo.CreateReg(B.RegVT); 2896 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2897 2898 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2899 2900 if (!B.FallthroughUnreachable) 2901 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2902 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2903 SwitchBB->normalizeSuccProbs(); 2904 2905 SDValue Root = CopyTo; 2906 if (!B.FallthroughUnreachable) { 2907 // Conditional branch to the default block. 2908 SDValue RangeCmp = DAG.getSetCC(dl, 2909 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2910 RangeSub.getValueType()), 2911 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2912 ISD::SETUGT); 2913 2914 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2915 DAG.getBasicBlock(B.Default)); 2916 } 2917 2918 // Avoid emitting unnecessary branches to the next block. 2919 if (MBB != NextBlock(SwitchBB)) 2920 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2921 2922 DAG.setRoot(Root); 2923 } 2924 2925 /// visitBitTestCase - this function produces one "bit test" 2926 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2927 MachineBasicBlock* NextMBB, 2928 BranchProbability BranchProbToNext, 2929 unsigned Reg, 2930 BitTestCase &B, 2931 MachineBasicBlock *SwitchBB) { 2932 SDLoc dl = getCurSDLoc(); 2933 MVT VT = BB.RegVT; 2934 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2935 SDValue Cmp; 2936 unsigned PopCount = llvm::popcount(B.Mask); 2937 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2938 if (PopCount == 1) { 2939 // Testing for a single bit; just compare the shift count with what it 2940 // would need to be to shift a 1 bit in that position. 2941 Cmp = DAG.getSetCC( 2942 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2943 ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT), 2944 ISD::SETEQ); 2945 } else if (PopCount == BB.Range) { 2946 // There is only one zero bit in the range, test for it directly. 2947 Cmp = DAG.getSetCC( 2948 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2949 ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE); 2950 } else { 2951 // Make desired shift 2952 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2953 DAG.getConstant(1, dl, VT), ShiftOp); 2954 2955 // Emit bit tests and jumps 2956 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2957 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2958 Cmp = DAG.getSetCC( 2959 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2960 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2961 } 2962 2963 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2964 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2965 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2966 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2967 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2968 // one as they are relative probabilities (and thus work more like weights), 2969 // and hence we need to normalize them to let the sum of them become one. 2970 SwitchBB->normalizeSuccProbs(); 2971 2972 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2973 MVT::Other, getControlRoot(), 2974 Cmp, DAG.getBasicBlock(B.TargetBB)); 2975 2976 // Avoid emitting unnecessary branches to the next block. 2977 if (NextMBB != NextBlock(SwitchBB)) 2978 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2979 DAG.getBasicBlock(NextMBB)); 2980 2981 DAG.setRoot(BrAnd); 2982 } 2983 2984 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2985 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2986 2987 // Retrieve successors. Look through artificial IR level blocks like 2988 // catchswitch for successors. 2989 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2990 const BasicBlock *EHPadBB = I.getSuccessor(1); 2991 MachineBasicBlock *EHPadMBB = FuncInfo.MBBMap[EHPadBB]; 2992 2993 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2994 // have to do anything here to lower funclet bundles. 2995 assert(!I.hasOperandBundlesOtherThan( 2996 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 2997 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 2998 LLVMContext::OB_cfguardtarget, 2999 LLVMContext::OB_clang_arc_attachedcall}) && 3000 "Cannot lower invokes with arbitrary operand bundles yet!"); 3001 3002 const Value *Callee(I.getCalledOperand()); 3003 const Function *Fn = dyn_cast<Function>(Callee); 3004 if (isa<InlineAsm>(Callee)) 3005 visitInlineAsm(I, EHPadBB); 3006 else if (Fn && Fn->isIntrinsic()) { 3007 switch (Fn->getIntrinsicID()) { 3008 default: 3009 llvm_unreachable("Cannot invoke this intrinsic"); 3010 case Intrinsic::donothing: 3011 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 3012 case Intrinsic::seh_try_begin: 3013 case Intrinsic::seh_scope_begin: 3014 case Intrinsic::seh_try_end: 3015 case Intrinsic::seh_scope_end: 3016 if (EHPadMBB) 3017 // a block referenced by EH table 3018 // so dtor-funclet not removed by opts 3019 EHPadMBB->setMachineBlockAddressTaken(); 3020 break; 3021 case Intrinsic::experimental_patchpoint_void: 3022 case Intrinsic::experimental_patchpoint_i64: 3023 visitPatchpoint(I, EHPadBB); 3024 break; 3025 case Intrinsic::experimental_gc_statepoint: 3026 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 3027 break; 3028 case Intrinsic::wasm_rethrow: { 3029 // This is usually done in visitTargetIntrinsic, but this intrinsic is 3030 // special because it can be invoked, so we manually lower it to a DAG 3031 // node here. 3032 SmallVector<SDValue, 8> Ops; 3033 Ops.push_back(getRoot()); // inchain 3034 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3035 Ops.push_back( 3036 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 3037 TLI.getPointerTy(DAG.getDataLayout()))); 3038 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 3039 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 3040 break; 3041 } 3042 } 3043 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 3044 // Currently we do not lower any intrinsic calls with deopt operand bundles. 3045 // Eventually we will support lowering the @llvm.experimental.deoptimize 3046 // intrinsic, and right now there are no plans to support other intrinsics 3047 // with deopt state. 3048 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 3049 } else { 3050 LowerCallTo(I, getValue(Callee), false, false, EHPadBB); 3051 } 3052 3053 // If the value of the invoke is used outside of its defining block, make it 3054 // available as a virtual register. 3055 // We already took care of the exported value for the statepoint instruction 3056 // during call to the LowerStatepoint. 3057 if (!isa<GCStatepointInst>(I)) { 3058 CopyToExportRegsIfNeeded(&I); 3059 } 3060 3061 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 3062 BranchProbabilityInfo *BPI = FuncInfo.BPI; 3063 BranchProbability EHPadBBProb = 3064 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 3065 : BranchProbability::getZero(); 3066 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 3067 3068 // Update successor info. 3069 addSuccessorWithProb(InvokeMBB, Return); 3070 for (auto &UnwindDest : UnwindDests) { 3071 UnwindDest.first->setIsEHPad(); 3072 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 3073 } 3074 InvokeMBB->normalizeSuccProbs(); 3075 3076 // Drop into normal successor. 3077 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 3078 DAG.getBasicBlock(Return))); 3079 } 3080 3081 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 3082 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 3083 3084 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3085 // have to do anything here to lower funclet bundles. 3086 assert(!I.hasOperandBundlesOtherThan( 3087 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 3088 "Cannot lower callbrs with arbitrary operand bundles yet!"); 3089 3090 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 3091 visitInlineAsm(I); 3092 CopyToExportRegsIfNeeded(&I); 3093 3094 // Retrieve successors. 3095 SmallPtrSet<BasicBlock *, 8> Dests; 3096 Dests.insert(I.getDefaultDest()); 3097 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 3098 3099 // Update successor info. 3100 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 3101 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 3102 BasicBlock *Dest = I.getIndirectDest(i); 3103 MachineBasicBlock *Target = FuncInfo.MBBMap[Dest]; 3104 Target->setIsInlineAsmBrIndirectTarget(); 3105 Target->setMachineBlockAddressTaken(); 3106 Target->setLabelMustBeEmitted(); 3107 // Don't add duplicate machine successors. 3108 if (Dests.insert(Dest).second) 3109 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 3110 } 3111 CallBrMBB->normalizeSuccProbs(); 3112 3113 // Drop into default successor. 3114 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 3115 MVT::Other, getControlRoot(), 3116 DAG.getBasicBlock(Return))); 3117 } 3118 3119 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 3120 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 3121 } 3122 3123 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 3124 assert(FuncInfo.MBB->isEHPad() && 3125 "Call to landingpad not in landing pad!"); 3126 3127 // If there aren't registers to copy the values into (e.g., during SjLj 3128 // exceptions), then don't bother to create these DAG nodes. 3129 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3130 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 3131 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 3132 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 3133 return; 3134 3135 // If landingpad's return type is token type, we don't create DAG nodes 3136 // for its exception pointer and selector value. The extraction of exception 3137 // pointer or selector value from token type landingpads is not currently 3138 // supported. 3139 if (LP.getType()->isTokenTy()) 3140 return; 3141 3142 SmallVector<EVT, 2> ValueVTs; 3143 SDLoc dl = getCurSDLoc(); 3144 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3145 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3146 3147 // Get the two live-in registers as SDValues. The physregs have already been 3148 // copied into virtual registers. 3149 SDValue Ops[2]; 3150 if (FuncInfo.ExceptionPointerVirtReg) { 3151 Ops[0] = DAG.getZExtOrTrunc( 3152 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3153 FuncInfo.ExceptionPointerVirtReg, 3154 TLI.getPointerTy(DAG.getDataLayout())), 3155 dl, ValueVTs[0]); 3156 } else { 3157 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3158 } 3159 Ops[1] = DAG.getZExtOrTrunc( 3160 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3161 FuncInfo.ExceptionSelectorVirtReg, 3162 TLI.getPointerTy(DAG.getDataLayout())), 3163 dl, ValueVTs[1]); 3164 3165 // Merge into one. 3166 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3167 DAG.getVTList(ValueVTs), Ops); 3168 setValue(&LP, Res); 3169 } 3170 3171 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3172 MachineBasicBlock *Last) { 3173 // Update JTCases. 3174 for (JumpTableBlock &JTB : SL->JTCases) 3175 if (JTB.first.HeaderBB == First) 3176 JTB.first.HeaderBB = Last; 3177 3178 // Update BitTestCases. 3179 for (BitTestBlock &BTB : SL->BitTestCases) 3180 if (BTB.Parent == First) 3181 BTB.Parent = Last; 3182 } 3183 3184 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3185 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3186 3187 // Update machine-CFG edges with unique successors. 3188 SmallSet<BasicBlock*, 32> Done; 3189 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3190 BasicBlock *BB = I.getSuccessor(i); 3191 bool Inserted = Done.insert(BB).second; 3192 if (!Inserted) 3193 continue; 3194 3195 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3196 addSuccessorWithProb(IndirectBrMBB, Succ); 3197 } 3198 IndirectBrMBB->normalizeSuccProbs(); 3199 3200 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3201 MVT::Other, getControlRoot(), 3202 getValue(I.getAddress()))); 3203 } 3204 3205 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3206 if (!DAG.getTarget().Options.TrapUnreachable) 3207 return; 3208 3209 // We may be able to ignore unreachable behind a noreturn call. 3210 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3211 const BasicBlock &BB = *I.getParent(); 3212 if (&I != &BB.front()) { 3213 BasicBlock::const_iterator PredI = 3214 std::prev(BasicBlock::const_iterator(&I)); 3215 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 3216 if (Call->doesNotReturn()) 3217 return; 3218 } 3219 } 3220 } 3221 3222 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3223 } 3224 3225 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3226 SDNodeFlags Flags; 3227 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3228 Flags.copyFMF(*FPOp); 3229 3230 SDValue Op = getValue(I.getOperand(0)); 3231 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3232 Op, Flags); 3233 setValue(&I, UnNodeValue); 3234 } 3235 3236 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3237 SDNodeFlags Flags; 3238 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3239 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3240 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3241 } 3242 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3243 Flags.setExact(ExactOp->isExact()); 3244 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3245 Flags.copyFMF(*FPOp); 3246 3247 SDValue Op1 = getValue(I.getOperand(0)); 3248 SDValue Op2 = getValue(I.getOperand(1)); 3249 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3250 Op1, Op2, Flags); 3251 setValue(&I, BinNodeValue); 3252 } 3253 3254 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3255 SDValue Op1 = getValue(I.getOperand(0)); 3256 SDValue Op2 = getValue(I.getOperand(1)); 3257 3258 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3259 Op1.getValueType(), DAG.getDataLayout()); 3260 3261 // Coerce the shift amount to the right type if we can. This exposes the 3262 // truncate or zext to optimization early. 3263 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3264 assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) && 3265 "Unexpected shift type"); 3266 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy); 3267 } 3268 3269 bool nuw = false; 3270 bool nsw = false; 3271 bool exact = false; 3272 3273 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3274 3275 if (const OverflowingBinaryOperator *OFBinOp = 3276 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3277 nuw = OFBinOp->hasNoUnsignedWrap(); 3278 nsw = OFBinOp->hasNoSignedWrap(); 3279 } 3280 if (const PossiblyExactOperator *ExactOp = 3281 dyn_cast<const PossiblyExactOperator>(&I)) 3282 exact = ExactOp->isExact(); 3283 } 3284 SDNodeFlags Flags; 3285 Flags.setExact(exact); 3286 Flags.setNoSignedWrap(nsw); 3287 Flags.setNoUnsignedWrap(nuw); 3288 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3289 Flags); 3290 setValue(&I, Res); 3291 } 3292 3293 void SelectionDAGBuilder::visitSDiv(const User &I) { 3294 SDValue Op1 = getValue(I.getOperand(0)); 3295 SDValue Op2 = getValue(I.getOperand(1)); 3296 3297 SDNodeFlags Flags; 3298 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3299 cast<PossiblyExactOperator>(&I)->isExact()); 3300 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3301 Op2, Flags)); 3302 } 3303 3304 void SelectionDAGBuilder::visitICmp(const User &I) { 3305 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3306 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3307 predicate = IC->getPredicate(); 3308 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3309 predicate = ICmpInst::Predicate(IC->getPredicate()); 3310 SDValue Op1 = getValue(I.getOperand(0)); 3311 SDValue Op2 = getValue(I.getOperand(1)); 3312 ISD::CondCode Opcode = getICmpCondCode(predicate); 3313 3314 auto &TLI = DAG.getTargetLoweringInfo(); 3315 EVT MemVT = 3316 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3317 3318 // If a pointer's DAG type is larger than its memory type then the DAG values 3319 // are zero-extended. This breaks signed comparisons so truncate back to the 3320 // underlying type before doing the compare. 3321 if (Op1.getValueType() != MemVT) { 3322 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3323 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3324 } 3325 3326 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3327 I.getType()); 3328 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3329 } 3330 3331 void SelectionDAGBuilder::visitFCmp(const User &I) { 3332 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3333 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3334 predicate = FC->getPredicate(); 3335 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3336 predicate = FCmpInst::Predicate(FC->getPredicate()); 3337 SDValue Op1 = getValue(I.getOperand(0)); 3338 SDValue Op2 = getValue(I.getOperand(1)); 3339 3340 ISD::CondCode Condition = getFCmpCondCode(predicate); 3341 auto *FPMO = cast<FPMathOperator>(&I); 3342 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3343 Condition = getFCmpCodeWithoutNaN(Condition); 3344 3345 SDNodeFlags Flags; 3346 Flags.copyFMF(*FPMO); 3347 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3348 3349 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3350 I.getType()); 3351 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3352 } 3353 3354 // Check if the condition of the select has one use or two users that are both 3355 // selects with the same condition. 3356 static bool hasOnlySelectUsers(const Value *Cond) { 3357 return llvm::all_of(Cond->users(), [](const Value *V) { 3358 return isa<SelectInst>(V); 3359 }); 3360 } 3361 3362 void SelectionDAGBuilder::visitSelect(const User &I) { 3363 SmallVector<EVT, 4> ValueVTs; 3364 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3365 ValueVTs); 3366 unsigned NumValues = ValueVTs.size(); 3367 if (NumValues == 0) return; 3368 3369 SmallVector<SDValue, 4> Values(NumValues); 3370 SDValue Cond = getValue(I.getOperand(0)); 3371 SDValue LHSVal = getValue(I.getOperand(1)); 3372 SDValue RHSVal = getValue(I.getOperand(2)); 3373 SmallVector<SDValue, 1> BaseOps(1, Cond); 3374 ISD::NodeType OpCode = 3375 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3376 3377 bool IsUnaryAbs = false; 3378 bool Negate = false; 3379 3380 SDNodeFlags Flags; 3381 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3382 Flags.copyFMF(*FPOp); 3383 3384 Flags.setUnpredictable( 3385 cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable)); 3386 3387 // Min/max matching is only viable if all output VTs are the same. 3388 if (all_equal(ValueVTs)) { 3389 EVT VT = ValueVTs[0]; 3390 LLVMContext &Ctx = *DAG.getContext(); 3391 auto &TLI = DAG.getTargetLoweringInfo(); 3392 3393 // We care about the legality of the operation after it has been type 3394 // legalized. 3395 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3396 VT = TLI.getTypeToTransformTo(Ctx, VT); 3397 3398 // If the vselect is legal, assume we want to leave this as a vector setcc + 3399 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3400 // min/max is legal on the scalar type. 3401 bool UseScalarMinMax = VT.isVector() && 3402 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3403 3404 // ValueTracking's select pattern matching does not account for -0.0, 3405 // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that 3406 // -0.0 is less than +0.0. 3407 Value *LHS, *RHS; 3408 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3409 ISD::NodeType Opc = ISD::DELETED_NODE; 3410 switch (SPR.Flavor) { 3411 case SPF_UMAX: Opc = ISD::UMAX; break; 3412 case SPF_UMIN: Opc = ISD::UMIN; break; 3413 case SPF_SMAX: Opc = ISD::SMAX; break; 3414 case SPF_SMIN: Opc = ISD::SMIN; break; 3415 case SPF_FMINNUM: 3416 switch (SPR.NaNBehavior) { 3417 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3418 case SPNB_RETURNS_NAN: break; 3419 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3420 case SPNB_RETURNS_ANY: 3421 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) || 3422 (UseScalarMinMax && 3423 TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()))) 3424 Opc = ISD::FMINNUM; 3425 break; 3426 } 3427 break; 3428 case SPF_FMAXNUM: 3429 switch (SPR.NaNBehavior) { 3430 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3431 case SPNB_RETURNS_NAN: break; 3432 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3433 case SPNB_RETURNS_ANY: 3434 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) || 3435 (UseScalarMinMax && 3436 TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()))) 3437 Opc = ISD::FMAXNUM; 3438 break; 3439 } 3440 break; 3441 case SPF_NABS: 3442 Negate = true; 3443 [[fallthrough]]; 3444 case SPF_ABS: 3445 IsUnaryAbs = true; 3446 Opc = ISD::ABS; 3447 break; 3448 default: break; 3449 } 3450 3451 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3452 (TLI.isOperationLegalOrCustom(Opc, VT) || 3453 (UseScalarMinMax && 3454 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3455 // If the underlying comparison instruction is used by any other 3456 // instruction, the consumed instructions won't be destroyed, so it is 3457 // not profitable to convert to a min/max. 3458 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3459 OpCode = Opc; 3460 LHSVal = getValue(LHS); 3461 RHSVal = getValue(RHS); 3462 BaseOps.clear(); 3463 } 3464 3465 if (IsUnaryAbs) { 3466 OpCode = Opc; 3467 LHSVal = getValue(LHS); 3468 BaseOps.clear(); 3469 } 3470 } 3471 3472 if (IsUnaryAbs) { 3473 for (unsigned i = 0; i != NumValues; ++i) { 3474 SDLoc dl = getCurSDLoc(); 3475 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3476 Values[i] = 3477 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3478 if (Negate) 3479 Values[i] = DAG.getNegative(Values[i], dl, VT); 3480 } 3481 } else { 3482 for (unsigned i = 0; i != NumValues; ++i) { 3483 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3484 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3485 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3486 Values[i] = DAG.getNode( 3487 OpCode, getCurSDLoc(), 3488 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3489 } 3490 } 3491 3492 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3493 DAG.getVTList(ValueVTs), Values)); 3494 } 3495 3496 void SelectionDAGBuilder::visitTrunc(const User &I) { 3497 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3498 SDValue N = getValue(I.getOperand(0)); 3499 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3500 I.getType()); 3501 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3502 } 3503 3504 void SelectionDAGBuilder::visitZExt(const User &I) { 3505 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3506 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3507 SDValue N = getValue(I.getOperand(0)); 3508 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3509 I.getType()); 3510 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3511 } 3512 3513 void SelectionDAGBuilder::visitSExt(const User &I) { 3514 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3515 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3516 SDValue N = getValue(I.getOperand(0)); 3517 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3518 I.getType()); 3519 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3520 } 3521 3522 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3523 // FPTrunc is never a no-op cast, no need to check 3524 SDValue N = getValue(I.getOperand(0)); 3525 SDLoc dl = getCurSDLoc(); 3526 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3527 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3528 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3529 DAG.getTargetConstant( 3530 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3531 } 3532 3533 void SelectionDAGBuilder::visitFPExt(const User &I) { 3534 // FPExt is never a no-op cast, no need to check 3535 SDValue N = getValue(I.getOperand(0)); 3536 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3537 I.getType()); 3538 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3539 } 3540 3541 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3542 // FPToUI is never a no-op cast, no need to check 3543 SDValue N = getValue(I.getOperand(0)); 3544 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3545 I.getType()); 3546 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3547 } 3548 3549 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3550 // FPToSI is never a no-op cast, no need to check 3551 SDValue N = getValue(I.getOperand(0)); 3552 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3553 I.getType()); 3554 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3555 } 3556 3557 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3558 // UIToFP is never a no-op cast, no need to check 3559 SDValue N = getValue(I.getOperand(0)); 3560 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3561 I.getType()); 3562 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3563 } 3564 3565 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3566 // SIToFP is never a no-op cast, no need to check 3567 SDValue N = getValue(I.getOperand(0)); 3568 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3569 I.getType()); 3570 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3571 } 3572 3573 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3574 // What to do depends on the size of the integer and the size of the pointer. 3575 // We can either truncate, zero extend, or no-op, accordingly. 3576 SDValue N = getValue(I.getOperand(0)); 3577 auto &TLI = DAG.getTargetLoweringInfo(); 3578 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3579 I.getType()); 3580 EVT PtrMemVT = 3581 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3582 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3583 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3584 setValue(&I, N); 3585 } 3586 3587 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3588 // What to do depends on the size of the integer and the size of the pointer. 3589 // We can either truncate, zero extend, or no-op, accordingly. 3590 SDValue N = getValue(I.getOperand(0)); 3591 auto &TLI = DAG.getTargetLoweringInfo(); 3592 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3593 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3594 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3595 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3596 setValue(&I, N); 3597 } 3598 3599 void SelectionDAGBuilder::visitBitCast(const User &I) { 3600 SDValue N = getValue(I.getOperand(0)); 3601 SDLoc dl = getCurSDLoc(); 3602 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3603 I.getType()); 3604 3605 // BitCast assures us that source and destination are the same size so this is 3606 // either a BITCAST or a no-op. 3607 if (DestVT != N.getValueType()) 3608 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3609 DestVT, N)); // convert types. 3610 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3611 // might fold any kind of constant expression to an integer constant and that 3612 // is not what we are looking for. Only recognize a bitcast of a genuine 3613 // constant integer as an opaque constant. 3614 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3615 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3616 /*isOpaque*/true)); 3617 else 3618 setValue(&I, N); // noop cast. 3619 } 3620 3621 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3622 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3623 const Value *SV = I.getOperand(0); 3624 SDValue N = getValue(SV); 3625 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3626 3627 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3628 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3629 3630 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3631 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3632 3633 setValue(&I, N); 3634 } 3635 3636 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3637 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3638 SDValue InVec = getValue(I.getOperand(0)); 3639 SDValue InVal = getValue(I.getOperand(1)); 3640 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3641 TLI.getVectorIdxTy(DAG.getDataLayout())); 3642 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3643 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3644 InVec, InVal, InIdx)); 3645 } 3646 3647 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3648 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3649 SDValue InVec = getValue(I.getOperand(0)); 3650 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3651 TLI.getVectorIdxTy(DAG.getDataLayout())); 3652 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3653 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3654 InVec, InIdx)); 3655 } 3656 3657 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3658 SDValue Src1 = getValue(I.getOperand(0)); 3659 SDValue Src2 = getValue(I.getOperand(1)); 3660 ArrayRef<int> Mask; 3661 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3662 Mask = SVI->getShuffleMask(); 3663 else 3664 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3665 SDLoc DL = getCurSDLoc(); 3666 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3667 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3668 EVT SrcVT = Src1.getValueType(); 3669 3670 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3671 VT.isScalableVector()) { 3672 // Canonical splat form of first element of first input vector. 3673 SDValue FirstElt = 3674 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3675 DAG.getVectorIdxConstant(0, DL)); 3676 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3677 return; 3678 } 3679 3680 // For now, we only handle splats for scalable vectors. 3681 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3682 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3683 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3684 3685 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3686 unsigned MaskNumElts = Mask.size(); 3687 3688 if (SrcNumElts == MaskNumElts) { 3689 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3690 return; 3691 } 3692 3693 // Normalize the shuffle vector since mask and vector length don't match. 3694 if (SrcNumElts < MaskNumElts) { 3695 // Mask is longer than the source vectors. We can use concatenate vector to 3696 // make the mask and vectors lengths match. 3697 3698 if (MaskNumElts % SrcNumElts == 0) { 3699 // Mask length is a multiple of the source vector length. 3700 // Check if the shuffle is some kind of concatenation of the input 3701 // vectors. 3702 unsigned NumConcat = MaskNumElts / SrcNumElts; 3703 bool IsConcat = true; 3704 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3705 for (unsigned i = 0; i != MaskNumElts; ++i) { 3706 int Idx = Mask[i]; 3707 if (Idx < 0) 3708 continue; 3709 // Ensure the indices in each SrcVT sized piece are sequential and that 3710 // the same source is used for the whole piece. 3711 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3712 (ConcatSrcs[i / SrcNumElts] >= 0 && 3713 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3714 IsConcat = false; 3715 break; 3716 } 3717 // Remember which source this index came from. 3718 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3719 } 3720 3721 // The shuffle is concatenating multiple vectors together. Just emit 3722 // a CONCAT_VECTORS operation. 3723 if (IsConcat) { 3724 SmallVector<SDValue, 8> ConcatOps; 3725 for (auto Src : ConcatSrcs) { 3726 if (Src < 0) 3727 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3728 else if (Src == 0) 3729 ConcatOps.push_back(Src1); 3730 else 3731 ConcatOps.push_back(Src2); 3732 } 3733 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3734 return; 3735 } 3736 } 3737 3738 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3739 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3740 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3741 PaddedMaskNumElts); 3742 3743 // Pad both vectors with undefs to make them the same length as the mask. 3744 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3745 3746 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3747 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3748 MOps1[0] = Src1; 3749 MOps2[0] = Src2; 3750 3751 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3752 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3753 3754 // Readjust mask for new input vector length. 3755 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3756 for (unsigned i = 0; i != MaskNumElts; ++i) { 3757 int Idx = Mask[i]; 3758 if (Idx >= (int)SrcNumElts) 3759 Idx -= SrcNumElts - PaddedMaskNumElts; 3760 MappedOps[i] = Idx; 3761 } 3762 3763 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3764 3765 // If the concatenated vector was padded, extract a subvector with the 3766 // correct number of elements. 3767 if (MaskNumElts != PaddedMaskNumElts) 3768 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3769 DAG.getVectorIdxConstant(0, DL)); 3770 3771 setValue(&I, Result); 3772 return; 3773 } 3774 3775 if (SrcNumElts > MaskNumElts) { 3776 // Analyze the access pattern of the vector to see if we can extract 3777 // two subvectors and do the shuffle. 3778 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3779 bool CanExtract = true; 3780 for (int Idx : Mask) { 3781 unsigned Input = 0; 3782 if (Idx < 0) 3783 continue; 3784 3785 if (Idx >= (int)SrcNumElts) { 3786 Input = 1; 3787 Idx -= SrcNumElts; 3788 } 3789 3790 // If all the indices come from the same MaskNumElts sized portion of 3791 // the sources we can use extract. Also make sure the extract wouldn't 3792 // extract past the end of the source. 3793 int NewStartIdx = alignDown(Idx, MaskNumElts); 3794 if (NewStartIdx + MaskNumElts > SrcNumElts || 3795 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3796 CanExtract = false; 3797 // Make sure we always update StartIdx as we use it to track if all 3798 // elements are undef. 3799 StartIdx[Input] = NewStartIdx; 3800 } 3801 3802 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3803 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3804 return; 3805 } 3806 if (CanExtract) { 3807 // Extract appropriate subvector and generate a vector shuffle 3808 for (unsigned Input = 0; Input < 2; ++Input) { 3809 SDValue &Src = Input == 0 ? Src1 : Src2; 3810 if (StartIdx[Input] < 0) 3811 Src = DAG.getUNDEF(VT); 3812 else { 3813 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3814 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3815 } 3816 } 3817 3818 // Calculate new mask. 3819 SmallVector<int, 8> MappedOps(Mask); 3820 for (int &Idx : MappedOps) { 3821 if (Idx >= (int)SrcNumElts) 3822 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3823 else if (Idx >= 0) 3824 Idx -= StartIdx[0]; 3825 } 3826 3827 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3828 return; 3829 } 3830 } 3831 3832 // We can't use either concat vectors or extract subvectors so fall back to 3833 // replacing the shuffle with extract and build vector. 3834 // to insert and build vector. 3835 EVT EltVT = VT.getVectorElementType(); 3836 SmallVector<SDValue,8> Ops; 3837 for (int Idx : Mask) { 3838 SDValue Res; 3839 3840 if (Idx < 0) { 3841 Res = DAG.getUNDEF(EltVT); 3842 } else { 3843 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3844 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3845 3846 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3847 DAG.getVectorIdxConstant(Idx, DL)); 3848 } 3849 3850 Ops.push_back(Res); 3851 } 3852 3853 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3854 } 3855 3856 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) { 3857 ArrayRef<unsigned> Indices = I.getIndices(); 3858 const Value *Op0 = I.getOperand(0); 3859 const Value *Op1 = I.getOperand(1); 3860 Type *AggTy = I.getType(); 3861 Type *ValTy = Op1->getType(); 3862 bool IntoUndef = isa<UndefValue>(Op0); 3863 bool FromUndef = isa<UndefValue>(Op1); 3864 3865 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3866 3867 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3868 SmallVector<EVT, 4> AggValueVTs; 3869 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3870 SmallVector<EVT, 4> ValValueVTs; 3871 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3872 3873 unsigned NumAggValues = AggValueVTs.size(); 3874 unsigned NumValValues = ValValueVTs.size(); 3875 SmallVector<SDValue, 4> Values(NumAggValues); 3876 3877 // Ignore an insertvalue that produces an empty object 3878 if (!NumAggValues) { 3879 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3880 return; 3881 } 3882 3883 SDValue Agg = getValue(Op0); 3884 unsigned i = 0; 3885 // Copy the beginning value(s) from the original aggregate. 3886 for (; i != LinearIndex; ++i) 3887 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3888 SDValue(Agg.getNode(), Agg.getResNo() + i); 3889 // Copy values from the inserted value(s). 3890 if (NumValValues) { 3891 SDValue Val = getValue(Op1); 3892 for (; i != LinearIndex + NumValValues; ++i) 3893 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3894 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3895 } 3896 // Copy remaining value(s) from the original aggregate. 3897 for (; i != NumAggValues; ++i) 3898 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3899 SDValue(Agg.getNode(), Agg.getResNo() + i); 3900 3901 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3902 DAG.getVTList(AggValueVTs), Values)); 3903 } 3904 3905 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) { 3906 ArrayRef<unsigned> Indices = I.getIndices(); 3907 const Value *Op0 = I.getOperand(0); 3908 Type *AggTy = Op0->getType(); 3909 Type *ValTy = I.getType(); 3910 bool OutOfUndef = isa<UndefValue>(Op0); 3911 3912 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3913 3914 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3915 SmallVector<EVT, 4> ValValueVTs; 3916 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3917 3918 unsigned NumValValues = ValValueVTs.size(); 3919 3920 // Ignore a extractvalue that produces an empty object 3921 if (!NumValValues) { 3922 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3923 return; 3924 } 3925 3926 SmallVector<SDValue, 4> Values(NumValValues); 3927 3928 SDValue Agg = getValue(Op0); 3929 // Copy out the selected value(s). 3930 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3931 Values[i - LinearIndex] = 3932 OutOfUndef ? 3933 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3934 SDValue(Agg.getNode(), Agg.getResNo() + i); 3935 3936 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3937 DAG.getVTList(ValValueVTs), Values)); 3938 } 3939 3940 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3941 Value *Op0 = I.getOperand(0); 3942 // Note that the pointer operand may be a vector of pointers. Take the scalar 3943 // element which holds a pointer. 3944 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3945 SDValue N = getValue(Op0); 3946 SDLoc dl = getCurSDLoc(); 3947 auto &TLI = DAG.getTargetLoweringInfo(); 3948 3949 // Normalize Vector GEP - all scalar operands should be converted to the 3950 // splat vector. 3951 bool IsVectorGEP = I.getType()->isVectorTy(); 3952 ElementCount VectorElementCount = 3953 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3954 : ElementCount::getFixed(0); 3955 3956 if (IsVectorGEP && !N.getValueType().isVector()) { 3957 LLVMContext &Context = *DAG.getContext(); 3958 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3959 N = DAG.getSplat(VT, dl, N); 3960 } 3961 3962 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3963 GTI != E; ++GTI) { 3964 const Value *Idx = GTI.getOperand(); 3965 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3966 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3967 if (Field) { 3968 // N = N + Offset 3969 uint64_t Offset = 3970 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field); 3971 3972 // In an inbounds GEP with an offset that is nonnegative even when 3973 // interpreted as signed, assume there is no unsigned overflow. 3974 SDNodeFlags Flags; 3975 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3976 Flags.setNoUnsignedWrap(true); 3977 3978 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3979 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3980 } 3981 } else { 3982 // IdxSize is the width of the arithmetic according to IR semantics. 3983 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3984 // (and fix up the result later). 3985 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3986 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3987 TypeSize ElementSize = 3988 DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType()); 3989 // We intentionally mask away the high bits here; ElementSize may not 3990 // fit in IdxTy. 3991 APInt ElementMul(IdxSize, ElementSize.getKnownMinValue()); 3992 bool ElementScalable = ElementSize.isScalable(); 3993 3994 // If this is a scalar constant or a splat vector of constants, 3995 // handle it quickly. 3996 const auto *C = dyn_cast<Constant>(Idx); 3997 if (C && isa<VectorType>(C->getType())) 3998 C = C->getSplatValue(); 3999 4000 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 4001 if (CI && CI->isZero()) 4002 continue; 4003 if (CI && !ElementScalable) { 4004 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 4005 LLVMContext &Context = *DAG.getContext(); 4006 SDValue OffsVal; 4007 if (IsVectorGEP) 4008 OffsVal = DAG.getConstant( 4009 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 4010 else 4011 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 4012 4013 // In an inbounds GEP with an offset that is nonnegative even when 4014 // interpreted as signed, assume there is no unsigned overflow. 4015 SDNodeFlags Flags; 4016 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 4017 Flags.setNoUnsignedWrap(true); 4018 4019 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 4020 4021 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 4022 continue; 4023 } 4024 4025 // N = N + Idx * ElementMul; 4026 SDValue IdxN = getValue(Idx); 4027 4028 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 4029 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 4030 VectorElementCount); 4031 IdxN = DAG.getSplat(VT, dl, IdxN); 4032 } 4033 4034 // If the index is smaller or larger than intptr_t, truncate or extend 4035 // it. 4036 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 4037 4038 if (ElementScalable) { 4039 EVT VScaleTy = N.getValueType().getScalarType(); 4040 SDValue VScale = DAG.getNode( 4041 ISD::VSCALE, dl, VScaleTy, 4042 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 4043 if (IsVectorGEP) 4044 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 4045 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 4046 } else { 4047 // If this is a multiply by a power of two, turn it into a shl 4048 // immediately. This is a very common case. 4049 if (ElementMul != 1) { 4050 if (ElementMul.isPowerOf2()) { 4051 unsigned Amt = ElementMul.logBase2(); 4052 IdxN = DAG.getNode(ISD::SHL, dl, 4053 N.getValueType(), IdxN, 4054 DAG.getConstant(Amt, dl, IdxN.getValueType())); 4055 } else { 4056 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 4057 IdxN.getValueType()); 4058 IdxN = DAG.getNode(ISD::MUL, dl, 4059 N.getValueType(), IdxN, Scale); 4060 } 4061 } 4062 } 4063 4064 N = DAG.getNode(ISD::ADD, dl, 4065 N.getValueType(), N, IdxN); 4066 } 4067 } 4068 4069 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 4070 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 4071 if (IsVectorGEP) { 4072 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 4073 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 4074 } 4075 4076 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 4077 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 4078 4079 setValue(&I, N); 4080 } 4081 4082 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 4083 // If this is a fixed sized alloca in the entry block of the function, 4084 // allocate it statically on the stack. 4085 if (FuncInfo.StaticAllocaMap.count(&I)) 4086 return; // getValue will auto-populate this. 4087 4088 SDLoc dl = getCurSDLoc(); 4089 Type *Ty = I.getAllocatedType(); 4090 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4091 auto &DL = DAG.getDataLayout(); 4092 TypeSize TySize = DL.getTypeAllocSize(Ty); 4093 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 4094 4095 SDValue AllocSize = getValue(I.getArraySize()); 4096 4097 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), I.getAddressSpace()); 4098 if (AllocSize.getValueType() != IntPtr) 4099 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 4100 4101 if (TySize.isScalable()) 4102 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4103 DAG.getVScale(dl, IntPtr, 4104 APInt(IntPtr.getScalarSizeInBits(), 4105 TySize.getKnownMinValue()))); 4106 else 4107 AllocSize = 4108 DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4109 DAG.getConstant(TySize.getFixedValue(), dl, IntPtr)); 4110 4111 // Handle alignment. If the requested alignment is less than or equal to 4112 // the stack alignment, ignore it. If the size is greater than or equal to 4113 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4114 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 4115 if (*Alignment <= StackAlign) 4116 Alignment = std::nullopt; 4117 4118 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4119 // Round the size of the allocation up to the stack alignment size 4120 // by add SA-1 to the size. This doesn't overflow because we're computing 4121 // an address inside an alloca. 4122 SDNodeFlags Flags; 4123 Flags.setNoUnsignedWrap(true); 4124 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4125 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4126 4127 // Mask out the low bits for alignment purposes. 4128 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4129 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 4130 4131 SDValue Ops[] = { 4132 getRoot(), AllocSize, 4133 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4134 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4135 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4136 setValue(&I, DSA); 4137 DAG.setRoot(DSA.getValue(1)); 4138 4139 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4140 } 4141 4142 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4143 if (I.isAtomic()) 4144 return visitAtomicLoad(I); 4145 4146 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4147 const Value *SV = I.getOperand(0); 4148 if (TLI.supportSwiftError()) { 4149 // Swifterror values can come from either a function parameter with 4150 // swifterror attribute or an alloca with swifterror attribute. 4151 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4152 if (Arg->hasSwiftErrorAttr()) 4153 return visitLoadFromSwiftError(I); 4154 } 4155 4156 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4157 if (Alloca->isSwiftError()) 4158 return visitLoadFromSwiftError(I); 4159 } 4160 } 4161 4162 SDValue Ptr = getValue(SV); 4163 4164 Type *Ty = I.getType(); 4165 SmallVector<EVT, 4> ValueVTs, MemVTs; 4166 SmallVector<uint64_t, 4> Offsets; 4167 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets, 0); 4168 unsigned NumValues = ValueVTs.size(); 4169 if (NumValues == 0) 4170 return; 4171 4172 Align Alignment = I.getAlign(); 4173 AAMDNodes AAInfo = I.getAAMetadata(); 4174 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4175 bool isVolatile = I.isVolatile(); 4176 MachineMemOperand::Flags MMOFlags = 4177 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 4178 4179 SDValue Root; 4180 bool ConstantMemory = false; 4181 if (isVolatile) 4182 // Serialize volatile loads with other side effects. 4183 Root = getRoot(); 4184 else if (NumValues > MaxParallelChains) 4185 Root = getMemoryRoot(); 4186 else if (AA && 4187 AA->pointsToConstantMemory(MemoryLocation( 4188 SV, 4189 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4190 AAInfo))) { 4191 // Do not serialize (non-volatile) loads of constant memory with anything. 4192 Root = DAG.getEntryNode(); 4193 ConstantMemory = true; 4194 MMOFlags |= MachineMemOperand::MOInvariant; 4195 } else { 4196 // Do not serialize non-volatile loads against each other. 4197 Root = DAG.getRoot(); 4198 } 4199 4200 SDLoc dl = getCurSDLoc(); 4201 4202 if (isVolatile) 4203 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4204 4205 // An aggregate load cannot wrap around the address space, so offsets to its 4206 // parts don't wrap either. 4207 SDNodeFlags Flags; 4208 Flags.setNoUnsignedWrap(true); 4209 4210 SmallVector<SDValue, 4> Values(NumValues); 4211 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4212 EVT PtrVT = Ptr.getValueType(); 4213 4214 unsigned ChainI = 0; 4215 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4216 // Serializing loads here may result in excessive register pressure, and 4217 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4218 // could recover a bit by hoisting nodes upward in the chain by recognizing 4219 // they are side-effect free or do not alias. The optimizer should really 4220 // avoid this case by converting large object/array copies to llvm.memcpy 4221 // (MaxParallelChains should always remain as failsafe). 4222 if (ChainI == MaxParallelChains) { 4223 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4224 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4225 ArrayRef(Chains.data(), ChainI)); 4226 Root = Chain; 4227 ChainI = 0; 4228 } 4229 SDValue A = DAG.getNode(ISD::ADD, dl, 4230 PtrVT, Ptr, 4231 DAG.getConstant(Offsets[i], dl, PtrVT), 4232 Flags); 4233 4234 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4235 MachinePointerInfo(SV, Offsets[i]), Alignment, 4236 MMOFlags, AAInfo, Ranges); 4237 Chains[ChainI] = L.getValue(1); 4238 4239 if (MemVTs[i] != ValueVTs[i]) 4240 L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]); 4241 4242 Values[i] = L; 4243 } 4244 4245 if (!ConstantMemory) { 4246 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4247 ArrayRef(Chains.data(), ChainI)); 4248 if (isVolatile) 4249 DAG.setRoot(Chain); 4250 else 4251 PendingLoads.push_back(Chain); 4252 } 4253 4254 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4255 DAG.getVTList(ValueVTs), Values)); 4256 } 4257 4258 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4259 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4260 "call visitStoreToSwiftError when backend supports swifterror"); 4261 4262 SmallVector<EVT, 4> ValueVTs; 4263 SmallVector<uint64_t, 4> Offsets; 4264 const Value *SrcV = I.getOperand(0); 4265 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4266 SrcV->getType(), ValueVTs, &Offsets, 0); 4267 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4268 "expect a single EVT for swifterror"); 4269 4270 SDValue Src = getValue(SrcV); 4271 // Create a virtual register, then update the virtual register. 4272 Register VReg = 4273 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4274 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4275 // Chain can be getRoot or getControlRoot. 4276 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4277 SDValue(Src.getNode(), Src.getResNo())); 4278 DAG.setRoot(CopyNode); 4279 } 4280 4281 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4282 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4283 "call visitLoadFromSwiftError when backend supports swifterror"); 4284 4285 assert(!I.isVolatile() && 4286 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4287 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4288 "Support volatile, non temporal, invariant for load_from_swift_error"); 4289 4290 const Value *SV = I.getOperand(0); 4291 Type *Ty = I.getType(); 4292 assert( 4293 (!AA || 4294 !AA->pointsToConstantMemory(MemoryLocation( 4295 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4296 I.getAAMetadata()))) && 4297 "load_from_swift_error should not be constant memory"); 4298 4299 SmallVector<EVT, 4> ValueVTs; 4300 SmallVector<uint64_t, 4> Offsets; 4301 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4302 ValueVTs, &Offsets, 0); 4303 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4304 "expect a single EVT for swifterror"); 4305 4306 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4307 SDValue L = DAG.getCopyFromReg( 4308 getRoot(), getCurSDLoc(), 4309 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4310 4311 setValue(&I, L); 4312 } 4313 4314 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4315 if (I.isAtomic()) 4316 return visitAtomicStore(I); 4317 4318 const Value *SrcV = I.getOperand(0); 4319 const Value *PtrV = I.getOperand(1); 4320 4321 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4322 if (TLI.supportSwiftError()) { 4323 // Swifterror values can come from either a function parameter with 4324 // swifterror attribute or an alloca with swifterror attribute. 4325 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4326 if (Arg->hasSwiftErrorAttr()) 4327 return visitStoreToSwiftError(I); 4328 } 4329 4330 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4331 if (Alloca->isSwiftError()) 4332 return visitStoreToSwiftError(I); 4333 } 4334 } 4335 4336 SmallVector<EVT, 4> ValueVTs, MemVTs; 4337 SmallVector<uint64_t, 4> Offsets; 4338 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4339 SrcV->getType(), ValueVTs, &MemVTs, &Offsets, 0); 4340 unsigned NumValues = ValueVTs.size(); 4341 if (NumValues == 0) 4342 return; 4343 4344 // Get the lowered operands. Note that we do this after 4345 // checking if NumResults is zero, because with zero results 4346 // the operands won't have values in the map. 4347 SDValue Src = getValue(SrcV); 4348 SDValue Ptr = getValue(PtrV); 4349 4350 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4351 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4352 SDLoc dl = getCurSDLoc(); 4353 Align Alignment = I.getAlign(); 4354 AAMDNodes AAInfo = I.getAAMetadata(); 4355 4356 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4357 4358 // An aggregate load cannot wrap around the address space, so offsets to its 4359 // parts don't wrap either. 4360 SDNodeFlags Flags; 4361 Flags.setNoUnsignedWrap(true); 4362 4363 unsigned ChainI = 0; 4364 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4365 // See visitLoad comments. 4366 if (ChainI == MaxParallelChains) { 4367 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4368 ArrayRef(Chains.data(), ChainI)); 4369 Root = Chain; 4370 ChainI = 0; 4371 } 4372 SDValue Add = 4373 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags); 4374 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4375 if (MemVTs[i] != ValueVTs[i]) 4376 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4377 SDValue St = 4378 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4379 Alignment, MMOFlags, AAInfo); 4380 Chains[ChainI] = St; 4381 } 4382 4383 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4384 ArrayRef(Chains.data(), ChainI)); 4385 setValue(&I, StoreNode); 4386 DAG.setRoot(StoreNode); 4387 } 4388 4389 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4390 bool IsCompressing) { 4391 SDLoc sdl = getCurSDLoc(); 4392 4393 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4394 MaybeAlign &Alignment) { 4395 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4396 Src0 = I.getArgOperand(0); 4397 Ptr = I.getArgOperand(1); 4398 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4399 Mask = I.getArgOperand(3); 4400 }; 4401 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4402 MaybeAlign &Alignment) { 4403 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4404 Src0 = I.getArgOperand(0); 4405 Ptr = I.getArgOperand(1); 4406 Mask = I.getArgOperand(2); 4407 Alignment = std::nullopt; 4408 }; 4409 4410 Value *PtrOperand, *MaskOperand, *Src0Operand; 4411 MaybeAlign Alignment; 4412 if (IsCompressing) 4413 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4414 else 4415 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4416 4417 SDValue Ptr = getValue(PtrOperand); 4418 SDValue Src0 = getValue(Src0Operand); 4419 SDValue Mask = getValue(MaskOperand); 4420 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4421 4422 EVT VT = Src0.getValueType(); 4423 if (!Alignment) 4424 Alignment = DAG.getEVTAlign(VT); 4425 4426 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4427 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4428 MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata()); 4429 SDValue StoreNode = 4430 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4431 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4432 DAG.setRoot(StoreNode); 4433 setValue(&I, StoreNode); 4434 } 4435 4436 // Get a uniform base for the Gather/Scatter intrinsic. 4437 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4438 // We try to represent it as a base pointer + vector of indices. 4439 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4440 // The first operand of the GEP may be a single pointer or a vector of pointers 4441 // Example: 4442 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4443 // or 4444 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4445 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4446 // 4447 // When the first GEP operand is a single pointer - it is the uniform base we 4448 // are looking for. If first operand of the GEP is a splat vector - we 4449 // extract the splat value and use it as a uniform base. 4450 // In all other cases the function returns 'false'. 4451 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4452 ISD::MemIndexType &IndexType, SDValue &Scale, 4453 SelectionDAGBuilder *SDB, const BasicBlock *CurBB, 4454 uint64_t ElemSize) { 4455 SelectionDAG& DAG = SDB->DAG; 4456 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4457 const DataLayout &DL = DAG.getDataLayout(); 4458 4459 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type"); 4460 4461 // Handle splat constant pointer. 4462 if (auto *C = dyn_cast<Constant>(Ptr)) { 4463 C = C->getSplatValue(); 4464 if (!C) 4465 return false; 4466 4467 Base = SDB->getValue(C); 4468 4469 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); 4470 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4471 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4472 IndexType = ISD::SIGNED_SCALED; 4473 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4474 return true; 4475 } 4476 4477 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4478 if (!GEP || GEP->getParent() != CurBB) 4479 return false; 4480 4481 if (GEP->getNumOperands() != 2) 4482 return false; 4483 4484 const Value *BasePtr = GEP->getPointerOperand(); 4485 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4486 4487 // Make sure the base is scalar and the index is a vector. 4488 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4489 return false; 4490 4491 uint64_t ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType()); 4492 4493 // Target may not support the required addressing mode. 4494 if (ScaleVal != 1 && 4495 !TLI.isLegalScaleForGatherScatter(ScaleVal, ElemSize)) 4496 return false; 4497 4498 Base = SDB->getValue(BasePtr); 4499 Index = SDB->getValue(IndexVal); 4500 IndexType = ISD::SIGNED_SCALED; 4501 4502 Scale = 4503 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4504 return true; 4505 } 4506 4507 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4508 SDLoc sdl = getCurSDLoc(); 4509 4510 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4511 const Value *Ptr = I.getArgOperand(1); 4512 SDValue Src0 = getValue(I.getArgOperand(0)); 4513 SDValue Mask = getValue(I.getArgOperand(3)); 4514 EVT VT = Src0.getValueType(); 4515 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4516 ->getMaybeAlignValue() 4517 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4518 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4519 4520 SDValue Base; 4521 SDValue Index; 4522 ISD::MemIndexType IndexType; 4523 SDValue Scale; 4524 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4525 I.getParent(), VT.getScalarStoreSize()); 4526 4527 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4528 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4529 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4530 // TODO: Make MachineMemOperands aware of scalable 4531 // vectors. 4532 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata()); 4533 if (!UniformBase) { 4534 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4535 Index = getValue(Ptr); 4536 IndexType = ISD::SIGNED_SCALED; 4537 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4538 } 4539 4540 EVT IdxVT = Index.getValueType(); 4541 EVT EltTy = IdxVT.getVectorElementType(); 4542 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4543 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4544 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4545 } 4546 4547 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4548 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4549 Ops, MMO, IndexType, false); 4550 DAG.setRoot(Scatter); 4551 setValue(&I, Scatter); 4552 } 4553 4554 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4555 SDLoc sdl = getCurSDLoc(); 4556 4557 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4558 MaybeAlign &Alignment) { 4559 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4560 Ptr = I.getArgOperand(0); 4561 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4562 Mask = I.getArgOperand(2); 4563 Src0 = I.getArgOperand(3); 4564 }; 4565 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4566 MaybeAlign &Alignment) { 4567 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4568 Ptr = I.getArgOperand(0); 4569 Alignment = std::nullopt; 4570 Mask = I.getArgOperand(1); 4571 Src0 = I.getArgOperand(2); 4572 }; 4573 4574 Value *PtrOperand, *MaskOperand, *Src0Operand; 4575 MaybeAlign Alignment; 4576 if (IsExpanding) 4577 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4578 else 4579 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4580 4581 SDValue Ptr = getValue(PtrOperand); 4582 SDValue Src0 = getValue(Src0Operand); 4583 SDValue Mask = getValue(MaskOperand); 4584 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4585 4586 EVT VT = Src0.getValueType(); 4587 if (!Alignment) 4588 Alignment = DAG.getEVTAlign(VT); 4589 4590 AAMDNodes AAInfo = I.getAAMetadata(); 4591 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4592 4593 // Do not serialize masked loads of constant memory with anything. 4594 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 4595 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4596 4597 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4598 4599 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4600 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4601 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 4602 4603 SDValue Load = 4604 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4605 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4606 if (AddToChain) 4607 PendingLoads.push_back(Load.getValue(1)); 4608 setValue(&I, Load); 4609 } 4610 4611 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4612 SDLoc sdl = getCurSDLoc(); 4613 4614 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4615 const Value *Ptr = I.getArgOperand(0); 4616 SDValue Src0 = getValue(I.getArgOperand(3)); 4617 SDValue Mask = getValue(I.getArgOperand(2)); 4618 4619 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4620 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4621 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4622 ->getMaybeAlignValue() 4623 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4624 4625 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4626 4627 SDValue Root = DAG.getRoot(); 4628 SDValue Base; 4629 SDValue Index; 4630 ISD::MemIndexType IndexType; 4631 SDValue Scale; 4632 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4633 I.getParent(), VT.getScalarStoreSize()); 4634 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4635 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4636 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4637 // TODO: Make MachineMemOperands aware of scalable 4638 // vectors. 4639 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges); 4640 4641 if (!UniformBase) { 4642 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4643 Index = getValue(Ptr); 4644 IndexType = ISD::SIGNED_SCALED; 4645 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4646 } 4647 4648 EVT IdxVT = Index.getValueType(); 4649 EVT EltTy = IdxVT.getVectorElementType(); 4650 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4651 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4652 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4653 } 4654 4655 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4656 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4657 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4658 4659 PendingLoads.push_back(Gather.getValue(1)); 4660 setValue(&I, Gather); 4661 } 4662 4663 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4664 SDLoc dl = getCurSDLoc(); 4665 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4666 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4667 SyncScope::ID SSID = I.getSyncScopeID(); 4668 4669 SDValue InChain = getRoot(); 4670 4671 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4672 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4673 4674 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4675 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4676 4677 MachineFunction &MF = DAG.getMachineFunction(); 4678 MachineMemOperand *MMO = MF.getMachineMemOperand( 4679 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4680 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4681 FailureOrdering); 4682 4683 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4684 dl, MemVT, VTs, InChain, 4685 getValue(I.getPointerOperand()), 4686 getValue(I.getCompareOperand()), 4687 getValue(I.getNewValOperand()), MMO); 4688 4689 SDValue OutChain = L.getValue(2); 4690 4691 setValue(&I, L); 4692 DAG.setRoot(OutChain); 4693 } 4694 4695 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4696 SDLoc dl = getCurSDLoc(); 4697 ISD::NodeType NT; 4698 switch (I.getOperation()) { 4699 default: llvm_unreachable("Unknown atomicrmw operation"); 4700 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4701 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4702 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4703 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4704 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4705 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4706 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4707 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4708 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4709 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4710 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4711 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4712 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4713 case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break; 4714 case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break; 4715 case AtomicRMWInst::UIncWrap: 4716 NT = ISD::ATOMIC_LOAD_UINC_WRAP; 4717 break; 4718 case AtomicRMWInst::UDecWrap: 4719 NT = ISD::ATOMIC_LOAD_UDEC_WRAP; 4720 break; 4721 } 4722 AtomicOrdering Ordering = I.getOrdering(); 4723 SyncScope::ID SSID = I.getSyncScopeID(); 4724 4725 SDValue InChain = getRoot(); 4726 4727 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4728 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4729 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4730 4731 MachineFunction &MF = DAG.getMachineFunction(); 4732 MachineMemOperand *MMO = MF.getMachineMemOperand( 4733 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4734 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4735 4736 SDValue L = 4737 DAG.getAtomic(NT, dl, MemVT, InChain, 4738 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4739 MMO); 4740 4741 SDValue OutChain = L.getValue(1); 4742 4743 setValue(&I, L); 4744 DAG.setRoot(OutChain); 4745 } 4746 4747 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4748 SDLoc dl = getCurSDLoc(); 4749 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4750 SDValue Ops[3]; 4751 Ops[0] = getRoot(); 4752 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4753 TLI.getFenceOperandTy(DAG.getDataLayout())); 4754 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4755 TLI.getFenceOperandTy(DAG.getDataLayout())); 4756 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops); 4757 setValue(&I, N); 4758 DAG.setRoot(N); 4759 } 4760 4761 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4762 SDLoc dl = getCurSDLoc(); 4763 AtomicOrdering Order = I.getOrdering(); 4764 SyncScope::ID SSID = I.getSyncScopeID(); 4765 4766 SDValue InChain = getRoot(); 4767 4768 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4769 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4770 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4771 4772 if (!TLI.supportsUnalignedAtomics() && 4773 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4774 report_fatal_error("Cannot generate unaligned atomic load"); 4775 4776 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 4777 4778 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4779 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4780 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4781 4782 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4783 4784 SDValue Ptr = getValue(I.getPointerOperand()); 4785 4786 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4787 // TODO: Once this is better exercised by tests, it should be merged with 4788 // the normal path for loads to prevent future divergence. 4789 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4790 if (MemVT != VT) 4791 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4792 4793 setValue(&I, L); 4794 SDValue OutChain = L.getValue(1); 4795 if (!I.isUnordered()) 4796 DAG.setRoot(OutChain); 4797 else 4798 PendingLoads.push_back(OutChain); 4799 return; 4800 } 4801 4802 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4803 Ptr, MMO); 4804 4805 SDValue OutChain = L.getValue(1); 4806 if (MemVT != VT) 4807 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4808 4809 setValue(&I, L); 4810 DAG.setRoot(OutChain); 4811 } 4812 4813 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4814 SDLoc dl = getCurSDLoc(); 4815 4816 AtomicOrdering Ordering = I.getOrdering(); 4817 SyncScope::ID SSID = I.getSyncScopeID(); 4818 4819 SDValue InChain = getRoot(); 4820 4821 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4822 EVT MemVT = 4823 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4824 4825 if (!TLI.supportsUnalignedAtomics() && 4826 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4827 report_fatal_error("Cannot generate unaligned atomic store"); 4828 4829 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4830 4831 MachineFunction &MF = DAG.getMachineFunction(); 4832 MachineMemOperand *MMO = MF.getMachineMemOperand( 4833 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4834 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4835 4836 SDValue Val = getValue(I.getValueOperand()); 4837 if (Val.getValueType() != MemVT) 4838 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4839 SDValue Ptr = getValue(I.getPointerOperand()); 4840 4841 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4842 // TODO: Once this is better exercised by tests, it should be merged with 4843 // the normal path for stores to prevent future divergence. 4844 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4845 setValue(&I, S); 4846 DAG.setRoot(S); 4847 return; 4848 } 4849 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4850 Ptr, Val, MMO); 4851 4852 setValue(&I, OutChain); 4853 DAG.setRoot(OutChain); 4854 } 4855 4856 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4857 /// node. 4858 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4859 unsigned Intrinsic) { 4860 // Ignore the callsite's attributes. A specific call site may be marked with 4861 // readnone, but the lowering code will expect the chain based on the 4862 // definition. 4863 const Function *F = I.getCalledFunction(); 4864 bool HasChain = !F->doesNotAccessMemory(); 4865 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4866 4867 // Build the operand list. 4868 SmallVector<SDValue, 8> Ops; 4869 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4870 if (OnlyLoad) { 4871 // We don't need to serialize loads against other loads. 4872 Ops.push_back(DAG.getRoot()); 4873 } else { 4874 Ops.push_back(getRoot()); 4875 } 4876 } 4877 4878 // Info is set by getTgtMemIntrinsic 4879 TargetLowering::IntrinsicInfo Info; 4880 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4881 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4882 DAG.getMachineFunction(), 4883 Intrinsic); 4884 4885 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4886 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4887 Info.opc == ISD::INTRINSIC_W_CHAIN) 4888 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4889 TLI.getPointerTy(DAG.getDataLayout()))); 4890 4891 // Add all operands of the call to the operand list. 4892 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) { 4893 const Value *Arg = I.getArgOperand(i); 4894 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4895 Ops.push_back(getValue(Arg)); 4896 continue; 4897 } 4898 4899 // Use TargetConstant instead of a regular constant for immarg. 4900 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true); 4901 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4902 assert(CI->getBitWidth() <= 64 && 4903 "large intrinsic immediates not handled"); 4904 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4905 } else { 4906 Ops.push_back( 4907 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4908 } 4909 } 4910 4911 SmallVector<EVT, 4> ValueVTs; 4912 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4913 4914 if (HasChain) 4915 ValueVTs.push_back(MVT::Other); 4916 4917 SDVTList VTs = DAG.getVTList(ValueVTs); 4918 4919 // Propagate fast-math-flags from IR to node(s). 4920 SDNodeFlags Flags; 4921 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 4922 Flags.copyFMF(*FPMO); 4923 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 4924 4925 // Create the node. 4926 SDValue Result; 4927 // In some cases, custom collection of operands from CallInst I may be needed. 4928 TLI.CollectTargetIntrinsicOperands(I, Ops, DAG); 4929 if (IsTgtIntrinsic) { 4930 // This is target intrinsic that touches memory 4931 // 4932 // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic 4933 // didn't yield anything useful. 4934 MachinePointerInfo MPI; 4935 if (Info.ptrVal) 4936 MPI = MachinePointerInfo(Info.ptrVal, Info.offset); 4937 else if (Info.fallbackAddressSpace) 4938 MPI = MachinePointerInfo(*Info.fallbackAddressSpace); 4939 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, 4940 Info.memVT, MPI, Info.align, Info.flags, 4941 Info.size, I.getAAMetadata()); 4942 } else if (!HasChain) { 4943 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4944 } else if (!I.getType()->isVoidTy()) { 4945 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4946 } else { 4947 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4948 } 4949 4950 if (HasChain) { 4951 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4952 if (OnlyLoad) 4953 PendingLoads.push_back(Chain); 4954 else 4955 DAG.setRoot(Chain); 4956 } 4957 4958 if (!I.getType()->isVoidTy()) { 4959 if (!isa<VectorType>(I.getType())) 4960 Result = lowerRangeToAssertZExt(DAG, I, Result); 4961 4962 MaybeAlign Alignment = I.getRetAlign(); 4963 4964 // Insert `assertalign` node if there's an alignment. 4965 if (InsertAssertAlign && Alignment) { 4966 Result = 4967 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 4968 } 4969 4970 setValue(&I, Result); 4971 } 4972 } 4973 4974 /// GetSignificand - Get the significand and build it into a floating-point 4975 /// number with exponent of 1: 4976 /// 4977 /// Op = (Op & 0x007fffff) | 0x3f800000; 4978 /// 4979 /// where Op is the hexadecimal representation of floating point value. 4980 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4981 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4982 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4983 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4984 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4985 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4986 } 4987 4988 /// GetExponent - Get the exponent: 4989 /// 4990 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4991 /// 4992 /// where Op is the hexadecimal representation of floating point value. 4993 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4994 const TargetLowering &TLI, const SDLoc &dl) { 4995 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4996 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4997 SDValue t1 = DAG.getNode( 4998 ISD::SRL, dl, MVT::i32, t0, 4999 DAG.getConstant(23, dl, 5000 TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout()))); 5001 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 5002 DAG.getConstant(127, dl, MVT::i32)); 5003 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 5004 } 5005 5006 /// getF32Constant - Get 32-bit floating point constant. 5007 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 5008 const SDLoc &dl) { 5009 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 5010 MVT::f32); 5011 } 5012 5013 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 5014 SelectionDAG &DAG) { 5015 // TODO: What fast-math-flags should be set on the floating-point nodes? 5016 5017 // IntegerPartOfX = ((int32_t)(t0); 5018 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 5019 5020 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 5021 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 5022 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 5023 5024 // IntegerPartOfX <<= 23; 5025 IntegerPartOfX = 5026 DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 5027 DAG.getConstant(23, dl, 5028 DAG.getTargetLoweringInfo().getShiftAmountTy( 5029 MVT::i32, DAG.getDataLayout()))); 5030 5031 SDValue TwoToFractionalPartOfX; 5032 if (LimitFloatPrecision <= 6) { 5033 // For floating-point precision of 6: 5034 // 5035 // TwoToFractionalPartOfX = 5036 // 0.997535578f + 5037 // (0.735607626f + 0.252464424f * x) * x; 5038 // 5039 // error 0.0144103317, which is 6 bits 5040 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5041 getF32Constant(DAG, 0x3e814304, dl)); 5042 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5043 getF32Constant(DAG, 0x3f3c50c8, dl)); 5044 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5045 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5046 getF32Constant(DAG, 0x3f7f5e7e, dl)); 5047 } else if (LimitFloatPrecision <= 12) { 5048 // For floating-point precision of 12: 5049 // 5050 // TwoToFractionalPartOfX = 5051 // 0.999892986f + 5052 // (0.696457318f + 5053 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 5054 // 5055 // error 0.000107046256, which is 13 to 14 bits 5056 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5057 getF32Constant(DAG, 0x3da235e3, dl)); 5058 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5059 getF32Constant(DAG, 0x3e65b8f3, dl)); 5060 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5061 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5062 getF32Constant(DAG, 0x3f324b07, dl)); 5063 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5064 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5065 getF32Constant(DAG, 0x3f7ff8fd, dl)); 5066 } else { // LimitFloatPrecision <= 18 5067 // For floating-point precision of 18: 5068 // 5069 // TwoToFractionalPartOfX = 5070 // 0.999999982f + 5071 // (0.693148872f + 5072 // (0.240227044f + 5073 // (0.554906021e-1f + 5074 // (0.961591928e-2f + 5075 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 5076 // error 2.47208000*10^(-7), which is better than 18 bits 5077 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5078 getF32Constant(DAG, 0x3924b03e, dl)); 5079 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5080 getF32Constant(DAG, 0x3ab24b87, dl)); 5081 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5082 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5083 getF32Constant(DAG, 0x3c1d8c17, dl)); 5084 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5085 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5086 getF32Constant(DAG, 0x3d634a1d, dl)); 5087 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5088 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5089 getF32Constant(DAG, 0x3e75fe14, dl)); 5090 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5091 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 5092 getF32Constant(DAG, 0x3f317234, dl)); 5093 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 5094 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 5095 getF32Constant(DAG, 0x3f800000, dl)); 5096 } 5097 5098 // Add the exponent into the result in integer domain. 5099 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 5100 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5101 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 5102 } 5103 5104 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5105 /// limited-precision mode. 5106 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5107 const TargetLowering &TLI, SDNodeFlags Flags) { 5108 if (Op.getValueType() == MVT::f32 && 5109 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5110 5111 // Put the exponent in the right bit position for later addition to the 5112 // final result: 5113 // 5114 // t0 = Op * log2(e) 5115 5116 // TODO: What fast-math-flags should be set here? 5117 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5118 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5119 return getLimitedPrecisionExp2(t0, dl, DAG); 5120 } 5121 5122 // No special expansion. 5123 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5124 } 5125 5126 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5127 /// limited-precision mode. 5128 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5129 const TargetLowering &TLI, SDNodeFlags Flags) { 5130 // TODO: What fast-math-flags should be set on the floating-point nodes? 5131 5132 if (Op.getValueType() == MVT::f32 && 5133 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5134 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5135 5136 // Scale the exponent by log(2). 5137 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5138 SDValue LogOfExponent = 5139 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5140 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5141 5142 // Get the significand and build it into a floating-point number with 5143 // exponent of 1. 5144 SDValue X = GetSignificand(DAG, Op1, dl); 5145 5146 SDValue LogOfMantissa; 5147 if (LimitFloatPrecision <= 6) { 5148 // For floating-point precision of 6: 5149 // 5150 // LogofMantissa = 5151 // -1.1609546f + 5152 // (1.4034025f - 0.23903021f * x) * x; 5153 // 5154 // error 0.0034276066, which is better than 8 bits 5155 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5156 getF32Constant(DAG, 0xbe74c456, dl)); 5157 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5158 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5159 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5160 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5161 getF32Constant(DAG, 0x3f949a29, dl)); 5162 } else if (LimitFloatPrecision <= 12) { 5163 // For floating-point precision of 12: 5164 // 5165 // LogOfMantissa = 5166 // -1.7417939f + 5167 // (2.8212026f + 5168 // (-1.4699568f + 5169 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5170 // 5171 // error 0.000061011436, which is 14 bits 5172 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5173 getF32Constant(DAG, 0xbd67b6d6, dl)); 5174 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5175 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5176 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5177 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5178 getF32Constant(DAG, 0x3fbc278b, dl)); 5179 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5180 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5181 getF32Constant(DAG, 0x40348e95, dl)); 5182 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5183 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5184 getF32Constant(DAG, 0x3fdef31a, dl)); 5185 } else { // LimitFloatPrecision <= 18 5186 // For floating-point precision of 18: 5187 // 5188 // LogOfMantissa = 5189 // -2.1072184f + 5190 // (4.2372794f + 5191 // (-3.7029485f + 5192 // (2.2781945f + 5193 // (-0.87823314f + 5194 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5195 // 5196 // error 0.0000023660568, which is better than 18 bits 5197 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5198 getF32Constant(DAG, 0xbc91e5ac, dl)); 5199 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5200 getF32Constant(DAG, 0x3e4350aa, dl)); 5201 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5202 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5203 getF32Constant(DAG, 0x3f60d3e3, dl)); 5204 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5205 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5206 getF32Constant(DAG, 0x4011cdf0, dl)); 5207 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5208 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5209 getF32Constant(DAG, 0x406cfd1c, dl)); 5210 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5211 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5212 getF32Constant(DAG, 0x408797cb, dl)); 5213 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5214 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5215 getF32Constant(DAG, 0x4006dcab, dl)); 5216 } 5217 5218 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5219 } 5220 5221 // No special expansion. 5222 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5223 } 5224 5225 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5226 /// limited-precision mode. 5227 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5228 const TargetLowering &TLI, SDNodeFlags Flags) { 5229 // TODO: What fast-math-flags should be set on the floating-point nodes? 5230 5231 if (Op.getValueType() == MVT::f32 && 5232 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5233 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5234 5235 // Get the exponent. 5236 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5237 5238 // Get the significand and build it into a floating-point number with 5239 // exponent of 1. 5240 SDValue X = GetSignificand(DAG, Op1, dl); 5241 5242 // Different possible minimax approximations of significand in 5243 // floating-point for various degrees of accuracy over [1,2]. 5244 SDValue Log2ofMantissa; 5245 if (LimitFloatPrecision <= 6) { 5246 // For floating-point precision of 6: 5247 // 5248 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5249 // 5250 // error 0.0049451742, which is more than 7 bits 5251 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5252 getF32Constant(DAG, 0xbeb08fe0, dl)); 5253 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5254 getF32Constant(DAG, 0x40019463, dl)); 5255 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5256 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5257 getF32Constant(DAG, 0x3fd6633d, dl)); 5258 } else if (LimitFloatPrecision <= 12) { 5259 // For floating-point precision of 12: 5260 // 5261 // Log2ofMantissa = 5262 // -2.51285454f + 5263 // (4.07009056f + 5264 // (-2.12067489f + 5265 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5266 // 5267 // error 0.0000876136000, which is better than 13 bits 5268 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5269 getF32Constant(DAG, 0xbda7262e, dl)); 5270 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5271 getF32Constant(DAG, 0x3f25280b, dl)); 5272 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5273 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5274 getF32Constant(DAG, 0x4007b923, dl)); 5275 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5276 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5277 getF32Constant(DAG, 0x40823e2f, dl)); 5278 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5279 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5280 getF32Constant(DAG, 0x4020d29c, dl)); 5281 } else { // LimitFloatPrecision <= 18 5282 // For floating-point precision of 18: 5283 // 5284 // Log2ofMantissa = 5285 // -3.0400495f + 5286 // (6.1129976f + 5287 // (-5.3420409f + 5288 // (3.2865683f + 5289 // (-1.2669343f + 5290 // (0.27515199f - 5291 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5292 // 5293 // error 0.0000018516, which is better than 18 bits 5294 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5295 getF32Constant(DAG, 0xbcd2769e, dl)); 5296 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5297 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5298 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5299 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5300 getF32Constant(DAG, 0x3fa22ae7, dl)); 5301 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5302 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5303 getF32Constant(DAG, 0x40525723, dl)); 5304 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5305 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5306 getF32Constant(DAG, 0x40aaf200, dl)); 5307 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5308 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5309 getF32Constant(DAG, 0x40c39dad, dl)); 5310 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5311 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5312 getF32Constant(DAG, 0x4042902c, dl)); 5313 } 5314 5315 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5316 } 5317 5318 // No special expansion. 5319 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5320 } 5321 5322 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5323 /// limited-precision mode. 5324 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5325 const TargetLowering &TLI, SDNodeFlags Flags) { 5326 // TODO: What fast-math-flags should be set on the floating-point nodes? 5327 5328 if (Op.getValueType() == MVT::f32 && 5329 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5330 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5331 5332 // Scale the exponent by log10(2) [0.30102999f]. 5333 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5334 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5335 getF32Constant(DAG, 0x3e9a209a, dl)); 5336 5337 // Get the significand and build it into a floating-point number with 5338 // exponent of 1. 5339 SDValue X = GetSignificand(DAG, Op1, dl); 5340 5341 SDValue Log10ofMantissa; 5342 if (LimitFloatPrecision <= 6) { 5343 // For floating-point precision of 6: 5344 // 5345 // Log10ofMantissa = 5346 // -0.50419619f + 5347 // (0.60948995f - 0.10380950f * x) * x; 5348 // 5349 // error 0.0014886165, which is 6 bits 5350 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5351 getF32Constant(DAG, 0xbdd49a13, dl)); 5352 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5353 getF32Constant(DAG, 0x3f1c0789, dl)); 5354 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5355 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5356 getF32Constant(DAG, 0x3f011300, dl)); 5357 } else if (LimitFloatPrecision <= 12) { 5358 // For floating-point precision of 12: 5359 // 5360 // Log10ofMantissa = 5361 // -0.64831180f + 5362 // (0.91751397f + 5363 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5364 // 5365 // error 0.00019228036, which is better than 12 bits 5366 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5367 getF32Constant(DAG, 0x3d431f31, dl)); 5368 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5369 getF32Constant(DAG, 0x3ea21fb2, dl)); 5370 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5371 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5372 getF32Constant(DAG, 0x3f6ae232, dl)); 5373 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5374 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5375 getF32Constant(DAG, 0x3f25f7c3, dl)); 5376 } else { // LimitFloatPrecision <= 18 5377 // For floating-point precision of 18: 5378 // 5379 // Log10ofMantissa = 5380 // -0.84299375f + 5381 // (1.5327582f + 5382 // (-1.0688956f + 5383 // (0.49102474f + 5384 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5385 // 5386 // error 0.0000037995730, which is better than 18 bits 5387 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5388 getF32Constant(DAG, 0x3c5d51ce, dl)); 5389 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5390 getF32Constant(DAG, 0x3e00685a, dl)); 5391 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5392 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5393 getF32Constant(DAG, 0x3efb6798, dl)); 5394 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5395 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5396 getF32Constant(DAG, 0x3f88d192, dl)); 5397 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5398 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5399 getF32Constant(DAG, 0x3fc4316c, dl)); 5400 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5401 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5402 getF32Constant(DAG, 0x3f57ce70, dl)); 5403 } 5404 5405 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5406 } 5407 5408 // No special expansion. 5409 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5410 } 5411 5412 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5413 /// limited-precision mode. 5414 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5415 const TargetLowering &TLI, SDNodeFlags Flags) { 5416 if (Op.getValueType() == MVT::f32 && 5417 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5418 return getLimitedPrecisionExp2(Op, dl, DAG); 5419 5420 // No special expansion. 5421 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5422 } 5423 5424 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5425 /// limited-precision mode with x == 10.0f. 5426 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5427 SelectionDAG &DAG, const TargetLowering &TLI, 5428 SDNodeFlags Flags) { 5429 bool IsExp10 = false; 5430 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5431 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5432 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5433 APFloat Ten(10.0f); 5434 IsExp10 = LHSC->isExactlyValue(Ten); 5435 } 5436 } 5437 5438 // TODO: What fast-math-flags should be set on the FMUL node? 5439 if (IsExp10) { 5440 // Put the exponent in the right bit position for later addition to the 5441 // final result: 5442 // 5443 // #define LOG2OF10 3.3219281f 5444 // t0 = Op * LOG2OF10; 5445 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5446 getF32Constant(DAG, 0x40549a78, dl)); 5447 return getLimitedPrecisionExp2(t0, dl, DAG); 5448 } 5449 5450 // No special expansion. 5451 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5452 } 5453 5454 /// ExpandPowI - Expand a llvm.powi intrinsic. 5455 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5456 SelectionDAG &DAG) { 5457 // If RHS is a constant, we can expand this out to a multiplication tree if 5458 // it's beneficial on the target, otherwise we end up lowering to a call to 5459 // __powidf2 (for example). 5460 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5461 unsigned Val = RHSC->getSExtValue(); 5462 5463 // powi(x, 0) -> 1.0 5464 if (Val == 0) 5465 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5466 5467 if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI( 5468 Val, DAG.shouldOptForSize())) { 5469 // Get the exponent as a positive value. 5470 if ((int)Val < 0) 5471 Val = -Val; 5472 // We use the simple binary decomposition method to generate the multiply 5473 // sequence. There are more optimal ways to do this (for example, 5474 // powi(x,15) generates one more multiply than it should), but this has 5475 // the benefit of being both really simple and much better than a libcall. 5476 SDValue Res; // Logically starts equal to 1.0 5477 SDValue CurSquare = LHS; 5478 // TODO: Intrinsics should have fast-math-flags that propagate to these 5479 // nodes. 5480 while (Val) { 5481 if (Val & 1) { 5482 if (Res.getNode()) 5483 Res = 5484 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare); 5485 else 5486 Res = CurSquare; // 1.0*CurSquare. 5487 } 5488 5489 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5490 CurSquare, CurSquare); 5491 Val >>= 1; 5492 } 5493 5494 // If the original was negative, invert the result, producing 1/(x*x*x). 5495 if (RHSC->getSExtValue() < 0) 5496 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5497 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5498 return Res; 5499 } 5500 } 5501 5502 // Otherwise, expand to a libcall. 5503 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5504 } 5505 5506 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5507 SDValue LHS, SDValue RHS, SDValue Scale, 5508 SelectionDAG &DAG, const TargetLowering &TLI) { 5509 EVT VT = LHS.getValueType(); 5510 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5511 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5512 LLVMContext &Ctx = *DAG.getContext(); 5513 5514 // If the type is legal but the operation isn't, this node might survive all 5515 // the way to operation legalization. If we end up there and we do not have 5516 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5517 // node. 5518 5519 // Coax the legalizer into expanding the node during type legalization instead 5520 // by bumping the size by one bit. This will force it to Promote, enabling the 5521 // early expansion and avoiding the need to expand later. 5522 5523 // We don't have to do this if Scale is 0; that can always be expanded, unless 5524 // it's a saturating signed operation. Those can experience true integer 5525 // division overflow, a case which we must avoid. 5526 5527 // FIXME: We wouldn't have to do this (or any of the early 5528 // expansion/promotion) if it was possible to expand a libcall of an 5529 // illegal type during operation legalization. But it's not, so things 5530 // get a bit hacky. 5531 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5532 if ((ScaleInt > 0 || (Saturating && Signed)) && 5533 (TLI.isTypeLegal(VT) || 5534 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5535 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5536 Opcode, VT, ScaleInt); 5537 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5538 EVT PromVT; 5539 if (VT.isScalarInteger()) 5540 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5541 else if (VT.isVector()) { 5542 PromVT = VT.getVectorElementType(); 5543 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5544 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5545 } else 5546 llvm_unreachable("Wrong VT for DIVFIX?"); 5547 if (Signed) { 5548 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5549 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5550 } else { 5551 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5552 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5553 } 5554 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5555 // For saturating operations, we need to shift up the LHS to get the 5556 // proper saturation width, and then shift down again afterwards. 5557 if (Saturating) 5558 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5559 DAG.getConstant(1, DL, ShiftTy)); 5560 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5561 if (Saturating) 5562 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5563 DAG.getConstant(1, DL, ShiftTy)); 5564 return DAG.getZExtOrTrunc(Res, DL, VT); 5565 } 5566 } 5567 5568 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5569 } 5570 5571 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5572 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5573 static void 5574 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5575 const SDValue &N) { 5576 switch (N.getOpcode()) { 5577 case ISD::CopyFromReg: { 5578 SDValue Op = N.getOperand(1); 5579 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5580 Op.getValueType().getSizeInBits()); 5581 return; 5582 } 5583 case ISD::BITCAST: 5584 case ISD::AssertZext: 5585 case ISD::AssertSext: 5586 case ISD::TRUNCATE: 5587 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5588 return; 5589 case ISD::BUILD_PAIR: 5590 case ISD::BUILD_VECTOR: 5591 case ISD::CONCAT_VECTORS: 5592 for (SDValue Op : N->op_values()) 5593 getUnderlyingArgRegs(Regs, Op); 5594 return; 5595 default: 5596 return; 5597 } 5598 } 5599 5600 /// If the DbgValueInst is a dbg_value of a function argument, create the 5601 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5602 /// instruction selection, they will be inserted to the entry BB. 5603 /// We don't currently support this for variadic dbg_values, as they shouldn't 5604 /// appear for function arguments or in the prologue. 5605 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5606 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5607 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) { 5608 const Argument *Arg = dyn_cast<Argument>(V); 5609 if (!Arg) 5610 return false; 5611 5612 MachineFunction &MF = DAG.getMachineFunction(); 5613 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5614 5615 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind 5616 // we've been asked to pursue. 5617 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr, 5618 bool Indirect) { 5619 if (Reg.isVirtual() && MF.useDebugInstrRef()) { 5620 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF 5621 // pointing at the VReg, which will be patched up later. 5622 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF); 5623 SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg( 5624 /* Reg */ Reg, /* isDef */ false, /* isImp */ false, 5625 /* isKill */ false, /* isDead */ false, 5626 /* isUndef */ false, /* isEarlyClobber */ false, 5627 /* SubReg */ 0, /* isDebug */ true)}); 5628 5629 auto *NewDIExpr = FragExpr; 5630 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into 5631 // the DIExpression. 5632 if (Indirect) 5633 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore); 5634 SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0}); 5635 NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops); 5636 return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr); 5637 } else { 5638 // Create a completely standard DBG_VALUE. 5639 auto &Inst = TII->get(TargetOpcode::DBG_VALUE); 5640 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr); 5641 } 5642 }; 5643 5644 if (Kind == FuncArgumentDbgValueKind::Value) { 5645 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5646 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5647 // the entry block. 5648 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5649 if (!IsInEntryBlock) 5650 return false; 5651 5652 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5653 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5654 // variable that also is a param. 5655 // 5656 // Although, if we are at the top of the entry block already, we can still 5657 // emit using ArgDbgValue. This might catch some situations when the 5658 // dbg.value refers to an argument that isn't used in the entry block, so 5659 // any CopyToReg node would be optimized out and the only way to express 5660 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5661 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5662 // we should only emit as ArgDbgValue if the Variable is an argument to the 5663 // current function, and the dbg.value intrinsic is found in the entry 5664 // block. 5665 bool VariableIsFunctionInputArg = Variable->isParameter() && 5666 !DL->getInlinedAt(); 5667 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5668 if (!IsInPrologue && !VariableIsFunctionInputArg) 5669 return false; 5670 5671 // Here we assume that a function argument on IR level only can be used to 5672 // describe one input parameter on source level. If we for example have 5673 // source code like this 5674 // 5675 // struct A { long x, y; }; 5676 // void foo(struct A a, long b) { 5677 // ... 5678 // b = a.x; 5679 // ... 5680 // } 5681 // 5682 // and IR like this 5683 // 5684 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5685 // entry: 5686 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5687 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5688 // call void @llvm.dbg.value(metadata i32 %b, "b", 5689 // ... 5690 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5691 // ... 5692 // 5693 // then the last dbg.value is describing a parameter "b" using a value that 5694 // is an argument. But since we already has used %a1 to describe a parameter 5695 // we should not handle that last dbg.value here (that would result in an 5696 // incorrect hoisting of the DBG_VALUE to the function entry). 5697 // Notice that we allow one dbg.value per IR level argument, to accommodate 5698 // for the situation with fragments above. 5699 if (VariableIsFunctionInputArg) { 5700 unsigned ArgNo = Arg->getArgNo(); 5701 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5702 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5703 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5704 return false; 5705 FuncInfo.DescribedArgs.set(ArgNo); 5706 } 5707 } 5708 5709 bool IsIndirect = false; 5710 std::optional<MachineOperand> Op; 5711 // Some arguments' frame index is recorded during argument lowering. 5712 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5713 if (FI != std::numeric_limits<int>::max()) 5714 Op = MachineOperand::CreateFI(FI); 5715 5716 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 5717 if (!Op && N.getNode()) { 5718 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5719 Register Reg; 5720 if (ArgRegsAndSizes.size() == 1) 5721 Reg = ArgRegsAndSizes.front().first; 5722 5723 if (Reg && Reg.isVirtual()) { 5724 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5725 Register PR = RegInfo.getLiveInPhysReg(Reg); 5726 if (PR) 5727 Reg = PR; 5728 } 5729 if (Reg) { 5730 Op = MachineOperand::CreateReg(Reg, false); 5731 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5732 } 5733 } 5734 5735 if (!Op && N.getNode()) { 5736 // Check if frame index is available. 5737 SDValue LCandidate = peekThroughBitcasts(N); 5738 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5739 if (FrameIndexSDNode *FINode = 5740 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5741 Op = MachineOperand::CreateFI(FINode->getIndex()); 5742 } 5743 5744 if (!Op) { 5745 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5746 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 5747 SplitRegs) { 5748 unsigned Offset = 0; 5749 for (const auto &RegAndSize : SplitRegs) { 5750 // If the expression is already a fragment, the current register 5751 // offset+size might extend beyond the fragment. In this case, only 5752 // the register bits that are inside the fragment are relevant. 5753 int RegFragmentSizeInBits = RegAndSize.second; 5754 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5755 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5756 // The register is entirely outside the expression fragment, 5757 // so is irrelevant for debug info. 5758 if (Offset >= ExprFragmentSizeInBits) 5759 break; 5760 // The register is partially outside the expression fragment, only 5761 // the low bits within the fragment are relevant for debug info. 5762 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5763 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5764 } 5765 } 5766 5767 auto FragmentExpr = DIExpression::createFragmentExpression( 5768 Expr, Offset, RegFragmentSizeInBits); 5769 Offset += RegAndSize.second; 5770 // If a valid fragment expression cannot be created, the variable's 5771 // correct value cannot be determined and so it is set as Undef. 5772 if (!FragmentExpr) { 5773 SDDbgValue *SDV = DAG.getConstantDbgValue( 5774 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5775 DAG.AddDbgValue(SDV, false); 5776 continue; 5777 } 5778 MachineInstr *NewMI = 5779 MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, 5780 Kind != FuncArgumentDbgValueKind::Value); 5781 FuncInfo.ArgDbgValues.push_back(NewMI); 5782 } 5783 }; 5784 5785 // Check if ValueMap has reg number. 5786 DenseMap<const Value *, Register>::const_iterator 5787 VMI = FuncInfo.ValueMap.find(V); 5788 if (VMI != FuncInfo.ValueMap.end()) { 5789 const auto &TLI = DAG.getTargetLoweringInfo(); 5790 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5791 V->getType(), std::nullopt); 5792 if (RFV.occupiesMultipleRegs()) { 5793 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5794 return true; 5795 } 5796 5797 Op = MachineOperand::CreateReg(VMI->second, false); 5798 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5799 } else if (ArgRegsAndSizes.size() > 1) { 5800 // This was split due to the calling convention, and no virtual register 5801 // mapping exists for the value. 5802 splitMultiRegDbgValue(ArgRegsAndSizes); 5803 return true; 5804 } 5805 } 5806 5807 if (!Op) 5808 return false; 5809 5810 // If the expression refers to the entry value of an Argument, use the 5811 // corresponding livein physical register. As per the Verifier, this is only 5812 // allowed for swiftasync Arguments. 5813 if (Op->isReg() && Expr->isEntryValue()) { 5814 assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync)); 5815 auto OpReg = Op->getReg(); 5816 for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins()) 5817 if (OpReg == VirtReg || OpReg == PhysReg) { 5818 SDDbgValue *SDV = DAG.getVRegDbgValue( 5819 Variable, Expr, PhysReg, 5820 Kind != FuncArgumentDbgValueKind::Value /*is indirect*/, DL, 5821 SDNodeOrder); 5822 DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/); 5823 return true; 5824 } 5825 LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but " 5826 "couldn't find a physical register\n"); 5827 return true; 5828 } 5829 5830 assert(Variable->isValidLocationForIntrinsic(DL) && 5831 "Expected inlined-at fields to agree"); 5832 MachineInstr *NewMI = nullptr; 5833 5834 if (Op->isReg()) 5835 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect); 5836 else 5837 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op, 5838 Variable, Expr); 5839 5840 // Otherwise, use ArgDbgValues. 5841 FuncInfo.ArgDbgValues.push_back(NewMI); 5842 return true; 5843 } 5844 5845 /// Return the appropriate SDDbgValue based on N. 5846 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5847 DILocalVariable *Variable, 5848 DIExpression *Expr, 5849 const DebugLoc &dl, 5850 unsigned DbgSDNodeOrder) { 5851 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5852 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5853 // stack slot locations. 5854 // 5855 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5856 // debug values here after optimization: 5857 // 5858 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5859 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5860 // 5861 // Both describe the direct values of their associated variables. 5862 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5863 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5864 } 5865 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5866 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5867 } 5868 5869 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5870 switch (Intrinsic) { 5871 case Intrinsic::smul_fix: 5872 return ISD::SMULFIX; 5873 case Intrinsic::umul_fix: 5874 return ISD::UMULFIX; 5875 case Intrinsic::smul_fix_sat: 5876 return ISD::SMULFIXSAT; 5877 case Intrinsic::umul_fix_sat: 5878 return ISD::UMULFIXSAT; 5879 case Intrinsic::sdiv_fix: 5880 return ISD::SDIVFIX; 5881 case Intrinsic::udiv_fix: 5882 return ISD::UDIVFIX; 5883 case Intrinsic::sdiv_fix_sat: 5884 return ISD::SDIVFIXSAT; 5885 case Intrinsic::udiv_fix_sat: 5886 return ISD::UDIVFIXSAT; 5887 default: 5888 llvm_unreachable("Unhandled fixed point intrinsic"); 5889 } 5890 } 5891 5892 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5893 const char *FunctionName) { 5894 assert(FunctionName && "FunctionName must not be nullptr"); 5895 SDValue Callee = DAG.getExternalSymbol( 5896 FunctionName, 5897 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5898 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 5899 } 5900 5901 /// Given a @llvm.call.preallocated.setup, return the corresponding 5902 /// preallocated call. 5903 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5904 assert(cast<CallBase>(PreallocatedSetup) 5905 ->getCalledFunction() 5906 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5907 "expected call_preallocated_setup Value"); 5908 for (const auto *U : PreallocatedSetup->users()) { 5909 auto *UseCall = cast<CallBase>(U); 5910 const Function *Fn = UseCall->getCalledFunction(); 5911 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5912 return UseCall; 5913 } 5914 } 5915 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5916 } 5917 5918 /// Lower the call to the specified intrinsic function. 5919 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5920 unsigned Intrinsic) { 5921 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5922 SDLoc sdl = getCurSDLoc(); 5923 DebugLoc dl = getCurDebugLoc(); 5924 SDValue Res; 5925 5926 SDNodeFlags Flags; 5927 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 5928 Flags.copyFMF(*FPOp); 5929 5930 switch (Intrinsic) { 5931 default: 5932 // By default, turn this into a target intrinsic node. 5933 visitTargetIntrinsic(I, Intrinsic); 5934 return; 5935 case Intrinsic::vscale: { 5936 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5937 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1))); 5938 return; 5939 } 5940 case Intrinsic::vastart: visitVAStart(I); return; 5941 case Intrinsic::vaend: visitVAEnd(I); return; 5942 case Intrinsic::vacopy: visitVACopy(I); return; 5943 case Intrinsic::returnaddress: 5944 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5945 TLI.getValueType(DAG.getDataLayout(), I.getType()), 5946 getValue(I.getArgOperand(0)))); 5947 return; 5948 case Intrinsic::addressofreturnaddress: 5949 setValue(&I, 5950 DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5951 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 5952 return; 5953 case Intrinsic::sponentry: 5954 setValue(&I, 5955 DAG.getNode(ISD::SPONENTRY, sdl, 5956 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 5957 return; 5958 case Intrinsic::frameaddress: 5959 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5960 TLI.getFrameIndexTy(DAG.getDataLayout()), 5961 getValue(I.getArgOperand(0)))); 5962 return; 5963 case Intrinsic::read_volatile_register: 5964 case Intrinsic::read_register: { 5965 Value *Reg = I.getArgOperand(0); 5966 SDValue Chain = getRoot(); 5967 SDValue RegName = 5968 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5969 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5970 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5971 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5972 setValue(&I, Res); 5973 DAG.setRoot(Res.getValue(1)); 5974 return; 5975 } 5976 case Intrinsic::write_register: { 5977 Value *Reg = I.getArgOperand(0); 5978 Value *RegValue = I.getArgOperand(1); 5979 SDValue Chain = getRoot(); 5980 SDValue RegName = 5981 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5982 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5983 RegName, getValue(RegValue))); 5984 return; 5985 } 5986 case Intrinsic::memcpy: { 5987 const auto &MCI = cast<MemCpyInst>(I); 5988 SDValue Op1 = getValue(I.getArgOperand(0)); 5989 SDValue Op2 = getValue(I.getArgOperand(1)); 5990 SDValue Op3 = getValue(I.getArgOperand(2)); 5991 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5992 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5993 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5994 Align Alignment = std::min(DstAlign, SrcAlign); 5995 bool isVol = MCI.isVolatile(); 5996 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5997 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5998 // node. 5999 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6000 SDValue MC = DAG.getMemcpy( 6001 Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6002 /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)), 6003 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 6004 updateDAGForMaybeTailCall(MC); 6005 return; 6006 } 6007 case Intrinsic::memcpy_inline: { 6008 const auto &MCI = cast<MemCpyInlineInst>(I); 6009 SDValue Dst = getValue(I.getArgOperand(0)); 6010 SDValue Src = getValue(I.getArgOperand(1)); 6011 SDValue Size = getValue(I.getArgOperand(2)); 6012 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 6013 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 6014 Align DstAlign = MCI.getDestAlign().valueOrOne(); 6015 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 6016 Align Alignment = std::min(DstAlign, SrcAlign); 6017 bool isVol = MCI.isVolatile(); 6018 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6019 // FIXME: Support passing different dest/src alignments to the memcpy DAG 6020 // node. 6021 SDValue MC = DAG.getMemcpy( 6022 getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 6023 /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)), 6024 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 6025 updateDAGForMaybeTailCall(MC); 6026 return; 6027 } 6028 case Intrinsic::memset: { 6029 const auto &MSI = cast<MemSetInst>(I); 6030 SDValue Op1 = getValue(I.getArgOperand(0)); 6031 SDValue Op2 = getValue(I.getArgOperand(1)); 6032 SDValue Op3 = getValue(I.getArgOperand(2)); 6033 // @llvm.memset defines 0 and 1 to both mean no alignment. 6034 Align Alignment = MSI.getDestAlign().valueOrOne(); 6035 bool isVol = MSI.isVolatile(); 6036 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6037 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6038 SDValue MS = DAG.getMemset( 6039 Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false, 6040 isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata()); 6041 updateDAGForMaybeTailCall(MS); 6042 return; 6043 } 6044 case Intrinsic::memset_inline: { 6045 const auto &MSII = cast<MemSetInlineInst>(I); 6046 SDValue Dst = getValue(I.getArgOperand(0)); 6047 SDValue Value = getValue(I.getArgOperand(1)); 6048 SDValue Size = getValue(I.getArgOperand(2)); 6049 assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size"); 6050 // @llvm.memset defines 0 and 1 to both mean no alignment. 6051 Align DstAlign = MSII.getDestAlign().valueOrOne(); 6052 bool isVol = MSII.isVolatile(); 6053 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6054 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6055 SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol, 6056 /* AlwaysInline */ true, isTC, 6057 MachinePointerInfo(I.getArgOperand(0)), 6058 I.getAAMetadata()); 6059 updateDAGForMaybeTailCall(MC); 6060 return; 6061 } 6062 case Intrinsic::memmove: { 6063 const auto &MMI = cast<MemMoveInst>(I); 6064 SDValue Op1 = getValue(I.getArgOperand(0)); 6065 SDValue Op2 = getValue(I.getArgOperand(1)); 6066 SDValue Op3 = getValue(I.getArgOperand(2)); 6067 // @llvm.memmove defines 0 and 1 to both mean no alignment. 6068 Align DstAlign = MMI.getDestAlign().valueOrOne(); 6069 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 6070 Align Alignment = std::min(DstAlign, SrcAlign); 6071 bool isVol = MMI.isVolatile(); 6072 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6073 // FIXME: Support passing different dest/src alignments to the memmove DAG 6074 // node. 6075 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6076 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6077 isTC, MachinePointerInfo(I.getArgOperand(0)), 6078 MachinePointerInfo(I.getArgOperand(1)), 6079 I.getAAMetadata(), AA); 6080 updateDAGForMaybeTailCall(MM); 6081 return; 6082 } 6083 case Intrinsic::memcpy_element_unordered_atomic: { 6084 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 6085 SDValue Dst = getValue(MI.getRawDest()); 6086 SDValue Src = getValue(MI.getRawSource()); 6087 SDValue Length = getValue(MI.getLength()); 6088 6089 Type *LengthTy = MI.getLength()->getType(); 6090 unsigned ElemSz = MI.getElementSizeInBytes(); 6091 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6092 SDValue MC = 6093 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6094 isTC, MachinePointerInfo(MI.getRawDest()), 6095 MachinePointerInfo(MI.getRawSource())); 6096 updateDAGForMaybeTailCall(MC); 6097 return; 6098 } 6099 case Intrinsic::memmove_element_unordered_atomic: { 6100 auto &MI = cast<AtomicMemMoveInst>(I); 6101 SDValue Dst = getValue(MI.getRawDest()); 6102 SDValue Src = getValue(MI.getRawSource()); 6103 SDValue Length = getValue(MI.getLength()); 6104 6105 Type *LengthTy = MI.getLength()->getType(); 6106 unsigned ElemSz = MI.getElementSizeInBytes(); 6107 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6108 SDValue MC = 6109 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6110 isTC, MachinePointerInfo(MI.getRawDest()), 6111 MachinePointerInfo(MI.getRawSource())); 6112 updateDAGForMaybeTailCall(MC); 6113 return; 6114 } 6115 case Intrinsic::memset_element_unordered_atomic: { 6116 auto &MI = cast<AtomicMemSetInst>(I); 6117 SDValue Dst = getValue(MI.getRawDest()); 6118 SDValue Val = getValue(MI.getValue()); 6119 SDValue Length = getValue(MI.getLength()); 6120 6121 Type *LengthTy = MI.getLength()->getType(); 6122 unsigned ElemSz = MI.getElementSizeInBytes(); 6123 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6124 SDValue MC = 6125 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz, 6126 isTC, MachinePointerInfo(MI.getRawDest())); 6127 updateDAGForMaybeTailCall(MC); 6128 return; 6129 } 6130 case Intrinsic::call_preallocated_setup: { 6131 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 6132 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6133 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 6134 getRoot(), SrcValue); 6135 setValue(&I, Res); 6136 DAG.setRoot(Res); 6137 return; 6138 } 6139 case Intrinsic::call_preallocated_arg: { 6140 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 6141 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6142 SDValue Ops[3]; 6143 Ops[0] = getRoot(); 6144 Ops[1] = SrcValue; 6145 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 6146 MVT::i32); // arg index 6147 SDValue Res = DAG.getNode( 6148 ISD::PREALLOCATED_ARG, sdl, 6149 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 6150 setValue(&I, Res); 6151 DAG.setRoot(Res.getValue(1)); 6152 return; 6153 } 6154 case Intrinsic::dbg_declare: { 6155 const auto &DI = cast<DbgDeclareInst>(I); 6156 // Debug intrinsics are handled separately in assignment tracking mode. 6157 // Some intrinsics are handled right after Argument lowering. 6158 if (AssignmentTrackingEnabled || 6159 FuncInfo.PreprocessedDbgDeclares.count(&DI)) 6160 return; 6161 // Assume dbg.declare can not currently use DIArgList, i.e. 6162 // it is non-variadic. 6163 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 6164 DILocalVariable *Variable = DI.getVariable(); 6165 DIExpression *Expression = DI.getExpression(); 6166 dropDanglingDebugInfo(Variable, Expression); 6167 assert(Variable && "Missing variable"); 6168 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 6169 << "\n"); 6170 // Check if address has undef value. 6171 const Value *Address = DI.getVariableLocationOp(0); 6172 if (!Address || isa<UndefValue>(Address) || 6173 (Address->use_empty() && !isa<Argument>(Address))) { 6174 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6175 << " (bad/undef/unused-arg address)\n"); 6176 return; 6177 } 6178 6179 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 6180 6181 SDValue &N = NodeMap[Address]; 6182 if (!N.getNode() && isa<Argument>(Address)) 6183 // Check unused arguments map. 6184 N = UnusedArgNodeMap[Address]; 6185 SDDbgValue *SDV; 6186 if (N.getNode()) { 6187 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 6188 Address = BCI->getOperand(0); 6189 // Parameters are handled specially. 6190 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 6191 if (isParameter && FINode) { 6192 // Byval parameter. We have a frame index at this point. 6193 SDV = 6194 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 6195 /*IsIndirect*/ true, dl, SDNodeOrder); 6196 } else if (isa<Argument>(Address)) { 6197 // Address is an argument, so try to emit its dbg value using 6198 // virtual register info from the FuncInfo.ValueMap. 6199 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 6200 FuncArgumentDbgValueKind::Declare, N); 6201 return; 6202 } else { 6203 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 6204 true, dl, SDNodeOrder); 6205 } 6206 DAG.AddDbgValue(SDV, isParameter); 6207 } else { 6208 // If Address is an argument then try to emit its dbg value using 6209 // virtual register info from the FuncInfo.ValueMap. 6210 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 6211 FuncArgumentDbgValueKind::Declare, N)) { 6212 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6213 << " (could not emit func-arg dbg_value)\n"); 6214 } 6215 } 6216 return; 6217 } 6218 case Intrinsic::dbg_label: { 6219 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6220 DILabel *Label = DI.getLabel(); 6221 assert(Label && "Missing label"); 6222 6223 SDDbgLabel *SDV; 6224 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6225 DAG.AddDbgLabel(SDV); 6226 return; 6227 } 6228 case Intrinsic::dbg_assign: { 6229 // Debug intrinsics are handled seperately in assignment tracking mode. 6230 if (AssignmentTrackingEnabled) 6231 return; 6232 // If assignment tracking hasn't been enabled then fall through and treat 6233 // the dbg.assign as a dbg.value. 6234 [[fallthrough]]; 6235 } 6236 case Intrinsic::dbg_value: { 6237 // Debug intrinsics are handled seperately in assignment tracking mode. 6238 if (AssignmentTrackingEnabled) 6239 return; 6240 const DbgValueInst &DI = cast<DbgValueInst>(I); 6241 assert(DI.getVariable() && "Missing variable"); 6242 6243 DILocalVariable *Variable = DI.getVariable(); 6244 DIExpression *Expression = DI.getExpression(); 6245 dropDanglingDebugInfo(Variable, Expression); 6246 6247 if (DI.isKillLocation()) { 6248 handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder); 6249 return; 6250 } 6251 6252 SmallVector<Value *, 4> Values(DI.getValues()); 6253 if (Values.empty()) 6254 return; 6255 6256 bool IsVariadic = DI.hasArgList(); 6257 if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(), 6258 SDNodeOrder, IsVariadic)) 6259 addDanglingDebugInfo(&DI, SDNodeOrder); 6260 return; 6261 } 6262 6263 case Intrinsic::eh_typeid_for: { 6264 // Find the type id for the given typeinfo. 6265 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6266 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6267 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6268 setValue(&I, Res); 6269 return; 6270 } 6271 6272 case Intrinsic::eh_return_i32: 6273 case Intrinsic::eh_return_i64: 6274 DAG.getMachineFunction().setCallsEHReturn(true); 6275 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6276 MVT::Other, 6277 getControlRoot(), 6278 getValue(I.getArgOperand(0)), 6279 getValue(I.getArgOperand(1)))); 6280 return; 6281 case Intrinsic::eh_unwind_init: 6282 DAG.getMachineFunction().setCallsUnwindInit(true); 6283 return; 6284 case Intrinsic::eh_dwarf_cfa: 6285 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6286 TLI.getPointerTy(DAG.getDataLayout()), 6287 getValue(I.getArgOperand(0)))); 6288 return; 6289 case Intrinsic::eh_sjlj_callsite: { 6290 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6291 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0)); 6292 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6293 6294 MMI.setCurrentCallSite(CI->getZExtValue()); 6295 return; 6296 } 6297 case Intrinsic::eh_sjlj_functioncontext: { 6298 // Get and store the index of the function context. 6299 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6300 AllocaInst *FnCtx = 6301 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6302 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6303 MFI.setFunctionContextIndex(FI); 6304 return; 6305 } 6306 case Intrinsic::eh_sjlj_setjmp: { 6307 SDValue Ops[2]; 6308 Ops[0] = getRoot(); 6309 Ops[1] = getValue(I.getArgOperand(0)); 6310 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6311 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6312 setValue(&I, Op.getValue(0)); 6313 DAG.setRoot(Op.getValue(1)); 6314 return; 6315 } 6316 case Intrinsic::eh_sjlj_longjmp: 6317 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6318 getRoot(), getValue(I.getArgOperand(0)))); 6319 return; 6320 case Intrinsic::eh_sjlj_setup_dispatch: 6321 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6322 getRoot())); 6323 return; 6324 case Intrinsic::masked_gather: 6325 visitMaskedGather(I); 6326 return; 6327 case Intrinsic::masked_load: 6328 visitMaskedLoad(I); 6329 return; 6330 case Intrinsic::masked_scatter: 6331 visitMaskedScatter(I); 6332 return; 6333 case Intrinsic::masked_store: 6334 visitMaskedStore(I); 6335 return; 6336 case Intrinsic::masked_expandload: 6337 visitMaskedLoad(I, true /* IsExpanding */); 6338 return; 6339 case Intrinsic::masked_compressstore: 6340 visitMaskedStore(I, true /* IsCompressing */); 6341 return; 6342 case Intrinsic::powi: 6343 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6344 getValue(I.getArgOperand(1)), DAG)); 6345 return; 6346 case Intrinsic::log: 6347 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6348 return; 6349 case Intrinsic::log2: 6350 setValue(&I, 6351 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6352 return; 6353 case Intrinsic::log10: 6354 setValue(&I, 6355 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6356 return; 6357 case Intrinsic::exp: 6358 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6359 return; 6360 case Intrinsic::exp2: 6361 setValue(&I, 6362 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6363 return; 6364 case Intrinsic::pow: 6365 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6366 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6367 return; 6368 case Intrinsic::sqrt: 6369 case Intrinsic::fabs: 6370 case Intrinsic::sin: 6371 case Intrinsic::cos: 6372 case Intrinsic::floor: 6373 case Intrinsic::ceil: 6374 case Intrinsic::trunc: 6375 case Intrinsic::rint: 6376 case Intrinsic::nearbyint: 6377 case Intrinsic::round: 6378 case Intrinsic::roundeven: 6379 case Intrinsic::canonicalize: { 6380 unsigned Opcode; 6381 switch (Intrinsic) { 6382 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6383 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6384 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6385 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6386 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6387 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6388 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6389 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6390 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6391 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6392 case Intrinsic::round: Opcode = ISD::FROUND; break; 6393 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6394 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6395 } 6396 6397 setValue(&I, DAG.getNode(Opcode, sdl, 6398 getValue(I.getArgOperand(0)).getValueType(), 6399 getValue(I.getArgOperand(0)), Flags)); 6400 return; 6401 } 6402 case Intrinsic::lround: 6403 case Intrinsic::llround: 6404 case Intrinsic::lrint: 6405 case Intrinsic::llrint: { 6406 unsigned Opcode; 6407 switch (Intrinsic) { 6408 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6409 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6410 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6411 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6412 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6413 } 6414 6415 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6416 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6417 getValue(I.getArgOperand(0)))); 6418 return; 6419 } 6420 case Intrinsic::minnum: 6421 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6422 getValue(I.getArgOperand(0)).getValueType(), 6423 getValue(I.getArgOperand(0)), 6424 getValue(I.getArgOperand(1)), Flags)); 6425 return; 6426 case Intrinsic::maxnum: 6427 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6428 getValue(I.getArgOperand(0)).getValueType(), 6429 getValue(I.getArgOperand(0)), 6430 getValue(I.getArgOperand(1)), Flags)); 6431 return; 6432 case Intrinsic::minimum: 6433 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6434 getValue(I.getArgOperand(0)).getValueType(), 6435 getValue(I.getArgOperand(0)), 6436 getValue(I.getArgOperand(1)), Flags)); 6437 return; 6438 case Intrinsic::maximum: 6439 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6440 getValue(I.getArgOperand(0)).getValueType(), 6441 getValue(I.getArgOperand(0)), 6442 getValue(I.getArgOperand(1)), Flags)); 6443 return; 6444 case Intrinsic::copysign: 6445 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6446 getValue(I.getArgOperand(0)).getValueType(), 6447 getValue(I.getArgOperand(0)), 6448 getValue(I.getArgOperand(1)), Flags)); 6449 return; 6450 case Intrinsic::arithmetic_fence: { 6451 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl, 6452 getValue(I.getArgOperand(0)).getValueType(), 6453 getValue(I.getArgOperand(0)), Flags)); 6454 return; 6455 } 6456 case Intrinsic::fma: 6457 setValue(&I, DAG.getNode( 6458 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6459 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6460 getValue(I.getArgOperand(2)), Flags)); 6461 return; 6462 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6463 case Intrinsic::INTRINSIC: 6464 #include "llvm/IR/ConstrainedOps.def" 6465 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6466 return; 6467 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6468 #include "llvm/IR/VPIntrinsics.def" 6469 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6470 return; 6471 case Intrinsic::fptrunc_round: { 6472 // Get the last argument, the metadata and convert it to an integer in the 6473 // call 6474 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata(); 6475 std::optional<RoundingMode> RoundMode = 6476 convertStrToRoundingMode(cast<MDString>(MD)->getString()); 6477 6478 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6479 6480 // Propagate fast-math-flags from IR to node(s). 6481 SDNodeFlags Flags; 6482 Flags.copyFMF(*cast<FPMathOperator>(&I)); 6483 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 6484 6485 SDValue Result; 6486 Result = DAG.getNode( 6487 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)), 6488 DAG.getTargetConstant((int)*RoundMode, sdl, 6489 TLI.getPointerTy(DAG.getDataLayout()))); 6490 setValue(&I, Result); 6491 6492 return; 6493 } 6494 case Intrinsic::fmuladd: { 6495 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6496 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6497 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6498 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6499 getValue(I.getArgOperand(0)).getValueType(), 6500 getValue(I.getArgOperand(0)), 6501 getValue(I.getArgOperand(1)), 6502 getValue(I.getArgOperand(2)), Flags)); 6503 } else { 6504 // TODO: Intrinsic calls should have fast-math-flags. 6505 SDValue Mul = DAG.getNode( 6506 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6507 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6508 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6509 getValue(I.getArgOperand(0)).getValueType(), 6510 Mul, getValue(I.getArgOperand(2)), Flags); 6511 setValue(&I, Add); 6512 } 6513 return; 6514 } 6515 case Intrinsic::convert_to_fp16: 6516 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6517 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6518 getValue(I.getArgOperand(0)), 6519 DAG.getTargetConstant(0, sdl, 6520 MVT::i32)))); 6521 return; 6522 case Intrinsic::convert_from_fp16: 6523 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6524 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6525 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6526 getValue(I.getArgOperand(0))))); 6527 return; 6528 case Intrinsic::fptosi_sat: { 6529 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6530 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 6531 getValue(I.getArgOperand(0)), 6532 DAG.getValueType(VT.getScalarType()))); 6533 return; 6534 } 6535 case Intrinsic::fptoui_sat: { 6536 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6537 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 6538 getValue(I.getArgOperand(0)), 6539 DAG.getValueType(VT.getScalarType()))); 6540 return; 6541 } 6542 case Intrinsic::set_rounding: 6543 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6544 {getRoot(), getValue(I.getArgOperand(0))}); 6545 setValue(&I, Res); 6546 DAG.setRoot(Res.getValue(0)); 6547 return; 6548 case Intrinsic::is_fpclass: { 6549 const DataLayout DLayout = DAG.getDataLayout(); 6550 EVT DestVT = TLI.getValueType(DLayout, I.getType()); 6551 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType()); 6552 FPClassTest Test = static_cast<FPClassTest>( 6553 cast<ConstantInt>(I.getArgOperand(1))->getZExtValue()); 6554 MachineFunction &MF = DAG.getMachineFunction(); 6555 const Function &F = MF.getFunction(); 6556 SDValue Op = getValue(I.getArgOperand(0)); 6557 SDNodeFlags Flags; 6558 Flags.setNoFPExcept( 6559 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP)); 6560 // If ISD::IS_FPCLASS should be expanded, do it right now, because the 6561 // expansion can use illegal types. Making expansion early allows 6562 // legalizing these types prior to selection. 6563 if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) { 6564 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG); 6565 setValue(&I, Result); 6566 return; 6567 } 6568 6569 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32); 6570 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags); 6571 setValue(&I, V); 6572 return; 6573 } 6574 case Intrinsic::pcmarker: { 6575 SDValue Tmp = getValue(I.getArgOperand(0)); 6576 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6577 return; 6578 } 6579 case Intrinsic::readcyclecounter: { 6580 SDValue Op = getRoot(); 6581 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6582 DAG.getVTList(MVT::i64, MVT::Other), Op); 6583 setValue(&I, Res); 6584 DAG.setRoot(Res.getValue(1)); 6585 return; 6586 } 6587 case Intrinsic::bitreverse: 6588 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6589 getValue(I.getArgOperand(0)).getValueType(), 6590 getValue(I.getArgOperand(0)))); 6591 return; 6592 case Intrinsic::bswap: 6593 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6594 getValue(I.getArgOperand(0)).getValueType(), 6595 getValue(I.getArgOperand(0)))); 6596 return; 6597 case Intrinsic::cttz: { 6598 SDValue Arg = getValue(I.getArgOperand(0)); 6599 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6600 EVT Ty = Arg.getValueType(); 6601 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6602 sdl, Ty, Arg)); 6603 return; 6604 } 6605 case Intrinsic::ctlz: { 6606 SDValue Arg = getValue(I.getArgOperand(0)); 6607 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6608 EVT Ty = Arg.getValueType(); 6609 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6610 sdl, Ty, Arg)); 6611 return; 6612 } 6613 case Intrinsic::ctpop: { 6614 SDValue Arg = getValue(I.getArgOperand(0)); 6615 EVT Ty = Arg.getValueType(); 6616 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6617 return; 6618 } 6619 case Intrinsic::fshl: 6620 case Intrinsic::fshr: { 6621 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6622 SDValue X = getValue(I.getArgOperand(0)); 6623 SDValue Y = getValue(I.getArgOperand(1)); 6624 SDValue Z = getValue(I.getArgOperand(2)); 6625 EVT VT = X.getValueType(); 6626 6627 if (X == Y) { 6628 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6629 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6630 } else { 6631 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6632 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6633 } 6634 return; 6635 } 6636 case Intrinsic::sadd_sat: { 6637 SDValue Op1 = getValue(I.getArgOperand(0)); 6638 SDValue Op2 = getValue(I.getArgOperand(1)); 6639 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6640 return; 6641 } 6642 case Intrinsic::uadd_sat: { 6643 SDValue Op1 = getValue(I.getArgOperand(0)); 6644 SDValue Op2 = getValue(I.getArgOperand(1)); 6645 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6646 return; 6647 } 6648 case Intrinsic::ssub_sat: { 6649 SDValue Op1 = getValue(I.getArgOperand(0)); 6650 SDValue Op2 = getValue(I.getArgOperand(1)); 6651 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6652 return; 6653 } 6654 case Intrinsic::usub_sat: { 6655 SDValue Op1 = getValue(I.getArgOperand(0)); 6656 SDValue Op2 = getValue(I.getArgOperand(1)); 6657 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6658 return; 6659 } 6660 case Intrinsic::sshl_sat: { 6661 SDValue Op1 = getValue(I.getArgOperand(0)); 6662 SDValue Op2 = getValue(I.getArgOperand(1)); 6663 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6664 return; 6665 } 6666 case Intrinsic::ushl_sat: { 6667 SDValue Op1 = getValue(I.getArgOperand(0)); 6668 SDValue Op2 = getValue(I.getArgOperand(1)); 6669 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6670 return; 6671 } 6672 case Intrinsic::smul_fix: 6673 case Intrinsic::umul_fix: 6674 case Intrinsic::smul_fix_sat: 6675 case Intrinsic::umul_fix_sat: { 6676 SDValue Op1 = getValue(I.getArgOperand(0)); 6677 SDValue Op2 = getValue(I.getArgOperand(1)); 6678 SDValue Op3 = getValue(I.getArgOperand(2)); 6679 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6680 Op1.getValueType(), Op1, Op2, Op3)); 6681 return; 6682 } 6683 case Intrinsic::sdiv_fix: 6684 case Intrinsic::udiv_fix: 6685 case Intrinsic::sdiv_fix_sat: 6686 case Intrinsic::udiv_fix_sat: { 6687 SDValue Op1 = getValue(I.getArgOperand(0)); 6688 SDValue Op2 = getValue(I.getArgOperand(1)); 6689 SDValue Op3 = getValue(I.getArgOperand(2)); 6690 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6691 Op1, Op2, Op3, DAG, TLI)); 6692 return; 6693 } 6694 case Intrinsic::smax: { 6695 SDValue Op1 = getValue(I.getArgOperand(0)); 6696 SDValue Op2 = getValue(I.getArgOperand(1)); 6697 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6698 return; 6699 } 6700 case Intrinsic::smin: { 6701 SDValue Op1 = getValue(I.getArgOperand(0)); 6702 SDValue Op2 = getValue(I.getArgOperand(1)); 6703 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6704 return; 6705 } 6706 case Intrinsic::umax: { 6707 SDValue Op1 = getValue(I.getArgOperand(0)); 6708 SDValue Op2 = getValue(I.getArgOperand(1)); 6709 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6710 return; 6711 } 6712 case Intrinsic::umin: { 6713 SDValue Op1 = getValue(I.getArgOperand(0)); 6714 SDValue Op2 = getValue(I.getArgOperand(1)); 6715 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6716 return; 6717 } 6718 case Intrinsic::abs: { 6719 // TODO: Preserve "int min is poison" arg in SDAG? 6720 SDValue Op1 = getValue(I.getArgOperand(0)); 6721 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6722 return; 6723 } 6724 case Intrinsic::stacksave: { 6725 SDValue Op = getRoot(); 6726 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6727 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6728 setValue(&I, Res); 6729 DAG.setRoot(Res.getValue(1)); 6730 return; 6731 } 6732 case Intrinsic::stackrestore: 6733 Res = getValue(I.getArgOperand(0)); 6734 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6735 return; 6736 case Intrinsic::get_dynamic_area_offset: { 6737 SDValue Op = getRoot(); 6738 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6739 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6740 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6741 // target. 6742 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 6743 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6744 " intrinsic!"); 6745 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6746 Op); 6747 DAG.setRoot(Op); 6748 setValue(&I, Res); 6749 return; 6750 } 6751 case Intrinsic::stackguard: { 6752 MachineFunction &MF = DAG.getMachineFunction(); 6753 const Module &M = *MF.getFunction().getParent(); 6754 SDValue Chain = getRoot(); 6755 if (TLI.useLoadStackGuardNode()) { 6756 Res = getLoadStackGuard(DAG, sdl, Chain); 6757 } else { 6758 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6759 const Value *Global = TLI.getSDagStackGuard(M); 6760 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType()); 6761 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6762 MachinePointerInfo(Global, 0), Align, 6763 MachineMemOperand::MOVolatile); 6764 } 6765 if (TLI.useStackGuardXorFP()) 6766 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6767 DAG.setRoot(Chain); 6768 setValue(&I, Res); 6769 return; 6770 } 6771 case Intrinsic::stackprotector: { 6772 // Emit code into the DAG to store the stack guard onto the stack. 6773 MachineFunction &MF = DAG.getMachineFunction(); 6774 MachineFrameInfo &MFI = MF.getFrameInfo(); 6775 SDValue Src, Chain = getRoot(); 6776 6777 if (TLI.useLoadStackGuardNode()) 6778 Src = getLoadStackGuard(DAG, sdl, Chain); 6779 else 6780 Src = getValue(I.getArgOperand(0)); // The guard's value. 6781 6782 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6783 6784 int FI = FuncInfo.StaticAllocaMap[Slot]; 6785 MFI.setStackProtectorIndex(FI); 6786 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6787 6788 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6789 6790 // Store the stack protector onto the stack. 6791 Res = DAG.getStore( 6792 Chain, sdl, Src, FIN, 6793 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 6794 MaybeAlign(), MachineMemOperand::MOVolatile); 6795 setValue(&I, Res); 6796 DAG.setRoot(Res); 6797 return; 6798 } 6799 case Intrinsic::objectsize: 6800 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6801 6802 case Intrinsic::is_constant: 6803 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6804 6805 case Intrinsic::annotation: 6806 case Intrinsic::ptr_annotation: 6807 case Intrinsic::launder_invariant_group: 6808 case Intrinsic::strip_invariant_group: 6809 // Drop the intrinsic, but forward the value 6810 setValue(&I, getValue(I.getOperand(0))); 6811 return; 6812 6813 case Intrinsic::assume: 6814 case Intrinsic::experimental_noalias_scope_decl: 6815 case Intrinsic::var_annotation: 6816 case Intrinsic::sideeffect: 6817 // Discard annotate attributes, noalias scope declarations, assumptions, and 6818 // artificial side-effects. 6819 return; 6820 6821 case Intrinsic::codeview_annotation: { 6822 // Emit a label associated with this metadata. 6823 MachineFunction &MF = DAG.getMachineFunction(); 6824 MCSymbol *Label = 6825 MF.getMMI().getContext().createTempSymbol("annotation", true); 6826 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6827 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6828 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6829 DAG.setRoot(Res); 6830 return; 6831 } 6832 6833 case Intrinsic::init_trampoline: { 6834 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6835 6836 SDValue Ops[6]; 6837 Ops[0] = getRoot(); 6838 Ops[1] = getValue(I.getArgOperand(0)); 6839 Ops[2] = getValue(I.getArgOperand(1)); 6840 Ops[3] = getValue(I.getArgOperand(2)); 6841 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6842 Ops[5] = DAG.getSrcValue(F); 6843 6844 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6845 6846 DAG.setRoot(Res); 6847 return; 6848 } 6849 case Intrinsic::adjust_trampoline: 6850 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6851 TLI.getPointerTy(DAG.getDataLayout()), 6852 getValue(I.getArgOperand(0)))); 6853 return; 6854 case Intrinsic::gcroot: { 6855 assert(DAG.getMachineFunction().getFunction().hasGC() && 6856 "only valid in functions with gc specified, enforced by Verifier"); 6857 assert(GFI && "implied by previous"); 6858 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6859 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6860 6861 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6862 GFI->addStackRoot(FI->getIndex(), TypeMap); 6863 return; 6864 } 6865 case Intrinsic::gcread: 6866 case Intrinsic::gcwrite: 6867 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6868 case Intrinsic::get_rounding: 6869 Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot()); 6870 setValue(&I, Res); 6871 DAG.setRoot(Res.getValue(1)); 6872 return; 6873 6874 case Intrinsic::expect: 6875 // Just replace __builtin_expect(exp, c) with EXP. 6876 setValue(&I, getValue(I.getArgOperand(0))); 6877 return; 6878 6879 case Intrinsic::ubsantrap: 6880 case Intrinsic::debugtrap: 6881 case Intrinsic::trap: { 6882 StringRef TrapFuncName = 6883 I.getAttributes().getFnAttr("trap-func-name").getValueAsString(); 6884 if (TrapFuncName.empty()) { 6885 switch (Intrinsic) { 6886 case Intrinsic::trap: 6887 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 6888 break; 6889 case Intrinsic::debugtrap: 6890 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 6891 break; 6892 case Intrinsic::ubsantrap: 6893 DAG.setRoot(DAG.getNode( 6894 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 6895 DAG.getTargetConstant( 6896 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 6897 MVT::i32))); 6898 break; 6899 default: llvm_unreachable("unknown trap intrinsic"); 6900 } 6901 return; 6902 } 6903 TargetLowering::ArgListTy Args; 6904 if (Intrinsic == Intrinsic::ubsantrap) { 6905 Args.push_back(TargetLoweringBase::ArgListEntry()); 6906 Args[0].Val = I.getArgOperand(0); 6907 Args[0].Node = getValue(Args[0].Val); 6908 Args[0].Ty = Args[0].Val->getType(); 6909 } 6910 6911 TargetLowering::CallLoweringInfo CLI(DAG); 6912 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6913 CallingConv::C, I.getType(), 6914 DAG.getExternalSymbol(TrapFuncName.data(), 6915 TLI.getPointerTy(DAG.getDataLayout())), 6916 std::move(Args)); 6917 6918 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6919 DAG.setRoot(Result.second); 6920 return; 6921 } 6922 6923 case Intrinsic::uadd_with_overflow: 6924 case Intrinsic::sadd_with_overflow: 6925 case Intrinsic::usub_with_overflow: 6926 case Intrinsic::ssub_with_overflow: 6927 case Intrinsic::umul_with_overflow: 6928 case Intrinsic::smul_with_overflow: { 6929 ISD::NodeType Op; 6930 switch (Intrinsic) { 6931 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6932 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6933 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6934 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6935 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6936 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6937 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6938 } 6939 SDValue Op1 = getValue(I.getArgOperand(0)); 6940 SDValue Op2 = getValue(I.getArgOperand(1)); 6941 6942 EVT ResultVT = Op1.getValueType(); 6943 EVT OverflowVT = MVT::i1; 6944 if (ResultVT.isVector()) 6945 OverflowVT = EVT::getVectorVT( 6946 *Context, OverflowVT, ResultVT.getVectorElementCount()); 6947 6948 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6949 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6950 return; 6951 } 6952 case Intrinsic::prefetch: { 6953 SDValue Ops[5]; 6954 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6955 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6956 Ops[0] = DAG.getRoot(); 6957 Ops[1] = getValue(I.getArgOperand(0)); 6958 Ops[2] = getValue(I.getArgOperand(1)); 6959 Ops[3] = getValue(I.getArgOperand(2)); 6960 Ops[4] = getValue(I.getArgOperand(3)); 6961 SDValue Result = DAG.getMemIntrinsicNode( 6962 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 6963 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 6964 /* align */ std::nullopt, Flags); 6965 6966 // Chain the prefetch in parallell with any pending loads, to stay out of 6967 // the way of later optimizations. 6968 PendingLoads.push_back(Result); 6969 Result = getRoot(); 6970 DAG.setRoot(Result); 6971 return; 6972 } 6973 case Intrinsic::lifetime_start: 6974 case Intrinsic::lifetime_end: { 6975 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6976 // Stack coloring is not enabled in O0, discard region information. 6977 if (TM.getOptLevel() == CodeGenOpt::None) 6978 return; 6979 6980 const int64_t ObjectSize = 6981 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6982 Value *const ObjectPtr = I.getArgOperand(1); 6983 SmallVector<const Value *, 4> Allocas; 6984 getUnderlyingObjects(ObjectPtr, Allocas); 6985 6986 for (const Value *Alloca : Allocas) { 6987 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 6988 6989 // Could not find an Alloca. 6990 if (!LifetimeObject) 6991 continue; 6992 6993 // First check that the Alloca is static, otherwise it won't have a 6994 // valid frame index. 6995 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6996 if (SI == FuncInfo.StaticAllocaMap.end()) 6997 return; 6998 6999 const int FrameIndex = SI->second; 7000 int64_t Offset; 7001 if (GetPointerBaseWithConstantOffset( 7002 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 7003 Offset = -1; // Cannot determine offset from alloca to lifetime object. 7004 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 7005 Offset); 7006 DAG.setRoot(Res); 7007 } 7008 return; 7009 } 7010 case Intrinsic::pseudoprobe: { 7011 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 7012 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 7013 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 7014 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 7015 DAG.setRoot(Res); 7016 return; 7017 } 7018 case Intrinsic::invariant_start: 7019 // Discard region information. 7020 setValue(&I, 7021 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType()))); 7022 return; 7023 case Intrinsic::invariant_end: 7024 // Discard region information. 7025 return; 7026 case Intrinsic::clear_cache: 7027 /// FunctionName may be null. 7028 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 7029 lowerCallToExternalSymbol(I, FunctionName); 7030 return; 7031 case Intrinsic::donothing: 7032 case Intrinsic::seh_try_begin: 7033 case Intrinsic::seh_scope_begin: 7034 case Intrinsic::seh_try_end: 7035 case Intrinsic::seh_scope_end: 7036 // ignore 7037 return; 7038 case Intrinsic::experimental_stackmap: 7039 visitStackmap(I); 7040 return; 7041 case Intrinsic::experimental_patchpoint_void: 7042 case Intrinsic::experimental_patchpoint_i64: 7043 visitPatchpoint(I); 7044 return; 7045 case Intrinsic::experimental_gc_statepoint: 7046 LowerStatepoint(cast<GCStatepointInst>(I)); 7047 return; 7048 case Intrinsic::experimental_gc_result: 7049 visitGCResult(cast<GCResultInst>(I)); 7050 return; 7051 case Intrinsic::experimental_gc_relocate: 7052 visitGCRelocate(cast<GCRelocateInst>(I)); 7053 return; 7054 case Intrinsic::instrprof_cover: 7055 llvm_unreachable("instrprof failed to lower a cover"); 7056 case Intrinsic::instrprof_increment: 7057 llvm_unreachable("instrprof failed to lower an increment"); 7058 case Intrinsic::instrprof_timestamp: 7059 llvm_unreachable("instrprof failed to lower a timestamp"); 7060 case Intrinsic::instrprof_value_profile: 7061 llvm_unreachable("instrprof failed to lower a value profiling call"); 7062 case Intrinsic::localescape: { 7063 MachineFunction &MF = DAG.getMachineFunction(); 7064 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 7065 7066 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 7067 // is the same on all targets. 7068 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) { 7069 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 7070 if (isa<ConstantPointerNull>(Arg)) 7071 continue; // Skip null pointers. They represent a hole in index space. 7072 AllocaInst *Slot = cast<AllocaInst>(Arg); 7073 assert(FuncInfo.StaticAllocaMap.count(Slot) && 7074 "can only escape static allocas"); 7075 int FI = FuncInfo.StaticAllocaMap[Slot]; 7076 MCSymbol *FrameAllocSym = 7077 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7078 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 7079 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 7080 TII->get(TargetOpcode::LOCAL_ESCAPE)) 7081 .addSym(FrameAllocSym) 7082 .addFrameIndex(FI); 7083 } 7084 7085 return; 7086 } 7087 7088 case Intrinsic::localrecover: { 7089 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 7090 MachineFunction &MF = DAG.getMachineFunction(); 7091 7092 // Get the symbol that defines the frame offset. 7093 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 7094 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 7095 unsigned IdxVal = 7096 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 7097 MCSymbol *FrameAllocSym = 7098 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7099 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 7100 7101 Value *FP = I.getArgOperand(1); 7102 SDValue FPVal = getValue(FP); 7103 EVT PtrVT = FPVal.getValueType(); 7104 7105 // Create a MCSymbol for the label to avoid any target lowering 7106 // that would make this PC relative. 7107 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 7108 SDValue OffsetVal = 7109 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 7110 7111 // Add the offset to the FP. 7112 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 7113 setValue(&I, Add); 7114 7115 return; 7116 } 7117 7118 case Intrinsic::eh_exceptionpointer: 7119 case Intrinsic::eh_exceptioncode: { 7120 // Get the exception pointer vreg, copy from it, and resize it to fit. 7121 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 7122 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 7123 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 7124 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 7125 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT); 7126 if (Intrinsic == Intrinsic::eh_exceptioncode) 7127 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32); 7128 setValue(&I, N); 7129 return; 7130 } 7131 case Intrinsic::xray_customevent: { 7132 // Here we want to make sure that the intrinsic behaves as if it has a 7133 // specific calling convention, and only for x86_64. 7134 // FIXME: Support other platforms later. 7135 const auto &Triple = DAG.getTarget().getTargetTriple(); 7136 if (Triple.getArch() != Triple::x86_64) 7137 return; 7138 7139 SmallVector<SDValue, 8> Ops; 7140 7141 // We want to say that we always want the arguments in registers. 7142 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 7143 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 7144 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7145 SDValue Chain = getRoot(); 7146 Ops.push_back(LogEntryVal); 7147 Ops.push_back(StrSizeVal); 7148 Ops.push_back(Chain); 7149 7150 // We need to enforce the calling convention for the callsite, so that 7151 // argument ordering is enforced correctly, and that register allocation can 7152 // see that some registers may be assumed clobbered and have to preserve 7153 // them across calls to the intrinsic. 7154 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 7155 sdl, NodeTys, Ops); 7156 SDValue patchableNode = SDValue(MN, 0); 7157 DAG.setRoot(patchableNode); 7158 setValue(&I, patchableNode); 7159 return; 7160 } 7161 case Intrinsic::xray_typedevent: { 7162 // Here we want to make sure that the intrinsic behaves as if it has a 7163 // specific calling convention, and only for x86_64. 7164 // FIXME: Support other platforms later. 7165 const auto &Triple = DAG.getTarget().getTargetTriple(); 7166 if (Triple.getArch() != Triple::x86_64) 7167 return; 7168 7169 SmallVector<SDValue, 8> Ops; 7170 7171 // We want to say that we always want the arguments in registers. 7172 // It's unclear to me how manipulating the selection DAG here forces callers 7173 // to provide arguments in registers instead of on the stack. 7174 SDValue LogTypeId = getValue(I.getArgOperand(0)); 7175 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 7176 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 7177 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7178 SDValue Chain = getRoot(); 7179 Ops.push_back(LogTypeId); 7180 Ops.push_back(LogEntryVal); 7181 Ops.push_back(StrSizeVal); 7182 Ops.push_back(Chain); 7183 7184 // We need to enforce the calling convention for the callsite, so that 7185 // argument ordering is enforced correctly, and that register allocation can 7186 // see that some registers may be assumed clobbered and have to preserve 7187 // them across calls to the intrinsic. 7188 MachineSDNode *MN = DAG.getMachineNode( 7189 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops); 7190 SDValue patchableNode = SDValue(MN, 0); 7191 DAG.setRoot(patchableNode); 7192 setValue(&I, patchableNode); 7193 return; 7194 } 7195 case Intrinsic::experimental_deoptimize: 7196 LowerDeoptimizeCall(&I); 7197 return; 7198 case Intrinsic::experimental_stepvector: 7199 visitStepVector(I); 7200 return; 7201 case Intrinsic::vector_reduce_fadd: 7202 case Intrinsic::vector_reduce_fmul: 7203 case Intrinsic::vector_reduce_add: 7204 case Intrinsic::vector_reduce_mul: 7205 case Intrinsic::vector_reduce_and: 7206 case Intrinsic::vector_reduce_or: 7207 case Intrinsic::vector_reduce_xor: 7208 case Intrinsic::vector_reduce_smax: 7209 case Intrinsic::vector_reduce_smin: 7210 case Intrinsic::vector_reduce_umax: 7211 case Intrinsic::vector_reduce_umin: 7212 case Intrinsic::vector_reduce_fmax: 7213 case Intrinsic::vector_reduce_fmin: 7214 visitVectorReduce(I, Intrinsic); 7215 return; 7216 7217 case Intrinsic::icall_branch_funnel: { 7218 SmallVector<SDValue, 16> Ops; 7219 Ops.push_back(getValue(I.getArgOperand(0))); 7220 7221 int64_t Offset; 7222 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7223 I.getArgOperand(1), Offset, DAG.getDataLayout())); 7224 if (!Base) 7225 report_fatal_error( 7226 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7227 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0)); 7228 7229 struct BranchFunnelTarget { 7230 int64_t Offset; 7231 SDValue Target; 7232 }; 7233 SmallVector<BranchFunnelTarget, 8> Targets; 7234 7235 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) { 7236 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7237 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7238 if (ElemBase != Base) 7239 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7240 "to the same GlobalValue"); 7241 7242 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7243 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7244 if (!GA) 7245 report_fatal_error( 7246 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7247 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7248 GA->getGlobal(), sdl, Val.getValueType(), 7249 GA->getOffset())}); 7250 } 7251 llvm::sort(Targets, 7252 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7253 return T1.Offset < T2.Offset; 7254 }); 7255 7256 for (auto &T : Targets) { 7257 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32)); 7258 Ops.push_back(T.Target); 7259 } 7260 7261 Ops.push_back(DAG.getRoot()); // Chain 7262 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl, 7263 MVT::Other, Ops), 7264 0); 7265 DAG.setRoot(N); 7266 setValue(&I, N); 7267 HasTailCall = true; 7268 return; 7269 } 7270 7271 case Intrinsic::wasm_landingpad_index: 7272 // Information this intrinsic contained has been transferred to 7273 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7274 // delete it now. 7275 return; 7276 7277 case Intrinsic::aarch64_settag: 7278 case Intrinsic::aarch64_settag_zero: { 7279 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7280 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7281 SDValue Val = TSI.EmitTargetCodeForSetTag( 7282 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)), 7283 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7284 ZeroMemory); 7285 DAG.setRoot(Val); 7286 setValue(&I, Val); 7287 return; 7288 } 7289 case Intrinsic::ptrmask: { 7290 SDValue Ptr = getValue(I.getOperand(0)); 7291 SDValue Const = getValue(I.getOperand(1)); 7292 7293 EVT PtrVT = Ptr.getValueType(); 7294 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, 7295 DAG.getZExtOrTrunc(Const, sdl, PtrVT))); 7296 return; 7297 } 7298 case Intrinsic::threadlocal_address: { 7299 setValue(&I, getValue(I.getOperand(0))); 7300 return; 7301 } 7302 case Intrinsic::get_active_lane_mask: { 7303 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7304 SDValue Index = getValue(I.getOperand(0)); 7305 EVT ElementVT = Index.getValueType(); 7306 7307 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) { 7308 visitTargetIntrinsic(I, Intrinsic); 7309 return; 7310 } 7311 7312 SDValue TripCount = getValue(I.getOperand(1)); 7313 auto VecTy = CCVT.changeVectorElementType(ElementVT); 7314 7315 SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index); 7316 SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount); 7317 SDValue VectorStep = DAG.getStepVector(sdl, VecTy); 7318 SDValue VectorInduction = DAG.getNode( 7319 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep); 7320 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction, 7321 VectorTripCount, ISD::CondCode::SETULT); 7322 setValue(&I, SetCC); 7323 return; 7324 } 7325 case Intrinsic::experimental_get_vector_length: { 7326 assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 && 7327 "Expected positive VF"); 7328 unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue(); 7329 bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne(); 7330 7331 SDValue Count = getValue(I.getOperand(0)); 7332 EVT CountVT = Count.getValueType(); 7333 7334 if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) { 7335 visitTargetIntrinsic(I, Intrinsic); 7336 return; 7337 } 7338 7339 // Expand to a umin between the trip count and the maximum elements the type 7340 // can hold. 7341 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7342 7343 // Extend the trip count to at least the result VT. 7344 if (CountVT.bitsLT(VT)) { 7345 Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count); 7346 CountVT = VT; 7347 } 7348 7349 SDValue MaxEVL = DAG.getElementCount(sdl, CountVT, 7350 ElementCount::get(VF, IsScalable)); 7351 7352 SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL); 7353 // Clip to the result type if needed. 7354 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin); 7355 7356 setValue(&I, Trunc); 7357 return; 7358 } 7359 case Intrinsic::vector_insert: { 7360 SDValue Vec = getValue(I.getOperand(0)); 7361 SDValue SubVec = getValue(I.getOperand(1)); 7362 SDValue Index = getValue(I.getOperand(2)); 7363 7364 // The intrinsic's index type is i64, but the SDNode requires an index type 7365 // suitable for the target. Convert the index as required. 7366 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7367 if (Index.getValueType() != VectorIdxTy) 7368 Index = DAG.getVectorIdxConstant( 7369 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7370 7371 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7372 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec, 7373 Index)); 7374 return; 7375 } 7376 case Intrinsic::vector_extract: { 7377 SDValue Vec = getValue(I.getOperand(0)); 7378 SDValue Index = getValue(I.getOperand(1)); 7379 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7380 7381 // The intrinsic's index type is i64, but the SDNode requires an index type 7382 // suitable for the target. Convert the index as required. 7383 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7384 if (Index.getValueType() != VectorIdxTy) 7385 Index = DAG.getVectorIdxConstant( 7386 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7387 7388 setValue(&I, 7389 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index)); 7390 return; 7391 } 7392 case Intrinsic::experimental_vector_reverse: 7393 visitVectorReverse(I); 7394 return; 7395 case Intrinsic::experimental_vector_splice: 7396 visitVectorSplice(I); 7397 return; 7398 case Intrinsic::callbr_landingpad: 7399 visitCallBrLandingPad(I); 7400 return; 7401 case Intrinsic::experimental_vector_interleave2: 7402 visitVectorInterleave(I); 7403 return; 7404 case Intrinsic::experimental_vector_deinterleave2: 7405 visitVectorDeinterleave(I); 7406 return; 7407 } 7408 } 7409 7410 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7411 const ConstrainedFPIntrinsic &FPI) { 7412 SDLoc sdl = getCurSDLoc(); 7413 7414 // We do not need to serialize constrained FP intrinsics against 7415 // each other or against (nonvolatile) loads, so they can be 7416 // chained like loads. 7417 SDValue Chain = DAG.getRoot(); 7418 SmallVector<SDValue, 4> Opers; 7419 Opers.push_back(Chain); 7420 if (FPI.isUnaryOp()) { 7421 Opers.push_back(getValue(FPI.getArgOperand(0))); 7422 } else if (FPI.isTernaryOp()) { 7423 Opers.push_back(getValue(FPI.getArgOperand(0))); 7424 Opers.push_back(getValue(FPI.getArgOperand(1))); 7425 Opers.push_back(getValue(FPI.getArgOperand(2))); 7426 } else { 7427 Opers.push_back(getValue(FPI.getArgOperand(0))); 7428 Opers.push_back(getValue(FPI.getArgOperand(1))); 7429 } 7430 7431 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7432 assert(Result.getNode()->getNumValues() == 2); 7433 7434 // Push node to the appropriate list so that future instructions can be 7435 // chained up correctly. 7436 SDValue OutChain = Result.getValue(1); 7437 switch (EB) { 7438 case fp::ExceptionBehavior::ebIgnore: 7439 // The only reason why ebIgnore nodes still need to be chained is that 7440 // they might depend on the current rounding mode, and therefore must 7441 // not be moved across instruction that may change that mode. 7442 [[fallthrough]]; 7443 case fp::ExceptionBehavior::ebMayTrap: 7444 // These must not be moved across calls or instructions that may change 7445 // floating-point exception masks. 7446 PendingConstrainedFP.push_back(OutChain); 7447 break; 7448 case fp::ExceptionBehavior::ebStrict: 7449 // These must not be moved across calls or instructions that may change 7450 // floating-point exception masks or read floating-point exception flags. 7451 // In addition, they cannot be optimized out even if unused. 7452 PendingConstrainedFPStrict.push_back(OutChain); 7453 break; 7454 } 7455 }; 7456 7457 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7458 EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType()); 7459 SDVTList VTs = DAG.getVTList(VT, MVT::Other); 7460 fp::ExceptionBehavior EB = *FPI.getExceptionBehavior(); 7461 7462 SDNodeFlags Flags; 7463 if (EB == fp::ExceptionBehavior::ebIgnore) 7464 Flags.setNoFPExcept(true); 7465 7466 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7467 Flags.copyFMF(*FPOp); 7468 7469 unsigned Opcode; 7470 switch (FPI.getIntrinsicID()) { 7471 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7472 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7473 case Intrinsic::INTRINSIC: \ 7474 Opcode = ISD::STRICT_##DAGN; \ 7475 break; 7476 #include "llvm/IR/ConstrainedOps.def" 7477 case Intrinsic::experimental_constrained_fmuladd: { 7478 Opcode = ISD::STRICT_FMA; 7479 // Break fmuladd into fmul and fadd. 7480 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7481 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 7482 Opers.pop_back(); 7483 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7484 pushOutChain(Mul, EB); 7485 Opcode = ISD::STRICT_FADD; 7486 Opers.clear(); 7487 Opers.push_back(Mul.getValue(1)); 7488 Opers.push_back(Mul.getValue(0)); 7489 Opers.push_back(getValue(FPI.getArgOperand(2))); 7490 } 7491 break; 7492 } 7493 } 7494 7495 // A few strict DAG nodes carry additional operands that are not 7496 // set up by the default code above. 7497 switch (Opcode) { 7498 default: break; 7499 case ISD::STRICT_FP_ROUND: 7500 Opers.push_back( 7501 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7502 break; 7503 case ISD::STRICT_FSETCC: 7504 case ISD::STRICT_FSETCCS: { 7505 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7506 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 7507 if (TM.Options.NoNaNsFPMath) 7508 Condition = getFCmpCodeWithoutNaN(Condition); 7509 Opers.push_back(DAG.getCondCode(Condition)); 7510 break; 7511 } 7512 } 7513 7514 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7515 pushOutChain(Result, EB); 7516 7517 SDValue FPResult = Result.getValue(0); 7518 setValue(&FPI, FPResult); 7519 } 7520 7521 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 7522 std::optional<unsigned> ResOPC; 7523 switch (VPIntrin.getIntrinsicID()) { 7524 case Intrinsic::vp_ctlz: { 7525 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 7526 ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ; 7527 break; 7528 } 7529 case Intrinsic::vp_cttz: { 7530 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 7531 ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ; 7532 break; 7533 } 7534 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \ 7535 case Intrinsic::VPID: \ 7536 ResOPC = ISD::VPSD; \ 7537 break; 7538 #include "llvm/IR/VPIntrinsics.def" 7539 } 7540 7541 if (!ResOPC) 7542 llvm_unreachable( 7543 "Inconsistency: no SDNode available for this VPIntrinsic!"); 7544 7545 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD || 7546 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) { 7547 if (VPIntrin.getFastMathFlags().allowReassoc()) 7548 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD 7549 : ISD::VP_REDUCE_FMUL; 7550 } 7551 7552 return *ResOPC; 7553 } 7554 7555 void SelectionDAGBuilder::visitVPLoad( 7556 const VPIntrinsic &VPIntrin, EVT VT, 7557 const SmallVectorImpl<SDValue> &OpValues) { 7558 SDLoc DL = getCurSDLoc(); 7559 Value *PtrOperand = VPIntrin.getArgOperand(0); 7560 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7561 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7562 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7563 SDValue LD; 7564 // Do not serialize variable-length loads of constant memory with 7565 // anything. 7566 if (!Alignment) 7567 Alignment = DAG.getEVTAlign(VT); 7568 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7569 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7570 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7571 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7572 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7573 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7574 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2], 7575 MMO, false /*IsExpanding */); 7576 if (AddToChain) 7577 PendingLoads.push_back(LD.getValue(1)); 7578 setValue(&VPIntrin, LD); 7579 } 7580 7581 void SelectionDAGBuilder::visitVPGather( 7582 const VPIntrinsic &VPIntrin, EVT VT, 7583 const SmallVectorImpl<SDValue> &OpValues) { 7584 SDLoc DL = getCurSDLoc(); 7585 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7586 Value *PtrOperand = VPIntrin.getArgOperand(0); 7587 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7588 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7589 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7590 SDValue LD; 7591 if (!Alignment) 7592 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7593 unsigned AS = 7594 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7595 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7596 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 7597 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7598 SDValue Base, Index, Scale; 7599 ISD::MemIndexType IndexType; 7600 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7601 this, VPIntrin.getParent(), 7602 VT.getScalarStoreSize()); 7603 if (!UniformBase) { 7604 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7605 Index = getValue(PtrOperand); 7606 IndexType = ISD::SIGNED_SCALED; 7607 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7608 } 7609 EVT IdxVT = Index.getValueType(); 7610 EVT EltTy = IdxVT.getVectorElementType(); 7611 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7612 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7613 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7614 } 7615 LD = DAG.getGatherVP( 7616 DAG.getVTList(VT, MVT::Other), VT, DL, 7617 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO, 7618 IndexType); 7619 PendingLoads.push_back(LD.getValue(1)); 7620 setValue(&VPIntrin, LD); 7621 } 7622 7623 void SelectionDAGBuilder::visitVPStore( 7624 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 7625 SDLoc DL = getCurSDLoc(); 7626 Value *PtrOperand = VPIntrin.getArgOperand(1); 7627 EVT VT = OpValues[0].getValueType(); 7628 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7629 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7630 SDValue ST; 7631 if (!Alignment) 7632 Alignment = DAG.getEVTAlign(VT); 7633 SDValue Ptr = OpValues[1]; 7634 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 7635 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7636 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7637 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7638 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset, 7639 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED, 7640 /* IsTruncating */ false, /*IsCompressing*/ false); 7641 DAG.setRoot(ST); 7642 setValue(&VPIntrin, ST); 7643 } 7644 7645 void SelectionDAGBuilder::visitVPScatter( 7646 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 7647 SDLoc DL = getCurSDLoc(); 7648 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7649 Value *PtrOperand = VPIntrin.getArgOperand(1); 7650 EVT VT = OpValues[0].getValueType(); 7651 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7652 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7653 SDValue ST; 7654 if (!Alignment) 7655 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7656 unsigned AS = 7657 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7658 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7659 MachinePointerInfo(AS), MachineMemOperand::MOStore, 7660 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7661 SDValue Base, Index, Scale; 7662 ISD::MemIndexType IndexType; 7663 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7664 this, VPIntrin.getParent(), 7665 VT.getScalarStoreSize()); 7666 if (!UniformBase) { 7667 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7668 Index = getValue(PtrOperand); 7669 IndexType = ISD::SIGNED_SCALED; 7670 Scale = 7671 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7672 } 7673 EVT IdxVT = Index.getValueType(); 7674 EVT EltTy = IdxVT.getVectorElementType(); 7675 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7676 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7677 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7678 } 7679 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL, 7680 {getMemoryRoot(), OpValues[0], Base, Index, Scale, 7681 OpValues[2], OpValues[3]}, 7682 MMO, IndexType); 7683 DAG.setRoot(ST); 7684 setValue(&VPIntrin, ST); 7685 } 7686 7687 void SelectionDAGBuilder::visitVPStridedLoad( 7688 const VPIntrinsic &VPIntrin, EVT VT, 7689 const SmallVectorImpl<SDValue> &OpValues) { 7690 SDLoc DL = getCurSDLoc(); 7691 Value *PtrOperand = VPIntrin.getArgOperand(0); 7692 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7693 if (!Alignment) 7694 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7695 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7696 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7697 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7698 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7699 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7700 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7701 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7702 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7703 7704 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], 7705 OpValues[2], OpValues[3], MMO, 7706 false /*IsExpanding*/); 7707 7708 if (AddToChain) 7709 PendingLoads.push_back(LD.getValue(1)); 7710 setValue(&VPIntrin, LD); 7711 } 7712 7713 void SelectionDAGBuilder::visitVPStridedStore( 7714 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 7715 SDLoc DL = getCurSDLoc(); 7716 Value *PtrOperand = VPIntrin.getArgOperand(1); 7717 EVT VT = OpValues[0].getValueType(); 7718 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7719 if (!Alignment) 7720 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7721 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7722 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7723 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7724 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7725 7726 SDValue ST = DAG.getStridedStoreVP( 7727 getMemoryRoot(), DL, OpValues[0], OpValues[1], 7728 DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3], 7729 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false, 7730 /*IsCompressing*/ false); 7731 7732 DAG.setRoot(ST); 7733 setValue(&VPIntrin, ST); 7734 } 7735 7736 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) { 7737 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7738 SDLoc DL = getCurSDLoc(); 7739 7740 ISD::CondCode Condition; 7741 CmpInst::Predicate CondCode = VPIntrin.getPredicate(); 7742 bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy(); 7743 if (IsFP) { 7744 // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan) 7745 // flags, but calls that don't return floating-point types can't be 7746 // FPMathOperators, like vp.fcmp. This affects constrained fcmp too. 7747 Condition = getFCmpCondCode(CondCode); 7748 if (TM.Options.NoNaNsFPMath) 7749 Condition = getFCmpCodeWithoutNaN(Condition); 7750 } else { 7751 Condition = getICmpCondCode(CondCode); 7752 } 7753 7754 SDValue Op1 = getValue(VPIntrin.getOperand(0)); 7755 SDValue Op2 = getValue(VPIntrin.getOperand(1)); 7756 // #2 is the condition code 7757 SDValue MaskOp = getValue(VPIntrin.getOperand(3)); 7758 SDValue EVL = getValue(VPIntrin.getOperand(4)); 7759 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7760 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7761 "Unexpected target EVL type"); 7762 EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL); 7763 7764 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7765 VPIntrin.getType()); 7766 setValue(&VPIntrin, 7767 DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL)); 7768 } 7769 7770 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 7771 const VPIntrinsic &VPIntrin) { 7772 SDLoc DL = getCurSDLoc(); 7773 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 7774 7775 auto IID = VPIntrin.getIntrinsicID(); 7776 7777 if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin)) 7778 return visitVPCmp(*CmpI); 7779 7780 SmallVector<EVT, 4> ValueVTs; 7781 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7782 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 7783 SDVTList VTs = DAG.getVTList(ValueVTs); 7784 7785 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID); 7786 7787 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7788 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7789 "Unexpected target EVL type"); 7790 7791 // Request operands. 7792 SmallVector<SDValue, 7> OpValues; 7793 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) { 7794 auto Op = getValue(VPIntrin.getArgOperand(I)); 7795 if (I == EVLParamPos) 7796 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op); 7797 OpValues.push_back(Op); 7798 } 7799 7800 switch (Opcode) { 7801 default: { 7802 SDNodeFlags SDFlags; 7803 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 7804 SDFlags.copyFMF(*FPMO); 7805 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags); 7806 setValue(&VPIntrin, Result); 7807 break; 7808 } 7809 case ISD::VP_LOAD: 7810 visitVPLoad(VPIntrin, ValueVTs[0], OpValues); 7811 break; 7812 case ISD::VP_GATHER: 7813 visitVPGather(VPIntrin, ValueVTs[0], OpValues); 7814 break; 7815 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: 7816 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues); 7817 break; 7818 case ISD::VP_STORE: 7819 visitVPStore(VPIntrin, OpValues); 7820 break; 7821 case ISD::VP_SCATTER: 7822 visitVPScatter(VPIntrin, OpValues); 7823 break; 7824 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: 7825 visitVPStridedStore(VPIntrin, OpValues); 7826 break; 7827 case ISD::VP_FMULADD: { 7828 assert(OpValues.size() == 5 && "Unexpected number of operands"); 7829 SDNodeFlags SDFlags; 7830 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 7831 SDFlags.copyFMF(*FPMO); 7832 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 7833 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) { 7834 setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags)); 7835 } else { 7836 SDValue Mul = DAG.getNode( 7837 ISD::VP_FMUL, DL, VTs, 7838 {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags); 7839 SDValue Add = 7840 DAG.getNode(ISD::VP_FADD, DL, VTs, 7841 {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags); 7842 setValue(&VPIntrin, Add); 7843 } 7844 break; 7845 } 7846 case ISD::VP_INTTOPTR: { 7847 SDValue N = OpValues[0]; 7848 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType()); 7849 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType()); 7850 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 7851 OpValues[2]); 7852 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 7853 OpValues[2]); 7854 setValue(&VPIntrin, N); 7855 break; 7856 } 7857 case ISD::VP_PTRTOINT: { 7858 SDValue N = OpValues[0]; 7859 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7860 VPIntrin.getType()); 7861 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), 7862 VPIntrin.getOperand(0)->getType()); 7863 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 7864 OpValues[2]); 7865 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 7866 OpValues[2]); 7867 setValue(&VPIntrin, N); 7868 break; 7869 } 7870 case ISD::VP_ABS: 7871 case ISD::VP_CTLZ: 7872 case ISD::VP_CTLZ_ZERO_UNDEF: 7873 case ISD::VP_CTTZ: 7874 case ISD::VP_CTTZ_ZERO_UNDEF: { 7875 SDValue Result = 7876 DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]}); 7877 setValue(&VPIntrin, Result); 7878 break; 7879 } 7880 } 7881 } 7882 7883 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 7884 const BasicBlock *EHPadBB, 7885 MCSymbol *&BeginLabel) { 7886 MachineFunction &MF = DAG.getMachineFunction(); 7887 MachineModuleInfo &MMI = MF.getMMI(); 7888 7889 // Insert a label before the invoke call to mark the try range. This can be 7890 // used to detect deletion of the invoke via the MachineModuleInfo. 7891 BeginLabel = MMI.getContext().createTempSymbol(); 7892 7893 // For SjLj, keep track of which landing pads go with which invokes 7894 // so as to maintain the ordering of pads in the LSDA. 7895 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7896 if (CallSiteIndex) { 7897 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7898 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7899 7900 // Now that the call site is handled, stop tracking it. 7901 MMI.setCurrentCallSite(0); 7902 } 7903 7904 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 7905 } 7906 7907 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 7908 const BasicBlock *EHPadBB, 7909 MCSymbol *BeginLabel) { 7910 assert(BeginLabel && "BeginLabel should've been set"); 7911 7912 MachineFunction &MF = DAG.getMachineFunction(); 7913 MachineModuleInfo &MMI = MF.getMMI(); 7914 7915 // Insert a label at the end of the invoke call to mark the try range. This 7916 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7917 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7918 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 7919 7920 // Inform MachineModuleInfo of range. 7921 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7922 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7923 // actually use outlined funclets and their LSDA info style. 7924 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7925 assert(II && "II should've been set"); 7926 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 7927 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 7928 } else if (!isScopedEHPersonality(Pers)) { 7929 assert(EHPadBB); 7930 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7931 } 7932 7933 return Chain; 7934 } 7935 7936 std::pair<SDValue, SDValue> 7937 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7938 const BasicBlock *EHPadBB) { 7939 MCSymbol *BeginLabel = nullptr; 7940 7941 if (EHPadBB) { 7942 // Both PendingLoads and PendingExports must be flushed here; 7943 // this call might not return. 7944 (void)getRoot(); 7945 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 7946 CLI.setChain(getRoot()); 7947 } 7948 7949 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7950 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7951 7952 assert((CLI.IsTailCall || Result.second.getNode()) && 7953 "Non-null chain expected with non-tail call!"); 7954 assert((Result.second.getNode() || !Result.first.getNode()) && 7955 "Null value expected with tail call!"); 7956 7957 if (!Result.second.getNode()) { 7958 // As a special case, a null chain means that a tail call has been emitted 7959 // and the DAG root is already updated. 7960 HasTailCall = true; 7961 7962 // Since there's no actual continuation from this block, nothing can be 7963 // relying on us setting vregs for them. 7964 PendingExports.clear(); 7965 } else { 7966 DAG.setRoot(Result.second); 7967 } 7968 7969 if (EHPadBB) { 7970 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 7971 BeginLabel)); 7972 } 7973 7974 return Result; 7975 } 7976 7977 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 7978 bool isTailCall, 7979 bool isMustTailCall, 7980 const BasicBlock *EHPadBB) { 7981 auto &DL = DAG.getDataLayout(); 7982 FunctionType *FTy = CB.getFunctionType(); 7983 Type *RetTy = CB.getType(); 7984 7985 TargetLowering::ArgListTy Args; 7986 Args.reserve(CB.arg_size()); 7987 7988 const Value *SwiftErrorVal = nullptr; 7989 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7990 7991 if (isTailCall) { 7992 // Avoid emitting tail calls in functions with the disable-tail-calls 7993 // attribute. 7994 auto *Caller = CB.getParent()->getParent(); 7995 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7996 "true" && !isMustTailCall) 7997 isTailCall = false; 7998 7999 // We can't tail call inside a function with a swifterror argument. Lowering 8000 // does not support this yet. It would have to move into the swifterror 8001 // register before the call. 8002 if (TLI.supportSwiftError() && 8003 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 8004 isTailCall = false; 8005 } 8006 8007 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 8008 TargetLowering::ArgListEntry Entry; 8009 const Value *V = *I; 8010 8011 // Skip empty types 8012 if (V->getType()->isEmptyTy()) 8013 continue; 8014 8015 SDValue ArgNode = getValue(V); 8016 Entry.Node = ArgNode; Entry.Ty = V->getType(); 8017 8018 Entry.setAttributes(&CB, I - CB.arg_begin()); 8019 8020 // Use swifterror virtual register as input to the call. 8021 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 8022 SwiftErrorVal = V; 8023 // We find the virtual register for the actual swifterror argument. 8024 // Instead of using the Value, we use the virtual register instead. 8025 Entry.Node = 8026 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 8027 EVT(TLI.getPointerTy(DL))); 8028 } 8029 8030 Args.push_back(Entry); 8031 8032 // If we have an explicit sret argument that is an Instruction, (i.e., it 8033 // might point to function-local memory), we can't meaningfully tail-call. 8034 if (Entry.IsSRet && isa<Instruction>(V)) 8035 isTailCall = false; 8036 } 8037 8038 // If call site has a cfguardtarget operand bundle, create and add an 8039 // additional ArgListEntry. 8040 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 8041 TargetLowering::ArgListEntry Entry; 8042 Value *V = Bundle->Inputs[0]; 8043 SDValue ArgNode = getValue(V); 8044 Entry.Node = ArgNode; 8045 Entry.Ty = V->getType(); 8046 Entry.IsCFGuardTarget = true; 8047 Args.push_back(Entry); 8048 } 8049 8050 // Check if target-independent constraints permit a tail call here. 8051 // Target-dependent constraints are checked within TLI->LowerCallTo. 8052 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 8053 isTailCall = false; 8054 8055 // Disable tail calls if there is an swifterror argument. Targets have not 8056 // been updated to support tail calls. 8057 if (TLI.supportSwiftError() && SwiftErrorVal) 8058 isTailCall = false; 8059 8060 ConstantInt *CFIType = nullptr; 8061 if (CB.isIndirectCall()) { 8062 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) { 8063 if (!TLI.supportKCFIBundles()) 8064 report_fatal_error( 8065 "Target doesn't support calls with kcfi operand bundles."); 8066 CFIType = cast<ConstantInt>(Bundle->Inputs[0]); 8067 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type"); 8068 } 8069 } 8070 8071 TargetLowering::CallLoweringInfo CLI(DAG); 8072 CLI.setDebugLoc(getCurSDLoc()) 8073 .setChain(getRoot()) 8074 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 8075 .setTailCall(isTailCall) 8076 .setConvergent(CB.isConvergent()) 8077 .setIsPreallocated( 8078 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0) 8079 .setCFIType(CFIType); 8080 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8081 8082 if (Result.first.getNode()) { 8083 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 8084 setValue(&CB, Result.first); 8085 } 8086 8087 // The last element of CLI.InVals has the SDValue for swifterror return. 8088 // Here we copy it to a virtual register and update SwiftErrorMap for 8089 // book-keeping. 8090 if (SwiftErrorVal && TLI.supportSwiftError()) { 8091 // Get the last element of InVals. 8092 SDValue Src = CLI.InVals.back(); 8093 Register VReg = 8094 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 8095 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 8096 DAG.setRoot(CopyNode); 8097 } 8098 } 8099 8100 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 8101 SelectionDAGBuilder &Builder) { 8102 // Check to see if this load can be trivially constant folded, e.g. if the 8103 // input is from a string literal. 8104 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 8105 // Cast pointer to the type we really want to load. 8106 Type *LoadTy = 8107 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 8108 if (LoadVT.isVector()) 8109 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 8110 8111 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 8112 PointerType::getUnqual(LoadTy)); 8113 8114 if (const Constant *LoadCst = 8115 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput), 8116 LoadTy, Builder.DAG.getDataLayout())) 8117 return Builder.getValue(LoadCst); 8118 } 8119 8120 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 8121 // still constant memory, the input chain can be the entry node. 8122 SDValue Root; 8123 bool ConstantMemory = false; 8124 8125 // Do not serialize (non-volatile) loads of constant memory with anything. 8126 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 8127 Root = Builder.DAG.getEntryNode(); 8128 ConstantMemory = true; 8129 } else { 8130 // Do not serialize non-volatile loads against each other. 8131 Root = Builder.DAG.getRoot(); 8132 } 8133 8134 SDValue Ptr = Builder.getValue(PtrVal); 8135 SDValue LoadVal = 8136 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 8137 MachinePointerInfo(PtrVal), Align(1)); 8138 8139 if (!ConstantMemory) 8140 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 8141 return LoadVal; 8142 } 8143 8144 /// Record the value for an instruction that produces an integer result, 8145 /// converting the type where necessary. 8146 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 8147 SDValue Value, 8148 bool IsSigned) { 8149 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8150 I.getType(), true); 8151 if (IsSigned) 8152 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 8153 else 8154 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 8155 setValue(&I, Value); 8156 } 8157 8158 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 8159 /// true and lower it. Otherwise return false, and it will be lowered like a 8160 /// normal call. 8161 /// The caller already checked that \p I calls the appropriate LibFunc with a 8162 /// correct prototype. 8163 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 8164 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 8165 const Value *Size = I.getArgOperand(2); 8166 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size)); 8167 if (CSize && CSize->getZExtValue() == 0) { 8168 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8169 I.getType(), true); 8170 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 8171 return true; 8172 } 8173 8174 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8175 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 8176 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 8177 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 8178 if (Res.first.getNode()) { 8179 processIntegerCallValue(I, Res.first, true); 8180 PendingLoads.push_back(Res.second); 8181 return true; 8182 } 8183 8184 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 8185 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 8186 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 8187 return false; 8188 8189 // If the target has a fast compare for the given size, it will return a 8190 // preferred load type for that size. Require that the load VT is legal and 8191 // that the target supports unaligned loads of that type. Otherwise, return 8192 // INVALID. 8193 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 8194 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8195 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 8196 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 8197 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 8198 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 8199 // TODO: Check alignment of src and dest ptrs. 8200 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 8201 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 8202 if (!TLI.isTypeLegal(LVT) || 8203 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 8204 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 8205 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 8206 } 8207 8208 return LVT; 8209 }; 8210 8211 // This turns into unaligned loads. We only do this if the target natively 8212 // supports the MVT we'll be loading or if it is small enough (<= 4) that 8213 // we'll only produce a small number of byte loads. 8214 MVT LoadVT; 8215 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 8216 switch (NumBitsToCompare) { 8217 default: 8218 return false; 8219 case 16: 8220 LoadVT = MVT::i16; 8221 break; 8222 case 32: 8223 LoadVT = MVT::i32; 8224 break; 8225 case 64: 8226 case 128: 8227 case 256: 8228 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 8229 break; 8230 } 8231 8232 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 8233 return false; 8234 8235 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 8236 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 8237 8238 // Bitcast to a wide integer type if the loads are vectors. 8239 if (LoadVT.isVector()) { 8240 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 8241 LoadL = DAG.getBitcast(CmpVT, LoadL); 8242 LoadR = DAG.getBitcast(CmpVT, LoadR); 8243 } 8244 8245 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 8246 processIntegerCallValue(I, Cmp, false); 8247 return true; 8248 } 8249 8250 /// See if we can lower a memchr call into an optimized form. If so, return 8251 /// true and lower it. Otherwise return false, and it will be lowered like a 8252 /// normal call. 8253 /// The caller already checked that \p I calls the appropriate LibFunc with a 8254 /// correct prototype. 8255 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 8256 const Value *Src = I.getArgOperand(0); 8257 const Value *Char = I.getArgOperand(1); 8258 const Value *Length = I.getArgOperand(2); 8259 8260 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8261 std::pair<SDValue, SDValue> Res = 8262 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 8263 getValue(Src), getValue(Char), getValue(Length), 8264 MachinePointerInfo(Src)); 8265 if (Res.first.getNode()) { 8266 setValue(&I, Res.first); 8267 PendingLoads.push_back(Res.second); 8268 return true; 8269 } 8270 8271 return false; 8272 } 8273 8274 /// See if we can lower a mempcpy call into an optimized form. If so, return 8275 /// true and lower it. Otherwise return false, and it will be lowered like a 8276 /// normal call. 8277 /// The caller already checked that \p I calls the appropriate LibFunc with a 8278 /// correct prototype. 8279 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 8280 SDValue Dst = getValue(I.getArgOperand(0)); 8281 SDValue Src = getValue(I.getArgOperand(1)); 8282 SDValue Size = getValue(I.getArgOperand(2)); 8283 8284 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 8285 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 8286 // DAG::getMemcpy needs Alignment to be defined. 8287 Align Alignment = std::min(DstAlign, SrcAlign); 8288 8289 SDLoc sdl = getCurSDLoc(); 8290 8291 // In the mempcpy context we need to pass in a false value for isTailCall 8292 // because the return pointer needs to be adjusted by the size of 8293 // the copied memory. 8294 SDValue Root = getMemoryRoot(); 8295 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, false, false, 8296 /*isTailCall=*/false, 8297 MachinePointerInfo(I.getArgOperand(0)), 8298 MachinePointerInfo(I.getArgOperand(1)), 8299 I.getAAMetadata()); 8300 assert(MC.getNode() != nullptr && 8301 "** memcpy should not be lowered as TailCall in mempcpy context **"); 8302 DAG.setRoot(MC); 8303 8304 // Check if Size needs to be truncated or extended. 8305 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 8306 8307 // Adjust return pointer to point just past the last dst byte. 8308 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 8309 Dst, Size); 8310 setValue(&I, DstPlusSize); 8311 return true; 8312 } 8313 8314 /// See if we can lower a strcpy call into an optimized form. If so, return 8315 /// true and lower it, otherwise return false and it will be lowered like a 8316 /// normal call. 8317 /// The caller already checked that \p I calls the appropriate LibFunc with a 8318 /// correct prototype. 8319 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 8320 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8321 8322 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8323 std::pair<SDValue, SDValue> Res = 8324 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 8325 getValue(Arg0), getValue(Arg1), 8326 MachinePointerInfo(Arg0), 8327 MachinePointerInfo(Arg1), isStpcpy); 8328 if (Res.first.getNode()) { 8329 setValue(&I, Res.first); 8330 DAG.setRoot(Res.second); 8331 return true; 8332 } 8333 8334 return false; 8335 } 8336 8337 /// See if we can lower a strcmp call into an optimized form. If so, return 8338 /// true and lower it, otherwise return false and it will be lowered like a 8339 /// normal call. 8340 /// The caller already checked that \p I calls the appropriate LibFunc with a 8341 /// correct prototype. 8342 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 8343 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8344 8345 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8346 std::pair<SDValue, SDValue> Res = 8347 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 8348 getValue(Arg0), getValue(Arg1), 8349 MachinePointerInfo(Arg0), 8350 MachinePointerInfo(Arg1)); 8351 if (Res.first.getNode()) { 8352 processIntegerCallValue(I, Res.first, true); 8353 PendingLoads.push_back(Res.second); 8354 return true; 8355 } 8356 8357 return false; 8358 } 8359 8360 /// See if we can lower a strlen call into an optimized form. If so, return 8361 /// true and lower it, otherwise return false and it will be lowered like a 8362 /// normal call. 8363 /// The caller already checked that \p I calls the appropriate LibFunc with a 8364 /// correct prototype. 8365 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 8366 const Value *Arg0 = I.getArgOperand(0); 8367 8368 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8369 std::pair<SDValue, SDValue> Res = 8370 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 8371 getValue(Arg0), MachinePointerInfo(Arg0)); 8372 if (Res.first.getNode()) { 8373 processIntegerCallValue(I, Res.first, false); 8374 PendingLoads.push_back(Res.second); 8375 return true; 8376 } 8377 8378 return false; 8379 } 8380 8381 /// See if we can lower a strnlen call into an optimized form. If so, return 8382 /// true and lower it, otherwise return false and it will be lowered like a 8383 /// normal call. 8384 /// The caller already checked that \p I calls the appropriate LibFunc with a 8385 /// correct prototype. 8386 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 8387 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8388 8389 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8390 std::pair<SDValue, SDValue> Res = 8391 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 8392 getValue(Arg0), getValue(Arg1), 8393 MachinePointerInfo(Arg0)); 8394 if (Res.first.getNode()) { 8395 processIntegerCallValue(I, Res.first, false); 8396 PendingLoads.push_back(Res.second); 8397 return true; 8398 } 8399 8400 return false; 8401 } 8402 8403 /// See if we can lower a unary floating-point operation into an SDNode with 8404 /// the specified Opcode. If so, return true and lower it, otherwise return 8405 /// false and it will be lowered like a normal call. 8406 /// The caller already checked that \p I calls the appropriate LibFunc with a 8407 /// correct prototype. 8408 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 8409 unsigned Opcode) { 8410 // We already checked this call's prototype; verify it doesn't modify errno. 8411 if (!I.onlyReadsMemory()) 8412 return false; 8413 8414 SDNodeFlags Flags; 8415 Flags.copyFMF(cast<FPMathOperator>(I)); 8416 8417 SDValue Tmp = getValue(I.getArgOperand(0)); 8418 setValue(&I, 8419 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 8420 return true; 8421 } 8422 8423 /// See if we can lower a binary floating-point operation into an SDNode with 8424 /// the specified Opcode. If so, return true and lower it. Otherwise return 8425 /// false, and it will be lowered like a normal call. 8426 /// The caller already checked that \p I calls the appropriate LibFunc with a 8427 /// correct prototype. 8428 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 8429 unsigned Opcode) { 8430 // We already checked this call's prototype; verify it doesn't modify errno. 8431 if (!I.onlyReadsMemory()) 8432 return false; 8433 8434 SDNodeFlags Flags; 8435 Flags.copyFMF(cast<FPMathOperator>(I)); 8436 8437 SDValue Tmp0 = getValue(I.getArgOperand(0)); 8438 SDValue Tmp1 = getValue(I.getArgOperand(1)); 8439 EVT VT = Tmp0.getValueType(); 8440 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 8441 return true; 8442 } 8443 8444 void SelectionDAGBuilder::visitCall(const CallInst &I) { 8445 // Handle inline assembly differently. 8446 if (I.isInlineAsm()) { 8447 visitInlineAsm(I); 8448 return; 8449 } 8450 8451 diagnoseDontCall(I); 8452 8453 if (Function *F = I.getCalledFunction()) { 8454 if (F->isDeclaration()) { 8455 // Is this an LLVM intrinsic or a target-specific intrinsic? 8456 unsigned IID = F->getIntrinsicID(); 8457 if (!IID) 8458 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 8459 IID = II->getIntrinsicID(F); 8460 8461 if (IID) { 8462 visitIntrinsicCall(I, IID); 8463 return; 8464 } 8465 } 8466 8467 // Check for well-known libc/libm calls. If the function is internal, it 8468 // can't be a library call. Don't do the check if marked as nobuiltin for 8469 // some reason or the call site requires strict floating point semantics. 8470 LibFunc Func; 8471 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 8472 F->hasName() && LibInfo->getLibFunc(*F, Func) && 8473 LibInfo->hasOptimizedCodeGen(Func)) { 8474 switch (Func) { 8475 default: break; 8476 case LibFunc_bcmp: 8477 if (visitMemCmpBCmpCall(I)) 8478 return; 8479 break; 8480 case LibFunc_copysign: 8481 case LibFunc_copysignf: 8482 case LibFunc_copysignl: 8483 // We already checked this call's prototype; verify it doesn't modify 8484 // errno. 8485 if (I.onlyReadsMemory()) { 8486 SDValue LHS = getValue(I.getArgOperand(0)); 8487 SDValue RHS = getValue(I.getArgOperand(1)); 8488 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 8489 LHS.getValueType(), LHS, RHS)); 8490 return; 8491 } 8492 break; 8493 case LibFunc_fabs: 8494 case LibFunc_fabsf: 8495 case LibFunc_fabsl: 8496 if (visitUnaryFloatCall(I, ISD::FABS)) 8497 return; 8498 break; 8499 case LibFunc_fmin: 8500 case LibFunc_fminf: 8501 case LibFunc_fminl: 8502 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 8503 return; 8504 break; 8505 case LibFunc_fmax: 8506 case LibFunc_fmaxf: 8507 case LibFunc_fmaxl: 8508 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 8509 return; 8510 break; 8511 case LibFunc_sin: 8512 case LibFunc_sinf: 8513 case LibFunc_sinl: 8514 if (visitUnaryFloatCall(I, ISD::FSIN)) 8515 return; 8516 break; 8517 case LibFunc_cos: 8518 case LibFunc_cosf: 8519 case LibFunc_cosl: 8520 if (visitUnaryFloatCall(I, ISD::FCOS)) 8521 return; 8522 break; 8523 case LibFunc_sqrt: 8524 case LibFunc_sqrtf: 8525 case LibFunc_sqrtl: 8526 case LibFunc_sqrt_finite: 8527 case LibFunc_sqrtf_finite: 8528 case LibFunc_sqrtl_finite: 8529 if (visitUnaryFloatCall(I, ISD::FSQRT)) 8530 return; 8531 break; 8532 case LibFunc_floor: 8533 case LibFunc_floorf: 8534 case LibFunc_floorl: 8535 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 8536 return; 8537 break; 8538 case LibFunc_nearbyint: 8539 case LibFunc_nearbyintf: 8540 case LibFunc_nearbyintl: 8541 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 8542 return; 8543 break; 8544 case LibFunc_ceil: 8545 case LibFunc_ceilf: 8546 case LibFunc_ceill: 8547 if (visitUnaryFloatCall(I, ISD::FCEIL)) 8548 return; 8549 break; 8550 case LibFunc_rint: 8551 case LibFunc_rintf: 8552 case LibFunc_rintl: 8553 if (visitUnaryFloatCall(I, ISD::FRINT)) 8554 return; 8555 break; 8556 case LibFunc_round: 8557 case LibFunc_roundf: 8558 case LibFunc_roundl: 8559 if (visitUnaryFloatCall(I, ISD::FROUND)) 8560 return; 8561 break; 8562 case LibFunc_trunc: 8563 case LibFunc_truncf: 8564 case LibFunc_truncl: 8565 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 8566 return; 8567 break; 8568 case LibFunc_log2: 8569 case LibFunc_log2f: 8570 case LibFunc_log2l: 8571 if (visitUnaryFloatCall(I, ISD::FLOG2)) 8572 return; 8573 break; 8574 case LibFunc_exp2: 8575 case LibFunc_exp2f: 8576 case LibFunc_exp2l: 8577 if (visitUnaryFloatCall(I, ISD::FEXP2)) 8578 return; 8579 break; 8580 case LibFunc_memcmp: 8581 if (visitMemCmpBCmpCall(I)) 8582 return; 8583 break; 8584 case LibFunc_mempcpy: 8585 if (visitMemPCpyCall(I)) 8586 return; 8587 break; 8588 case LibFunc_memchr: 8589 if (visitMemChrCall(I)) 8590 return; 8591 break; 8592 case LibFunc_strcpy: 8593 if (visitStrCpyCall(I, false)) 8594 return; 8595 break; 8596 case LibFunc_stpcpy: 8597 if (visitStrCpyCall(I, true)) 8598 return; 8599 break; 8600 case LibFunc_strcmp: 8601 if (visitStrCmpCall(I)) 8602 return; 8603 break; 8604 case LibFunc_strlen: 8605 if (visitStrLenCall(I)) 8606 return; 8607 break; 8608 case LibFunc_strnlen: 8609 if (visitStrNLenCall(I)) 8610 return; 8611 break; 8612 } 8613 } 8614 } 8615 8616 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 8617 // have to do anything here to lower funclet bundles. 8618 // CFGuardTarget bundles are lowered in LowerCallTo. 8619 assert(!I.hasOperandBundlesOtherThan( 8620 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 8621 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 8622 LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) && 8623 "Cannot lower calls with arbitrary operand bundles!"); 8624 8625 SDValue Callee = getValue(I.getCalledOperand()); 8626 8627 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 8628 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 8629 else 8630 // Check if we can potentially perform a tail call. More detailed checking 8631 // is be done within LowerCallTo, after more information about the call is 8632 // known. 8633 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 8634 } 8635 8636 namespace { 8637 8638 /// AsmOperandInfo - This contains information for each constraint that we are 8639 /// lowering. 8640 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 8641 public: 8642 /// CallOperand - If this is the result output operand or a clobber 8643 /// this is null, otherwise it is the incoming operand to the CallInst. 8644 /// This gets modified as the asm is processed. 8645 SDValue CallOperand; 8646 8647 /// AssignedRegs - If this is a register or register class operand, this 8648 /// contains the set of register corresponding to the operand. 8649 RegsForValue AssignedRegs; 8650 8651 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 8652 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 8653 } 8654 8655 /// Whether or not this operand accesses memory 8656 bool hasMemory(const TargetLowering &TLI) const { 8657 // Indirect operand accesses access memory. 8658 if (isIndirect) 8659 return true; 8660 8661 for (const auto &Code : Codes) 8662 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 8663 return true; 8664 8665 return false; 8666 } 8667 }; 8668 8669 8670 } // end anonymous namespace 8671 8672 /// Make sure that the output operand \p OpInfo and its corresponding input 8673 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 8674 /// out). 8675 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 8676 SDISelAsmOperandInfo &MatchingOpInfo, 8677 SelectionDAG &DAG) { 8678 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 8679 return; 8680 8681 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 8682 const auto &TLI = DAG.getTargetLoweringInfo(); 8683 8684 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 8685 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 8686 OpInfo.ConstraintVT); 8687 std::pair<unsigned, const TargetRegisterClass *> InputRC = 8688 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 8689 MatchingOpInfo.ConstraintVT); 8690 if ((OpInfo.ConstraintVT.isInteger() != 8691 MatchingOpInfo.ConstraintVT.isInteger()) || 8692 (MatchRC.second != InputRC.second)) { 8693 // FIXME: error out in a more elegant fashion 8694 report_fatal_error("Unsupported asm: input constraint" 8695 " with a matching output constraint of" 8696 " incompatible type!"); 8697 } 8698 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 8699 } 8700 8701 /// Get a direct memory input to behave well as an indirect operand. 8702 /// This may introduce stores, hence the need for a \p Chain. 8703 /// \return The (possibly updated) chain. 8704 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 8705 SDISelAsmOperandInfo &OpInfo, 8706 SelectionDAG &DAG) { 8707 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8708 8709 // If we don't have an indirect input, put it in the constpool if we can, 8710 // otherwise spill it to a stack slot. 8711 // TODO: This isn't quite right. We need to handle these according to 8712 // the addressing mode that the constraint wants. Also, this may take 8713 // an additional register for the computation and we don't want that 8714 // either. 8715 8716 // If the operand is a float, integer, or vector constant, spill to a 8717 // constant pool entry to get its address. 8718 const Value *OpVal = OpInfo.CallOperandVal; 8719 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 8720 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 8721 OpInfo.CallOperand = DAG.getConstantPool( 8722 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 8723 return Chain; 8724 } 8725 8726 // Otherwise, create a stack slot and emit a store to it before the asm. 8727 Type *Ty = OpVal->getType(); 8728 auto &DL = DAG.getDataLayout(); 8729 uint64_t TySize = DL.getTypeAllocSize(Ty); 8730 MachineFunction &MF = DAG.getMachineFunction(); 8731 int SSFI = MF.getFrameInfo().CreateStackObject( 8732 TySize, DL.getPrefTypeAlign(Ty), false); 8733 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 8734 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 8735 MachinePointerInfo::getFixedStack(MF, SSFI), 8736 TLI.getMemValueType(DL, Ty)); 8737 OpInfo.CallOperand = StackSlot; 8738 8739 return Chain; 8740 } 8741 8742 /// GetRegistersForValue - Assign registers (virtual or physical) for the 8743 /// specified operand. We prefer to assign virtual registers, to allow the 8744 /// register allocator to handle the assignment process. However, if the asm 8745 /// uses features that we can't model on machineinstrs, we have SDISel do the 8746 /// allocation. This produces generally horrible, but correct, code. 8747 /// 8748 /// OpInfo describes the operand 8749 /// RefOpInfo describes the matching operand if any, the operand otherwise 8750 static std::optional<unsigned> 8751 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 8752 SDISelAsmOperandInfo &OpInfo, 8753 SDISelAsmOperandInfo &RefOpInfo) { 8754 LLVMContext &Context = *DAG.getContext(); 8755 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8756 8757 MachineFunction &MF = DAG.getMachineFunction(); 8758 SmallVector<unsigned, 4> Regs; 8759 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8760 8761 // No work to do for memory/address operands. 8762 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8763 OpInfo.ConstraintType == TargetLowering::C_Address) 8764 return std::nullopt; 8765 8766 // If this is a constraint for a single physreg, or a constraint for a 8767 // register class, find it. 8768 unsigned AssignedReg; 8769 const TargetRegisterClass *RC; 8770 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 8771 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 8772 // RC is unset only on failure. Return immediately. 8773 if (!RC) 8774 return std::nullopt; 8775 8776 // Get the actual register value type. This is important, because the user 8777 // may have asked for (e.g.) the AX register in i32 type. We need to 8778 // remember that AX is actually i16 to get the right extension. 8779 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 8780 8781 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) { 8782 // If this is an FP operand in an integer register (or visa versa), or more 8783 // generally if the operand value disagrees with the register class we plan 8784 // to stick it in, fix the operand type. 8785 // 8786 // If this is an input value, the bitcast to the new type is done now. 8787 // Bitcast for output value is done at the end of visitInlineAsm(). 8788 if ((OpInfo.Type == InlineAsm::isOutput || 8789 OpInfo.Type == InlineAsm::isInput) && 8790 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 8791 // Try to convert to the first EVT that the reg class contains. If the 8792 // types are identical size, use a bitcast to convert (e.g. two differing 8793 // vector types). Note: output bitcast is done at the end of 8794 // visitInlineAsm(). 8795 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 8796 // Exclude indirect inputs while they are unsupported because the code 8797 // to perform the load is missing and thus OpInfo.CallOperand still 8798 // refers to the input address rather than the pointed-to value. 8799 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 8800 OpInfo.CallOperand = 8801 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 8802 OpInfo.ConstraintVT = RegVT; 8803 // If the operand is an FP value and we want it in integer registers, 8804 // use the corresponding integer type. This turns an f64 value into 8805 // i64, which can be passed with two i32 values on a 32-bit machine. 8806 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 8807 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 8808 if (OpInfo.Type == InlineAsm::isInput) 8809 OpInfo.CallOperand = 8810 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 8811 OpInfo.ConstraintVT = VT; 8812 } 8813 } 8814 } 8815 8816 // No need to allocate a matching input constraint since the constraint it's 8817 // matching to has already been allocated. 8818 if (OpInfo.isMatchingInputConstraint()) 8819 return std::nullopt; 8820 8821 EVT ValueVT = OpInfo.ConstraintVT; 8822 if (OpInfo.ConstraintVT == MVT::Other) 8823 ValueVT = RegVT; 8824 8825 // Initialize NumRegs. 8826 unsigned NumRegs = 1; 8827 if (OpInfo.ConstraintVT != MVT::Other) 8828 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT); 8829 8830 // If this is a constraint for a specific physical register, like {r17}, 8831 // assign it now. 8832 8833 // If this associated to a specific register, initialize iterator to correct 8834 // place. If virtual, make sure we have enough registers 8835 8836 // Initialize iterator if necessary 8837 TargetRegisterClass::iterator I = RC->begin(); 8838 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8839 8840 // Do not check for single registers. 8841 if (AssignedReg) { 8842 I = std::find(I, RC->end(), AssignedReg); 8843 if (I == RC->end()) { 8844 // RC does not contain the selected register, which indicates a 8845 // mismatch between the register and the required type/bitwidth. 8846 return {AssignedReg}; 8847 } 8848 } 8849 8850 for (; NumRegs; --NumRegs, ++I) { 8851 assert(I != RC->end() && "Ran out of registers to allocate!"); 8852 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8853 Regs.push_back(R); 8854 } 8855 8856 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8857 return std::nullopt; 8858 } 8859 8860 static unsigned 8861 findMatchingInlineAsmOperand(unsigned OperandNo, 8862 const std::vector<SDValue> &AsmNodeOperands) { 8863 // Scan until we find the definition we already emitted of this operand. 8864 unsigned CurOp = InlineAsm::Op_FirstOperand; 8865 for (; OperandNo; --OperandNo) { 8866 // Advance to the next operand. 8867 unsigned OpFlag = 8868 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8869 assert((InlineAsm::isRegDefKind(OpFlag) || 8870 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8871 InlineAsm::isMemKind(OpFlag)) && 8872 "Skipped past definitions?"); 8873 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8874 } 8875 return CurOp; 8876 } 8877 8878 namespace { 8879 8880 class ExtraFlags { 8881 unsigned Flags = 0; 8882 8883 public: 8884 explicit ExtraFlags(const CallBase &Call) { 8885 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8886 if (IA->hasSideEffects()) 8887 Flags |= InlineAsm::Extra_HasSideEffects; 8888 if (IA->isAlignStack()) 8889 Flags |= InlineAsm::Extra_IsAlignStack; 8890 if (Call.isConvergent()) 8891 Flags |= InlineAsm::Extra_IsConvergent; 8892 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8893 } 8894 8895 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8896 // Ideally, we would only check against memory constraints. However, the 8897 // meaning of an Other constraint can be target-specific and we can't easily 8898 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8899 // for Other constraints as well. 8900 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8901 OpInfo.ConstraintType == TargetLowering::C_Other) { 8902 if (OpInfo.Type == InlineAsm::isInput) 8903 Flags |= InlineAsm::Extra_MayLoad; 8904 else if (OpInfo.Type == InlineAsm::isOutput) 8905 Flags |= InlineAsm::Extra_MayStore; 8906 else if (OpInfo.Type == InlineAsm::isClobber) 8907 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8908 } 8909 } 8910 8911 unsigned get() const { return Flags; } 8912 }; 8913 8914 } // end anonymous namespace 8915 8916 static bool isFunction(SDValue Op) { 8917 if (Op && Op.getOpcode() == ISD::GlobalAddress) { 8918 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 8919 auto Fn = dyn_cast_or_null<Function>(GA->getGlobal()); 8920 8921 // In normal "call dllimport func" instruction (non-inlineasm) it force 8922 // indirect access by specifing call opcode. And usually specially print 8923 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can 8924 // not do in this way now. (In fact, this is similar with "Data Access" 8925 // action). So here we ignore dllimport function. 8926 if (Fn && !Fn->hasDLLImportStorageClass()) 8927 return true; 8928 } 8929 } 8930 return false; 8931 } 8932 8933 /// visitInlineAsm - Handle a call to an InlineAsm object. 8934 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 8935 const BasicBlock *EHPadBB) { 8936 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8937 8938 /// ConstraintOperands - Information about all of the constraints. 8939 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 8940 8941 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8942 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8943 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 8944 8945 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8946 // AsmDialect, MayLoad, MayStore). 8947 bool HasSideEffect = IA->hasSideEffects(); 8948 ExtraFlags ExtraInfo(Call); 8949 8950 for (auto &T : TargetConstraints) { 8951 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8952 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8953 8954 if (OpInfo.CallOperandVal) 8955 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8956 8957 if (!HasSideEffect) 8958 HasSideEffect = OpInfo.hasMemory(TLI); 8959 8960 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8961 // FIXME: Could we compute this on OpInfo rather than T? 8962 8963 // Compute the constraint code and ConstraintType to use. 8964 TLI.ComputeConstraintToUse(T, SDValue()); 8965 8966 if (T.ConstraintType == TargetLowering::C_Immediate && 8967 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8968 // We've delayed emitting a diagnostic like the "n" constraint because 8969 // inlining could cause an integer showing up. 8970 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 8971 "' expects an integer constant " 8972 "expression"); 8973 8974 ExtraInfo.update(T); 8975 } 8976 8977 // We won't need to flush pending loads if this asm doesn't touch 8978 // memory and is nonvolatile. 8979 SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8980 8981 bool EmitEHLabels = isa<InvokeInst>(Call); 8982 if (EmitEHLabels) { 8983 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 8984 } 8985 bool IsCallBr = isa<CallBrInst>(Call); 8986 8987 if (IsCallBr || EmitEHLabels) { 8988 // If this is a callbr or invoke we need to flush pending exports since 8989 // inlineasm_br and invoke are terminators. 8990 // We need to do this before nodes are glued to the inlineasm_br node. 8991 Chain = getControlRoot(); 8992 } 8993 8994 MCSymbol *BeginLabel = nullptr; 8995 if (EmitEHLabels) { 8996 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 8997 } 8998 8999 int OpNo = -1; 9000 SmallVector<StringRef> AsmStrs; 9001 IA->collectAsmStrs(AsmStrs); 9002 9003 // Second pass over the constraints: compute which constraint option to use. 9004 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9005 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput) 9006 OpNo++; 9007 9008 // If this is an output operand with a matching input operand, look up the 9009 // matching input. If their types mismatch, e.g. one is an integer, the 9010 // other is floating point, or their sizes are different, flag it as an 9011 // error. 9012 if (OpInfo.hasMatchingInput()) { 9013 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 9014 patchMatchingInput(OpInfo, Input, DAG); 9015 } 9016 9017 // Compute the constraint code and ConstraintType to use. 9018 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 9019 9020 if ((OpInfo.ConstraintType == TargetLowering::C_Memory && 9021 OpInfo.Type == InlineAsm::isClobber) || 9022 OpInfo.ConstraintType == TargetLowering::C_Address) 9023 continue; 9024 9025 // In Linux PIC model, there are 4 cases about value/label addressing: 9026 // 9027 // 1: Function call or Label jmp inside the module. 9028 // 2: Data access (such as global variable, static variable) inside module. 9029 // 3: Function call or Label jmp outside the module. 9030 // 4: Data access (such as global variable) outside the module. 9031 // 9032 // Due to current llvm inline asm architecture designed to not "recognize" 9033 // the asm code, there are quite troubles for us to treat mem addressing 9034 // differently for same value/adress used in different instuctions. 9035 // For example, in pic model, call a func may in plt way or direclty 9036 // pc-related, but lea/mov a function adress may use got. 9037 // 9038 // Here we try to "recognize" function call for the case 1 and case 3 in 9039 // inline asm. And try to adjust the constraint for them. 9040 // 9041 // TODO: Due to current inline asm didn't encourage to jmp to the outsider 9042 // label, so here we don't handle jmp function label now, but we need to 9043 // enhance it (especilly in PIC model) if we meet meaningful requirements. 9044 if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) && 9045 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) && 9046 TM.getCodeModel() != CodeModel::Large) { 9047 OpInfo.isIndirect = false; 9048 OpInfo.ConstraintType = TargetLowering::C_Address; 9049 } 9050 9051 // If this is a memory input, and if the operand is not indirect, do what we 9052 // need to provide an address for the memory input. 9053 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 9054 !OpInfo.isIndirect) { 9055 assert((OpInfo.isMultipleAlternative || 9056 (OpInfo.Type == InlineAsm::isInput)) && 9057 "Can only indirectify direct input operands!"); 9058 9059 // Memory operands really want the address of the value. 9060 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 9061 9062 // There is no longer a Value* corresponding to this operand. 9063 OpInfo.CallOperandVal = nullptr; 9064 9065 // It is now an indirect operand. 9066 OpInfo.isIndirect = true; 9067 } 9068 9069 } 9070 9071 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 9072 std::vector<SDValue> AsmNodeOperands; 9073 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 9074 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 9075 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 9076 9077 // If we have a !srcloc metadata node associated with it, we want to attach 9078 // this to the ultimately generated inline asm machineinstr. To do this, we 9079 // pass in the third operand as this (potentially null) inline asm MDNode. 9080 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 9081 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 9082 9083 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 9084 // bits as operand 3. 9085 AsmNodeOperands.push_back(DAG.getTargetConstant( 9086 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9087 9088 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 9089 // this, assign virtual and physical registers for inputs and otput. 9090 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9091 // Assign Registers. 9092 SDISelAsmOperandInfo &RefOpInfo = 9093 OpInfo.isMatchingInputConstraint() 9094 ? ConstraintOperands[OpInfo.getMatchedOperand()] 9095 : OpInfo; 9096 const auto RegError = 9097 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 9098 if (RegError) { 9099 const MachineFunction &MF = DAG.getMachineFunction(); 9100 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9101 const char *RegName = TRI.getName(*RegError); 9102 emitInlineAsmError(Call, "register '" + Twine(RegName) + 9103 "' allocated for constraint '" + 9104 Twine(OpInfo.ConstraintCode) + 9105 "' does not match required type"); 9106 return; 9107 } 9108 9109 auto DetectWriteToReservedRegister = [&]() { 9110 const MachineFunction &MF = DAG.getMachineFunction(); 9111 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9112 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 9113 if (Register::isPhysicalRegister(Reg) && 9114 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 9115 const char *RegName = TRI.getName(Reg); 9116 emitInlineAsmError(Call, "write to reserved register '" + 9117 Twine(RegName) + "'"); 9118 return true; 9119 } 9120 } 9121 return false; 9122 }; 9123 assert((OpInfo.ConstraintType != TargetLowering::C_Address || 9124 (OpInfo.Type == InlineAsm::isInput && 9125 !OpInfo.isMatchingInputConstraint())) && 9126 "Only address as input operand is allowed."); 9127 9128 switch (OpInfo.Type) { 9129 case InlineAsm::isOutput: 9130 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9131 unsigned ConstraintID = 9132 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9133 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9134 "Failed to convert memory constraint code to constraint id."); 9135 9136 // Add information to the INLINEASM node to know about this output. 9137 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9138 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 9139 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 9140 MVT::i32)); 9141 AsmNodeOperands.push_back(OpInfo.CallOperand); 9142 } else { 9143 // Otherwise, this outputs to a register (directly for C_Register / 9144 // C_RegisterClass, and a target-defined fashion for 9145 // C_Immediate/C_Other). Find a register that we can use. 9146 if (OpInfo.AssignedRegs.Regs.empty()) { 9147 emitInlineAsmError( 9148 Call, "couldn't allocate output register for constraint '" + 9149 Twine(OpInfo.ConstraintCode) + "'"); 9150 return; 9151 } 9152 9153 if (DetectWriteToReservedRegister()) 9154 return; 9155 9156 // Add information to the INLINEASM node to know that this register is 9157 // set. 9158 OpInfo.AssignedRegs.AddInlineAsmOperands( 9159 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 9160 : InlineAsm::Kind_RegDef, 9161 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 9162 } 9163 break; 9164 9165 case InlineAsm::isInput: 9166 case InlineAsm::isLabel: { 9167 SDValue InOperandVal = OpInfo.CallOperand; 9168 9169 if (OpInfo.isMatchingInputConstraint()) { 9170 // If this is required to match an output register we have already set, 9171 // just use its register. 9172 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 9173 AsmNodeOperands); 9174 unsigned OpFlag = 9175 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 9176 if (InlineAsm::isRegDefKind(OpFlag) || 9177 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 9178 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 9179 if (OpInfo.isIndirect) { 9180 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 9181 emitInlineAsmError(Call, "inline asm not supported yet: " 9182 "don't know how to handle tied " 9183 "indirect register inputs"); 9184 return; 9185 } 9186 9187 SmallVector<unsigned, 4> Regs; 9188 MachineFunction &MF = DAG.getMachineFunction(); 9189 MachineRegisterInfo &MRI = MF.getRegInfo(); 9190 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9191 auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]); 9192 Register TiedReg = R->getReg(); 9193 MVT RegVT = R->getSimpleValueType(0); 9194 const TargetRegisterClass *RC = 9195 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg) 9196 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT) 9197 : TRI.getMinimalPhysRegClass(TiedReg); 9198 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 9199 for (unsigned i = 0; i != NumRegs; ++i) 9200 Regs.push_back(MRI.createVirtualRegister(RC)); 9201 9202 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 9203 9204 SDLoc dl = getCurSDLoc(); 9205 // Use the produced MatchedRegs object to 9206 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call); 9207 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 9208 true, OpInfo.getMatchedOperand(), dl, 9209 DAG, AsmNodeOperands); 9210 break; 9211 } 9212 9213 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 9214 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 9215 "Unexpected number of operands"); 9216 // Add information to the INLINEASM node to know about this input. 9217 // See InlineAsm.h isUseOperandTiedToDef. 9218 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 9219 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 9220 OpInfo.getMatchedOperand()); 9221 AsmNodeOperands.push_back(DAG.getTargetConstant( 9222 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9223 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 9224 break; 9225 } 9226 9227 // Treat indirect 'X' constraint as memory. 9228 if (OpInfo.ConstraintType == TargetLowering::C_Other && 9229 OpInfo.isIndirect) 9230 OpInfo.ConstraintType = TargetLowering::C_Memory; 9231 9232 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 9233 OpInfo.ConstraintType == TargetLowering::C_Other) { 9234 std::vector<SDValue> Ops; 9235 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 9236 Ops, DAG); 9237 if (Ops.empty()) { 9238 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 9239 if (isa<ConstantSDNode>(InOperandVal)) { 9240 emitInlineAsmError(Call, "value out of range for constraint '" + 9241 Twine(OpInfo.ConstraintCode) + "'"); 9242 return; 9243 } 9244 9245 emitInlineAsmError(Call, 9246 "invalid operand for inline asm constraint '" + 9247 Twine(OpInfo.ConstraintCode) + "'"); 9248 return; 9249 } 9250 9251 // Add information to the INLINEASM node to know about this input. 9252 unsigned ResOpType = 9253 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 9254 AsmNodeOperands.push_back(DAG.getTargetConstant( 9255 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9256 llvm::append_range(AsmNodeOperands, Ops); 9257 break; 9258 } 9259 9260 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9261 assert((OpInfo.isIndirect || 9262 OpInfo.ConstraintType != TargetLowering::C_Memory) && 9263 "Operand must be indirect to be a mem!"); 9264 assert(InOperandVal.getValueType() == 9265 TLI.getPointerTy(DAG.getDataLayout()) && 9266 "Memory operands expect pointer values"); 9267 9268 unsigned ConstraintID = 9269 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9270 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9271 "Failed to convert memory constraint code to constraint id."); 9272 9273 // Add information to the INLINEASM node to know about this input. 9274 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9275 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 9276 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 9277 getCurSDLoc(), 9278 MVT::i32)); 9279 AsmNodeOperands.push_back(InOperandVal); 9280 break; 9281 } 9282 9283 if (OpInfo.ConstraintType == TargetLowering::C_Address) { 9284 assert(InOperandVal.getValueType() == 9285 TLI.getPointerTy(DAG.getDataLayout()) && 9286 "Address operands expect pointer values"); 9287 9288 unsigned ConstraintID = 9289 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9290 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9291 "Failed to convert memory constraint code to constraint id."); 9292 9293 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9294 9295 SDValue AsmOp = InOperandVal; 9296 if (isFunction(InOperandVal)) { 9297 auto *GA = cast<GlobalAddressSDNode>(InOperandVal); 9298 ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Func, 1); 9299 AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(), 9300 InOperandVal.getValueType(), 9301 GA->getOffset()); 9302 } 9303 9304 // Add information to the INLINEASM node to know about this input. 9305 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 9306 9307 AsmNodeOperands.push_back( 9308 DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32)); 9309 9310 AsmNodeOperands.push_back(AsmOp); 9311 break; 9312 } 9313 9314 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 9315 OpInfo.ConstraintType == TargetLowering::C_Register) && 9316 "Unknown constraint type!"); 9317 9318 // TODO: Support this. 9319 if (OpInfo.isIndirect) { 9320 emitInlineAsmError( 9321 Call, "Don't know how to handle indirect register inputs yet " 9322 "for constraint '" + 9323 Twine(OpInfo.ConstraintCode) + "'"); 9324 return; 9325 } 9326 9327 // Copy the input into the appropriate registers. 9328 if (OpInfo.AssignedRegs.Regs.empty()) { 9329 emitInlineAsmError(Call, 9330 "couldn't allocate input reg for constraint '" + 9331 Twine(OpInfo.ConstraintCode) + "'"); 9332 return; 9333 } 9334 9335 if (DetectWriteToReservedRegister()) 9336 return; 9337 9338 SDLoc dl = getCurSDLoc(); 9339 9340 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, 9341 &Call); 9342 9343 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 9344 dl, DAG, AsmNodeOperands); 9345 break; 9346 } 9347 case InlineAsm::isClobber: 9348 // Add the clobbered value to the operand list, so that the register 9349 // allocator is aware that the physreg got clobbered. 9350 if (!OpInfo.AssignedRegs.Regs.empty()) 9351 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 9352 false, 0, getCurSDLoc(), DAG, 9353 AsmNodeOperands); 9354 break; 9355 } 9356 } 9357 9358 // Finish up input operands. Set the input chain and add the flag last. 9359 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 9360 if (Glue.getNode()) AsmNodeOperands.push_back(Glue); 9361 9362 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 9363 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 9364 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 9365 Glue = Chain.getValue(1); 9366 9367 // Do additional work to generate outputs. 9368 9369 SmallVector<EVT, 1> ResultVTs; 9370 SmallVector<SDValue, 1> ResultValues; 9371 SmallVector<SDValue, 8> OutChains; 9372 9373 llvm::Type *CallResultType = Call.getType(); 9374 ArrayRef<Type *> ResultTypes; 9375 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 9376 ResultTypes = StructResult->elements(); 9377 else if (!CallResultType->isVoidTy()) 9378 ResultTypes = ArrayRef(CallResultType); 9379 9380 auto CurResultType = ResultTypes.begin(); 9381 auto handleRegAssign = [&](SDValue V) { 9382 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 9383 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 9384 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 9385 ++CurResultType; 9386 // If the type of the inline asm call site return value is different but has 9387 // same size as the type of the asm output bitcast it. One example of this 9388 // is for vectors with different width / number of elements. This can 9389 // happen for register classes that can contain multiple different value 9390 // types. The preg or vreg allocated may not have the same VT as was 9391 // expected. 9392 // 9393 // This can also happen for a return value that disagrees with the register 9394 // class it is put in, eg. a double in a general-purpose register on a 9395 // 32-bit machine. 9396 if (ResultVT != V.getValueType() && 9397 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 9398 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 9399 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 9400 V.getValueType().isInteger()) { 9401 // If a result value was tied to an input value, the computed result 9402 // may have a wider width than the expected result. Extract the 9403 // relevant portion. 9404 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 9405 } 9406 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 9407 ResultVTs.push_back(ResultVT); 9408 ResultValues.push_back(V); 9409 }; 9410 9411 // Deal with output operands. 9412 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9413 if (OpInfo.Type == InlineAsm::isOutput) { 9414 SDValue Val; 9415 // Skip trivial output operands. 9416 if (OpInfo.AssignedRegs.Regs.empty()) 9417 continue; 9418 9419 switch (OpInfo.ConstraintType) { 9420 case TargetLowering::C_Register: 9421 case TargetLowering::C_RegisterClass: 9422 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 9423 Chain, &Glue, &Call); 9424 break; 9425 case TargetLowering::C_Immediate: 9426 case TargetLowering::C_Other: 9427 Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(), 9428 OpInfo, DAG); 9429 break; 9430 case TargetLowering::C_Memory: 9431 break; // Already handled. 9432 case TargetLowering::C_Address: 9433 break; // Silence warning. 9434 case TargetLowering::C_Unknown: 9435 assert(false && "Unexpected unknown constraint"); 9436 } 9437 9438 // Indirect output manifest as stores. Record output chains. 9439 if (OpInfo.isIndirect) { 9440 const Value *Ptr = OpInfo.CallOperandVal; 9441 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 9442 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 9443 MachinePointerInfo(Ptr)); 9444 OutChains.push_back(Store); 9445 } else { 9446 // generate CopyFromRegs to associated registers. 9447 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 9448 if (Val.getOpcode() == ISD::MERGE_VALUES) { 9449 for (const SDValue &V : Val->op_values()) 9450 handleRegAssign(V); 9451 } else 9452 handleRegAssign(Val); 9453 } 9454 } 9455 } 9456 9457 // Set results. 9458 if (!ResultValues.empty()) { 9459 assert(CurResultType == ResultTypes.end() && 9460 "Mismatch in number of ResultTypes"); 9461 assert(ResultValues.size() == ResultTypes.size() && 9462 "Mismatch in number of output operands in asm result"); 9463 9464 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 9465 DAG.getVTList(ResultVTs), ResultValues); 9466 setValue(&Call, V); 9467 } 9468 9469 // Collect store chains. 9470 if (!OutChains.empty()) 9471 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 9472 9473 if (EmitEHLabels) { 9474 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 9475 } 9476 9477 // Only Update Root if inline assembly has a memory effect. 9478 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 9479 EmitEHLabels) 9480 DAG.setRoot(Chain); 9481 } 9482 9483 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 9484 const Twine &Message) { 9485 LLVMContext &Ctx = *DAG.getContext(); 9486 Ctx.emitError(&Call, Message); 9487 9488 // Make sure we leave the DAG in a valid state 9489 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9490 SmallVector<EVT, 1> ValueVTs; 9491 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 9492 9493 if (ValueVTs.empty()) 9494 return; 9495 9496 SmallVector<SDValue, 1> Ops; 9497 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 9498 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 9499 9500 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 9501 } 9502 9503 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 9504 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 9505 MVT::Other, getRoot(), 9506 getValue(I.getArgOperand(0)), 9507 DAG.getSrcValue(I.getArgOperand(0)))); 9508 } 9509 9510 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 9511 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9512 const DataLayout &DL = DAG.getDataLayout(); 9513 SDValue V = DAG.getVAArg( 9514 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 9515 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 9516 DL.getABITypeAlign(I.getType()).value()); 9517 DAG.setRoot(V.getValue(1)); 9518 9519 if (I.getType()->isPointerTy()) 9520 V = DAG.getPtrExtOrTrunc( 9521 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 9522 setValue(&I, V); 9523 } 9524 9525 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 9526 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 9527 MVT::Other, getRoot(), 9528 getValue(I.getArgOperand(0)), 9529 DAG.getSrcValue(I.getArgOperand(0)))); 9530 } 9531 9532 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 9533 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 9534 MVT::Other, getRoot(), 9535 getValue(I.getArgOperand(0)), 9536 getValue(I.getArgOperand(1)), 9537 DAG.getSrcValue(I.getArgOperand(0)), 9538 DAG.getSrcValue(I.getArgOperand(1)))); 9539 } 9540 9541 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 9542 const Instruction &I, 9543 SDValue Op) { 9544 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 9545 if (!Range) 9546 return Op; 9547 9548 ConstantRange CR = getConstantRangeFromMetadata(*Range); 9549 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 9550 return Op; 9551 9552 APInt Lo = CR.getUnsignedMin(); 9553 if (!Lo.isMinValue()) 9554 return Op; 9555 9556 APInt Hi = CR.getUnsignedMax(); 9557 unsigned Bits = std::max(Hi.getActiveBits(), 9558 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 9559 9560 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9561 9562 SDLoc SL = getCurSDLoc(); 9563 9564 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 9565 DAG.getValueType(SmallVT)); 9566 unsigned NumVals = Op.getNode()->getNumValues(); 9567 if (NumVals == 1) 9568 return ZExt; 9569 9570 SmallVector<SDValue, 4> Ops; 9571 9572 Ops.push_back(ZExt); 9573 for (unsigned I = 1; I != NumVals; ++I) 9574 Ops.push_back(Op.getValue(I)); 9575 9576 return DAG.getMergeValues(Ops, SL); 9577 } 9578 9579 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 9580 /// the call being lowered. 9581 /// 9582 /// This is a helper for lowering intrinsics that follow a target calling 9583 /// convention or require stack pointer adjustment. Only a subset of the 9584 /// intrinsic's operands need to participate in the calling convention. 9585 void SelectionDAGBuilder::populateCallLoweringInfo( 9586 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 9587 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 9588 bool IsPatchPoint) { 9589 TargetLowering::ArgListTy Args; 9590 Args.reserve(NumArgs); 9591 9592 // Populate the argument list. 9593 // Attributes for args start at offset 1, after the return attribute. 9594 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 9595 ArgI != ArgE; ++ArgI) { 9596 const Value *V = Call->getOperand(ArgI); 9597 9598 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 9599 9600 TargetLowering::ArgListEntry Entry; 9601 Entry.Node = getValue(V); 9602 Entry.Ty = V->getType(); 9603 Entry.setAttributes(Call, ArgI); 9604 Args.push_back(Entry); 9605 } 9606 9607 CLI.setDebugLoc(getCurSDLoc()) 9608 .setChain(getRoot()) 9609 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 9610 .setDiscardResult(Call->use_empty()) 9611 .setIsPatchPoint(IsPatchPoint) 9612 .setIsPreallocated( 9613 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 9614 } 9615 9616 /// Add a stack map intrinsic call's live variable operands to a stackmap 9617 /// or patchpoint target node's operand list. 9618 /// 9619 /// Constants are converted to TargetConstants purely as an optimization to 9620 /// avoid constant materialization and register allocation. 9621 /// 9622 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 9623 /// generate addess computation nodes, and so FinalizeISel can convert the 9624 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 9625 /// address materialization and register allocation, but may also be required 9626 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 9627 /// alloca in the entry block, then the runtime may assume that the alloca's 9628 /// StackMap location can be read immediately after compilation and that the 9629 /// location is valid at any point during execution (this is similar to the 9630 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 9631 /// only available in a register, then the runtime would need to trap when 9632 /// execution reaches the StackMap in order to read the alloca's location. 9633 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 9634 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 9635 SelectionDAGBuilder &Builder) { 9636 SelectionDAG &DAG = Builder.DAG; 9637 for (unsigned I = StartIdx; I < Call.arg_size(); I++) { 9638 SDValue Op = Builder.getValue(Call.getArgOperand(I)); 9639 9640 // Things on the stack are pointer-typed, meaning that they are already 9641 // legal and can be emitted directly to target nodes. 9642 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) { 9643 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType())); 9644 } else { 9645 // Otherwise emit a target independent node to be legalised. 9646 Ops.push_back(Builder.getValue(Call.getArgOperand(I))); 9647 } 9648 } 9649 } 9650 9651 /// Lower llvm.experimental.stackmap. 9652 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 9653 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>, 9654 // [live variables...]) 9655 9656 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 9657 9658 SDValue Chain, InGlue, Callee; 9659 SmallVector<SDValue, 32> Ops; 9660 9661 SDLoc DL = getCurSDLoc(); 9662 Callee = getValue(CI.getCalledOperand()); 9663 9664 // The stackmap intrinsic only records the live variables (the arguments 9665 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 9666 // intrinsic, this won't be lowered to a function call. This means we don't 9667 // have to worry about calling conventions and target specific lowering code. 9668 // Instead we perform the call lowering right here. 9669 // 9670 // chain, flag = CALLSEQ_START(chain, 0, 0) 9671 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 9672 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 9673 // 9674 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 9675 InGlue = Chain.getValue(1); 9676 9677 // Add the STACKMAP operands, starting with DAG house-keeping. 9678 Ops.push_back(Chain); 9679 Ops.push_back(InGlue); 9680 9681 // Add the <id>, <numShadowBytes> operands. 9682 // 9683 // These do not require legalisation, and can be emitted directly to target 9684 // constant nodes. 9685 SDValue ID = getValue(CI.getArgOperand(0)); 9686 assert(ID.getValueType() == MVT::i64); 9687 SDValue IDConst = DAG.getTargetConstant( 9688 cast<ConstantSDNode>(ID)->getZExtValue(), DL, ID.getValueType()); 9689 Ops.push_back(IDConst); 9690 9691 SDValue Shad = getValue(CI.getArgOperand(1)); 9692 assert(Shad.getValueType() == MVT::i32); 9693 SDValue ShadConst = DAG.getTargetConstant( 9694 cast<ConstantSDNode>(Shad)->getZExtValue(), DL, Shad.getValueType()); 9695 Ops.push_back(ShadConst); 9696 9697 // Add the live variables. 9698 addStackMapLiveVars(CI, 2, DL, Ops, *this); 9699 9700 // Create the STACKMAP node. 9701 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9702 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops); 9703 InGlue = Chain.getValue(1); 9704 9705 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL); 9706 9707 // Stackmaps don't generate values, so nothing goes into the NodeMap. 9708 9709 // Set the root to the target-lowered call chain. 9710 DAG.setRoot(Chain); 9711 9712 // Inform the Frame Information that we have a stackmap in this function. 9713 FuncInfo.MF->getFrameInfo().setHasStackMap(); 9714 } 9715 9716 /// Lower llvm.experimental.patchpoint directly to its target opcode. 9717 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 9718 const BasicBlock *EHPadBB) { 9719 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 9720 // i32 <numBytes>, 9721 // i8* <target>, 9722 // i32 <numArgs>, 9723 // [Args...], 9724 // [live variables...]) 9725 9726 CallingConv::ID CC = CB.getCallingConv(); 9727 bool IsAnyRegCC = CC == CallingConv::AnyReg; 9728 bool HasDef = !CB.getType()->isVoidTy(); 9729 SDLoc dl = getCurSDLoc(); 9730 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 9731 9732 // Handle immediate and symbolic callees. 9733 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 9734 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 9735 /*isTarget=*/true); 9736 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 9737 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 9738 SDLoc(SymbolicCallee), 9739 SymbolicCallee->getValueType(0)); 9740 9741 // Get the real number of arguments participating in the call <numArgs> 9742 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 9743 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 9744 9745 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 9746 // Intrinsics include all meta-operands up to but not including CC. 9747 unsigned NumMetaOpers = PatchPointOpers::CCPos; 9748 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 9749 "Not enough arguments provided to the patchpoint intrinsic"); 9750 9751 // For AnyRegCC the arguments are lowered later on manually. 9752 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 9753 Type *ReturnTy = 9754 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 9755 9756 TargetLowering::CallLoweringInfo CLI(DAG); 9757 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 9758 ReturnTy, true); 9759 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 9760 9761 SDNode *CallEnd = Result.second.getNode(); 9762 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 9763 CallEnd = CallEnd->getOperand(0).getNode(); 9764 9765 /// Get a call instruction from the call sequence chain. 9766 /// Tail calls are not allowed. 9767 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 9768 "Expected a callseq node."); 9769 SDNode *Call = CallEnd->getOperand(0).getNode(); 9770 bool HasGlue = Call->getGluedNode(); 9771 9772 // Replace the target specific call node with the patchable intrinsic. 9773 SmallVector<SDValue, 8> Ops; 9774 9775 // Push the chain. 9776 Ops.push_back(*(Call->op_begin())); 9777 9778 // Optionally, push the glue (if any). 9779 if (HasGlue) 9780 Ops.push_back(*(Call->op_end() - 1)); 9781 9782 // Push the register mask info. 9783 if (HasGlue) 9784 Ops.push_back(*(Call->op_end() - 2)); 9785 else 9786 Ops.push_back(*(Call->op_end() - 1)); 9787 9788 // Add the <id> and <numBytes> constants. 9789 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 9790 Ops.push_back(DAG.getTargetConstant( 9791 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 9792 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 9793 Ops.push_back(DAG.getTargetConstant( 9794 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 9795 MVT::i32)); 9796 9797 // Add the callee. 9798 Ops.push_back(Callee); 9799 9800 // Adjust <numArgs> to account for any arguments that have been passed on the 9801 // stack instead. 9802 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 9803 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 9804 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 9805 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 9806 9807 // Add the calling convention 9808 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 9809 9810 // Add the arguments we omitted previously. The register allocator should 9811 // place these in any free register. 9812 if (IsAnyRegCC) 9813 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 9814 Ops.push_back(getValue(CB.getArgOperand(i))); 9815 9816 // Push the arguments from the call instruction. 9817 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 9818 Ops.append(Call->op_begin() + 2, e); 9819 9820 // Push live variables for the stack map. 9821 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 9822 9823 SDVTList NodeTys; 9824 if (IsAnyRegCC && HasDef) { 9825 // Create the return types based on the intrinsic definition 9826 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9827 SmallVector<EVT, 3> ValueVTs; 9828 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 9829 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 9830 9831 // There is always a chain and a glue type at the end 9832 ValueVTs.push_back(MVT::Other); 9833 ValueVTs.push_back(MVT::Glue); 9834 NodeTys = DAG.getVTList(ValueVTs); 9835 } else 9836 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9837 9838 // Replace the target specific call node with a PATCHPOINT node. 9839 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops); 9840 9841 // Update the NodeMap. 9842 if (HasDef) { 9843 if (IsAnyRegCC) 9844 setValue(&CB, SDValue(PPV.getNode(), 0)); 9845 else 9846 setValue(&CB, Result.first); 9847 } 9848 9849 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 9850 // call sequence. Furthermore the location of the chain and glue can change 9851 // when the AnyReg calling convention is used and the intrinsic returns a 9852 // value. 9853 if (IsAnyRegCC && HasDef) { 9854 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 9855 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)}; 9856 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 9857 } else 9858 DAG.ReplaceAllUsesWith(Call, PPV.getNode()); 9859 DAG.DeleteNode(Call); 9860 9861 // Inform the Frame Information that we have a patchpoint in this function. 9862 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 9863 } 9864 9865 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 9866 unsigned Intrinsic) { 9867 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9868 SDValue Op1 = getValue(I.getArgOperand(0)); 9869 SDValue Op2; 9870 if (I.arg_size() > 1) 9871 Op2 = getValue(I.getArgOperand(1)); 9872 SDLoc dl = getCurSDLoc(); 9873 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 9874 SDValue Res; 9875 SDNodeFlags SDFlags; 9876 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 9877 SDFlags.copyFMF(*FPMO); 9878 9879 switch (Intrinsic) { 9880 case Intrinsic::vector_reduce_fadd: 9881 if (SDFlags.hasAllowReassociation()) 9882 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 9883 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 9884 SDFlags); 9885 else 9886 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 9887 break; 9888 case Intrinsic::vector_reduce_fmul: 9889 if (SDFlags.hasAllowReassociation()) 9890 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 9891 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 9892 SDFlags); 9893 else 9894 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 9895 break; 9896 case Intrinsic::vector_reduce_add: 9897 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 9898 break; 9899 case Intrinsic::vector_reduce_mul: 9900 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 9901 break; 9902 case Intrinsic::vector_reduce_and: 9903 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 9904 break; 9905 case Intrinsic::vector_reduce_or: 9906 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 9907 break; 9908 case Intrinsic::vector_reduce_xor: 9909 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 9910 break; 9911 case Intrinsic::vector_reduce_smax: 9912 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 9913 break; 9914 case Intrinsic::vector_reduce_smin: 9915 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 9916 break; 9917 case Intrinsic::vector_reduce_umax: 9918 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 9919 break; 9920 case Intrinsic::vector_reduce_umin: 9921 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 9922 break; 9923 case Intrinsic::vector_reduce_fmax: 9924 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 9925 break; 9926 case Intrinsic::vector_reduce_fmin: 9927 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 9928 break; 9929 default: 9930 llvm_unreachable("Unhandled vector reduce intrinsic"); 9931 } 9932 setValue(&I, Res); 9933 } 9934 9935 /// Returns an AttributeList representing the attributes applied to the return 9936 /// value of the given call. 9937 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9938 SmallVector<Attribute::AttrKind, 2> Attrs; 9939 if (CLI.RetSExt) 9940 Attrs.push_back(Attribute::SExt); 9941 if (CLI.RetZExt) 9942 Attrs.push_back(Attribute::ZExt); 9943 if (CLI.IsInReg) 9944 Attrs.push_back(Attribute::InReg); 9945 9946 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9947 Attrs); 9948 } 9949 9950 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9951 /// implementation, which just calls LowerCall. 9952 /// FIXME: When all targets are 9953 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9954 std::pair<SDValue, SDValue> 9955 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9956 // Handle the incoming return values from the call. 9957 CLI.Ins.clear(); 9958 Type *OrigRetTy = CLI.RetTy; 9959 SmallVector<EVT, 4> RetTys; 9960 SmallVector<uint64_t, 4> Offsets; 9961 auto &DL = CLI.DAG.getDataLayout(); 9962 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets, 0); 9963 9964 if (CLI.IsPostTypeLegalization) { 9965 // If we are lowering a libcall after legalization, split the return type. 9966 SmallVector<EVT, 4> OldRetTys; 9967 SmallVector<uint64_t, 4> OldOffsets; 9968 RetTys.swap(OldRetTys); 9969 Offsets.swap(OldOffsets); 9970 9971 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9972 EVT RetVT = OldRetTys[i]; 9973 uint64_t Offset = OldOffsets[i]; 9974 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9975 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9976 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9977 RetTys.append(NumRegs, RegisterVT); 9978 for (unsigned j = 0; j != NumRegs; ++j) 9979 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9980 } 9981 } 9982 9983 SmallVector<ISD::OutputArg, 4> Outs; 9984 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9985 9986 bool CanLowerReturn = 9987 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9988 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9989 9990 SDValue DemoteStackSlot; 9991 int DemoteStackIdx = -100; 9992 if (!CanLowerReturn) { 9993 // FIXME: equivalent assert? 9994 // assert(!CS.hasInAllocaArgument() && 9995 // "sret demotion is incompatible with inalloca"); 9996 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9997 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 9998 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9999 DemoteStackIdx = 10000 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 10001 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 10002 DL.getAllocaAddrSpace()); 10003 10004 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 10005 ArgListEntry Entry; 10006 Entry.Node = DemoteStackSlot; 10007 Entry.Ty = StackSlotPtrType; 10008 Entry.IsSExt = false; 10009 Entry.IsZExt = false; 10010 Entry.IsInReg = false; 10011 Entry.IsSRet = true; 10012 Entry.IsNest = false; 10013 Entry.IsByVal = false; 10014 Entry.IsByRef = false; 10015 Entry.IsReturned = false; 10016 Entry.IsSwiftSelf = false; 10017 Entry.IsSwiftAsync = false; 10018 Entry.IsSwiftError = false; 10019 Entry.IsCFGuardTarget = false; 10020 Entry.Alignment = Alignment; 10021 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 10022 CLI.NumFixedArgs += 1; 10023 CLI.getArgs()[0].IndirectType = CLI.RetTy; 10024 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 10025 10026 // sret demotion isn't compatible with tail-calls, since the sret argument 10027 // points into the callers stack frame. 10028 CLI.IsTailCall = false; 10029 } else { 10030 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10031 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL); 10032 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 10033 ISD::ArgFlagsTy Flags; 10034 if (NeedsRegBlock) { 10035 Flags.setInConsecutiveRegs(); 10036 if (I == RetTys.size() - 1) 10037 Flags.setInConsecutiveRegsLast(); 10038 } 10039 EVT VT = RetTys[I]; 10040 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10041 CLI.CallConv, VT); 10042 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10043 CLI.CallConv, VT); 10044 for (unsigned i = 0; i != NumRegs; ++i) { 10045 ISD::InputArg MyFlags; 10046 MyFlags.Flags = Flags; 10047 MyFlags.VT = RegisterVT; 10048 MyFlags.ArgVT = VT; 10049 MyFlags.Used = CLI.IsReturnValueUsed; 10050 if (CLI.RetTy->isPointerTy()) { 10051 MyFlags.Flags.setPointer(); 10052 MyFlags.Flags.setPointerAddrSpace( 10053 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 10054 } 10055 if (CLI.RetSExt) 10056 MyFlags.Flags.setSExt(); 10057 if (CLI.RetZExt) 10058 MyFlags.Flags.setZExt(); 10059 if (CLI.IsInReg) 10060 MyFlags.Flags.setInReg(); 10061 CLI.Ins.push_back(MyFlags); 10062 } 10063 } 10064 } 10065 10066 // We push in swifterror return as the last element of CLI.Ins. 10067 ArgListTy &Args = CLI.getArgs(); 10068 if (supportSwiftError()) { 10069 for (const ArgListEntry &Arg : Args) { 10070 if (Arg.IsSwiftError) { 10071 ISD::InputArg MyFlags; 10072 MyFlags.VT = getPointerTy(DL); 10073 MyFlags.ArgVT = EVT(getPointerTy(DL)); 10074 MyFlags.Flags.setSwiftError(); 10075 CLI.Ins.push_back(MyFlags); 10076 } 10077 } 10078 } 10079 10080 // Handle all of the outgoing arguments. 10081 CLI.Outs.clear(); 10082 CLI.OutVals.clear(); 10083 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 10084 SmallVector<EVT, 4> ValueVTs; 10085 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 10086 // FIXME: Split arguments if CLI.IsPostTypeLegalization 10087 Type *FinalType = Args[i].Ty; 10088 if (Args[i].IsByVal) 10089 FinalType = Args[i].IndirectType; 10090 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10091 FinalType, CLI.CallConv, CLI.IsVarArg, DL); 10092 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 10093 ++Value) { 10094 EVT VT = ValueVTs[Value]; 10095 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 10096 SDValue Op = SDValue(Args[i].Node.getNode(), 10097 Args[i].Node.getResNo() + Value); 10098 ISD::ArgFlagsTy Flags; 10099 10100 // Certain targets (such as MIPS), may have a different ABI alignment 10101 // for a type depending on the context. Give the target a chance to 10102 // specify the alignment it wants. 10103 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 10104 Flags.setOrigAlign(OriginalAlignment); 10105 10106 if (Args[i].Ty->isPointerTy()) { 10107 Flags.setPointer(); 10108 Flags.setPointerAddrSpace( 10109 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 10110 } 10111 if (Args[i].IsZExt) 10112 Flags.setZExt(); 10113 if (Args[i].IsSExt) 10114 Flags.setSExt(); 10115 if (Args[i].IsInReg) { 10116 // If we are using vectorcall calling convention, a structure that is 10117 // passed InReg - is surely an HVA 10118 if (CLI.CallConv == CallingConv::X86_VectorCall && 10119 isa<StructType>(FinalType)) { 10120 // The first value of a structure is marked 10121 if (0 == Value) 10122 Flags.setHvaStart(); 10123 Flags.setHva(); 10124 } 10125 // Set InReg Flag 10126 Flags.setInReg(); 10127 } 10128 if (Args[i].IsSRet) 10129 Flags.setSRet(); 10130 if (Args[i].IsSwiftSelf) 10131 Flags.setSwiftSelf(); 10132 if (Args[i].IsSwiftAsync) 10133 Flags.setSwiftAsync(); 10134 if (Args[i].IsSwiftError) 10135 Flags.setSwiftError(); 10136 if (Args[i].IsCFGuardTarget) 10137 Flags.setCFGuardTarget(); 10138 if (Args[i].IsByVal) 10139 Flags.setByVal(); 10140 if (Args[i].IsByRef) 10141 Flags.setByRef(); 10142 if (Args[i].IsPreallocated) { 10143 Flags.setPreallocated(); 10144 // Set the byval flag for CCAssignFn callbacks that don't know about 10145 // preallocated. This way we can know how many bytes we should've 10146 // allocated and how many bytes a callee cleanup function will pop. If 10147 // we port preallocated to more targets, we'll have to add custom 10148 // preallocated handling in the various CC lowering callbacks. 10149 Flags.setByVal(); 10150 } 10151 if (Args[i].IsInAlloca) { 10152 Flags.setInAlloca(); 10153 // Set the byval flag for CCAssignFn callbacks that don't know about 10154 // inalloca. This way we can know how many bytes we should've allocated 10155 // and how many bytes a callee cleanup function will pop. If we port 10156 // inalloca to more targets, we'll have to add custom inalloca handling 10157 // in the various CC lowering callbacks. 10158 Flags.setByVal(); 10159 } 10160 Align MemAlign; 10161 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 10162 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType); 10163 Flags.setByValSize(FrameSize); 10164 10165 // info is not there but there are cases it cannot get right. 10166 if (auto MA = Args[i].Alignment) 10167 MemAlign = *MA; 10168 else 10169 MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL)); 10170 } else if (auto MA = Args[i].Alignment) { 10171 MemAlign = *MA; 10172 } else { 10173 MemAlign = OriginalAlignment; 10174 } 10175 Flags.setMemAlign(MemAlign); 10176 if (Args[i].IsNest) 10177 Flags.setNest(); 10178 if (NeedsRegBlock) 10179 Flags.setInConsecutiveRegs(); 10180 10181 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10182 CLI.CallConv, VT); 10183 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10184 CLI.CallConv, VT); 10185 SmallVector<SDValue, 4> Parts(NumParts); 10186 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 10187 10188 if (Args[i].IsSExt) 10189 ExtendKind = ISD::SIGN_EXTEND; 10190 else if (Args[i].IsZExt) 10191 ExtendKind = ISD::ZERO_EXTEND; 10192 10193 // Conservatively only handle 'returned' on non-vectors that can be lowered, 10194 // for now. 10195 if (Args[i].IsReturned && !Op.getValueType().isVector() && 10196 CanLowerReturn) { 10197 assert((CLI.RetTy == Args[i].Ty || 10198 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 10199 CLI.RetTy->getPointerAddressSpace() == 10200 Args[i].Ty->getPointerAddressSpace())) && 10201 RetTys.size() == NumValues && "unexpected use of 'returned'"); 10202 // Before passing 'returned' to the target lowering code, ensure that 10203 // either the register MVT and the actual EVT are the same size or that 10204 // the return value and argument are extended in the same way; in these 10205 // cases it's safe to pass the argument register value unchanged as the 10206 // return register value (although it's at the target's option whether 10207 // to do so) 10208 // TODO: allow code generation to take advantage of partially preserved 10209 // registers rather than clobbering the entire register when the 10210 // parameter extension method is not compatible with the return 10211 // extension method 10212 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 10213 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 10214 CLI.RetZExt == Args[i].IsZExt)) 10215 Flags.setReturned(); 10216 } 10217 10218 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 10219 CLI.CallConv, ExtendKind); 10220 10221 for (unsigned j = 0; j != NumParts; ++j) { 10222 // if it isn't first piece, alignment must be 1 10223 // For scalable vectors the scalable part is currently handled 10224 // by individual targets, so we just use the known minimum size here. 10225 ISD::OutputArg MyFlags( 10226 Flags, Parts[j].getValueType().getSimpleVT(), VT, 10227 i < CLI.NumFixedArgs, i, 10228 j * Parts[j].getValueType().getStoreSize().getKnownMinValue()); 10229 if (NumParts > 1 && j == 0) 10230 MyFlags.Flags.setSplit(); 10231 else if (j != 0) { 10232 MyFlags.Flags.setOrigAlign(Align(1)); 10233 if (j == NumParts - 1) 10234 MyFlags.Flags.setSplitEnd(); 10235 } 10236 10237 CLI.Outs.push_back(MyFlags); 10238 CLI.OutVals.push_back(Parts[j]); 10239 } 10240 10241 if (NeedsRegBlock && Value == NumValues - 1) 10242 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 10243 } 10244 } 10245 10246 SmallVector<SDValue, 4> InVals; 10247 CLI.Chain = LowerCall(CLI, InVals); 10248 10249 // Update CLI.InVals to use outside of this function. 10250 CLI.InVals = InVals; 10251 10252 // Verify that the target's LowerCall behaved as expected. 10253 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 10254 "LowerCall didn't return a valid chain!"); 10255 assert((!CLI.IsTailCall || InVals.empty()) && 10256 "LowerCall emitted a return value for a tail call!"); 10257 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 10258 "LowerCall didn't emit the correct number of values!"); 10259 10260 // For a tail call, the return value is merely live-out and there aren't 10261 // any nodes in the DAG representing it. Return a special value to 10262 // indicate that a tail call has been emitted and no more Instructions 10263 // should be processed in the current block. 10264 if (CLI.IsTailCall) { 10265 CLI.DAG.setRoot(CLI.Chain); 10266 return std::make_pair(SDValue(), SDValue()); 10267 } 10268 10269 #ifndef NDEBUG 10270 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 10271 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 10272 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 10273 "LowerCall emitted a value with the wrong type!"); 10274 } 10275 #endif 10276 10277 SmallVector<SDValue, 4> ReturnValues; 10278 if (!CanLowerReturn) { 10279 // The instruction result is the result of loading from the 10280 // hidden sret parameter. 10281 SmallVector<EVT, 1> PVTs; 10282 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 10283 10284 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 10285 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 10286 EVT PtrVT = PVTs[0]; 10287 10288 unsigned NumValues = RetTys.size(); 10289 ReturnValues.resize(NumValues); 10290 SmallVector<SDValue, 4> Chains(NumValues); 10291 10292 // An aggregate return value cannot wrap around the address space, so 10293 // offsets to its parts don't wrap either. 10294 SDNodeFlags Flags; 10295 Flags.setNoUnsignedWrap(true); 10296 10297 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10298 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 10299 for (unsigned i = 0; i < NumValues; ++i) { 10300 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 10301 CLI.DAG.getConstant(Offsets[i], CLI.DL, 10302 PtrVT), Flags); 10303 SDValue L = CLI.DAG.getLoad( 10304 RetTys[i], CLI.DL, CLI.Chain, Add, 10305 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 10306 DemoteStackIdx, Offsets[i]), 10307 HiddenSRetAlign); 10308 ReturnValues[i] = L; 10309 Chains[i] = L.getValue(1); 10310 } 10311 10312 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 10313 } else { 10314 // Collect the legal value parts into potentially illegal values 10315 // that correspond to the original function's return values. 10316 std::optional<ISD::NodeType> AssertOp; 10317 if (CLI.RetSExt) 10318 AssertOp = ISD::AssertSext; 10319 else if (CLI.RetZExt) 10320 AssertOp = ISD::AssertZext; 10321 unsigned CurReg = 0; 10322 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 10323 EVT VT = RetTys[I]; 10324 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10325 CLI.CallConv, VT); 10326 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10327 CLI.CallConv, VT); 10328 10329 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 10330 NumRegs, RegisterVT, VT, nullptr, 10331 CLI.CallConv, AssertOp)); 10332 CurReg += NumRegs; 10333 } 10334 10335 // For a function returning void, there is no return value. We can't create 10336 // such a node, so we just return a null return value in that case. In 10337 // that case, nothing will actually look at the value. 10338 if (ReturnValues.empty()) 10339 return std::make_pair(SDValue(), CLI.Chain); 10340 } 10341 10342 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 10343 CLI.DAG.getVTList(RetTys), ReturnValues); 10344 return std::make_pair(Res, CLI.Chain); 10345 } 10346 10347 /// Places new result values for the node in Results (their number 10348 /// and types must exactly match those of the original return values of 10349 /// the node), or leaves Results empty, which indicates that the node is not 10350 /// to be custom lowered after all. 10351 void TargetLowering::LowerOperationWrapper(SDNode *N, 10352 SmallVectorImpl<SDValue> &Results, 10353 SelectionDAG &DAG) const { 10354 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 10355 10356 if (!Res.getNode()) 10357 return; 10358 10359 // If the original node has one result, take the return value from 10360 // LowerOperation as is. It might not be result number 0. 10361 if (N->getNumValues() == 1) { 10362 Results.push_back(Res); 10363 return; 10364 } 10365 10366 // If the original node has multiple results, then the return node should 10367 // have the same number of results. 10368 assert((N->getNumValues() == Res->getNumValues()) && 10369 "Lowering returned the wrong number of results!"); 10370 10371 // Places new result values base on N result number. 10372 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 10373 Results.push_back(Res.getValue(I)); 10374 } 10375 10376 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10377 llvm_unreachable("LowerOperation not implemented for this target!"); 10378 } 10379 10380 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, 10381 unsigned Reg, 10382 ISD::NodeType ExtendType) { 10383 SDValue Op = getNonRegisterValue(V); 10384 assert((Op.getOpcode() != ISD::CopyFromReg || 10385 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 10386 "Copy from a reg to the same reg!"); 10387 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 10388 10389 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10390 // If this is an InlineAsm we have to match the registers required, not the 10391 // notional registers required by the type. 10392 10393 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 10394 std::nullopt); // This is not an ABI copy. 10395 SDValue Chain = DAG.getEntryNode(); 10396 10397 if (ExtendType == ISD::ANY_EXTEND) { 10398 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V); 10399 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end()) 10400 ExtendType = PreferredExtendIt->second; 10401 } 10402 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 10403 PendingExports.push_back(Chain); 10404 } 10405 10406 #include "llvm/CodeGen/SelectionDAGISel.h" 10407 10408 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 10409 /// entry block, return true. This includes arguments used by switches, since 10410 /// the switch may expand into multiple basic blocks. 10411 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 10412 // With FastISel active, we may be splitting blocks, so force creation 10413 // of virtual registers for all non-dead arguments. 10414 if (FastISel) 10415 return A->use_empty(); 10416 10417 const BasicBlock &Entry = A->getParent()->front(); 10418 for (const User *U : A->users()) 10419 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 10420 return false; // Use not in entry block. 10421 10422 return true; 10423 } 10424 10425 using ArgCopyElisionMapTy = 10426 DenseMap<const Argument *, 10427 std::pair<const AllocaInst *, const StoreInst *>>; 10428 10429 /// Scan the entry block of the function in FuncInfo for arguments that look 10430 /// like copies into a local alloca. Record any copied arguments in 10431 /// ArgCopyElisionCandidates. 10432 static void 10433 findArgumentCopyElisionCandidates(const DataLayout &DL, 10434 FunctionLoweringInfo *FuncInfo, 10435 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 10436 // Record the state of every static alloca used in the entry block. Argument 10437 // allocas are all used in the entry block, so we need approximately as many 10438 // entries as we have arguments. 10439 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 10440 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 10441 unsigned NumArgs = FuncInfo->Fn->arg_size(); 10442 StaticAllocas.reserve(NumArgs * 2); 10443 10444 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 10445 if (!V) 10446 return nullptr; 10447 V = V->stripPointerCasts(); 10448 const auto *AI = dyn_cast<AllocaInst>(V); 10449 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 10450 return nullptr; 10451 auto Iter = StaticAllocas.insert({AI, Unknown}); 10452 return &Iter.first->second; 10453 }; 10454 10455 // Look for stores of arguments to static allocas. Look through bitcasts and 10456 // GEPs to handle type coercions, as long as the alloca is fully initialized 10457 // by the store. Any non-store use of an alloca escapes it and any subsequent 10458 // unanalyzed store might write it. 10459 // FIXME: Handle structs initialized with multiple stores. 10460 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 10461 // Look for stores, and handle non-store uses conservatively. 10462 const auto *SI = dyn_cast<StoreInst>(&I); 10463 if (!SI) { 10464 // We will look through cast uses, so ignore them completely. 10465 if (I.isCast()) 10466 continue; 10467 // Ignore debug info and pseudo op intrinsics, they don't escape or store 10468 // to allocas. 10469 if (I.isDebugOrPseudoInst()) 10470 continue; 10471 // This is an unknown instruction. Assume it escapes or writes to all 10472 // static alloca operands. 10473 for (const Use &U : I.operands()) { 10474 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 10475 *Info = StaticAllocaInfo::Clobbered; 10476 } 10477 continue; 10478 } 10479 10480 // If the stored value is a static alloca, mark it as escaped. 10481 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 10482 *Info = StaticAllocaInfo::Clobbered; 10483 10484 // Check if the destination is a static alloca. 10485 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 10486 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 10487 if (!Info) 10488 continue; 10489 const AllocaInst *AI = cast<AllocaInst>(Dst); 10490 10491 // Skip allocas that have been initialized or clobbered. 10492 if (*Info != StaticAllocaInfo::Unknown) 10493 continue; 10494 10495 // Check if the stored value is an argument, and that this store fully 10496 // initializes the alloca. 10497 // If the argument type has padding bits we can't directly forward a pointer 10498 // as the upper bits may contain garbage. 10499 // Don't elide copies from the same argument twice. 10500 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 10501 const auto *Arg = dyn_cast<Argument>(Val); 10502 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 10503 Arg->getType()->isEmptyTy() || 10504 DL.getTypeStoreSize(Arg->getType()) != 10505 DL.getTypeAllocSize(AI->getAllocatedType()) || 10506 !DL.typeSizeEqualsStoreSize(Arg->getType()) || 10507 ArgCopyElisionCandidates.count(Arg)) { 10508 *Info = StaticAllocaInfo::Clobbered; 10509 continue; 10510 } 10511 10512 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 10513 << '\n'); 10514 10515 // Mark this alloca and store for argument copy elision. 10516 *Info = StaticAllocaInfo::Elidable; 10517 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 10518 10519 // Stop scanning if we've seen all arguments. This will happen early in -O0 10520 // builds, which is useful, because -O0 builds have large entry blocks and 10521 // many allocas. 10522 if (ArgCopyElisionCandidates.size() == NumArgs) 10523 break; 10524 } 10525 } 10526 10527 /// Try to elide argument copies from memory into a local alloca. Succeeds if 10528 /// ArgVal is a load from a suitable fixed stack object. 10529 static void tryToElideArgumentCopy( 10530 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 10531 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 10532 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 10533 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 10534 SDValue ArgVal, bool &ArgHasUses) { 10535 // Check if this is a load from a fixed stack object. 10536 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 10537 if (!LNode) 10538 return; 10539 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 10540 if (!FINode) 10541 return; 10542 10543 // Check that the fixed stack object is the right size and alignment. 10544 // Look at the alignment that the user wrote on the alloca instead of looking 10545 // at the stack object. 10546 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 10547 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 10548 const AllocaInst *AI = ArgCopyIter->second.first; 10549 int FixedIndex = FINode->getIndex(); 10550 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 10551 int OldIndex = AllocaIndex; 10552 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 10553 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 10554 LLVM_DEBUG( 10555 dbgs() << " argument copy elision failed due to bad fixed stack " 10556 "object size\n"); 10557 return; 10558 } 10559 Align RequiredAlignment = AI->getAlign(); 10560 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 10561 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 10562 "greater than stack argument alignment (" 10563 << DebugStr(RequiredAlignment) << " vs " 10564 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 10565 return; 10566 } 10567 10568 // Perform the elision. Delete the old stack object and replace its only use 10569 // in the variable info map. Mark the stack object as mutable. 10570 LLVM_DEBUG({ 10571 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 10572 << " Replacing frame index " << OldIndex << " with " << FixedIndex 10573 << '\n'; 10574 }); 10575 MFI.RemoveStackObject(OldIndex); 10576 MFI.setIsImmutableObjectIndex(FixedIndex, false); 10577 AllocaIndex = FixedIndex; 10578 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 10579 Chains.push_back(ArgVal.getValue(1)); 10580 10581 // Avoid emitting code for the store implementing the copy. 10582 const StoreInst *SI = ArgCopyIter->second.second; 10583 ElidedArgCopyInstrs.insert(SI); 10584 10585 // Check for uses of the argument again so that we can avoid exporting ArgVal 10586 // if it is't used by anything other than the store. 10587 for (const Value *U : Arg.users()) { 10588 if (U != SI) { 10589 ArgHasUses = true; 10590 break; 10591 } 10592 } 10593 } 10594 10595 void SelectionDAGISel::LowerArguments(const Function &F) { 10596 SelectionDAG &DAG = SDB->DAG; 10597 SDLoc dl = SDB->getCurSDLoc(); 10598 const DataLayout &DL = DAG.getDataLayout(); 10599 SmallVector<ISD::InputArg, 16> Ins; 10600 10601 // In Naked functions we aren't going to save any registers. 10602 if (F.hasFnAttribute(Attribute::Naked)) 10603 return; 10604 10605 if (!FuncInfo->CanLowerReturn) { 10606 // Put in an sret pointer parameter before all the other parameters. 10607 SmallVector<EVT, 1> ValueVTs; 10608 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10609 F.getReturnType()->getPointerTo( 10610 DAG.getDataLayout().getAllocaAddrSpace()), 10611 ValueVTs); 10612 10613 // NOTE: Assuming that a pointer will never break down to more than one VT 10614 // or one register. 10615 ISD::ArgFlagsTy Flags; 10616 Flags.setSRet(); 10617 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 10618 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 10619 ISD::InputArg::NoArgIndex, 0); 10620 Ins.push_back(RetArg); 10621 } 10622 10623 // Look for stores of arguments to static allocas. Mark such arguments with a 10624 // flag to ask the target to give us the memory location of that argument if 10625 // available. 10626 ArgCopyElisionMapTy ArgCopyElisionCandidates; 10627 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 10628 ArgCopyElisionCandidates); 10629 10630 // Set up the incoming argument description vector. 10631 for (const Argument &Arg : F.args()) { 10632 unsigned ArgNo = Arg.getArgNo(); 10633 SmallVector<EVT, 4> ValueVTs; 10634 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10635 bool isArgValueUsed = !Arg.use_empty(); 10636 unsigned PartBase = 0; 10637 Type *FinalType = Arg.getType(); 10638 if (Arg.hasAttribute(Attribute::ByVal)) 10639 FinalType = Arg.getParamByValType(); 10640 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 10641 FinalType, F.getCallingConv(), F.isVarArg(), DL); 10642 for (unsigned Value = 0, NumValues = ValueVTs.size(); 10643 Value != NumValues; ++Value) { 10644 EVT VT = ValueVTs[Value]; 10645 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 10646 ISD::ArgFlagsTy Flags; 10647 10648 10649 if (Arg.getType()->isPointerTy()) { 10650 Flags.setPointer(); 10651 Flags.setPointerAddrSpace( 10652 cast<PointerType>(Arg.getType())->getAddressSpace()); 10653 } 10654 if (Arg.hasAttribute(Attribute::ZExt)) 10655 Flags.setZExt(); 10656 if (Arg.hasAttribute(Attribute::SExt)) 10657 Flags.setSExt(); 10658 if (Arg.hasAttribute(Attribute::InReg)) { 10659 // If we are using vectorcall calling convention, a structure that is 10660 // passed InReg - is surely an HVA 10661 if (F.getCallingConv() == CallingConv::X86_VectorCall && 10662 isa<StructType>(Arg.getType())) { 10663 // The first value of a structure is marked 10664 if (0 == Value) 10665 Flags.setHvaStart(); 10666 Flags.setHva(); 10667 } 10668 // Set InReg Flag 10669 Flags.setInReg(); 10670 } 10671 if (Arg.hasAttribute(Attribute::StructRet)) 10672 Flags.setSRet(); 10673 if (Arg.hasAttribute(Attribute::SwiftSelf)) 10674 Flags.setSwiftSelf(); 10675 if (Arg.hasAttribute(Attribute::SwiftAsync)) 10676 Flags.setSwiftAsync(); 10677 if (Arg.hasAttribute(Attribute::SwiftError)) 10678 Flags.setSwiftError(); 10679 if (Arg.hasAttribute(Attribute::ByVal)) 10680 Flags.setByVal(); 10681 if (Arg.hasAttribute(Attribute::ByRef)) 10682 Flags.setByRef(); 10683 if (Arg.hasAttribute(Attribute::InAlloca)) { 10684 Flags.setInAlloca(); 10685 // Set the byval flag for CCAssignFn callbacks that don't know about 10686 // inalloca. This way we can know how many bytes we should've allocated 10687 // and how many bytes a callee cleanup function will pop. If we port 10688 // inalloca to more targets, we'll have to add custom inalloca handling 10689 // in the various CC lowering callbacks. 10690 Flags.setByVal(); 10691 } 10692 if (Arg.hasAttribute(Attribute::Preallocated)) { 10693 Flags.setPreallocated(); 10694 // Set the byval flag for CCAssignFn callbacks that don't know about 10695 // preallocated. This way we can know how many bytes we should've 10696 // allocated and how many bytes a callee cleanup function will pop. If 10697 // we port preallocated to more targets, we'll have to add custom 10698 // preallocated handling in the various CC lowering callbacks. 10699 Flags.setByVal(); 10700 } 10701 10702 // Certain targets (such as MIPS), may have a different ABI alignment 10703 // for a type depending on the context. Give the target a chance to 10704 // specify the alignment it wants. 10705 const Align OriginalAlignment( 10706 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 10707 Flags.setOrigAlign(OriginalAlignment); 10708 10709 Align MemAlign; 10710 Type *ArgMemTy = nullptr; 10711 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 10712 Flags.isByRef()) { 10713 if (!ArgMemTy) 10714 ArgMemTy = Arg.getPointeeInMemoryValueType(); 10715 10716 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 10717 10718 // For in-memory arguments, size and alignment should be passed from FE. 10719 // BE will guess if this info is not there but there are cases it cannot 10720 // get right. 10721 if (auto ParamAlign = Arg.getParamStackAlign()) 10722 MemAlign = *ParamAlign; 10723 else if ((ParamAlign = Arg.getParamAlign())) 10724 MemAlign = *ParamAlign; 10725 else 10726 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 10727 if (Flags.isByRef()) 10728 Flags.setByRefSize(MemSize); 10729 else 10730 Flags.setByValSize(MemSize); 10731 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 10732 MemAlign = *ParamAlign; 10733 } else { 10734 MemAlign = OriginalAlignment; 10735 } 10736 Flags.setMemAlign(MemAlign); 10737 10738 if (Arg.hasAttribute(Attribute::Nest)) 10739 Flags.setNest(); 10740 if (NeedsRegBlock) 10741 Flags.setInConsecutiveRegs(); 10742 if (ArgCopyElisionCandidates.count(&Arg)) 10743 Flags.setCopyElisionCandidate(); 10744 if (Arg.hasAttribute(Attribute::Returned)) 10745 Flags.setReturned(); 10746 10747 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 10748 *CurDAG->getContext(), F.getCallingConv(), VT); 10749 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 10750 *CurDAG->getContext(), F.getCallingConv(), VT); 10751 for (unsigned i = 0; i != NumRegs; ++i) { 10752 // For scalable vectors, use the minimum size; individual targets 10753 // are responsible for handling scalable vector arguments and 10754 // return values. 10755 ISD::InputArg MyFlags( 10756 Flags, RegisterVT, VT, isArgValueUsed, ArgNo, 10757 PartBase + i * RegisterVT.getStoreSize().getKnownMinValue()); 10758 if (NumRegs > 1 && i == 0) 10759 MyFlags.Flags.setSplit(); 10760 // if it isn't first piece, alignment must be 1 10761 else if (i > 0) { 10762 MyFlags.Flags.setOrigAlign(Align(1)); 10763 if (i == NumRegs - 1) 10764 MyFlags.Flags.setSplitEnd(); 10765 } 10766 Ins.push_back(MyFlags); 10767 } 10768 if (NeedsRegBlock && Value == NumValues - 1) 10769 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 10770 PartBase += VT.getStoreSize().getKnownMinValue(); 10771 } 10772 } 10773 10774 // Call the target to set up the argument values. 10775 SmallVector<SDValue, 8> InVals; 10776 SDValue NewRoot = TLI->LowerFormalArguments( 10777 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 10778 10779 // Verify that the target's LowerFormalArguments behaved as expected. 10780 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 10781 "LowerFormalArguments didn't return a valid chain!"); 10782 assert(InVals.size() == Ins.size() && 10783 "LowerFormalArguments didn't emit the correct number of values!"); 10784 LLVM_DEBUG({ 10785 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 10786 assert(InVals[i].getNode() && 10787 "LowerFormalArguments emitted a null value!"); 10788 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 10789 "LowerFormalArguments emitted a value with the wrong type!"); 10790 } 10791 }); 10792 10793 // Update the DAG with the new chain value resulting from argument lowering. 10794 DAG.setRoot(NewRoot); 10795 10796 // Set up the argument values. 10797 unsigned i = 0; 10798 if (!FuncInfo->CanLowerReturn) { 10799 // Create a virtual register for the sret pointer, and put in a copy 10800 // from the sret argument into it. 10801 SmallVector<EVT, 1> ValueVTs; 10802 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10803 F.getReturnType()->getPointerTo( 10804 DAG.getDataLayout().getAllocaAddrSpace()), 10805 ValueVTs); 10806 MVT VT = ValueVTs[0].getSimpleVT(); 10807 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 10808 std::optional<ISD::NodeType> AssertOp; 10809 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 10810 nullptr, F.getCallingConv(), AssertOp); 10811 10812 MachineFunction& MF = SDB->DAG.getMachineFunction(); 10813 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 10814 Register SRetReg = 10815 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 10816 FuncInfo->DemoteRegister = SRetReg; 10817 NewRoot = 10818 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 10819 DAG.setRoot(NewRoot); 10820 10821 // i indexes lowered arguments. Bump it past the hidden sret argument. 10822 ++i; 10823 } 10824 10825 SmallVector<SDValue, 4> Chains; 10826 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 10827 for (const Argument &Arg : F.args()) { 10828 SmallVector<SDValue, 4> ArgValues; 10829 SmallVector<EVT, 4> ValueVTs; 10830 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10831 unsigned NumValues = ValueVTs.size(); 10832 if (NumValues == 0) 10833 continue; 10834 10835 bool ArgHasUses = !Arg.use_empty(); 10836 10837 // Elide the copying store if the target loaded this argument from a 10838 // suitable fixed stack object. 10839 if (Ins[i].Flags.isCopyElisionCandidate()) { 10840 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 10841 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 10842 InVals[i], ArgHasUses); 10843 } 10844 10845 // If this argument is unused then remember its value. It is used to generate 10846 // debugging information. 10847 bool isSwiftErrorArg = 10848 TLI->supportSwiftError() && 10849 Arg.hasAttribute(Attribute::SwiftError); 10850 if (!ArgHasUses && !isSwiftErrorArg) { 10851 SDB->setUnusedArgValue(&Arg, InVals[i]); 10852 10853 // Also remember any frame index for use in FastISel. 10854 if (FrameIndexSDNode *FI = 10855 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 10856 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10857 } 10858 10859 for (unsigned Val = 0; Val != NumValues; ++Val) { 10860 EVT VT = ValueVTs[Val]; 10861 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 10862 F.getCallingConv(), VT); 10863 unsigned NumParts = TLI->getNumRegistersForCallingConv( 10864 *CurDAG->getContext(), F.getCallingConv(), VT); 10865 10866 // Even an apparent 'unused' swifterror argument needs to be returned. So 10867 // we do generate a copy for it that can be used on return from the 10868 // function. 10869 if (ArgHasUses || isSwiftErrorArg) { 10870 std::optional<ISD::NodeType> AssertOp; 10871 if (Arg.hasAttribute(Attribute::SExt)) 10872 AssertOp = ISD::AssertSext; 10873 else if (Arg.hasAttribute(Attribute::ZExt)) 10874 AssertOp = ISD::AssertZext; 10875 10876 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 10877 PartVT, VT, nullptr, 10878 F.getCallingConv(), AssertOp)); 10879 } 10880 10881 i += NumParts; 10882 } 10883 10884 // We don't need to do anything else for unused arguments. 10885 if (ArgValues.empty()) 10886 continue; 10887 10888 // Note down frame index. 10889 if (FrameIndexSDNode *FI = 10890 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 10891 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10892 10893 SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues), 10894 SDB->getCurSDLoc()); 10895 10896 SDB->setValue(&Arg, Res); 10897 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 10898 // We want to associate the argument with the frame index, among 10899 // involved operands, that correspond to the lowest address. The 10900 // getCopyFromParts function, called earlier, is swapping the order of 10901 // the operands to BUILD_PAIR depending on endianness. The result of 10902 // that swapping is that the least significant bits of the argument will 10903 // be in the first operand of the BUILD_PAIR node, and the most 10904 // significant bits will be in the second operand. 10905 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 10906 if (LoadSDNode *LNode = 10907 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 10908 if (FrameIndexSDNode *FI = 10909 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 10910 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10911 } 10912 10913 // Analyses past this point are naive and don't expect an assertion. 10914 if (Res.getOpcode() == ISD::AssertZext) 10915 Res = Res.getOperand(0); 10916 10917 // Update the SwiftErrorVRegDefMap. 10918 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 10919 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10920 if (Register::isVirtualRegister(Reg)) 10921 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 10922 Reg); 10923 } 10924 10925 // If this argument is live outside of the entry block, insert a copy from 10926 // wherever we got it to the vreg that other BB's will reference it as. 10927 if (Res.getOpcode() == ISD::CopyFromReg) { 10928 // If we can, though, try to skip creating an unnecessary vreg. 10929 // FIXME: This isn't very clean... it would be nice to make this more 10930 // general. 10931 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10932 if (Register::isVirtualRegister(Reg)) { 10933 FuncInfo->ValueMap[&Arg] = Reg; 10934 continue; 10935 } 10936 } 10937 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 10938 FuncInfo->InitializeRegForValue(&Arg); 10939 SDB->CopyToExportRegsIfNeeded(&Arg); 10940 } 10941 } 10942 10943 if (!Chains.empty()) { 10944 Chains.push_back(NewRoot); 10945 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 10946 } 10947 10948 DAG.setRoot(NewRoot); 10949 10950 assert(i == InVals.size() && "Argument register count mismatch!"); 10951 10952 // If any argument copy elisions occurred and we have debug info, update the 10953 // stale frame indices used in the dbg.declare variable info table. 10954 if (!ArgCopyElisionFrameIndexMap.empty()) { 10955 for (MachineFunction::VariableDbgInfo &VI : 10956 MF->getInStackSlotVariableDbgInfo()) { 10957 auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot()); 10958 if (I != ArgCopyElisionFrameIndexMap.end()) 10959 VI.updateStackSlot(I->second); 10960 } 10961 } 10962 10963 // Finally, if the target has anything special to do, allow it to do so. 10964 emitFunctionEntryCode(); 10965 } 10966 10967 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 10968 /// ensure constants are generated when needed. Remember the virtual registers 10969 /// that need to be added to the Machine PHI nodes as input. We cannot just 10970 /// directly add them, because expansion might result in multiple MBB's for one 10971 /// BB. As such, the start of the BB might correspond to a different MBB than 10972 /// the end. 10973 void 10974 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 10975 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10976 10977 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 10978 10979 // Check PHI nodes in successors that expect a value to be available from this 10980 // block. 10981 for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) { 10982 if (!isa<PHINode>(SuccBB->begin())) continue; 10983 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 10984 10985 // If this terminator has multiple identical successors (common for 10986 // switches), only handle each succ once. 10987 if (!SuccsHandled.insert(SuccMBB).second) 10988 continue; 10989 10990 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 10991 10992 // At this point we know that there is a 1-1 correspondence between LLVM PHI 10993 // nodes and Machine PHI nodes, but the incoming operands have not been 10994 // emitted yet. 10995 for (const PHINode &PN : SuccBB->phis()) { 10996 // Ignore dead phi's. 10997 if (PN.use_empty()) 10998 continue; 10999 11000 // Skip empty types 11001 if (PN.getType()->isEmptyTy()) 11002 continue; 11003 11004 unsigned Reg; 11005 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 11006 11007 if (const auto *C = dyn_cast<Constant>(PHIOp)) { 11008 unsigned &RegOut = ConstantsOut[C]; 11009 if (RegOut == 0) { 11010 RegOut = FuncInfo.CreateRegs(C); 11011 // We need to zero/sign extend ConstantInt phi operands to match 11012 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo. 11013 ISD::NodeType ExtendType = ISD::ANY_EXTEND; 11014 if (auto *CI = dyn_cast<ConstantInt>(C)) 11015 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND 11016 : ISD::ZERO_EXTEND; 11017 CopyValueToVirtualRegister(C, RegOut, ExtendType); 11018 } 11019 Reg = RegOut; 11020 } else { 11021 DenseMap<const Value *, Register>::iterator I = 11022 FuncInfo.ValueMap.find(PHIOp); 11023 if (I != FuncInfo.ValueMap.end()) 11024 Reg = I->second; 11025 else { 11026 assert(isa<AllocaInst>(PHIOp) && 11027 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 11028 "Didn't codegen value into a register!??"); 11029 Reg = FuncInfo.CreateRegs(PHIOp); 11030 CopyValueToVirtualRegister(PHIOp, Reg); 11031 } 11032 } 11033 11034 // Remember that this register needs to added to the machine PHI node as 11035 // the input for this MBB. 11036 SmallVector<EVT, 4> ValueVTs; 11037 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 11038 for (EVT VT : ValueVTs) { 11039 const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 11040 for (unsigned i = 0; i != NumRegisters; ++i) 11041 FuncInfo.PHINodesToUpdate.push_back( 11042 std::make_pair(&*MBBI++, Reg + i)); 11043 Reg += NumRegisters; 11044 } 11045 } 11046 } 11047 11048 ConstantsOut.clear(); 11049 } 11050 11051 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 11052 MachineFunction::iterator I(MBB); 11053 if (++I == FuncInfo.MF->end()) 11054 return nullptr; 11055 return &*I; 11056 } 11057 11058 /// During lowering new call nodes can be created (such as memset, etc.). 11059 /// Those will become new roots of the current DAG, but complications arise 11060 /// when they are tail calls. In such cases, the call lowering will update 11061 /// the root, but the builder still needs to know that a tail call has been 11062 /// lowered in order to avoid generating an additional return. 11063 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 11064 // If the node is null, we do have a tail call. 11065 if (MaybeTC.getNode() != nullptr) 11066 DAG.setRoot(MaybeTC); 11067 else 11068 HasTailCall = true; 11069 } 11070 11071 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 11072 MachineBasicBlock *SwitchMBB, 11073 MachineBasicBlock *DefaultMBB) { 11074 MachineFunction *CurMF = FuncInfo.MF; 11075 MachineBasicBlock *NextMBB = nullptr; 11076 MachineFunction::iterator BBI(W.MBB); 11077 if (++BBI != FuncInfo.MF->end()) 11078 NextMBB = &*BBI; 11079 11080 unsigned Size = W.LastCluster - W.FirstCluster + 1; 11081 11082 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11083 11084 if (Size == 2 && W.MBB == SwitchMBB) { 11085 // If any two of the cases has the same destination, and if one value 11086 // is the same as the other, but has one bit unset that the other has set, 11087 // use bit manipulation to do two compares at once. For example: 11088 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 11089 // TODO: This could be extended to merge any 2 cases in switches with 3 11090 // cases. 11091 // TODO: Handle cases where W.CaseBB != SwitchBB. 11092 CaseCluster &Small = *W.FirstCluster; 11093 CaseCluster &Big = *W.LastCluster; 11094 11095 if (Small.Low == Small.High && Big.Low == Big.High && 11096 Small.MBB == Big.MBB) { 11097 const APInt &SmallValue = Small.Low->getValue(); 11098 const APInt &BigValue = Big.Low->getValue(); 11099 11100 // Check that there is only one bit different. 11101 APInt CommonBit = BigValue ^ SmallValue; 11102 if (CommonBit.isPowerOf2()) { 11103 SDValue CondLHS = getValue(Cond); 11104 EVT VT = CondLHS.getValueType(); 11105 SDLoc DL = getCurSDLoc(); 11106 11107 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 11108 DAG.getConstant(CommonBit, DL, VT)); 11109 SDValue Cond = DAG.getSetCC( 11110 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 11111 ISD::SETEQ); 11112 11113 // Update successor info. 11114 // Both Small and Big will jump to Small.BB, so we sum up the 11115 // probabilities. 11116 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 11117 if (BPI) 11118 addSuccessorWithProb( 11119 SwitchMBB, DefaultMBB, 11120 // The default destination is the first successor in IR. 11121 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 11122 else 11123 addSuccessorWithProb(SwitchMBB, DefaultMBB); 11124 11125 // Insert the true branch. 11126 SDValue BrCond = 11127 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 11128 DAG.getBasicBlock(Small.MBB)); 11129 // Insert the false branch. 11130 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 11131 DAG.getBasicBlock(DefaultMBB)); 11132 11133 DAG.setRoot(BrCond); 11134 return; 11135 } 11136 } 11137 } 11138 11139 if (TM.getOptLevel() != CodeGenOpt::None) { 11140 // Here, we order cases by probability so the most likely case will be 11141 // checked first. However, two clusters can have the same probability in 11142 // which case their relative ordering is non-deterministic. So we use Low 11143 // as a tie-breaker as clusters are guaranteed to never overlap. 11144 llvm::sort(W.FirstCluster, W.LastCluster + 1, 11145 [](const CaseCluster &a, const CaseCluster &b) { 11146 return a.Prob != b.Prob ? 11147 a.Prob > b.Prob : 11148 a.Low->getValue().slt(b.Low->getValue()); 11149 }); 11150 11151 // Rearrange the case blocks so that the last one falls through if possible 11152 // without changing the order of probabilities. 11153 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 11154 --I; 11155 if (I->Prob > W.LastCluster->Prob) 11156 break; 11157 if (I->Kind == CC_Range && I->MBB == NextMBB) { 11158 std::swap(*I, *W.LastCluster); 11159 break; 11160 } 11161 } 11162 } 11163 11164 // Compute total probability. 11165 BranchProbability DefaultProb = W.DefaultProb; 11166 BranchProbability UnhandledProbs = DefaultProb; 11167 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 11168 UnhandledProbs += I->Prob; 11169 11170 MachineBasicBlock *CurMBB = W.MBB; 11171 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 11172 bool FallthroughUnreachable = false; 11173 MachineBasicBlock *Fallthrough; 11174 if (I == W.LastCluster) { 11175 // For the last cluster, fall through to the default destination. 11176 Fallthrough = DefaultMBB; 11177 FallthroughUnreachable = isa<UnreachableInst>( 11178 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 11179 } else { 11180 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 11181 CurMF->insert(BBI, Fallthrough); 11182 // Put Cond in a virtual register to make it available from the new blocks. 11183 ExportFromCurrentBlock(Cond); 11184 } 11185 UnhandledProbs -= I->Prob; 11186 11187 switch (I->Kind) { 11188 case CC_JumpTable: { 11189 // FIXME: Optimize away range check based on pivot comparisons. 11190 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 11191 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 11192 11193 // The jump block hasn't been inserted yet; insert it here. 11194 MachineBasicBlock *JumpMBB = JT->MBB; 11195 CurMF->insert(BBI, JumpMBB); 11196 11197 auto JumpProb = I->Prob; 11198 auto FallthroughProb = UnhandledProbs; 11199 11200 // If the default statement is a target of the jump table, we evenly 11201 // distribute the default probability to successors of CurMBB. Also 11202 // update the probability on the edge from JumpMBB to Fallthrough. 11203 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 11204 SE = JumpMBB->succ_end(); 11205 SI != SE; ++SI) { 11206 if (*SI == DefaultMBB) { 11207 JumpProb += DefaultProb / 2; 11208 FallthroughProb -= DefaultProb / 2; 11209 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 11210 JumpMBB->normalizeSuccProbs(); 11211 break; 11212 } 11213 } 11214 11215 if (FallthroughUnreachable) 11216 JTH->FallthroughUnreachable = true; 11217 11218 if (!JTH->FallthroughUnreachable) 11219 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 11220 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 11221 CurMBB->normalizeSuccProbs(); 11222 11223 // The jump table header will be inserted in our current block, do the 11224 // range check, and fall through to our fallthrough block. 11225 JTH->HeaderBB = CurMBB; 11226 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 11227 11228 // If we're in the right place, emit the jump table header right now. 11229 if (CurMBB == SwitchMBB) { 11230 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 11231 JTH->Emitted = true; 11232 } 11233 break; 11234 } 11235 case CC_BitTests: { 11236 // FIXME: Optimize away range check based on pivot comparisons. 11237 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 11238 11239 // The bit test blocks haven't been inserted yet; insert them here. 11240 for (BitTestCase &BTC : BTB->Cases) 11241 CurMF->insert(BBI, BTC.ThisBB); 11242 11243 // Fill in fields of the BitTestBlock. 11244 BTB->Parent = CurMBB; 11245 BTB->Default = Fallthrough; 11246 11247 BTB->DefaultProb = UnhandledProbs; 11248 // If the cases in bit test don't form a contiguous range, we evenly 11249 // distribute the probability on the edge to Fallthrough to two 11250 // successors of CurMBB. 11251 if (!BTB->ContiguousRange) { 11252 BTB->Prob += DefaultProb / 2; 11253 BTB->DefaultProb -= DefaultProb / 2; 11254 } 11255 11256 if (FallthroughUnreachable) 11257 BTB->FallthroughUnreachable = true; 11258 11259 // If we're in the right place, emit the bit test header right now. 11260 if (CurMBB == SwitchMBB) { 11261 visitBitTestHeader(*BTB, SwitchMBB); 11262 BTB->Emitted = true; 11263 } 11264 break; 11265 } 11266 case CC_Range: { 11267 const Value *RHS, *LHS, *MHS; 11268 ISD::CondCode CC; 11269 if (I->Low == I->High) { 11270 // Check Cond == I->Low. 11271 CC = ISD::SETEQ; 11272 LHS = Cond; 11273 RHS=I->Low; 11274 MHS = nullptr; 11275 } else { 11276 // Check I->Low <= Cond <= I->High. 11277 CC = ISD::SETLE; 11278 LHS = I->Low; 11279 MHS = Cond; 11280 RHS = I->High; 11281 } 11282 11283 // If Fallthrough is unreachable, fold away the comparison. 11284 if (FallthroughUnreachable) 11285 CC = ISD::SETTRUE; 11286 11287 // The false probability is the sum of all unhandled cases. 11288 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 11289 getCurSDLoc(), I->Prob, UnhandledProbs); 11290 11291 if (CurMBB == SwitchMBB) 11292 visitSwitchCase(CB, SwitchMBB); 11293 else 11294 SL->SwitchCases.push_back(CB); 11295 11296 break; 11297 } 11298 } 11299 CurMBB = Fallthrough; 11300 } 11301 } 11302 11303 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 11304 CaseClusterIt First, 11305 CaseClusterIt Last) { 11306 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 11307 if (X.Prob != CC.Prob) 11308 return X.Prob > CC.Prob; 11309 11310 // Ties are broken by comparing the case value. 11311 return X.Low->getValue().slt(CC.Low->getValue()); 11312 }); 11313 } 11314 11315 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 11316 const SwitchWorkListItem &W, 11317 Value *Cond, 11318 MachineBasicBlock *SwitchMBB) { 11319 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 11320 "Clusters not sorted?"); 11321 11322 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 11323 11324 // Balance the tree based on branch probabilities to create a near-optimal (in 11325 // terms of search time given key frequency) binary search tree. See e.g. Kurt 11326 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 11327 CaseClusterIt LastLeft = W.FirstCluster; 11328 CaseClusterIt FirstRight = W.LastCluster; 11329 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 11330 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 11331 11332 // Move LastLeft and FirstRight towards each other from opposite directions to 11333 // find a partitioning of the clusters which balances the probability on both 11334 // sides. If LeftProb and RightProb are equal, alternate which side is 11335 // taken to ensure 0-probability nodes are distributed evenly. 11336 unsigned I = 0; 11337 while (LastLeft + 1 < FirstRight) { 11338 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 11339 LeftProb += (++LastLeft)->Prob; 11340 else 11341 RightProb += (--FirstRight)->Prob; 11342 I++; 11343 } 11344 11345 while (true) { 11346 // Our binary search tree differs from a typical BST in that ours can have up 11347 // to three values in each leaf. The pivot selection above doesn't take that 11348 // into account, which means the tree might require more nodes and be less 11349 // efficient. We compensate for this here. 11350 11351 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 11352 unsigned NumRight = W.LastCluster - FirstRight + 1; 11353 11354 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 11355 // If one side has less than 3 clusters, and the other has more than 3, 11356 // consider taking a cluster from the other side. 11357 11358 if (NumLeft < NumRight) { 11359 // Consider moving the first cluster on the right to the left side. 11360 CaseCluster &CC = *FirstRight; 11361 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11362 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11363 if (LeftSideRank <= RightSideRank) { 11364 // Moving the cluster to the left does not demote it. 11365 ++LastLeft; 11366 ++FirstRight; 11367 continue; 11368 } 11369 } else { 11370 assert(NumRight < NumLeft); 11371 // Consider moving the last element on the left to the right side. 11372 CaseCluster &CC = *LastLeft; 11373 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11374 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11375 if (RightSideRank <= LeftSideRank) { 11376 // Moving the cluster to the right does not demot it. 11377 --LastLeft; 11378 --FirstRight; 11379 continue; 11380 } 11381 } 11382 } 11383 break; 11384 } 11385 11386 assert(LastLeft + 1 == FirstRight); 11387 assert(LastLeft >= W.FirstCluster); 11388 assert(FirstRight <= W.LastCluster); 11389 11390 // Use the first element on the right as pivot since we will make less-than 11391 // comparisons against it. 11392 CaseClusterIt PivotCluster = FirstRight; 11393 assert(PivotCluster > W.FirstCluster); 11394 assert(PivotCluster <= W.LastCluster); 11395 11396 CaseClusterIt FirstLeft = W.FirstCluster; 11397 CaseClusterIt LastRight = W.LastCluster; 11398 11399 const ConstantInt *Pivot = PivotCluster->Low; 11400 11401 // New blocks will be inserted immediately after the current one. 11402 MachineFunction::iterator BBI(W.MBB); 11403 ++BBI; 11404 11405 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 11406 // we can branch to its destination directly if it's squeezed exactly in 11407 // between the known lower bound and Pivot - 1. 11408 MachineBasicBlock *LeftMBB; 11409 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 11410 FirstLeft->Low == W.GE && 11411 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 11412 LeftMBB = FirstLeft->MBB; 11413 } else { 11414 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11415 FuncInfo.MF->insert(BBI, LeftMBB); 11416 WorkList.push_back( 11417 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 11418 // Put Cond in a virtual register to make it available from the new blocks. 11419 ExportFromCurrentBlock(Cond); 11420 } 11421 11422 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 11423 // single cluster, RHS.Low == Pivot, and we can branch to its destination 11424 // directly if RHS.High equals the current upper bound. 11425 MachineBasicBlock *RightMBB; 11426 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 11427 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 11428 RightMBB = FirstRight->MBB; 11429 } else { 11430 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11431 FuncInfo.MF->insert(BBI, RightMBB); 11432 WorkList.push_back( 11433 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 11434 // Put Cond in a virtual register to make it available from the new blocks. 11435 ExportFromCurrentBlock(Cond); 11436 } 11437 11438 // Create the CaseBlock record that will be used to lower the branch. 11439 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 11440 getCurSDLoc(), LeftProb, RightProb); 11441 11442 if (W.MBB == SwitchMBB) 11443 visitSwitchCase(CB, SwitchMBB); 11444 else 11445 SL->SwitchCases.push_back(CB); 11446 } 11447 11448 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 11449 // from the swith statement. 11450 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 11451 BranchProbability PeeledCaseProb) { 11452 if (PeeledCaseProb == BranchProbability::getOne()) 11453 return BranchProbability::getZero(); 11454 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 11455 11456 uint32_t Numerator = CaseProb.getNumerator(); 11457 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 11458 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 11459 } 11460 11461 // Try to peel the top probability case if it exceeds the threshold. 11462 // Return current MachineBasicBlock for the switch statement if the peeling 11463 // does not occur. 11464 // If the peeling is performed, return the newly created MachineBasicBlock 11465 // for the peeled switch statement. Also update Clusters to remove the peeled 11466 // case. PeeledCaseProb is the BranchProbability for the peeled case. 11467 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 11468 const SwitchInst &SI, CaseClusterVector &Clusters, 11469 BranchProbability &PeeledCaseProb) { 11470 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11471 // Don't perform if there is only one cluster or optimizing for size. 11472 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 11473 TM.getOptLevel() == CodeGenOpt::None || 11474 SwitchMBB->getParent()->getFunction().hasMinSize()) 11475 return SwitchMBB; 11476 11477 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 11478 unsigned PeeledCaseIndex = 0; 11479 bool SwitchPeeled = false; 11480 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 11481 CaseCluster &CC = Clusters[Index]; 11482 if (CC.Prob < TopCaseProb) 11483 continue; 11484 TopCaseProb = CC.Prob; 11485 PeeledCaseIndex = Index; 11486 SwitchPeeled = true; 11487 } 11488 if (!SwitchPeeled) 11489 return SwitchMBB; 11490 11491 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 11492 << TopCaseProb << "\n"); 11493 11494 // Record the MBB for the peeled switch statement. 11495 MachineFunction::iterator BBI(SwitchMBB); 11496 ++BBI; 11497 MachineBasicBlock *PeeledSwitchMBB = 11498 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 11499 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 11500 11501 ExportFromCurrentBlock(SI.getCondition()); 11502 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 11503 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 11504 nullptr, nullptr, TopCaseProb.getCompl()}; 11505 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 11506 11507 Clusters.erase(PeeledCaseIt); 11508 for (CaseCluster &CC : Clusters) { 11509 LLVM_DEBUG( 11510 dbgs() << "Scale the probablity for one cluster, before scaling: " 11511 << CC.Prob << "\n"); 11512 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 11513 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 11514 } 11515 PeeledCaseProb = TopCaseProb; 11516 return PeeledSwitchMBB; 11517 } 11518 11519 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 11520 // Extract cases from the switch. 11521 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11522 CaseClusterVector Clusters; 11523 Clusters.reserve(SI.getNumCases()); 11524 for (auto I : SI.cases()) { 11525 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 11526 const ConstantInt *CaseVal = I.getCaseValue(); 11527 BranchProbability Prob = 11528 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 11529 : BranchProbability(1, SI.getNumCases() + 1); 11530 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 11531 } 11532 11533 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 11534 11535 // Cluster adjacent cases with the same destination. We do this at all 11536 // optimization levels because it's cheap to do and will make codegen faster 11537 // if there are many clusters. 11538 sortAndRangeify(Clusters); 11539 11540 // The branch probablity of the peeled case. 11541 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 11542 MachineBasicBlock *PeeledSwitchMBB = 11543 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 11544 11545 // If there is only the default destination, jump there directly. 11546 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11547 if (Clusters.empty()) { 11548 assert(PeeledSwitchMBB == SwitchMBB); 11549 SwitchMBB->addSuccessor(DefaultMBB); 11550 if (DefaultMBB != NextBlock(SwitchMBB)) { 11551 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 11552 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 11553 } 11554 return; 11555 } 11556 11557 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 11558 SL->findBitTestClusters(Clusters, &SI); 11559 11560 LLVM_DEBUG({ 11561 dbgs() << "Case clusters: "; 11562 for (const CaseCluster &C : Clusters) { 11563 if (C.Kind == CC_JumpTable) 11564 dbgs() << "JT:"; 11565 if (C.Kind == CC_BitTests) 11566 dbgs() << "BT:"; 11567 11568 C.Low->getValue().print(dbgs(), true); 11569 if (C.Low != C.High) { 11570 dbgs() << '-'; 11571 C.High->getValue().print(dbgs(), true); 11572 } 11573 dbgs() << ' '; 11574 } 11575 dbgs() << '\n'; 11576 }); 11577 11578 assert(!Clusters.empty()); 11579 SwitchWorkList WorkList; 11580 CaseClusterIt First = Clusters.begin(); 11581 CaseClusterIt Last = Clusters.end() - 1; 11582 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 11583 // Scale the branchprobability for DefaultMBB if the peel occurs and 11584 // DefaultMBB is not replaced. 11585 if (PeeledCaseProb != BranchProbability::getZero() && 11586 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 11587 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 11588 WorkList.push_back( 11589 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 11590 11591 while (!WorkList.empty()) { 11592 SwitchWorkListItem W = WorkList.pop_back_val(); 11593 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 11594 11595 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 11596 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 11597 // For optimized builds, lower large range as a balanced binary tree. 11598 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 11599 continue; 11600 } 11601 11602 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 11603 } 11604 } 11605 11606 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 11607 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11608 auto DL = getCurSDLoc(); 11609 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11610 setValue(&I, DAG.getStepVector(DL, ResultVT)); 11611 } 11612 11613 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 11614 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11615 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11616 11617 SDLoc DL = getCurSDLoc(); 11618 SDValue V = getValue(I.getOperand(0)); 11619 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 11620 11621 if (VT.isScalableVector()) { 11622 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 11623 return; 11624 } 11625 11626 // Use VECTOR_SHUFFLE for the fixed-length vector 11627 // to maintain existing behavior. 11628 SmallVector<int, 8> Mask; 11629 unsigned NumElts = VT.getVectorMinNumElements(); 11630 for (unsigned i = 0; i != NumElts; ++i) 11631 Mask.push_back(NumElts - 1 - i); 11632 11633 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 11634 } 11635 11636 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) { 11637 auto DL = getCurSDLoc(); 11638 SDValue InVec = getValue(I.getOperand(0)); 11639 EVT OutVT = 11640 InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 11641 11642 unsigned OutNumElts = OutVT.getVectorMinNumElements(); 11643 11644 // ISD Node needs the input vectors split into two equal parts 11645 SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 11646 DAG.getVectorIdxConstant(0, DL)); 11647 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 11648 DAG.getVectorIdxConstant(OutNumElts, DL)); 11649 11650 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 11651 // legalisation and combines. 11652 if (OutVT.isFixedLengthVector()) { 11653 SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 11654 createStrideMask(0, 2, OutNumElts)); 11655 SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 11656 createStrideMask(1, 2, OutNumElts)); 11657 SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc()); 11658 setValue(&I, Res); 11659 return; 11660 } 11661 11662 SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL, 11663 DAG.getVTList(OutVT, OutVT), Lo, Hi); 11664 setValue(&I, Res); 11665 } 11666 11667 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) { 11668 auto DL = getCurSDLoc(); 11669 EVT InVT = getValue(I.getOperand(0)).getValueType(); 11670 SDValue InVec0 = getValue(I.getOperand(0)); 11671 SDValue InVec1 = getValue(I.getOperand(1)); 11672 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11673 EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11674 11675 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 11676 // legalisation and combines. 11677 if (OutVT.isFixedLengthVector()) { 11678 unsigned NumElts = InVT.getVectorMinNumElements(); 11679 SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1); 11680 setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT), 11681 createInterleaveMask(NumElts, 2))); 11682 return; 11683 } 11684 11685 SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, 11686 DAG.getVTList(InVT, InVT), InVec0, InVec1); 11687 Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0), 11688 Res.getValue(1)); 11689 setValue(&I, Res); 11690 } 11691 11692 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 11693 SmallVector<EVT, 4> ValueVTs; 11694 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 11695 ValueVTs); 11696 unsigned NumValues = ValueVTs.size(); 11697 if (NumValues == 0) return; 11698 11699 SmallVector<SDValue, 4> Values(NumValues); 11700 SDValue Op = getValue(I.getOperand(0)); 11701 11702 for (unsigned i = 0; i != NumValues; ++i) 11703 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 11704 SDValue(Op.getNode(), Op.getResNo() + i)); 11705 11706 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 11707 DAG.getVTList(ValueVTs), Values)); 11708 } 11709 11710 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 11711 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11712 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11713 11714 SDLoc DL = getCurSDLoc(); 11715 SDValue V1 = getValue(I.getOperand(0)); 11716 SDValue V2 = getValue(I.getOperand(1)); 11717 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 11718 11719 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 11720 if (VT.isScalableVector()) { 11721 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 11722 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 11723 DAG.getConstant(Imm, DL, IdxVT))); 11724 return; 11725 } 11726 11727 unsigned NumElts = VT.getVectorNumElements(); 11728 11729 uint64_t Idx = (NumElts + Imm) % NumElts; 11730 11731 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 11732 SmallVector<int, 8> Mask; 11733 for (unsigned i = 0; i < NumElts; ++i) 11734 Mask.push_back(Idx + i); 11735 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 11736 } 11737 11738 // Consider the following MIR after SelectionDAG, which produces output in 11739 // phyregs in the first case or virtregs in the second case. 11740 // 11741 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx 11742 // %5:gr32 = COPY $ebx 11743 // %6:gr32 = COPY $edx 11744 // %1:gr32 = COPY %6:gr32 11745 // %0:gr32 = COPY %5:gr32 11746 // 11747 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32 11748 // %1:gr32 = COPY %6:gr32 11749 // %0:gr32 = COPY %5:gr32 11750 // 11751 // Given %0, we'd like to return $ebx in the first case and %5 in the second. 11752 // Given %1, we'd like to return $edx in the first case and %6 in the second. 11753 // 11754 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap 11755 // to a single virtreg (such as %0). The remaining outputs monotonically 11756 // increase in virtreg number from there. If a callbr has no outputs, then it 11757 // should not have a corresponding callbr landingpad; in fact, the callbr 11758 // landingpad would not even be able to refer to such a callbr. 11759 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) { 11760 MachineInstr *MI = MRI.def_begin(Reg)->getParent(); 11761 // There is definitely at least one copy. 11762 assert(MI->getOpcode() == TargetOpcode::COPY && 11763 "start of copy chain MUST be COPY"); 11764 Reg = MI->getOperand(1).getReg(); 11765 MI = MRI.def_begin(Reg)->getParent(); 11766 // There may be an optional second copy. 11767 if (MI->getOpcode() == TargetOpcode::COPY) { 11768 assert(Reg.isVirtual() && "expected COPY of virtual register"); 11769 Reg = MI->getOperand(1).getReg(); 11770 assert(Reg.isPhysical() && "expected COPY of physical register"); 11771 MI = MRI.def_begin(Reg)->getParent(); 11772 } 11773 // The start of the chain must be an INLINEASM_BR. 11774 assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR && 11775 "end of copy chain MUST be INLINEASM_BR"); 11776 return Reg; 11777 } 11778 11779 // We must do this walk rather than the simpler 11780 // setValue(&I, getCopyFromRegs(CBR, CBR->getType())); 11781 // otherwise we will end up with copies of virtregs only valid along direct 11782 // edges. 11783 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) { 11784 SmallVector<EVT, 8> ResultVTs; 11785 SmallVector<SDValue, 8> ResultValues; 11786 const auto *CBR = 11787 cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator()); 11788 11789 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11790 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 11791 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11792 11793 unsigned InitialDef = FuncInfo.ValueMap[CBR]; 11794 SDValue Chain = DAG.getRoot(); 11795 11796 // Re-parse the asm constraints string. 11797 TargetLowering::AsmOperandInfoVector TargetConstraints = 11798 TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR); 11799 for (auto &T : TargetConstraints) { 11800 SDISelAsmOperandInfo OpInfo(T); 11801 if (OpInfo.Type != InlineAsm::isOutput) 11802 continue; 11803 11804 // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the 11805 // individual constraint. 11806 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 11807 11808 switch (OpInfo.ConstraintType) { 11809 case TargetLowering::C_Register: 11810 case TargetLowering::C_RegisterClass: { 11811 // Fill in OpInfo.AssignedRegs.Regs. 11812 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo); 11813 11814 // getRegistersForValue may produce 1 to many registers based on whether 11815 // the OpInfo.ConstraintVT is legal on the target or not. 11816 for (size_t i = 0, e = OpInfo.AssignedRegs.Regs.size(); i != e; ++i) { 11817 Register OriginalDef = FollowCopyChain(MRI, InitialDef++); 11818 if (Register::isPhysicalRegister(OriginalDef)) 11819 FuncInfo.MBB->addLiveIn(OriginalDef); 11820 // Update the assigned registers to use the original defs. 11821 OpInfo.AssignedRegs.Regs[i] = OriginalDef; 11822 } 11823 11824 SDValue V = OpInfo.AssignedRegs.getCopyFromRegs( 11825 DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR); 11826 ResultValues.push_back(V); 11827 ResultVTs.push_back(OpInfo.ConstraintVT); 11828 break; 11829 } 11830 case TargetLowering::C_Other: { 11831 SDValue Flag; 11832 SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 11833 OpInfo, DAG); 11834 ++InitialDef; 11835 ResultValues.push_back(V); 11836 ResultVTs.push_back(OpInfo.ConstraintVT); 11837 break; 11838 } 11839 default: 11840 break; 11841 } 11842 } 11843 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 11844 DAG.getVTList(ResultVTs), ResultValues); 11845 setValue(&I, V); 11846 } 11847