1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This implements routines for translating from LLVM IR into SelectionDAG IR. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "SelectionDAGBuilder.h" 14 #include "SDNodeDbgValue.h" 15 #include "llvm/ADT/APFloat.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/BitVector.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/ADT/SmallPtrSet.h" 20 #include "llvm/ADT/SmallSet.h" 21 #include "llvm/ADT/StringRef.h" 22 #include "llvm/ADT/Twine.h" 23 #include "llvm/Analysis/AliasAnalysis.h" 24 #include "llvm/Analysis/BranchProbabilityInfo.h" 25 #include "llvm/Analysis/ConstantFolding.h" 26 #include "llvm/Analysis/Loads.h" 27 #include "llvm/Analysis/MemoryLocation.h" 28 #include "llvm/Analysis/TargetLibraryInfo.h" 29 #include "llvm/Analysis/ValueTracking.h" 30 #include "llvm/Analysis/VectorUtils.h" 31 #include "llvm/CodeGen/Analysis.h" 32 #include "llvm/CodeGen/AssignmentTrackingAnalysis.h" 33 #include "llvm/CodeGen/CodeGenCommonISel.h" 34 #include "llvm/CodeGen/FunctionLoweringInfo.h" 35 #include "llvm/CodeGen/GCMetadata.h" 36 #include "llvm/CodeGen/ISDOpcodes.h" 37 #include "llvm/CodeGen/MachineBasicBlock.h" 38 #include "llvm/CodeGen/MachineFrameInfo.h" 39 #include "llvm/CodeGen/MachineFunction.h" 40 #include "llvm/CodeGen/MachineInstrBuilder.h" 41 #include "llvm/CodeGen/MachineInstrBundleIterator.h" 42 #include "llvm/CodeGen/MachineMemOperand.h" 43 #include "llvm/CodeGen/MachineModuleInfo.h" 44 #include "llvm/CodeGen/MachineOperand.h" 45 #include "llvm/CodeGen/MachineRegisterInfo.h" 46 #include "llvm/CodeGen/RuntimeLibcalls.h" 47 #include "llvm/CodeGen/SelectionDAG.h" 48 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 49 #include "llvm/CodeGen/StackMaps.h" 50 #include "llvm/CodeGen/SwiftErrorValueTracking.h" 51 #include "llvm/CodeGen/TargetFrameLowering.h" 52 #include "llvm/CodeGen/TargetInstrInfo.h" 53 #include "llvm/CodeGen/TargetOpcodes.h" 54 #include "llvm/CodeGen/TargetRegisterInfo.h" 55 #include "llvm/CodeGen/TargetSubtargetInfo.h" 56 #include "llvm/CodeGen/WinEHFuncInfo.h" 57 #include "llvm/IR/Argument.h" 58 #include "llvm/IR/Attributes.h" 59 #include "llvm/IR/BasicBlock.h" 60 #include "llvm/IR/CFG.h" 61 #include "llvm/IR/CallingConv.h" 62 #include "llvm/IR/Constant.h" 63 #include "llvm/IR/ConstantRange.h" 64 #include "llvm/IR/Constants.h" 65 #include "llvm/IR/DataLayout.h" 66 #include "llvm/IR/DebugInfo.h" 67 #include "llvm/IR/DebugInfoMetadata.h" 68 #include "llvm/IR/DerivedTypes.h" 69 #include "llvm/IR/DiagnosticInfo.h" 70 #include "llvm/IR/EHPersonalities.h" 71 #include "llvm/IR/Function.h" 72 #include "llvm/IR/GetElementPtrTypeIterator.h" 73 #include "llvm/IR/InlineAsm.h" 74 #include "llvm/IR/InstrTypes.h" 75 #include "llvm/IR/Instructions.h" 76 #include "llvm/IR/IntrinsicInst.h" 77 #include "llvm/IR/Intrinsics.h" 78 #include "llvm/IR/IntrinsicsAArch64.h" 79 #include "llvm/IR/IntrinsicsWebAssembly.h" 80 #include "llvm/IR/LLVMContext.h" 81 #include "llvm/IR/Metadata.h" 82 #include "llvm/IR/Module.h" 83 #include "llvm/IR/Operator.h" 84 #include "llvm/IR/PatternMatch.h" 85 #include "llvm/IR/Statepoint.h" 86 #include "llvm/IR/Type.h" 87 #include "llvm/IR/User.h" 88 #include "llvm/IR/Value.h" 89 #include "llvm/MC/MCContext.h" 90 #include "llvm/Support/AtomicOrdering.h" 91 #include "llvm/Support/Casting.h" 92 #include "llvm/Support/CommandLine.h" 93 #include "llvm/Support/Compiler.h" 94 #include "llvm/Support/Debug.h" 95 #include "llvm/Support/MathExtras.h" 96 #include "llvm/Support/raw_ostream.h" 97 #include "llvm/Target/TargetIntrinsicInfo.h" 98 #include "llvm/Target/TargetMachine.h" 99 #include "llvm/Target/TargetOptions.h" 100 #include "llvm/TargetParser/Triple.h" 101 #include "llvm/Transforms/Utils/Local.h" 102 #include <cstddef> 103 #include <iterator> 104 #include <limits> 105 #include <optional> 106 #include <tuple> 107 108 using namespace llvm; 109 using namespace PatternMatch; 110 using namespace SwitchCG; 111 112 #define DEBUG_TYPE "isel" 113 114 /// LimitFloatPrecision - Generate low-precision inline sequences for 115 /// some float libcalls (6, 8 or 12 bits). 116 static unsigned LimitFloatPrecision; 117 118 static cl::opt<bool> 119 InsertAssertAlign("insert-assert-align", cl::init(true), 120 cl::desc("Insert the experimental `assertalign` node."), 121 cl::ReallyHidden); 122 123 static cl::opt<unsigned, true> 124 LimitFPPrecision("limit-float-precision", 125 cl::desc("Generate low-precision inline sequences " 126 "for some float libcalls"), 127 cl::location(LimitFloatPrecision), cl::Hidden, 128 cl::init(0)); 129 130 static cl::opt<unsigned> SwitchPeelThreshold( 131 "switch-peel-threshold", cl::Hidden, cl::init(66), 132 cl::desc("Set the case probability threshold for peeling the case from a " 133 "switch statement. A value greater than 100 will void this " 134 "optimization")); 135 136 // Limit the width of DAG chains. This is important in general to prevent 137 // DAG-based analysis from blowing up. For example, alias analysis and 138 // load clustering may not complete in reasonable time. It is difficult to 139 // recognize and avoid this situation within each individual analysis, and 140 // future analyses are likely to have the same behavior. Limiting DAG width is 141 // the safe approach and will be especially important with global DAGs. 142 // 143 // MaxParallelChains default is arbitrarily high to avoid affecting 144 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 145 // sequence over this should have been converted to llvm.memcpy by the 146 // frontend. It is easy to induce this behavior with .ll code such as: 147 // %buffer = alloca [4096 x i8] 148 // %data = load [4096 x i8]* %argPtr 149 // store [4096 x i8] %data, [4096 x i8]* %buffer 150 static const unsigned MaxParallelChains = 64; 151 152 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 153 const SDValue *Parts, unsigned NumParts, 154 MVT PartVT, EVT ValueVT, const Value *V, 155 std::optional<CallingConv::ID> CC); 156 157 /// getCopyFromParts - Create a value that contains the specified legal parts 158 /// combined into the value they represent. If the parts combine to a type 159 /// larger than ValueVT then AssertOp can be used to specify whether the extra 160 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 161 /// (ISD::AssertSext). 162 static SDValue 163 getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, 164 unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V, 165 std::optional<CallingConv::ID> CC = std::nullopt, 166 std::optional<ISD::NodeType> AssertOp = std::nullopt) { 167 // Let the target assemble the parts if it wants to 168 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 169 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts, 170 PartVT, ValueVT, CC)) 171 return Val; 172 173 if (ValueVT.isVector()) 174 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 175 CC); 176 177 assert(NumParts > 0 && "No parts to assemble!"); 178 SDValue Val = Parts[0]; 179 180 if (NumParts > 1) { 181 // Assemble the value from multiple parts. 182 if (ValueVT.isInteger()) { 183 unsigned PartBits = PartVT.getSizeInBits(); 184 unsigned ValueBits = ValueVT.getSizeInBits(); 185 186 // Assemble the power of 2 part. 187 unsigned RoundParts = llvm::bit_floor(NumParts); 188 unsigned RoundBits = PartBits * RoundParts; 189 EVT RoundVT = RoundBits == ValueBits ? 190 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 191 SDValue Lo, Hi; 192 193 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 194 195 if (RoundParts > 2) { 196 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 197 PartVT, HalfVT, V); 198 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 199 RoundParts / 2, PartVT, HalfVT, V); 200 } else { 201 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 202 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 203 } 204 205 if (DAG.getDataLayout().isBigEndian()) 206 std::swap(Lo, Hi); 207 208 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 209 210 if (RoundParts < NumParts) { 211 // Assemble the trailing non-power-of-2 part. 212 unsigned OddParts = NumParts - RoundParts; 213 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 214 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 215 OddVT, V, CC); 216 217 // Combine the round and odd parts. 218 Lo = Val; 219 if (DAG.getDataLayout().isBigEndian()) 220 std::swap(Lo, Hi); 221 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 222 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 223 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 224 DAG.getConstant(Lo.getValueSizeInBits(), DL, 225 TLI.getShiftAmountTy( 226 TotalVT, DAG.getDataLayout()))); 227 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 228 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 229 } 230 } else if (PartVT.isFloatingPoint()) { 231 // FP split into multiple FP parts (for ppcf128) 232 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 233 "Unexpected split"); 234 SDValue Lo, Hi; 235 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 236 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 237 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 238 std::swap(Lo, Hi); 239 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 240 } else { 241 // FP split into integer parts (soft fp) 242 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 243 !PartVT.isVector() && "Unexpected split"); 244 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 245 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 246 } 247 } 248 249 // There is now one part, held in Val. Correct it to match ValueVT. 250 // PartEVT is the type of the register class that holds the value. 251 // ValueVT is the type of the inline asm operation. 252 EVT PartEVT = Val.getValueType(); 253 254 if (PartEVT == ValueVT) 255 return Val; 256 257 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 258 ValueVT.bitsLT(PartEVT)) { 259 // For an FP value in an integer part, we need to truncate to the right 260 // width first. 261 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 262 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 263 } 264 265 // Handle types that have the same size. 266 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 267 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 268 269 // Handle types with different sizes. 270 if (PartEVT.isInteger() && ValueVT.isInteger()) { 271 if (ValueVT.bitsLT(PartEVT)) { 272 // For a truncate, see if we have any information to 273 // indicate whether the truncated bits will always be 274 // zero or sign-extension. 275 if (AssertOp) 276 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 277 DAG.getValueType(ValueVT)); 278 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 279 } 280 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 281 } 282 283 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 284 // FP_ROUND's are always exact here. 285 if (ValueVT.bitsLT(Val.getValueType())) 286 return DAG.getNode( 287 ISD::FP_ROUND, DL, ValueVT, Val, 288 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 289 290 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 291 } 292 293 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 294 // then truncating. 295 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 296 ValueVT.bitsLT(PartEVT)) { 297 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 298 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 299 } 300 301 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 302 } 303 304 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 305 const Twine &ErrMsg) { 306 const Instruction *I = dyn_cast_or_null<Instruction>(V); 307 if (!V) 308 return Ctx.emitError(ErrMsg); 309 310 const char *AsmError = ", possible invalid constraint for vector type"; 311 if (const CallInst *CI = dyn_cast<CallInst>(I)) 312 if (CI->isInlineAsm()) 313 return Ctx.emitError(I, ErrMsg + AsmError); 314 315 return Ctx.emitError(I, ErrMsg); 316 } 317 318 /// getCopyFromPartsVector - Create a value that contains the specified legal 319 /// parts combined into the value they represent. If the parts combine to a 320 /// type larger than ValueVT then AssertOp can be used to specify whether the 321 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 322 /// ValueVT (ISD::AssertSext). 323 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 324 const SDValue *Parts, unsigned NumParts, 325 MVT PartVT, EVT ValueVT, const Value *V, 326 std::optional<CallingConv::ID> CallConv) { 327 assert(ValueVT.isVector() && "Not a vector value"); 328 assert(NumParts > 0 && "No parts to assemble!"); 329 const bool IsABIRegCopy = CallConv.has_value(); 330 331 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 332 SDValue Val = Parts[0]; 333 334 // Handle a multi-element vector. 335 if (NumParts > 1) { 336 EVT IntermediateVT; 337 MVT RegisterVT; 338 unsigned NumIntermediates; 339 unsigned NumRegs; 340 341 if (IsABIRegCopy) { 342 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 343 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, 344 NumIntermediates, RegisterVT); 345 } else { 346 NumRegs = 347 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 348 NumIntermediates, RegisterVT); 349 } 350 351 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 352 NumParts = NumRegs; // Silence a compiler warning. 353 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 354 assert(RegisterVT.getSizeInBits() == 355 Parts[0].getSimpleValueType().getSizeInBits() && 356 "Part type sizes don't match!"); 357 358 // Assemble the parts into intermediate operands. 359 SmallVector<SDValue, 8> Ops(NumIntermediates); 360 if (NumIntermediates == NumParts) { 361 // If the register was not expanded, truncate or copy the value, 362 // as appropriate. 363 for (unsigned i = 0; i != NumParts; ++i) 364 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 365 PartVT, IntermediateVT, V, CallConv); 366 } else if (NumParts > 0) { 367 // If the intermediate type was expanded, build the intermediate 368 // operands from the parts. 369 assert(NumParts % NumIntermediates == 0 && 370 "Must expand into a divisible number of parts!"); 371 unsigned Factor = NumParts / NumIntermediates; 372 for (unsigned i = 0; i != NumIntermediates; ++i) 373 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 374 PartVT, IntermediateVT, V, CallConv); 375 } 376 377 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 378 // intermediate operands. 379 EVT BuiltVectorTy = 380 IntermediateVT.isVector() 381 ? EVT::getVectorVT( 382 *DAG.getContext(), IntermediateVT.getScalarType(), 383 IntermediateVT.getVectorElementCount() * NumParts) 384 : EVT::getVectorVT(*DAG.getContext(), 385 IntermediateVT.getScalarType(), 386 NumIntermediates); 387 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 388 : ISD::BUILD_VECTOR, 389 DL, BuiltVectorTy, Ops); 390 } 391 392 // There is now one part, held in Val. Correct it to match ValueVT. 393 EVT PartEVT = Val.getValueType(); 394 395 if (PartEVT == ValueVT) 396 return Val; 397 398 if (PartEVT.isVector()) { 399 // Vector/Vector bitcast. 400 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 401 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 402 403 // If the parts vector has more elements than the value vector, then we 404 // have a vector widening case (e.g. <2 x float> -> <4 x float>). 405 // Extract the elements we want. 406 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) { 407 assert((PartEVT.getVectorElementCount().getKnownMinValue() > 408 ValueVT.getVectorElementCount().getKnownMinValue()) && 409 (PartEVT.getVectorElementCount().isScalable() == 410 ValueVT.getVectorElementCount().isScalable()) && 411 "Cannot narrow, it would be a lossy transformation"); 412 PartEVT = 413 EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(), 414 ValueVT.getVectorElementCount()); 415 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val, 416 DAG.getVectorIdxConstant(0, DL)); 417 if (PartEVT == ValueVT) 418 return Val; 419 if (PartEVT.isInteger() && ValueVT.isFloatingPoint()) 420 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 421 422 // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>). 423 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 424 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 425 } 426 427 // Promoted vector extract 428 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 429 } 430 431 // Trivial bitcast if the types are the same size and the destination 432 // vector type is legal. 433 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 434 TLI.isTypeLegal(ValueVT)) 435 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 436 437 if (ValueVT.getVectorNumElements() != 1) { 438 // Certain ABIs require that vectors are passed as integers. For vectors 439 // are the same size, this is an obvious bitcast. 440 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 441 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 442 } else if (ValueVT.bitsLT(PartEVT)) { 443 const uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 444 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 445 // Drop the extra bits. 446 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 447 return DAG.getBitcast(ValueVT, Val); 448 } 449 450 diagnosePossiblyInvalidConstraint( 451 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 452 return DAG.getUNDEF(ValueVT); 453 } 454 455 // Handle cases such as i8 -> <1 x i1> 456 EVT ValueSVT = ValueVT.getVectorElementType(); 457 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 458 unsigned ValueSize = ValueSVT.getSizeInBits(); 459 if (ValueSize == PartEVT.getSizeInBits()) { 460 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 461 } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) { 462 // It's possible a scalar floating point type gets softened to integer and 463 // then promoted to a larger integer. If PartEVT is the larger integer 464 // we need to truncate it and then bitcast to the FP type. 465 assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types"); 466 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 467 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 468 Val = DAG.getBitcast(ValueSVT, Val); 469 } else { 470 Val = ValueVT.isFloatingPoint() 471 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 472 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 473 } 474 } 475 476 return DAG.getBuildVector(ValueVT, DL, Val); 477 } 478 479 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 480 SDValue Val, SDValue *Parts, unsigned NumParts, 481 MVT PartVT, const Value *V, 482 std::optional<CallingConv::ID> CallConv); 483 484 /// getCopyToParts - Create a series of nodes that contain the specified value 485 /// split into legal parts. If the parts contain more bits than Val, then, for 486 /// integers, ExtendKind can be used to specify how to generate the extra bits. 487 static void 488 getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 489 unsigned NumParts, MVT PartVT, const Value *V, 490 std::optional<CallingConv::ID> CallConv = std::nullopt, 491 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 492 // Let the target split the parts if it wants to 493 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 494 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 495 CallConv)) 496 return; 497 EVT ValueVT = Val.getValueType(); 498 499 // Handle the vector case separately. 500 if (ValueVT.isVector()) 501 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 502 CallConv); 503 504 unsigned OrigNumParts = NumParts; 505 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 506 "Copying to an illegal type!"); 507 508 if (NumParts == 0) 509 return; 510 511 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 512 EVT PartEVT = PartVT; 513 if (PartEVT == ValueVT) { 514 assert(NumParts == 1 && "No-op copy with multiple parts!"); 515 Parts[0] = Val; 516 return; 517 } 518 519 unsigned PartBits = PartVT.getSizeInBits(); 520 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 521 // If the parts cover more bits than the value has, promote the value. 522 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 523 assert(NumParts == 1 && "Do not know what to promote to!"); 524 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 525 } else { 526 if (ValueVT.isFloatingPoint()) { 527 // FP values need to be bitcast, then extended if they are being put 528 // into a larger container. 529 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 530 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 531 } 532 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 533 ValueVT.isInteger() && 534 "Unknown mismatch!"); 535 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 536 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 537 if (PartVT == MVT::x86mmx) 538 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 539 } 540 } else if (PartBits == ValueVT.getSizeInBits()) { 541 // Different types of the same size. 542 assert(NumParts == 1 && PartEVT != ValueVT); 543 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 544 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 545 // If the parts cover less bits than value has, truncate the value. 546 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 547 ValueVT.isInteger() && 548 "Unknown mismatch!"); 549 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 550 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 551 if (PartVT == MVT::x86mmx) 552 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 553 } 554 555 // The value may have changed - recompute ValueVT. 556 ValueVT = Val.getValueType(); 557 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 558 "Failed to tile the value with PartVT!"); 559 560 if (NumParts == 1) { 561 if (PartEVT != ValueVT) { 562 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 563 "scalar-to-vector conversion failed"); 564 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 565 } 566 567 Parts[0] = Val; 568 return; 569 } 570 571 // Expand the value into multiple parts. 572 if (NumParts & (NumParts - 1)) { 573 // The number of parts is not a power of 2. Split off and copy the tail. 574 assert(PartVT.isInteger() && ValueVT.isInteger() && 575 "Do not know what to expand to!"); 576 unsigned RoundParts = llvm::bit_floor(NumParts); 577 unsigned RoundBits = RoundParts * PartBits; 578 unsigned OddParts = NumParts - RoundParts; 579 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 580 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL)); 581 582 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 583 CallConv); 584 585 if (DAG.getDataLayout().isBigEndian()) 586 // The odd parts were reversed by getCopyToParts - unreverse them. 587 std::reverse(Parts + RoundParts, Parts + NumParts); 588 589 NumParts = RoundParts; 590 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 591 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 592 } 593 594 // The number of parts is a power of 2. Repeatedly bisect the value using 595 // EXTRACT_ELEMENT. 596 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 597 EVT::getIntegerVT(*DAG.getContext(), 598 ValueVT.getSizeInBits()), 599 Val); 600 601 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 602 for (unsigned i = 0; i < NumParts; i += StepSize) { 603 unsigned ThisBits = StepSize * PartBits / 2; 604 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 605 SDValue &Part0 = Parts[i]; 606 SDValue &Part1 = Parts[i+StepSize/2]; 607 608 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 609 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 610 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 611 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 612 613 if (ThisBits == PartBits && ThisVT != PartVT) { 614 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 615 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 616 } 617 } 618 } 619 620 if (DAG.getDataLayout().isBigEndian()) 621 std::reverse(Parts, Parts + OrigNumParts); 622 } 623 624 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val, 625 const SDLoc &DL, EVT PartVT) { 626 if (!PartVT.isVector()) 627 return SDValue(); 628 629 EVT ValueVT = Val.getValueType(); 630 EVT PartEVT = PartVT.getVectorElementType(); 631 EVT ValueEVT = ValueVT.getVectorElementType(); 632 ElementCount PartNumElts = PartVT.getVectorElementCount(); 633 ElementCount ValueNumElts = ValueVT.getVectorElementCount(); 634 635 // We only support widening vectors with equivalent element types and 636 // fixed/scalable properties. If a target needs to widen a fixed-length type 637 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below. 638 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) || 639 PartNumElts.isScalable() != ValueNumElts.isScalable()) 640 return SDValue(); 641 642 // Have a try for bf16 because some targets share its ABI with fp16. 643 if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) { 644 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 645 "Cannot widen to illegal type"); 646 Val = DAG.getNode(ISD::BITCAST, DL, 647 ValueVT.changeVectorElementType(MVT::f16), Val); 648 } else if (PartEVT != ValueEVT) { 649 return SDValue(); 650 } 651 652 // Widening a scalable vector to another scalable vector is done by inserting 653 // the vector into a larger undef one. 654 if (PartNumElts.isScalable()) 655 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 656 Val, DAG.getVectorIdxConstant(0, DL)); 657 658 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 659 // undef elements. 660 SmallVector<SDValue, 16> Ops; 661 DAG.ExtractVectorElements(Val, Ops); 662 SDValue EltUndef = DAG.getUNDEF(PartEVT); 663 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef); 664 665 // FIXME: Use CONCAT for 2x -> 4x. 666 return DAG.getBuildVector(PartVT, DL, Ops); 667 } 668 669 /// getCopyToPartsVector - Create a series of nodes that contain the specified 670 /// value split into legal parts. 671 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 672 SDValue Val, SDValue *Parts, unsigned NumParts, 673 MVT PartVT, const Value *V, 674 std::optional<CallingConv::ID> CallConv) { 675 EVT ValueVT = Val.getValueType(); 676 assert(ValueVT.isVector() && "Not a vector"); 677 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 678 const bool IsABIRegCopy = CallConv.has_value(); 679 680 if (NumParts == 1) { 681 EVT PartEVT = PartVT; 682 if (PartEVT == ValueVT) { 683 // Nothing to do. 684 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 685 // Bitconvert vector->vector case. 686 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 687 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 688 Val = Widened; 689 } else if (PartVT.isVector() && 690 PartEVT.getVectorElementType().bitsGE( 691 ValueVT.getVectorElementType()) && 692 PartEVT.getVectorElementCount() == 693 ValueVT.getVectorElementCount()) { 694 695 // Promoted vector extract 696 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 697 } else if (PartEVT.isVector() && 698 PartEVT.getVectorElementType() != 699 ValueVT.getVectorElementType() && 700 TLI.getTypeAction(*DAG.getContext(), ValueVT) == 701 TargetLowering::TypeWidenVector) { 702 // Combination of widening and promotion. 703 EVT WidenVT = 704 EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(), 705 PartVT.getVectorElementCount()); 706 SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT); 707 Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT); 708 } else { 709 // Don't extract an integer from a float vector. This can happen if the 710 // FP type gets softened to integer and then promoted. The promotion 711 // prevents it from being picked up by the earlier bitcast case. 712 if (ValueVT.getVectorElementCount().isScalar() && 713 (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) { 714 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 715 DAG.getVectorIdxConstant(0, DL)); 716 } else { 717 uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 718 assert(PartVT.getFixedSizeInBits() > ValueSize && 719 "lossy conversion of vector to scalar type"); 720 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 721 Val = DAG.getBitcast(IntermediateType, Val); 722 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 723 } 724 } 725 726 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 727 Parts[0] = Val; 728 return; 729 } 730 731 // Handle a multi-element vector. 732 EVT IntermediateVT; 733 MVT RegisterVT; 734 unsigned NumIntermediates; 735 unsigned NumRegs; 736 if (IsABIRegCopy) { 737 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 738 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates, 739 RegisterVT); 740 } else { 741 NumRegs = 742 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 743 NumIntermediates, RegisterVT); 744 } 745 746 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 747 NumParts = NumRegs; // Silence a compiler warning. 748 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 749 750 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 751 "Mixing scalable and fixed vectors when copying in parts"); 752 753 std::optional<ElementCount> DestEltCnt; 754 755 if (IntermediateVT.isVector()) 756 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 757 else 758 DestEltCnt = ElementCount::getFixed(NumIntermediates); 759 760 EVT BuiltVectorTy = EVT::getVectorVT( 761 *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt); 762 763 if (ValueVT == BuiltVectorTy) { 764 // Nothing to do. 765 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) { 766 // Bitconvert vector->vector case. 767 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 768 } else { 769 if (BuiltVectorTy.getVectorElementType().bitsGT( 770 ValueVT.getVectorElementType())) { 771 // Integer promotion. 772 ValueVT = EVT::getVectorVT(*DAG.getContext(), 773 BuiltVectorTy.getVectorElementType(), 774 ValueVT.getVectorElementCount()); 775 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 776 } 777 778 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) { 779 Val = Widened; 780 } 781 } 782 783 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type"); 784 785 // Split the vector into intermediate operands. 786 SmallVector<SDValue, 8> Ops(NumIntermediates); 787 for (unsigned i = 0; i != NumIntermediates; ++i) { 788 if (IntermediateVT.isVector()) { 789 // This does something sensible for scalable vectors - see the 790 // definition of EXTRACT_SUBVECTOR for further details. 791 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 792 Ops[i] = 793 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 794 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 795 } else { 796 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 797 DAG.getVectorIdxConstant(i, DL)); 798 } 799 } 800 801 // Split the intermediate operands into legal parts. 802 if (NumParts == NumIntermediates) { 803 // If the register was not expanded, promote or copy the value, 804 // as appropriate. 805 for (unsigned i = 0; i != NumParts; ++i) 806 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 807 } else if (NumParts > 0) { 808 // If the intermediate type was expanded, split each the value into 809 // legal parts. 810 assert(NumIntermediates != 0 && "division by zero"); 811 assert(NumParts % NumIntermediates == 0 && 812 "Must expand into a divisible number of parts!"); 813 unsigned Factor = NumParts / NumIntermediates; 814 for (unsigned i = 0; i != NumIntermediates; ++i) 815 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 816 CallConv); 817 } 818 } 819 820 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 821 EVT valuevt, std::optional<CallingConv::ID> CC) 822 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 823 RegCount(1, regs.size()), CallConv(CC) {} 824 825 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 826 const DataLayout &DL, unsigned Reg, Type *Ty, 827 std::optional<CallingConv::ID> CC) { 828 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 829 830 CallConv = CC; 831 832 for (EVT ValueVT : ValueVTs) { 833 unsigned NumRegs = 834 isABIMangled() 835 ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT) 836 : TLI.getNumRegisters(Context, ValueVT); 837 MVT RegisterVT = 838 isABIMangled() 839 ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT) 840 : TLI.getRegisterType(Context, ValueVT); 841 for (unsigned i = 0; i != NumRegs; ++i) 842 Regs.push_back(Reg + i); 843 RegVTs.push_back(RegisterVT); 844 RegCount.push_back(NumRegs); 845 Reg += NumRegs; 846 } 847 } 848 849 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 850 FunctionLoweringInfo &FuncInfo, 851 const SDLoc &dl, SDValue &Chain, 852 SDValue *Glue, const Value *V) const { 853 // A Value with type {} or [0 x %t] needs no registers. 854 if (ValueVTs.empty()) 855 return SDValue(); 856 857 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 858 859 // Assemble the legal parts into the final values. 860 SmallVector<SDValue, 4> Values(ValueVTs.size()); 861 SmallVector<SDValue, 8> Parts; 862 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 863 // Copy the legal parts from the registers. 864 EVT ValueVT = ValueVTs[Value]; 865 unsigned NumRegs = RegCount[Value]; 866 MVT RegisterVT = isABIMangled() 867 ? TLI.getRegisterTypeForCallingConv( 868 *DAG.getContext(), *CallConv, RegVTs[Value]) 869 : RegVTs[Value]; 870 871 Parts.resize(NumRegs); 872 for (unsigned i = 0; i != NumRegs; ++i) { 873 SDValue P; 874 if (!Glue) { 875 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 876 } else { 877 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue); 878 *Glue = P.getValue(2); 879 } 880 881 Chain = P.getValue(1); 882 Parts[i] = P; 883 884 // If the source register was virtual and if we know something about it, 885 // add an assert node. 886 if (!Register::isVirtualRegister(Regs[Part + i]) || 887 !RegisterVT.isInteger()) 888 continue; 889 890 const FunctionLoweringInfo::LiveOutInfo *LOI = 891 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 892 if (!LOI) 893 continue; 894 895 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 896 unsigned NumSignBits = LOI->NumSignBits; 897 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 898 899 if (NumZeroBits == RegSize) { 900 // The current value is a zero. 901 // Explicitly express that as it would be easier for 902 // optimizations to kick in. 903 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 904 continue; 905 } 906 907 // FIXME: We capture more information than the dag can represent. For 908 // now, just use the tightest assertzext/assertsext possible. 909 bool isSExt; 910 EVT FromVT(MVT::Other); 911 if (NumZeroBits) { 912 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 913 isSExt = false; 914 } else if (NumSignBits > 1) { 915 FromVT = 916 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 917 isSExt = true; 918 } else { 919 continue; 920 } 921 // Add an assertion node. 922 assert(FromVT != MVT::Other); 923 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 924 RegisterVT, P, DAG.getValueType(FromVT)); 925 } 926 927 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 928 RegisterVT, ValueVT, V, CallConv); 929 Part += NumRegs; 930 Parts.clear(); 931 } 932 933 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 934 } 935 936 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 937 const SDLoc &dl, SDValue &Chain, SDValue *Glue, 938 const Value *V, 939 ISD::NodeType PreferredExtendType) const { 940 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 941 ISD::NodeType ExtendKind = PreferredExtendType; 942 943 // Get the list of the values's legal parts. 944 unsigned NumRegs = Regs.size(); 945 SmallVector<SDValue, 8> Parts(NumRegs); 946 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 947 unsigned NumParts = RegCount[Value]; 948 949 MVT RegisterVT = isABIMangled() 950 ? TLI.getRegisterTypeForCallingConv( 951 *DAG.getContext(), *CallConv, RegVTs[Value]) 952 : RegVTs[Value]; 953 954 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 955 ExtendKind = ISD::ZERO_EXTEND; 956 957 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 958 NumParts, RegisterVT, V, CallConv, ExtendKind); 959 Part += NumParts; 960 } 961 962 // Copy the parts into the registers. 963 SmallVector<SDValue, 8> Chains(NumRegs); 964 for (unsigned i = 0; i != NumRegs; ++i) { 965 SDValue Part; 966 if (!Glue) { 967 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 968 } else { 969 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue); 970 *Glue = Part.getValue(1); 971 } 972 973 Chains[i] = Part.getValue(0); 974 } 975 976 if (NumRegs == 1 || Glue) 977 // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is 978 // flagged to it. That is the CopyToReg nodes and the user are considered 979 // a single scheduling unit. If we create a TokenFactor and return it as 980 // chain, then the TokenFactor is both a predecessor (operand) of the 981 // user as well as a successor (the TF operands are flagged to the user). 982 // c1, f1 = CopyToReg 983 // c2, f2 = CopyToReg 984 // c3 = TokenFactor c1, c2 985 // ... 986 // = op c3, ..., f2 987 Chain = Chains[NumRegs-1]; 988 else 989 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 990 } 991 992 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 993 unsigned MatchingIdx, const SDLoc &dl, 994 SelectionDAG &DAG, 995 std::vector<SDValue> &Ops) const { 996 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 997 998 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 999 if (HasMatching) 1000 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 1001 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 1002 // Put the register class of the virtual registers in the flag word. That 1003 // way, later passes can recompute register class constraints for inline 1004 // assembly as well as normal instructions. 1005 // Don't do this for tied operands that can use the regclass information 1006 // from the def. 1007 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1008 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 1009 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 1010 } 1011 1012 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 1013 Ops.push_back(Res); 1014 1015 if (Code == InlineAsm::Kind_Clobber) { 1016 // Clobbers should always have a 1:1 mapping with registers, and may 1017 // reference registers that have illegal (e.g. vector) types. Hence, we 1018 // shouldn't try to apply any sort of splitting logic to them. 1019 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 1020 "No 1:1 mapping from clobbers to regs?"); 1021 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 1022 (void)SP; 1023 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 1024 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 1025 assert( 1026 (Regs[I] != SP || 1027 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 1028 "If we clobbered the stack pointer, MFI should know about it."); 1029 } 1030 return; 1031 } 1032 1033 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 1034 MVT RegisterVT = RegVTs[Value]; 1035 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value], 1036 RegisterVT); 1037 for (unsigned i = 0; i != NumRegs; ++i) { 1038 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 1039 unsigned TheReg = Regs[Reg++]; 1040 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 1041 } 1042 } 1043 } 1044 1045 SmallVector<std::pair<unsigned, TypeSize>, 4> 1046 RegsForValue::getRegsAndSizes() const { 1047 SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec; 1048 unsigned I = 0; 1049 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1050 unsigned RegCount = std::get<0>(CountAndVT); 1051 MVT RegisterVT = std::get<1>(CountAndVT); 1052 TypeSize RegisterSize = RegisterVT.getSizeInBits(); 1053 for (unsigned E = I + RegCount; I != E; ++I) 1054 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1055 } 1056 return OutVec; 1057 } 1058 1059 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1060 AssumptionCache *ac, 1061 const TargetLibraryInfo *li) { 1062 AA = aa; 1063 AC = ac; 1064 GFI = gfi; 1065 LibInfo = li; 1066 Context = DAG.getContext(); 1067 LPadToCallSiteMap.clear(); 1068 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1069 AssignmentTrackingEnabled = isAssignmentTrackingEnabled( 1070 *DAG.getMachineFunction().getFunction().getParent()); 1071 } 1072 1073 void SelectionDAGBuilder::clear() { 1074 NodeMap.clear(); 1075 UnusedArgNodeMap.clear(); 1076 PendingLoads.clear(); 1077 PendingExports.clear(); 1078 PendingConstrainedFP.clear(); 1079 PendingConstrainedFPStrict.clear(); 1080 CurInst = nullptr; 1081 HasTailCall = false; 1082 SDNodeOrder = LowestSDNodeOrder; 1083 StatepointLowering.clear(); 1084 } 1085 1086 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1087 DanglingDebugInfoMap.clear(); 1088 } 1089 1090 // Update DAG root to include dependencies on Pending chains. 1091 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1092 SDValue Root = DAG.getRoot(); 1093 1094 if (Pending.empty()) 1095 return Root; 1096 1097 // Add current root to PendingChains, unless we already indirectly 1098 // depend on it. 1099 if (Root.getOpcode() != ISD::EntryToken) { 1100 unsigned i = 0, e = Pending.size(); 1101 for (; i != e; ++i) { 1102 assert(Pending[i].getNode()->getNumOperands() > 1); 1103 if (Pending[i].getNode()->getOperand(0) == Root) 1104 break; // Don't add the root if we already indirectly depend on it. 1105 } 1106 1107 if (i == e) 1108 Pending.push_back(Root); 1109 } 1110 1111 if (Pending.size() == 1) 1112 Root = Pending[0]; 1113 else 1114 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1115 1116 DAG.setRoot(Root); 1117 Pending.clear(); 1118 return Root; 1119 } 1120 1121 SDValue SelectionDAGBuilder::getMemoryRoot() { 1122 return updateRoot(PendingLoads); 1123 } 1124 1125 SDValue SelectionDAGBuilder::getRoot() { 1126 // Chain up all pending constrained intrinsics together with all 1127 // pending loads, by simply appending them to PendingLoads and 1128 // then calling getMemoryRoot(). 1129 PendingLoads.reserve(PendingLoads.size() + 1130 PendingConstrainedFP.size() + 1131 PendingConstrainedFPStrict.size()); 1132 PendingLoads.append(PendingConstrainedFP.begin(), 1133 PendingConstrainedFP.end()); 1134 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1135 PendingConstrainedFPStrict.end()); 1136 PendingConstrainedFP.clear(); 1137 PendingConstrainedFPStrict.clear(); 1138 return getMemoryRoot(); 1139 } 1140 1141 SDValue SelectionDAGBuilder::getControlRoot() { 1142 // We need to emit pending fpexcept.strict constrained intrinsics, 1143 // so append them to the PendingExports list. 1144 PendingExports.append(PendingConstrainedFPStrict.begin(), 1145 PendingConstrainedFPStrict.end()); 1146 PendingConstrainedFPStrict.clear(); 1147 return updateRoot(PendingExports); 1148 } 1149 1150 void SelectionDAGBuilder::visit(const Instruction &I) { 1151 // Set up outgoing PHI node register values before emitting the terminator. 1152 if (I.isTerminator()) { 1153 HandlePHINodesInSuccessorBlocks(I.getParent()); 1154 } 1155 1156 // Add SDDbgValue nodes for any var locs here. Do so before updating 1157 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1158 if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) { 1159 // Add SDDbgValue nodes for any var locs here. Do so before updating 1160 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1161 for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I); 1162 It != End; ++It) { 1163 auto *Var = FnVarLocs->getDILocalVariable(It->VariableID); 1164 dropDanglingDebugInfo(Var, It->Expr); 1165 if (It->Values.isKillLocation(It->Expr)) { 1166 handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder); 1167 continue; 1168 } 1169 SmallVector<Value *> Values(It->Values.location_ops()); 1170 if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder, 1171 It->Values.hasArgList())) 1172 addDanglingDebugInfo(It, SDNodeOrder); 1173 } 1174 } 1175 1176 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1177 if (!isa<DbgInfoIntrinsic>(I)) 1178 ++SDNodeOrder; 1179 1180 CurInst = &I; 1181 1182 // Set inserted listener only if required. 1183 bool NodeInserted = false; 1184 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener; 1185 MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections); 1186 if (PCSectionsMD) { 1187 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>( 1188 DAG, [&](SDNode *) { NodeInserted = true; }); 1189 } 1190 1191 visit(I.getOpcode(), I); 1192 1193 if (!I.isTerminator() && !HasTailCall && 1194 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1195 CopyToExportRegsIfNeeded(&I); 1196 1197 // Handle metadata. 1198 if (PCSectionsMD) { 1199 auto It = NodeMap.find(&I); 1200 if (It != NodeMap.end()) { 1201 DAG.addPCSections(It->second.getNode(), PCSectionsMD); 1202 } else if (NodeInserted) { 1203 // This should not happen; if it does, don't let it go unnoticed so we can 1204 // fix it. Relevant visit*() function is probably missing a setValue(). 1205 errs() << "warning: loosing !pcsections metadata [" 1206 << I.getModule()->getName() << "]\n"; 1207 LLVM_DEBUG(I.dump()); 1208 assert(false); 1209 } 1210 } 1211 1212 CurInst = nullptr; 1213 } 1214 1215 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1216 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1217 } 1218 1219 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1220 // Note: this doesn't use InstVisitor, because it has to work with 1221 // ConstantExpr's in addition to instructions. 1222 switch (Opcode) { 1223 default: llvm_unreachable("Unknown instruction type encountered!"); 1224 // Build the switch statement using the Instruction.def file. 1225 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1226 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1227 #include "llvm/IR/Instruction.def" 1228 } 1229 } 1230 1231 static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG, 1232 DILocalVariable *Variable, 1233 DebugLoc DL, unsigned Order, 1234 RawLocationWrapper Values, 1235 DIExpression *Expression) { 1236 if (!Values.hasArgList()) 1237 return false; 1238 // For variadic dbg_values we will now insert an undef. 1239 // FIXME: We can potentially recover these! 1240 SmallVector<SDDbgOperand, 2> Locs; 1241 for (const Value *V : Values.location_ops()) { 1242 auto *Undef = UndefValue::get(V->getType()); 1243 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1244 } 1245 SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {}, 1246 /*IsIndirect=*/false, DL, Order, 1247 /*IsVariadic=*/true); 1248 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1249 return true; 1250 } 1251 1252 void SelectionDAGBuilder::addDanglingDebugInfo(const VarLocInfo *VarLoc, 1253 unsigned Order) { 1254 if (!handleDanglingVariadicDebugInfo( 1255 DAG, 1256 const_cast<DILocalVariable *>(DAG.getFunctionVarLocs() 1257 ->getVariable(VarLoc->VariableID) 1258 .getVariable()), 1259 VarLoc->DL, Order, VarLoc->Values, VarLoc->Expr)) { 1260 DanglingDebugInfoMap[VarLoc->Values.getVariableLocationOp(0)].emplace_back( 1261 VarLoc, Order); 1262 } 1263 } 1264 1265 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI, 1266 unsigned Order) { 1267 // We treat variadic dbg_values differently at this stage. 1268 if (!handleDanglingVariadicDebugInfo( 1269 DAG, DI->getVariable(), DI->getDebugLoc(), Order, 1270 DI->getWrappedLocation(), DI->getExpression())) { 1271 // TODO: Dangling debug info will eventually either be resolved or produce 1272 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1273 // between the original dbg.value location and its resolved DBG_VALUE, 1274 // which we should ideally fill with an extra Undef DBG_VALUE. 1275 assert(DI->getNumVariableLocationOps() == 1 && 1276 "DbgValueInst without an ArgList should have a single location " 1277 "operand."); 1278 DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, Order); 1279 } 1280 } 1281 1282 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1283 const DIExpression *Expr) { 1284 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1285 DIVariable *DanglingVariable = DDI.getVariable(DAG.getFunctionVarLocs()); 1286 DIExpression *DanglingExpr = DDI.getExpression(); 1287 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1288 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << printDDI(DDI) 1289 << "\n"); 1290 return true; 1291 } 1292 return false; 1293 }; 1294 1295 for (auto &DDIMI : DanglingDebugInfoMap) { 1296 DanglingDebugInfoVector &DDIV = DDIMI.second; 1297 1298 // If debug info is to be dropped, run it through final checks to see 1299 // whether it can be salvaged. 1300 for (auto &DDI : DDIV) 1301 if (isMatchingDbgValue(DDI)) 1302 salvageUnresolvedDbgValue(DDI); 1303 1304 erase_if(DDIV, isMatchingDbgValue); 1305 } 1306 } 1307 1308 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1309 // generate the debug data structures now that we've seen its definition. 1310 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1311 SDValue Val) { 1312 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1313 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1314 return; 1315 1316 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1317 for (auto &DDI : DDIV) { 1318 DebugLoc DL = DDI.getDebugLoc(); 1319 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1320 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1321 DILocalVariable *Variable = DDI.getVariable(DAG.getFunctionVarLocs()); 1322 DIExpression *Expr = DDI.getExpression(); 1323 assert(Variable->isValidLocationForIntrinsic(DL) && 1324 "Expected inlined-at fields to agree"); 1325 SDDbgValue *SDV; 1326 if (Val.getNode()) { 1327 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1328 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1329 // we couldn't resolve it directly when examining the DbgValue intrinsic 1330 // in the first place we should not be more successful here). Unless we 1331 // have some test case that prove this to be correct we should avoid 1332 // calling EmitFuncArgumentDbgValue here. 1333 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL, 1334 FuncArgumentDbgValueKind::Value, Val)) { 1335 LLVM_DEBUG(dbgs() << "Resolve dangling debug info for " << printDDI(DDI) 1336 << "\n"); 1337 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1338 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1339 // inserted after the definition of Val when emitting the instructions 1340 // after ISel. An alternative could be to teach 1341 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1342 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1343 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1344 << ValSDNodeOrder << "\n"); 1345 SDV = getDbgValue(Val, Variable, Expr, DL, 1346 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1347 DAG.AddDbgValue(SDV, false); 1348 } else 1349 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " 1350 << printDDI(DDI) << " in EmitFuncArgumentDbgValue\n"); 1351 } else { 1352 LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(DDI) << "\n"); 1353 auto Undef = UndefValue::get(V->getType()); 1354 auto SDV = 1355 DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder); 1356 DAG.AddDbgValue(SDV, false); 1357 } 1358 } 1359 DDIV.clear(); 1360 } 1361 1362 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1363 // TODO: For the variadic implementation, instead of only checking the fail 1364 // state of `handleDebugValue`, we need know specifically which values were 1365 // invalid, so that we attempt to salvage only those values when processing 1366 // a DIArgList. 1367 Value *V = DDI.getVariableLocationOp(0); 1368 Value *OrigV = V; 1369 DILocalVariable *Var = DDI.getVariable(DAG.getFunctionVarLocs()); 1370 DIExpression *Expr = DDI.getExpression(); 1371 DebugLoc DL = DDI.getDebugLoc(); 1372 unsigned SDOrder = DDI.getSDNodeOrder(); 1373 1374 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1375 // that DW_OP_stack_value is desired. 1376 bool StackValue = true; 1377 1378 // Can this Value can be encoded without any further work? 1379 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) 1380 return; 1381 1382 // Attempt to salvage back through as many instructions as possible. Bail if 1383 // a non-instruction is seen, such as a constant expression or global 1384 // variable. FIXME: Further work could recover those too. 1385 while (isa<Instruction>(V)) { 1386 Instruction &VAsInst = *cast<Instruction>(V); 1387 // Temporary "0", awaiting real implementation. 1388 SmallVector<uint64_t, 16> Ops; 1389 SmallVector<Value *, 4> AdditionalValues; 1390 V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops, 1391 AdditionalValues); 1392 // If we cannot salvage any further, and haven't yet found a suitable debug 1393 // expression, bail out. 1394 if (!V) 1395 break; 1396 1397 // TODO: If AdditionalValues isn't empty, then the salvage can only be 1398 // represented with a DBG_VALUE_LIST, so we give up. When we have support 1399 // here for variadic dbg_values, remove that condition. 1400 if (!AdditionalValues.empty()) 1401 break; 1402 1403 // New value and expr now represent this debuginfo. 1404 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue); 1405 1406 // Some kind of simplification occurred: check whether the operand of the 1407 // salvaged debug expression can be encoded in this DAG. 1408 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) { 1409 LLVM_DEBUG( 1410 dbgs() << "Salvaged debug location info for:\n " << *Var << "\n" 1411 << *OrigV << "\nBy stripping back to:\n " << *V << "\n"); 1412 return; 1413 } 1414 } 1415 1416 // This was the final opportunity to salvage this debug information, and it 1417 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1418 // any earlier variable location. 1419 assert(OrigV && "V shouldn't be null"); 1420 auto *Undef = UndefValue::get(OrigV->getType()); 1421 auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1422 DAG.AddDbgValue(SDV, false); 1423 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << printDDI(DDI) 1424 << "\n"); 1425 } 1426 1427 void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var, 1428 DIExpression *Expr, 1429 DebugLoc DbgLoc, 1430 unsigned Order) { 1431 Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context)); 1432 DIExpression *NewExpr = 1433 const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr)); 1434 handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order, 1435 /*IsVariadic*/ false); 1436 } 1437 1438 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1439 DILocalVariable *Var, 1440 DIExpression *Expr, DebugLoc DbgLoc, 1441 unsigned Order, bool IsVariadic) { 1442 if (Values.empty()) 1443 return true; 1444 SmallVector<SDDbgOperand> LocationOps; 1445 SmallVector<SDNode *> Dependencies; 1446 for (const Value *V : Values) { 1447 // Constant value. 1448 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1449 isa<ConstantPointerNull>(V)) { 1450 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1451 continue; 1452 } 1453 1454 // Look through IntToPtr constants. 1455 if (auto *CE = dyn_cast<ConstantExpr>(V)) 1456 if (CE->getOpcode() == Instruction::IntToPtr) { 1457 LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0))); 1458 continue; 1459 } 1460 1461 // If the Value is a frame index, we can create a FrameIndex debug value 1462 // without relying on the DAG at all. 1463 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1464 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1465 if (SI != FuncInfo.StaticAllocaMap.end()) { 1466 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1467 continue; 1468 } 1469 } 1470 1471 // Do not use getValue() in here; we don't want to generate code at 1472 // this point if it hasn't been done yet. 1473 SDValue N = NodeMap[V]; 1474 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1475 N = UnusedArgNodeMap[V]; 1476 if (N.getNode()) { 1477 // Only emit func arg dbg value for non-variadic dbg.values for now. 1478 if (!IsVariadic && 1479 EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc, 1480 FuncArgumentDbgValueKind::Value, N)) 1481 return true; 1482 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1483 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1484 // describe stack slot locations. 1485 // 1486 // Consider "int x = 0; int *px = &x;". There are two kinds of 1487 // interesting debug values here after optimization: 1488 // 1489 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1490 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1491 // 1492 // Both describe the direct values of their associated variables. 1493 Dependencies.push_back(N.getNode()); 1494 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1495 continue; 1496 } 1497 LocationOps.emplace_back( 1498 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1499 continue; 1500 } 1501 1502 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1503 // Special rules apply for the first dbg.values of parameter variables in a 1504 // function. Identify them by the fact they reference Argument Values, that 1505 // they're parameters, and they are parameters of the current function. We 1506 // need to let them dangle until they get an SDNode. 1507 bool IsParamOfFunc = 1508 isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt(); 1509 if (IsParamOfFunc) 1510 return false; 1511 1512 // The value is not used in this block yet (or it would have an SDNode). 1513 // We still want the value to appear for the user if possible -- if it has 1514 // an associated VReg, we can refer to that instead. 1515 auto VMI = FuncInfo.ValueMap.find(V); 1516 if (VMI != FuncInfo.ValueMap.end()) { 1517 unsigned Reg = VMI->second; 1518 // If this is a PHI node, it may be split up into several MI PHI nodes 1519 // (in FunctionLoweringInfo::set). 1520 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1521 V->getType(), std::nullopt); 1522 if (RFV.occupiesMultipleRegs()) { 1523 // FIXME: We could potentially support variadic dbg_values here. 1524 if (IsVariadic) 1525 return false; 1526 unsigned Offset = 0; 1527 unsigned BitsToDescribe = 0; 1528 if (auto VarSize = Var->getSizeInBits()) 1529 BitsToDescribe = *VarSize; 1530 if (auto Fragment = Expr->getFragmentInfo()) 1531 BitsToDescribe = Fragment->SizeInBits; 1532 for (const auto &RegAndSize : RFV.getRegsAndSizes()) { 1533 // Bail out if all bits are described already. 1534 if (Offset >= BitsToDescribe) 1535 break; 1536 // TODO: handle scalable vectors. 1537 unsigned RegisterSize = RegAndSize.second; 1538 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1539 ? BitsToDescribe - Offset 1540 : RegisterSize; 1541 auto FragmentExpr = DIExpression::createFragmentExpression( 1542 Expr, Offset, FragmentSize); 1543 if (!FragmentExpr) 1544 continue; 1545 SDDbgValue *SDV = DAG.getVRegDbgValue( 1546 Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, SDNodeOrder); 1547 DAG.AddDbgValue(SDV, false); 1548 Offset += RegisterSize; 1549 } 1550 return true; 1551 } 1552 // We can use simple vreg locations for variadic dbg_values as well. 1553 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1554 continue; 1555 } 1556 // We failed to create a SDDbgOperand for V. 1557 return false; 1558 } 1559 1560 // We have created a SDDbgOperand for each Value in Values. 1561 // Should use Order instead of SDNodeOrder? 1562 assert(!LocationOps.empty()); 1563 SDDbgValue *SDV = DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1564 /*IsIndirect=*/false, DbgLoc, 1565 SDNodeOrder, IsVariadic); 1566 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1567 return true; 1568 } 1569 1570 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1571 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1572 for (auto &Pair : DanglingDebugInfoMap) 1573 for (auto &DDI : Pair.second) 1574 salvageUnresolvedDbgValue(DDI); 1575 clearDanglingDebugInfo(); 1576 } 1577 1578 /// getCopyFromRegs - If there was virtual register allocated for the value V 1579 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1580 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1581 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1582 SDValue Result; 1583 1584 if (It != FuncInfo.ValueMap.end()) { 1585 Register InReg = It->second; 1586 1587 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1588 DAG.getDataLayout(), InReg, Ty, 1589 std::nullopt); // This is not an ABI copy. 1590 SDValue Chain = DAG.getEntryNode(); 1591 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1592 V); 1593 resolveDanglingDebugInfo(V, Result); 1594 } 1595 1596 return Result; 1597 } 1598 1599 /// getValue - Return an SDValue for the given Value. 1600 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1601 // If we already have an SDValue for this value, use it. It's important 1602 // to do this first, so that we don't create a CopyFromReg if we already 1603 // have a regular SDValue. 1604 SDValue &N = NodeMap[V]; 1605 if (N.getNode()) return N; 1606 1607 // If there's a virtual register allocated and initialized for this 1608 // value, use it. 1609 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1610 return copyFromReg; 1611 1612 // Otherwise create a new SDValue and remember it. 1613 SDValue Val = getValueImpl(V); 1614 NodeMap[V] = Val; 1615 resolveDanglingDebugInfo(V, Val); 1616 return Val; 1617 } 1618 1619 /// getNonRegisterValue - Return an SDValue for the given Value, but 1620 /// don't look in FuncInfo.ValueMap for a virtual register. 1621 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1622 // If we already have an SDValue for this value, use it. 1623 SDValue &N = NodeMap[V]; 1624 if (N.getNode()) { 1625 if (isIntOrFPConstant(N)) { 1626 // Remove the debug location from the node as the node is about to be used 1627 // in a location which may differ from the original debug location. This 1628 // is relevant to Constant and ConstantFP nodes because they can appear 1629 // as constant expressions inside PHI nodes. 1630 N->setDebugLoc(DebugLoc()); 1631 } 1632 return N; 1633 } 1634 1635 // Otherwise create a new SDValue and remember it. 1636 SDValue Val = getValueImpl(V); 1637 NodeMap[V] = Val; 1638 resolveDanglingDebugInfo(V, Val); 1639 return Val; 1640 } 1641 1642 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1643 /// Create an SDValue for the given value. 1644 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1645 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1646 1647 if (const Constant *C = dyn_cast<Constant>(V)) { 1648 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1649 1650 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1651 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1652 1653 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1654 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1655 1656 if (isa<ConstantPointerNull>(C)) { 1657 unsigned AS = V->getType()->getPointerAddressSpace(); 1658 return DAG.getConstant(0, getCurSDLoc(), 1659 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1660 } 1661 1662 if (match(C, m_VScale())) 1663 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1664 1665 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1666 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1667 1668 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1669 return DAG.getUNDEF(VT); 1670 1671 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1672 visit(CE->getOpcode(), *CE); 1673 SDValue N1 = NodeMap[V]; 1674 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1675 return N1; 1676 } 1677 1678 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1679 SmallVector<SDValue, 4> Constants; 1680 for (const Use &U : C->operands()) { 1681 SDNode *Val = getValue(U).getNode(); 1682 // If the operand is an empty aggregate, there are no values. 1683 if (!Val) continue; 1684 // Add each leaf value from the operand to the Constants list 1685 // to form a flattened list of all the values. 1686 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1687 Constants.push_back(SDValue(Val, i)); 1688 } 1689 1690 return DAG.getMergeValues(Constants, getCurSDLoc()); 1691 } 1692 1693 if (const ConstantDataSequential *CDS = 1694 dyn_cast<ConstantDataSequential>(C)) { 1695 SmallVector<SDValue, 4> Ops; 1696 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1697 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1698 // Add each leaf value from the operand to the Constants list 1699 // to form a flattened list of all the values. 1700 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1701 Ops.push_back(SDValue(Val, i)); 1702 } 1703 1704 if (isa<ArrayType>(CDS->getType())) 1705 return DAG.getMergeValues(Ops, getCurSDLoc()); 1706 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1707 } 1708 1709 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1710 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1711 "Unknown struct or array constant!"); 1712 1713 SmallVector<EVT, 4> ValueVTs; 1714 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1715 unsigned NumElts = ValueVTs.size(); 1716 if (NumElts == 0) 1717 return SDValue(); // empty struct 1718 SmallVector<SDValue, 4> Constants(NumElts); 1719 for (unsigned i = 0; i != NumElts; ++i) { 1720 EVT EltVT = ValueVTs[i]; 1721 if (isa<UndefValue>(C)) 1722 Constants[i] = DAG.getUNDEF(EltVT); 1723 else if (EltVT.isFloatingPoint()) 1724 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1725 else 1726 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1727 } 1728 1729 return DAG.getMergeValues(Constants, getCurSDLoc()); 1730 } 1731 1732 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1733 return DAG.getBlockAddress(BA, VT); 1734 1735 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1736 return getValue(Equiv->getGlobalValue()); 1737 1738 if (const auto *NC = dyn_cast<NoCFIValue>(C)) 1739 return getValue(NC->getGlobalValue()); 1740 1741 VectorType *VecTy = cast<VectorType>(V->getType()); 1742 1743 // Now that we know the number and type of the elements, get that number of 1744 // elements into the Ops array based on what kind of constant it is. 1745 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1746 SmallVector<SDValue, 16> Ops; 1747 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1748 for (unsigned i = 0; i != NumElements; ++i) 1749 Ops.push_back(getValue(CV->getOperand(i))); 1750 1751 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1752 } 1753 1754 if (isa<ConstantAggregateZero>(C)) { 1755 EVT EltVT = 1756 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1757 1758 SDValue Op; 1759 if (EltVT.isFloatingPoint()) 1760 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1761 else 1762 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1763 1764 return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op); 1765 } 1766 1767 llvm_unreachable("Unknown vector constant"); 1768 } 1769 1770 // If this is a static alloca, generate it as the frameindex instead of 1771 // computation. 1772 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1773 DenseMap<const AllocaInst*, int>::iterator SI = 1774 FuncInfo.StaticAllocaMap.find(AI); 1775 if (SI != FuncInfo.StaticAllocaMap.end()) 1776 return DAG.getFrameIndex( 1777 SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType())); 1778 } 1779 1780 // If this is an instruction which fast-isel has deferred, select it now. 1781 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1782 Register InReg = FuncInfo.InitializeRegForValue(Inst); 1783 1784 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1785 Inst->getType(), std::nullopt); 1786 SDValue Chain = DAG.getEntryNode(); 1787 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1788 } 1789 1790 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) 1791 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1792 1793 if (const auto *BB = dyn_cast<BasicBlock>(V)) 1794 return DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 1795 1796 llvm_unreachable("Can't get register for value!"); 1797 } 1798 1799 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1800 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1801 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1802 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1803 bool IsSEH = isAsynchronousEHPersonality(Pers); 1804 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1805 if (!IsSEH) 1806 CatchPadMBB->setIsEHScopeEntry(); 1807 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1808 if (IsMSVCCXX || IsCoreCLR) 1809 CatchPadMBB->setIsEHFuncletEntry(); 1810 } 1811 1812 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1813 // Update machine-CFG edge. 1814 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1815 FuncInfo.MBB->addSuccessor(TargetMBB); 1816 TargetMBB->setIsEHCatchretTarget(true); 1817 DAG.getMachineFunction().setHasEHCatchret(true); 1818 1819 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1820 bool IsSEH = isAsynchronousEHPersonality(Pers); 1821 if (IsSEH) { 1822 // If this is not a fall-through branch or optimizations are switched off, 1823 // emit the branch. 1824 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1825 TM.getOptLevel() == CodeGenOpt::None) 1826 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1827 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1828 return; 1829 } 1830 1831 // Figure out the funclet membership for the catchret's successor. 1832 // This will be used by the FuncletLayout pass to determine how to order the 1833 // BB's. 1834 // A 'catchret' returns to the outer scope's color. 1835 Value *ParentPad = I.getCatchSwitchParentPad(); 1836 const BasicBlock *SuccessorColor; 1837 if (isa<ConstantTokenNone>(ParentPad)) 1838 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1839 else 1840 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1841 assert(SuccessorColor && "No parent funclet for catchret!"); 1842 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1843 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1844 1845 // Create the terminator node. 1846 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1847 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1848 DAG.getBasicBlock(SuccessorColorMBB)); 1849 DAG.setRoot(Ret); 1850 } 1851 1852 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1853 // Don't emit any special code for the cleanuppad instruction. It just marks 1854 // the start of an EH scope/funclet. 1855 FuncInfo.MBB->setIsEHScopeEntry(); 1856 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1857 if (Pers != EHPersonality::Wasm_CXX) { 1858 FuncInfo.MBB->setIsEHFuncletEntry(); 1859 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1860 } 1861 } 1862 1863 // In wasm EH, even though a catchpad may not catch an exception if a tag does 1864 // not match, it is OK to add only the first unwind destination catchpad to the 1865 // successors, because there will be at least one invoke instruction within the 1866 // catch scope that points to the next unwind destination, if one exists, so 1867 // CFGSort cannot mess up with BB sorting order. 1868 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 1869 // call within them, and catchpads only consisting of 'catch (...)' have a 1870 // '__cxa_end_catch' call within them, both of which generate invokes in case 1871 // the next unwind destination exists, i.e., the next unwind destination is not 1872 // the caller.) 1873 // 1874 // Having at most one EH pad successor is also simpler and helps later 1875 // transformations. 1876 // 1877 // For example, 1878 // current: 1879 // invoke void @foo to ... unwind label %catch.dispatch 1880 // catch.dispatch: 1881 // %0 = catchswitch within ... [label %catch.start] unwind label %next 1882 // catch.start: 1883 // ... 1884 // ... in this BB or some other child BB dominated by this BB there will be an 1885 // invoke that points to 'next' BB as an unwind destination 1886 // 1887 // next: ; We don't need to add this to 'current' BB's successor 1888 // ... 1889 static void findWasmUnwindDestinations( 1890 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1891 BranchProbability Prob, 1892 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1893 &UnwindDests) { 1894 while (EHPadBB) { 1895 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1896 if (isa<CleanupPadInst>(Pad)) { 1897 // Stop on cleanup pads. 1898 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1899 UnwindDests.back().first->setIsEHScopeEntry(); 1900 break; 1901 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1902 // Add the catchpad handlers to the possible destinations. We don't 1903 // continue to the unwind destination of the catchswitch for wasm. 1904 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1905 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1906 UnwindDests.back().first->setIsEHScopeEntry(); 1907 } 1908 break; 1909 } else { 1910 continue; 1911 } 1912 } 1913 } 1914 1915 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1916 /// many places it could ultimately go. In the IR, we have a single unwind 1917 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1918 /// This function skips over imaginary basic blocks that hold catchswitch 1919 /// instructions, and finds all the "real" machine 1920 /// basic block destinations. As those destinations may not be successors of 1921 /// EHPadBB, here we also calculate the edge probability to those destinations. 1922 /// The passed-in Prob is the edge probability to EHPadBB. 1923 static void findUnwindDestinations( 1924 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1925 BranchProbability Prob, 1926 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1927 &UnwindDests) { 1928 EHPersonality Personality = 1929 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1930 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1931 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1932 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1933 bool IsSEH = isAsynchronousEHPersonality(Personality); 1934 1935 if (IsWasmCXX) { 1936 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1937 assert(UnwindDests.size() <= 1 && 1938 "There should be at most one unwind destination for wasm"); 1939 return; 1940 } 1941 1942 while (EHPadBB) { 1943 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1944 BasicBlock *NewEHPadBB = nullptr; 1945 if (isa<LandingPadInst>(Pad)) { 1946 // Stop on landingpads. They are not funclets. 1947 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1948 break; 1949 } else if (isa<CleanupPadInst>(Pad)) { 1950 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1951 // personalities. 1952 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1953 UnwindDests.back().first->setIsEHScopeEntry(); 1954 UnwindDests.back().first->setIsEHFuncletEntry(); 1955 break; 1956 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1957 // Add the catchpad handlers to the possible destinations. 1958 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1959 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1960 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1961 if (IsMSVCCXX || IsCoreCLR) 1962 UnwindDests.back().first->setIsEHFuncletEntry(); 1963 if (!IsSEH) 1964 UnwindDests.back().first->setIsEHScopeEntry(); 1965 } 1966 NewEHPadBB = CatchSwitch->getUnwindDest(); 1967 } else { 1968 continue; 1969 } 1970 1971 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1972 if (BPI && NewEHPadBB) 1973 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1974 EHPadBB = NewEHPadBB; 1975 } 1976 } 1977 1978 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1979 // Update successor info. 1980 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1981 auto UnwindDest = I.getUnwindDest(); 1982 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1983 BranchProbability UnwindDestProb = 1984 (BPI && UnwindDest) 1985 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1986 : BranchProbability::getZero(); 1987 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1988 for (auto &UnwindDest : UnwindDests) { 1989 UnwindDest.first->setIsEHPad(); 1990 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1991 } 1992 FuncInfo.MBB->normalizeSuccProbs(); 1993 1994 // Create the terminator node. 1995 SDValue Ret = 1996 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1997 DAG.setRoot(Ret); 1998 } 1999 2000 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 2001 report_fatal_error("visitCatchSwitch not yet implemented!"); 2002 } 2003 2004 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 2005 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2006 auto &DL = DAG.getDataLayout(); 2007 SDValue Chain = getControlRoot(); 2008 SmallVector<ISD::OutputArg, 8> Outs; 2009 SmallVector<SDValue, 8> OutVals; 2010 2011 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 2012 // lower 2013 // 2014 // %val = call <ty> @llvm.experimental.deoptimize() 2015 // ret <ty> %val 2016 // 2017 // differently. 2018 if (I.getParent()->getTerminatingDeoptimizeCall()) { 2019 LowerDeoptimizingReturn(); 2020 return; 2021 } 2022 2023 if (!FuncInfo.CanLowerReturn) { 2024 unsigned DemoteReg = FuncInfo.DemoteRegister; 2025 const Function *F = I.getParent()->getParent(); 2026 2027 // Emit a store of the return value through the virtual register. 2028 // Leave Outs empty so that LowerReturn won't try to load return 2029 // registers the usual way. 2030 SmallVector<EVT, 1> PtrValueVTs; 2031 ComputeValueVTs(TLI, DL, 2032 PointerType::get(F->getContext(), 2033 DAG.getDataLayout().getAllocaAddrSpace()), 2034 PtrValueVTs); 2035 2036 SDValue RetPtr = 2037 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]); 2038 SDValue RetOp = getValue(I.getOperand(0)); 2039 2040 SmallVector<EVT, 4> ValueVTs, MemVTs; 2041 SmallVector<uint64_t, 4> Offsets; 2042 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 2043 &Offsets, 0); 2044 unsigned NumValues = ValueVTs.size(); 2045 2046 SmallVector<SDValue, 4> Chains(NumValues); 2047 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 2048 for (unsigned i = 0; i != NumValues; ++i) { 2049 // An aggregate return value cannot wrap around the address space, so 2050 // offsets to its parts don't wrap either. 2051 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 2052 TypeSize::Fixed(Offsets[i])); 2053 2054 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 2055 if (MemVTs[i] != ValueVTs[i]) 2056 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 2057 Chains[i] = DAG.getStore( 2058 Chain, getCurSDLoc(), Val, 2059 // FIXME: better loc info would be nice. 2060 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 2061 commonAlignment(BaseAlign, Offsets[i])); 2062 } 2063 2064 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 2065 MVT::Other, Chains); 2066 } else if (I.getNumOperands() != 0) { 2067 SmallVector<EVT, 4> ValueVTs; 2068 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 2069 unsigned NumValues = ValueVTs.size(); 2070 if (NumValues) { 2071 SDValue RetOp = getValue(I.getOperand(0)); 2072 2073 const Function *F = I.getParent()->getParent(); 2074 2075 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 2076 I.getOperand(0)->getType(), F->getCallingConv(), 2077 /*IsVarArg*/ false, DL); 2078 2079 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 2080 if (F->getAttributes().hasRetAttr(Attribute::SExt)) 2081 ExtendKind = ISD::SIGN_EXTEND; 2082 else if (F->getAttributes().hasRetAttr(Attribute::ZExt)) 2083 ExtendKind = ISD::ZERO_EXTEND; 2084 2085 LLVMContext &Context = F->getContext(); 2086 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg); 2087 2088 for (unsigned j = 0; j != NumValues; ++j) { 2089 EVT VT = ValueVTs[j]; 2090 2091 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 2092 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 2093 2094 CallingConv::ID CC = F->getCallingConv(); 2095 2096 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 2097 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 2098 SmallVector<SDValue, 4> Parts(NumParts); 2099 getCopyToParts(DAG, getCurSDLoc(), 2100 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 2101 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 2102 2103 // 'inreg' on function refers to return value 2104 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2105 if (RetInReg) 2106 Flags.setInReg(); 2107 2108 if (I.getOperand(0)->getType()->isPointerTy()) { 2109 Flags.setPointer(); 2110 Flags.setPointerAddrSpace( 2111 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 2112 } 2113 2114 if (NeedsRegBlock) { 2115 Flags.setInConsecutiveRegs(); 2116 if (j == NumValues - 1) 2117 Flags.setInConsecutiveRegsLast(); 2118 } 2119 2120 // Propagate extension type if any 2121 if (ExtendKind == ISD::SIGN_EXTEND) 2122 Flags.setSExt(); 2123 else if (ExtendKind == ISD::ZERO_EXTEND) 2124 Flags.setZExt(); 2125 2126 for (unsigned i = 0; i < NumParts; ++i) { 2127 Outs.push_back(ISD::OutputArg(Flags, 2128 Parts[i].getValueType().getSimpleVT(), 2129 VT, /*isfixed=*/true, 0, 0)); 2130 OutVals.push_back(Parts[i]); 2131 } 2132 } 2133 } 2134 } 2135 2136 // Push in swifterror virtual register as the last element of Outs. This makes 2137 // sure swifterror virtual register will be returned in the swifterror 2138 // physical register. 2139 const Function *F = I.getParent()->getParent(); 2140 if (TLI.supportSwiftError() && 2141 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2142 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2143 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2144 Flags.setSwiftError(); 2145 Outs.push_back(ISD::OutputArg( 2146 Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)), 2147 /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0)); 2148 // Create SDNode for the swifterror virtual register. 2149 OutVals.push_back( 2150 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2151 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2152 EVT(TLI.getPointerTy(DL)))); 2153 } 2154 2155 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2156 CallingConv::ID CallConv = 2157 DAG.getMachineFunction().getFunction().getCallingConv(); 2158 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2159 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2160 2161 // Verify that the target's LowerReturn behaved as expected. 2162 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2163 "LowerReturn didn't return a valid chain!"); 2164 2165 // Update the DAG with the new chain value resulting from return lowering. 2166 DAG.setRoot(Chain); 2167 } 2168 2169 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2170 /// created for it, emit nodes to copy the value into the virtual 2171 /// registers. 2172 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2173 // Skip empty types 2174 if (V->getType()->isEmptyTy()) 2175 return; 2176 2177 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2178 if (VMI != FuncInfo.ValueMap.end()) { 2179 assert((!V->use_empty() || isa<CallBrInst>(V)) && 2180 "Unused value assigned virtual registers!"); 2181 CopyValueToVirtualRegister(V, VMI->second); 2182 } 2183 } 2184 2185 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2186 /// the current basic block, add it to ValueMap now so that we'll get a 2187 /// CopyTo/FromReg. 2188 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2189 // No need to export constants. 2190 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2191 2192 // Already exported? 2193 if (FuncInfo.isExportedInst(V)) return; 2194 2195 Register Reg = FuncInfo.InitializeRegForValue(V); 2196 CopyValueToVirtualRegister(V, Reg); 2197 } 2198 2199 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2200 const BasicBlock *FromBB) { 2201 // The operands of the setcc have to be in this block. We don't know 2202 // how to export them from some other block. 2203 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2204 // Can export from current BB. 2205 if (VI->getParent() == FromBB) 2206 return true; 2207 2208 // Is already exported, noop. 2209 return FuncInfo.isExportedInst(V); 2210 } 2211 2212 // If this is an argument, we can export it if the BB is the entry block or 2213 // if it is already exported. 2214 if (isa<Argument>(V)) { 2215 if (FromBB->isEntryBlock()) 2216 return true; 2217 2218 // Otherwise, can only export this if it is already exported. 2219 return FuncInfo.isExportedInst(V); 2220 } 2221 2222 // Otherwise, constants can always be exported. 2223 return true; 2224 } 2225 2226 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2227 BranchProbability 2228 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2229 const MachineBasicBlock *Dst) const { 2230 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2231 const BasicBlock *SrcBB = Src->getBasicBlock(); 2232 const BasicBlock *DstBB = Dst->getBasicBlock(); 2233 if (!BPI) { 2234 // If BPI is not available, set the default probability as 1 / N, where N is 2235 // the number of successors. 2236 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2237 return BranchProbability(1, SuccSize); 2238 } 2239 return BPI->getEdgeProbability(SrcBB, DstBB); 2240 } 2241 2242 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2243 MachineBasicBlock *Dst, 2244 BranchProbability Prob) { 2245 if (!FuncInfo.BPI) 2246 Src->addSuccessorWithoutProb(Dst); 2247 else { 2248 if (Prob.isUnknown()) 2249 Prob = getEdgeProbability(Src, Dst); 2250 Src->addSuccessor(Dst, Prob); 2251 } 2252 } 2253 2254 static bool InBlock(const Value *V, const BasicBlock *BB) { 2255 if (const Instruction *I = dyn_cast<Instruction>(V)) 2256 return I->getParent() == BB; 2257 return true; 2258 } 2259 2260 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2261 /// This function emits a branch and is used at the leaves of an OR or an 2262 /// AND operator tree. 2263 void 2264 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2265 MachineBasicBlock *TBB, 2266 MachineBasicBlock *FBB, 2267 MachineBasicBlock *CurBB, 2268 MachineBasicBlock *SwitchBB, 2269 BranchProbability TProb, 2270 BranchProbability FProb, 2271 bool InvertCond) { 2272 const BasicBlock *BB = CurBB->getBasicBlock(); 2273 2274 // If the leaf of the tree is a comparison, merge the condition into 2275 // the caseblock. 2276 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2277 // The operands of the cmp have to be in this block. We don't know 2278 // how to export them from some other block. If this is the first block 2279 // of the sequence, no exporting is needed. 2280 if (CurBB == SwitchBB || 2281 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2282 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2283 ISD::CondCode Condition; 2284 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2285 ICmpInst::Predicate Pred = 2286 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2287 Condition = getICmpCondCode(Pred); 2288 } else { 2289 const FCmpInst *FC = cast<FCmpInst>(Cond); 2290 FCmpInst::Predicate Pred = 2291 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2292 Condition = getFCmpCondCode(Pred); 2293 if (TM.Options.NoNaNsFPMath) 2294 Condition = getFCmpCodeWithoutNaN(Condition); 2295 } 2296 2297 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2298 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2299 SL->SwitchCases.push_back(CB); 2300 return; 2301 } 2302 } 2303 2304 // Create a CaseBlock record representing this branch. 2305 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2306 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2307 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2308 SL->SwitchCases.push_back(CB); 2309 } 2310 2311 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2312 MachineBasicBlock *TBB, 2313 MachineBasicBlock *FBB, 2314 MachineBasicBlock *CurBB, 2315 MachineBasicBlock *SwitchBB, 2316 Instruction::BinaryOps Opc, 2317 BranchProbability TProb, 2318 BranchProbability FProb, 2319 bool InvertCond) { 2320 // Skip over not part of the tree and remember to invert op and operands at 2321 // next level. 2322 Value *NotCond; 2323 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2324 InBlock(NotCond, CurBB->getBasicBlock())) { 2325 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2326 !InvertCond); 2327 return; 2328 } 2329 2330 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2331 const Value *BOpOp0, *BOpOp1; 2332 // Compute the effective opcode for Cond, taking into account whether it needs 2333 // to be inverted, e.g. 2334 // and (not (or A, B)), C 2335 // gets lowered as 2336 // and (and (not A, not B), C) 2337 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2338 if (BOp) { 2339 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2340 ? Instruction::And 2341 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2342 ? Instruction::Or 2343 : (Instruction::BinaryOps)0); 2344 if (InvertCond) { 2345 if (BOpc == Instruction::And) 2346 BOpc = Instruction::Or; 2347 else if (BOpc == Instruction::Or) 2348 BOpc = Instruction::And; 2349 } 2350 } 2351 2352 // If this node is not part of the or/and tree, emit it as a branch. 2353 // Note that all nodes in the tree should have same opcode. 2354 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2355 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2356 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2357 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2358 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2359 TProb, FProb, InvertCond); 2360 return; 2361 } 2362 2363 // Create TmpBB after CurBB. 2364 MachineFunction::iterator BBI(CurBB); 2365 MachineFunction &MF = DAG.getMachineFunction(); 2366 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2367 CurBB->getParent()->insert(++BBI, TmpBB); 2368 2369 if (Opc == Instruction::Or) { 2370 // Codegen X | Y as: 2371 // BB1: 2372 // jmp_if_X TBB 2373 // jmp TmpBB 2374 // TmpBB: 2375 // jmp_if_Y TBB 2376 // jmp FBB 2377 // 2378 2379 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2380 // The requirement is that 2381 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2382 // = TrueProb for original BB. 2383 // Assuming the original probabilities are A and B, one choice is to set 2384 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2385 // A/(1+B) and 2B/(1+B). This choice assumes that 2386 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2387 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2388 // TmpBB, but the math is more complicated. 2389 2390 auto NewTrueProb = TProb / 2; 2391 auto NewFalseProb = TProb / 2 + FProb; 2392 // Emit the LHS condition. 2393 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2394 NewFalseProb, InvertCond); 2395 2396 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2397 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2398 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2399 // Emit the RHS condition into TmpBB. 2400 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2401 Probs[1], InvertCond); 2402 } else { 2403 assert(Opc == Instruction::And && "Unknown merge op!"); 2404 // Codegen X & Y as: 2405 // BB1: 2406 // jmp_if_X TmpBB 2407 // jmp FBB 2408 // TmpBB: 2409 // jmp_if_Y TBB 2410 // jmp FBB 2411 // 2412 // This requires creation of TmpBB after CurBB. 2413 2414 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2415 // The requirement is that 2416 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2417 // = FalseProb for original BB. 2418 // Assuming the original probabilities are A and B, one choice is to set 2419 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2420 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2421 // TrueProb for BB1 * FalseProb for TmpBB. 2422 2423 auto NewTrueProb = TProb + FProb / 2; 2424 auto NewFalseProb = FProb / 2; 2425 // Emit the LHS condition. 2426 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2427 NewFalseProb, InvertCond); 2428 2429 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2430 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2431 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2432 // Emit the RHS condition into TmpBB. 2433 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2434 Probs[1], InvertCond); 2435 } 2436 } 2437 2438 /// If the set of cases should be emitted as a series of branches, return true. 2439 /// If we should emit this as a bunch of and/or'd together conditions, return 2440 /// false. 2441 bool 2442 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2443 if (Cases.size() != 2) return true; 2444 2445 // If this is two comparisons of the same values or'd or and'd together, they 2446 // will get folded into a single comparison, so don't emit two blocks. 2447 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2448 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2449 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2450 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2451 return false; 2452 } 2453 2454 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2455 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2456 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2457 Cases[0].CC == Cases[1].CC && 2458 isa<Constant>(Cases[0].CmpRHS) && 2459 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2460 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2461 return false; 2462 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2463 return false; 2464 } 2465 2466 return true; 2467 } 2468 2469 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2470 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2471 2472 // Update machine-CFG edges. 2473 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2474 2475 if (I.isUnconditional()) { 2476 // Update machine-CFG edges. 2477 BrMBB->addSuccessor(Succ0MBB); 2478 2479 // If this is not a fall-through branch or optimizations are switched off, 2480 // emit the branch. 2481 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) { 2482 auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 2483 getControlRoot(), DAG.getBasicBlock(Succ0MBB)); 2484 setValue(&I, Br); 2485 DAG.setRoot(Br); 2486 } 2487 2488 return; 2489 } 2490 2491 // If this condition is one of the special cases we handle, do special stuff 2492 // now. 2493 const Value *CondVal = I.getCondition(); 2494 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2495 2496 // If this is a series of conditions that are or'd or and'd together, emit 2497 // this as a sequence of branches instead of setcc's with and/or operations. 2498 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2499 // unpredictable branches, and vector extracts because those jumps are likely 2500 // expensive for any target), this should improve performance. 2501 // For example, instead of something like: 2502 // cmp A, B 2503 // C = seteq 2504 // cmp D, E 2505 // F = setle 2506 // or C, F 2507 // jnz foo 2508 // Emit: 2509 // cmp A, B 2510 // je foo 2511 // cmp D, E 2512 // jle foo 2513 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2514 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2515 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2516 Value *Vec; 2517 const Value *BOp0, *BOp1; 2518 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2519 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2520 Opcode = Instruction::And; 2521 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2522 Opcode = Instruction::Or; 2523 2524 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2525 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2526 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2527 getEdgeProbability(BrMBB, Succ0MBB), 2528 getEdgeProbability(BrMBB, Succ1MBB), 2529 /*InvertCond=*/false); 2530 // If the compares in later blocks need to use values not currently 2531 // exported from this block, export them now. This block should always 2532 // be the first entry. 2533 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2534 2535 // Allow some cases to be rejected. 2536 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2537 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2538 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2539 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2540 } 2541 2542 // Emit the branch for this block. 2543 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2544 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2545 return; 2546 } 2547 2548 // Okay, we decided not to do this, remove any inserted MBB's and clear 2549 // SwitchCases. 2550 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2551 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2552 2553 SL->SwitchCases.clear(); 2554 } 2555 } 2556 2557 // Create a CaseBlock record representing this branch. 2558 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2559 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2560 2561 // Use visitSwitchCase to actually insert the fast branch sequence for this 2562 // cond branch. 2563 visitSwitchCase(CB, BrMBB); 2564 } 2565 2566 /// visitSwitchCase - Emits the necessary code to represent a single node in 2567 /// the binary search tree resulting from lowering a switch instruction. 2568 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2569 MachineBasicBlock *SwitchBB) { 2570 SDValue Cond; 2571 SDValue CondLHS = getValue(CB.CmpLHS); 2572 SDLoc dl = CB.DL; 2573 2574 if (CB.CC == ISD::SETTRUE) { 2575 // Branch or fall through to TrueBB. 2576 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2577 SwitchBB->normalizeSuccProbs(); 2578 if (CB.TrueBB != NextBlock(SwitchBB)) { 2579 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2580 DAG.getBasicBlock(CB.TrueBB))); 2581 } 2582 return; 2583 } 2584 2585 auto &TLI = DAG.getTargetLoweringInfo(); 2586 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2587 2588 // Build the setcc now. 2589 if (!CB.CmpMHS) { 2590 // Fold "(X == true)" to X and "(X == false)" to !X to 2591 // handle common cases produced by branch lowering. 2592 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2593 CB.CC == ISD::SETEQ) 2594 Cond = CondLHS; 2595 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2596 CB.CC == ISD::SETEQ) { 2597 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2598 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2599 } else { 2600 SDValue CondRHS = getValue(CB.CmpRHS); 2601 2602 // If a pointer's DAG type is larger than its memory type then the DAG 2603 // values are zero-extended. This breaks signed comparisons so truncate 2604 // back to the underlying type before doing the compare. 2605 if (CondLHS.getValueType() != MemVT) { 2606 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2607 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2608 } 2609 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2610 } 2611 } else { 2612 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2613 2614 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2615 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2616 2617 SDValue CmpOp = getValue(CB.CmpMHS); 2618 EVT VT = CmpOp.getValueType(); 2619 2620 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2621 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2622 ISD::SETLE); 2623 } else { 2624 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2625 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2626 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2627 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2628 } 2629 } 2630 2631 // Update successor info 2632 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2633 // TrueBB and FalseBB are always different unless the incoming IR is 2634 // degenerate. This only happens when running llc on weird IR. 2635 if (CB.TrueBB != CB.FalseBB) 2636 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2637 SwitchBB->normalizeSuccProbs(); 2638 2639 // If the lhs block is the next block, invert the condition so that we can 2640 // fall through to the lhs instead of the rhs block. 2641 if (CB.TrueBB == NextBlock(SwitchBB)) { 2642 std::swap(CB.TrueBB, CB.FalseBB); 2643 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2644 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2645 } 2646 2647 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2648 MVT::Other, getControlRoot(), Cond, 2649 DAG.getBasicBlock(CB.TrueBB)); 2650 2651 setValue(CurInst, BrCond); 2652 2653 // Insert the false branch. Do this even if it's a fall through branch, 2654 // this makes it easier to do DAG optimizations which require inverting 2655 // the branch condition. 2656 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2657 DAG.getBasicBlock(CB.FalseBB)); 2658 2659 DAG.setRoot(BrCond); 2660 } 2661 2662 /// visitJumpTable - Emit JumpTable node in the current MBB 2663 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2664 // Emit the code for the jump table 2665 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2666 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2667 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2668 JT.Reg, PTy); 2669 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2670 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2671 MVT::Other, Index.getValue(1), 2672 Table, Index); 2673 DAG.setRoot(BrJumpTable); 2674 } 2675 2676 /// visitJumpTableHeader - This function emits necessary code to produce index 2677 /// in the JumpTable from switch case. 2678 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2679 JumpTableHeader &JTH, 2680 MachineBasicBlock *SwitchBB) { 2681 SDLoc dl = getCurSDLoc(); 2682 2683 // Subtract the lowest switch case value from the value being switched on. 2684 SDValue SwitchOp = getValue(JTH.SValue); 2685 EVT VT = SwitchOp.getValueType(); 2686 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2687 DAG.getConstant(JTH.First, dl, VT)); 2688 2689 // The SDNode we just created, which holds the value being switched on minus 2690 // the smallest case value, needs to be copied to a virtual register so it 2691 // can be used as an index into the jump table in a subsequent basic block. 2692 // This value may be smaller or larger than the target's pointer type, and 2693 // therefore require extension or truncating. 2694 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2695 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2696 2697 unsigned JumpTableReg = 2698 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2699 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2700 JumpTableReg, SwitchOp); 2701 JT.Reg = JumpTableReg; 2702 2703 if (!JTH.FallthroughUnreachable) { 2704 // Emit the range check for the jump table, and branch to the default block 2705 // for the switch statement if the value being switched on exceeds the 2706 // largest case in the switch. 2707 SDValue CMP = DAG.getSetCC( 2708 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2709 Sub.getValueType()), 2710 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2711 2712 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2713 MVT::Other, CopyTo, CMP, 2714 DAG.getBasicBlock(JT.Default)); 2715 2716 // Avoid emitting unnecessary branches to the next block. 2717 if (JT.MBB != NextBlock(SwitchBB)) 2718 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2719 DAG.getBasicBlock(JT.MBB)); 2720 2721 DAG.setRoot(BrCond); 2722 } else { 2723 // Avoid emitting unnecessary branches to the next block. 2724 if (JT.MBB != NextBlock(SwitchBB)) 2725 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2726 DAG.getBasicBlock(JT.MBB))); 2727 else 2728 DAG.setRoot(CopyTo); 2729 } 2730 } 2731 2732 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2733 /// variable if there exists one. 2734 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2735 SDValue &Chain) { 2736 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2737 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2738 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2739 MachineFunction &MF = DAG.getMachineFunction(); 2740 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2741 MachineSDNode *Node = 2742 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2743 if (Global) { 2744 MachinePointerInfo MPInfo(Global); 2745 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2746 MachineMemOperand::MODereferenceable; 2747 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2748 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2749 DAG.setNodeMemRefs(Node, {MemRef}); 2750 } 2751 if (PtrTy != PtrMemTy) 2752 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2753 return SDValue(Node, 0); 2754 } 2755 2756 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2757 /// tail spliced into a stack protector check success bb. 2758 /// 2759 /// For a high level explanation of how this fits into the stack protector 2760 /// generation see the comment on the declaration of class 2761 /// StackProtectorDescriptor. 2762 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2763 MachineBasicBlock *ParentBB) { 2764 2765 // First create the loads to the guard/stack slot for the comparison. 2766 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2767 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2768 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2769 2770 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2771 int FI = MFI.getStackProtectorIndex(); 2772 2773 SDValue Guard; 2774 SDLoc dl = getCurSDLoc(); 2775 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2776 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2777 Align Align = 2778 DAG.getDataLayout().getPrefTypeAlign(PointerType::get(M.getContext(), 0)); 2779 2780 // Generate code to load the content of the guard slot. 2781 SDValue GuardVal = DAG.getLoad( 2782 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2783 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2784 MachineMemOperand::MOVolatile); 2785 2786 if (TLI.useStackGuardXorFP()) 2787 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2788 2789 // Retrieve guard check function, nullptr if instrumentation is inlined. 2790 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2791 // The target provides a guard check function to validate the guard value. 2792 // Generate a call to that function with the content of the guard slot as 2793 // argument. 2794 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2795 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2796 2797 TargetLowering::ArgListTy Args; 2798 TargetLowering::ArgListEntry Entry; 2799 Entry.Node = GuardVal; 2800 Entry.Ty = FnTy->getParamType(0); 2801 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg)) 2802 Entry.IsInReg = true; 2803 Args.push_back(Entry); 2804 2805 TargetLowering::CallLoweringInfo CLI(DAG); 2806 CLI.setDebugLoc(getCurSDLoc()) 2807 .setChain(DAG.getEntryNode()) 2808 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2809 getValue(GuardCheckFn), std::move(Args)); 2810 2811 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2812 DAG.setRoot(Result.second); 2813 return; 2814 } 2815 2816 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2817 // Otherwise, emit a volatile load to retrieve the stack guard value. 2818 SDValue Chain = DAG.getEntryNode(); 2819 if (TLI.useLoadStackGuardNode()) { 2820 Guard = getLoadStackGuard(DAG, dl, Chain); 2821 } else { 2822 const Value *IRGuard = TLI.getSDagStackGuard(M); 2823 SDValue GuardPtr = getValue(IRGuard); 2824 2825 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2826 MachinePointerInfo(IRGuard, 0), Align, 2827 MachineMemOperand::MOVolatile); 2828 } 2829 2830 // Perform the comparison via a getsetcc. 2831 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2832 *DAG.getContext(), 2833 Guard.getValueType()), 2834 Guard, GuardVal, ISD::SETNE); 2835 2836 // If the guard/stackslot do not equal, branch to failure MBB. 2837 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2838 MVT::Other, GuardVal.getOperand(0), 2839 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2840 // Otherwise branch to success MBB. 2841 SDValue Br = DAG.getNode(ISD::BR, dl, 2842 MVT::Other, BrCond, 2843 DAG.getBasicBlock(SPD.getSuccessMBB())); 2844 2845 DAG.setRoot(Br); 2846 } 2847 2848 /// Codegen the failure basic block for a stack protector check. 2849 /// 2850 /// A failure stack protector machine basic block consists simply of a call to 2851 /// __stack_chk_fail(). 2852 /// 2853 /// For a high level explanation of how this fits into the stack protector 2854 /// generation see the comment on the declaration of class 2855 /// StackProtectorDescriptor. 2856 void 2857 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2858 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2859 TargetLowering::MakeLibCallOptions CallOptions; 2860 CallOptions.setDiscardResult(true); 2861 SDValue Chain = 2862 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2863 std::nullopt, CallOptions, getCurSDLoc()) 2864 .second; 2865 // On PS4/PS5, the "return address" must still be within the calling 2866 // function, even if it's at the very end, so emit an explicit TRAP here. 2867 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2868 if (TM.getTargetTriple().isPS()) 2869 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2870 // WebAssembly needs an unreachable instruction after a non-returning call, 2871 // because the function return type can be different from __stack_chk_fail's 2872 // return type (void). 2873 if (TM.getTargetTriple().isWasm()) 2874 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2875 2876 DAG.setRoot(Chain); 2877 } 2878 2879 /// visitBitTestHeader - This function emits necessary code to produce value 2880 /// suitable for "bit tests" 2881 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2882 MachineBasicBlock *SwitchBB) { 2883 SDLoc dl = getCurSDLoc(); 2884 2885 // Subtract the minimum value. 2886 SDValue SwitchOp = getValue(B.SValue); 2887 EVT VT = SwitchOp.getValueType(); 2888 SDValue RangeSub = 2889 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2890 2891 // Determine the type of the test operands. 2892 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2893 bool UsePtrType = false; 2894 if (!TLI.isTypeLegal(VT)) { 2895 UsePtrType = true; 2896 } else { 2897 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2898 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2899 // Switch table case range are encoded into series of masks. 2900 // Just use pointer type, it's guaranteed to fit. 2901 UsePtrType = true; 2902 break; 2903 } 2904 } 2905 SDValue Sub = RangeSub; 2906 if (UsePtrType) { 2907 VT = TLI.getPointerTy(DAG.getDataLayout()); 2908 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2909 } 2910 2911 B.RegVT = VT.getSimpleVT(); 2912 B.Reg = FuncInfo.CreateReg(B.RegVT); 2913 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2914 2915 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2916 2917 if (!B.FallthroughUnreachable) 2918 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2919 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2920 SwitchBB->normalizeSuccProbs(); 2921 2922 SDValue Root = CopyTo; 2923 if (!B.FallthroughUnreachable) { 2924 // Conditional branch to the default block. 2925 SDValue RangeCmp = DAG.getSetCC(dl, 2926 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2927 RangeSub.getValueType()), 2928 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2929 ISD::SETUGT); 2930 2931 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2932 DAG.getBasicBlock(B.Default)); 2933 } 2934 2935 // Avoid emitting unnecessary branches to the next block. 2936 if (MBB != NextBlock(SwitchBB)) 2937 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2938 2939 DAG.setRoot(Root); 2940 } 2941 2942 /// visitBitTestCase - this function produces one "bit test" 2943 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2944 MachineBasicBlock* NextMBB, 2945 BranchProbability BranchProbToNext, 2946 unsigned Reg, 2947 BitTestCase &B, 2948 MachineBasicBlock *SwitchBB) { 2949 SDLoc dl = getCurSDLoc(); 2950 MVT VT = BB.RegVT; 2951 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2952 SDValue Cmp; 2953 unsigned PopCount = llvm::popcount(B.Mask); 2954 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2955 if (PopCount == 1) { 2956 // Testing for a single bit; just compare the shift count with what it 2957 // would need to be to shift a 1 bit in that position. 2958 Cmp = DAG.getSetCC( 2959 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2960 ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT), 2961 ISD::SETEQ); 2962 } else if (PopCount == BB.Range) { 2963 // There is only one zero bit in the range, test for it directly. 2964 Cmp = DAG.getSetCC( 2965 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2966 ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE); 2967 } else { 2968 // Make desired shift 2969 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2970 DAG.getConstant(1, dl, VT), ShiftOp); 2971 2972 // Emit bit tests and jumps 2973 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2974 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2975 Cmp = DAG.getSetCC( 2976 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2977 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2978 } 2979 2980 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2981 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2982 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2983 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2984 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2985 // one as they are relative probabilities (and thus work more like weights), 2986 // and hence we need to normalize them to let the sum of them become one. 2987 SwitchBB->normalizeSuccProbs(); 2988 2989 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2990 MVT::Other, getControlRoot(), 2991 Cmp, DAG.getBasicBlock(B.TargetBB)); 2992 2993 // Avoid emitting unnecessary branches to the next block. 2994 if (NextMBB != NextBlock(SwitchBB)) 2995 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2996 DAG.getBasicBlock(NextMBB)); 2997 2998 DAG.setRoot(BrAnd); 2999 } 3000 3001 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 3002 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 3003 3004 // Retrieve successors. Look through artificial IR level blocks like 3005 // catchswitch for successors. 3006 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 3007 const BasicBlock *EHPadBB = I.getSuccessor(1); 3008 MachineBasicBlock *EHPadMBB = FuncInfo.MBBMap[EHPadBB]; 3009 3010 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3011 // have to do anything here to lower funclet bundles. 3012 assert(!I.hasOperandBundlesOtherThan( 3013 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 3014 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 3015 LLVMContext::OB_cfguardtarget, 3016 LLVMContext::OB_clang_arc_attachedcall}) && 3017 "Cannot lower invokes with arbitrary operand bundles yet!"); 3018 3019 const Value *Callee(I.getCalledOperand()); 3020 const Function *Fn = dyn_cast<Function>(Callee); 3021 if (isa<InlineAsm>(Callee)) 3022 visitInlineAsm(I, EHPadBB); 3023 else if (Fn && Fn->isIntrinsic()) { 3024 switch (Fn->getIntrinsicID()) { 3025 default: 3026 llvm_unreachable("Cannot invoke this intrinsic"); 3027 case Intrinsic::donothing: 3028 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 3029 case Intrinsic::seh_try_begin: 3030 case Intrinsic::seh_scope_begin: 3031 case Intrinsic::seh_try_end: 3032 case Intrinsic::seh_scope_end: 3033 if (EHPadMBB) 3034 // a block referenced by EH table 3035 // so dtor-funclet not removed by opts 3036 EHPadMBB->setMachineBlockAddressTaken(); 3037 break; 3038 case Intrinsic::experimental_patchpoint_void: 3039 case Intrinsic::experimental_patchpoint_i64: 3040 visitPatchpoint(I, EHPadBB); 3041 break; 3042 case Intrinsic::experimental_gc_statepoint: 3043 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 3044 break; 3045 case Intrinsic::wasm_rethrow: { 3046 // This is usually done in visitTargetIntrinsic, but this intrinsic is 3047 // special because it can be invoked, so we manually lower it to a DAG 3048 // node here. 3049 SmallVector<SDValue, 8> Ops; 3050 Ops.push_back(getRoot()); // inchain 3051 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3052 Ops.push_back( 3053 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 3054 TLI.getPointerTy(DAG.getDataLayout()))); 3055 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 3056 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 3057 break; 3058 } 3059 } 3060 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 3061 // Currently we do not lower any intrinsic calls with deopt operand bundles. 3062 // Eventually we will support lowering the @llvm.experimental.deoptimize 3063 // intrinsic, and right now there are no plans to support other intrinsics 3064 // with deopt state. 3065 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 3066 } else { 3067 LowerCallTo(I, getValue(Callee), false, false, EHPadBB); 3068 } 3069 3070 // If the value of the invoke is used outside of its defining block, make it 3071 // available as a virtual register. 3072 // We already took care of the exported value for the statepoint instruction 3073 // during call to the LowerStatepoint. 3074 if (!isa<GCStatepointInst>(I)) { 3075 CopyToExportRegsIfNeeded(&I); 3076 } 3077 3078 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 3079 BranchProbabilityInfo *BPI = FuncInfo.BPI; 3080 BranchProbability EHPadBBProb = 3081 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 3082 : BranchProbability::getZero(); 3083 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 3084 3085 // Update successor info. 3086 addSuccessorWithProb(InvokeMBB, Return); 3087 for (auto &UnwindDest : UnwindDests) { 3088 UnwindDest.first->setIsEHPad(); 3089 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 3090 } 3091 InvokeMBB->normalizeSuccProbs(); 3092 3093 // Drop into normal successor. 3094 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 3095 DAG.getBasicBlock(Return))); 3096 } 3097 3098 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 3099 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 3100 3101 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3102 // have to do anything here to lower funclet bundles. 3103 assert(!I.hasOperandBundlesOtherThan( 3104 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 3105 "Cannot lower callbrs with arbitrary operand bundles yet!"); 3106 3107 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 3108 visitInlineAsm(I); 3109 CopyToExportRegsIfNeeded(&I); 3110 3111 // Retrieve successors. 3112 SmallPtrSet<BasicBlock *, 8> Dests; 3113 Dests.insert(I.getDefaultDest()); 3114 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 3115 3116 // Update successor info. 3117 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 3118 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 3119 BasicBlock *Dest = I.getIndirectDest(i); 3120 MachineBasicBlock *Target = FuncInfo.MBBMap[Dest]; 3121 Target->setIsInlineAsmBrIndirectTarget(); 3122 Target->setMachineBlockAddressTaken(); 3123 Target->setLabelMustBeEmitted(); 3124 // Don't add duplicate machine successors. 3125 if (Dests.insert(Dest).second) 3126 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 3127 } 3128 CallBrMBB->normalizeSuccProbs(); 3129 3130 // Drop into default successor. 3131 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 3132 MVT::Other, getControlRoot(), 3133 DAG.getBasicBlock(Return))); 3134 } 3135 3136 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 3137 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 3138 } 3139 3140 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 3141 assert(FuncInfo.MBB->isEHPad() && 3142 "Call to landingpad not in landing pad!"); 3143 3144 // If there aren't registers to copy the values into (e.g., during SjLj 3145 // exceptions), then don't bother to create these DAG nodes. 3146 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3147 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 3148 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 3149 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 3150 return; 3151 3152 // If landingpad's return type is token type, we don't create DAG nodes 3153 // for its exception pointer and selector value. The extraction of exception 3154 // pointer or selector value from token type landingpads is not currently 3155 // supported. 3156 if (LP.getType()->isTokenTy()) 3157 return; 3158 3159 SmallVector<EVT, 2> ValueVTs; 3160 SDLoc dl = getCurSDLoc(); 3161 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3162 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3163 3164 // Get the two live-in registers as SDValues. The physregs have already been 3165 // copied into virtual registers. 3166 SDValue Ops[2]; 3167 if (FuncInfo.ExceptionPointerVirtReg) { 3168 Ops[0] = DAG.getZExtOrTrunc( 3169 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3170 FuncInfo.ExceptionPointerVirtReg, 3171 TLI.getPointerTy(DAG.getDataLayout())), 3172 dl, ValueVTs[0]); 3173 } else { 3174 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3175 } 3176 Ops[1] = DAG.getZExtOrTrunc( 3177 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3178 FuncInfo.ExceptionSelectorVirtReg, 3179 TLI.getPointerTy(DAG.getDataLayout())), 3180 dl, ValueVTs[1]); 3181 3182 // Merge into one. 3183 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3184 DAG.getVTList(ValueVTs), Ops); 3185 setValue(&LP, Res); 3186 } 3187 3188 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3189 MachineBasicBlock *Last) { 3190 // Update JTCases. 3191 for (JumpTableBlock &JTB : SL->JTCases) 3192 if (JTB.first.HeaderBB == First) 3193 JTB.first.HeaderBB = Last; 3194 3195 // Update BitTestCases. 3196 for (BitTestBlock &BTB : SL->BitTestCases) 3197 if (BTB.Parent == First) 3198 BTB.Parent = Last; 3199 } 3200 3201 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3202 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3203 3204 // Update machine-CFG edges with unique successors. 3205 SmallSet<BasicBlock*, 32> Done; 3206 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3207 BasicBlock *BB = I.getSuccessor(i); 3208 bool Inserted = Done.insert(BB).second; 3209 if (!Inserted) 3210 continue; 3211 3212 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3213 addSuccessorWithProb(IndirectBrMBB, Succ); 3214 } 3215 IndirectBrMBB->normalizeSuccProbs(); 3216 3217 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3218 MVT::Other, getControlRoot(), 3219 getValue(I.getAddress()))); 3220 } 3221 3222 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3223 if (!DAG.getTarget().Options.TrapUnreachable) 3224 return; 3225 3226 // We may be able to ignore unreachable behind a noreturn call. 3227 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3228 const BasicBlock &BB = *I.getParent(); 3229 if (&I != &BB.front()) { 3230 BasicBlock::const_iterator PredI = 3231 std::prev(BasicBlock::const_iterator(&I)); 3232 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 3233 if (Call->doesNotReturn()) 3234 return; 3235 } 3236 } 3237 } 3238 3239 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3240 } 3241 3242 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3243 SDNodeFlags Flags; 3244 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3245 Flags.copyFMF(*FPOp); 3246 3247 SDValue Op = getValue(I.getOperand(0)); 3248 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3249 Op, Flags); 3250 setValue(&I, UnNodeValue); 3251 } 3252 3253 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3254 SDNodeFlags Flags; 3255 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3256 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3257 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3258 } 3259 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3260 Flags.setExact(ExactOp->isExact()); 3261 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3262 Flags.copyFMF(*FPOp); 3263 3264 SDValue Op1 = getValue(I.getOperand(0)); 3265 SDValue Op2 = getValue(I.getOperand(1)); 3266 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3267 Op1, Op2, Flags); 3268 setValue(&I, BinNodeValue); 3269 } 3270 3271 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3272 SDValue Op1 = getValue(I.getOperand(0)); 3273 SDValue Op2 = getValue(I.getOperand(1)); 3274 3275 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3276 Op1.getValueType(), DAG.getDataLayout()); 3277 3278 // Coerce the shift amount to the right type if we can. This exposes the 3279 // truncate or zext to optimization early. 3280 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3281 assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) && 3282 "Unexpected shift type"); 3283 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy); 3284 } 3285 3286 bool nuw = false; 3287 bool nsw = false; 3288 bool exact = false; 3289 3290 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3291 3292 if (const OverflowingBinaryOperator *OFBinOp = 3293 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3294 nuw = OFBinOp->hasNoUnsignedWrap(); 3295 nsw = OFBinOp->hasNoSignedWrap(); 3296 } 3297 if (const PossiblyExactOperator *ExactOp = 3298 dyn_cast<const PossiblyExactOperator>(&I)) 3299 exact = ExactOp->isExact(); 3300 } 3301 SDNodeFlags Flags; 3302 Flags.setExact(exact); 3303 Flags.setNoSignedWrap(nsw); 3304 Flags.setNoUnsignedWrap(nuw); 3305 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3306 Flags); 3307 setValue(&I, Res); 3308 } 3309 3310 void SelectionDAGBuilder::visitSDiv(const User &I) { 3311 SDValue Op1 = getValue(I.getOperand(0)); 3312 SDValue Op2 = getValue(I.getOperand(1)); 3313 3314 SDNodeFlags Flags; 3315 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3316 cast<PossiblyExactOperator>(&I)->isExact()); 3317 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3318 Op2, Flags)); 3319 } 3320 3321 void SelectionDAGBuilder::visitICmp(const User &I) { 3322 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3323 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3324 predicate = IC->getPredicate(); 3325 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3326 predicate = ICmpInst::Predicate(IC->getPredicate()); 3327 SDValue Op1 = getValue(I.getOperand(0)); 3328 SDValue Op2 = getValue(I.getOperand(1)); 3329 ISD::CondCode Opcode = getICmpCondCode(predicate); 3330 3331 auto &TLI = DAG.getTargetLoweringInfo(); 3332 EVT MemVT = 3333 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3334 3335 // If a pointer's DAG type is larger than its memory type then the DAG values 3336 // are zero-extended. This breaks signed comparisons so truncate back to the 3337 // underlying type before doing the compare. 3338 if (Op1.getValueType() != MemVT) { 3339 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3340 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3341 } 3342 3343 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3344 I.getType()); 3345 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3346 } 3347 3348 void SelectionDAGBuilder::visitFCmp(const User &I) { 3349 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3350 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3351 predicate = FC->getPredicate(); 3352 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3353 predicate = FCmpInst::Predicate(FC->getPredicate()); 3354 SDValue Op1 = getValue(I.getOperand(0)); 3355 SDValue Op2 = getValue(I.getOperand(1)); 3356 3357 ISD::CondCode Condition = getFCmpCondCode(predicate); 3358 auto *FPMO = cast<FPMathOperator>(&I); 3359 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3360 Condition = getFCmpCodeWithoutNaN(Condition); 3361 3362 SDNodeFlags Flags; 3363 Flags.copyFMF(*FPMO); 3364 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3365 3366 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3367 I.getType()); 3368 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3369 } 3370 3371 // Check if the condition of the select has one use or two users that are both 3372 // selects with the same condition. 3373 static bool hasOnlySelectUsers(const Value *Cond) { 3374 return llvm::all_of(Cond->users(), [](const Value *V) { 3375 return isa<SelectInst>(V); 3376 }); 3377 } 3378 3379 void SelectionDAGBuilder::visitSelect(const User &I) { 3380 SmallVector<EVT, 4> ValueVTs; 3381 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3382 ValueVTs); 3383 unsigned NumValues = ValueVTs.size(); 3384 if (NumValues == 0) return; 3385 3386 SmallVector<SDValue, 4> Values(NumValues); 3387 SDValue Cond = getValue(I.getOperand(0)); 3388 SDValue LHSVal = getValue(I.getOperand(1)); 3389 SDValue RHSVal = getValue(I.getOperand(2)); 3390 SmallVector<SDValue, 1> BaseOps(1, Cond); 3391 ISD::NodeType OpCode = 3392 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3393 3394 bool IsUnaryAbs = false; 3395 bool Negate = false; 3396 3397 SDNodeFlags Flags; 3398 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3399 Flags.copyFMF(*FPOp); 3400 3401 Flags.setUnpredictable( 3402 cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable)); 3403 3404 // Min/max matching is only viable if all output VTs are the same. 3405 if (all_equal(ValueVTs)) { 3406 EVT VT = ValueVTs[0]; 3407 LLVMContext &Ctx = *DAG.getContext(); 3408 auto &TLI = DAG.getTargetLoweringInfo(); 3409 3410 // We care about the legality of the operation after it has been type 3411 // legalized. 3412 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3413 VT = TLI.getTypeToTransformTo(Ctx, VT); 3414 3415 // If the vselect is legal, assume we want to leave this as a vector setcc + 3416 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3417 // min/max is legal on the scalar type. 3418 bool UseScalarMinMax = VT.isVector() && 3419 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3420 3421 // ValueTracking's select pattern matching does not account for -0.0, 3422 // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that 3423 // -0.0 is less than +0.0. 3424 Value *LHS, *RHS; 3425 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3426 ISD::NodeType Opc = ISD::DELETED_NODE; 3427 switch (SPR.Flavor) { 3428 case SPF_UMAX: Opc = ISD::UMAX; break; 3429 case SPF_UMIN: Opc = ISD::UMIN; break; 3430 case SPF_SMAX: Opc = ISD::SMAX; break; 3431 case SPF_SMIN: Opc = ISD::SMIN; break; 3432 case SPF_FMINNUM: 3433 switch (SPR.NaNBehavior) { 3434 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3435 case SPNB_RETURNS_NAN: break; 3436 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3437 case SPNB_RETURNS_ANY: 3438 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) || 3439 (UseScalarMinMax && 3440 TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()))) 3441 Opc = ISD::FMINNUM; 3442 break; 3443 } 3444 break; 3445 case SPF_FMAXNUM: 3446 switch (SPR.NaNBehavior) { 3447 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3448 case SPNB_RETURNS_NAN: break; 3449 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3450 case SPNB_RETURNS_ANY: 3451 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) || 3452 (UseScalarMinMax && 3453 TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()))) 3454 Opc = ISD::FMAXNUM; 3455 break; 3456 } 3457 break; 3458 case SPF_NABS: 3459 Negate = true; 3460 [[fallthrough]]; 3461 case SPF_ABS: 3462 IsUnaryAbs = true; 3463 Opc = ISD::ABS; 3464 break; 3465 default: break; 3466 } 3467 3468 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3469 (TLI.isOperationLegalOrCustom(Opc, VT) || 3470 (UseScalarMinMax && 3471 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3472 // If the underlying comparison instruction is used by any other 3473 // instruction, the consumed instructions won't be destroyed, so it is 3474 // not profitable to convert to a min/max. 3475 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3476 OpCode = Opc; 3477 LHSVal = getValue(LHS); 3478 RHSVal = getValue(RHS); 3479 BaseOps.clear(); 3480 } 3481 3482 if (IsUnaryAbs) { 3483 OpCode = Opc; 3484 LHSVal = getValue(LHS); 3485 BaseOps.clear(); 3486 } 3487 } 3488 3489 if (IsUnaryAbs) { 3490 for (unsigned i = 0; i != NumValues; ++i) { 3491 SDLoc dl = getCurSDLoc(); 3492 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3493 Values[i] = 3494 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3495 if (Negate) 3496 Values[i] = DAG.getNegative(Values[i], dl, VT); 3497 } 3498 } else { 3499 for (unsigned i = 0; i != NumValues; ++i) { 3500 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3501 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3502 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3503 Values[i] = DAG.getNode( 3504 OpCode, getCurSDLoc(), 3505 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3506 } 3507 } 3508 3509 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3510 DAG.getVTList(ValueVTs), Values)); 3511 } 3512 3513 void SelectionDAGBuilder::visitTrunc(const User &I) { 3514 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3515 SDValue N = getValue(I.getOperand(0)); 3516 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3517 I.getType()); 3518 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3519 } 3520 3521 void SelectionDAGBuilder::visitZExt(const User &I) { 3522 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3523 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3524 SDValue N = getValue(I.getOperand(0)); 3525 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3526 I.getType()); 3527 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3528 } 3529 3530 void SelectionDAGBuilder::visitSExt(const User &I) { 3531 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3532 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3533 SDValue N = getValue(I.getOperand(0)); 3534 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3535 I.getType()); 3536 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3537 } 3538 3539 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3540 // FPTrunc is never a no-op cast, no need to check 3541 SDValue N = getValue(I.getOperand(0)); 3542 SDLoc dl = getCurSDLoc(); 3543 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3544 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3545 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3546 DAG.getTargetConstant( 3547 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3548 } 3549 3550 void SelectionDAGBuilder::visitFPExt(const User &I) { 3551 // FPExt is never a no-op cast, no need to check 3552 SDValue N = getValue(I.getOperand(0)); 3553 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3554 I.getType()); 3555 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3556 } 3557 3558 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3559 // FPToUI is never a no-op cast, no need to check 3560 SDValue N = getValue(I.getOperand(0)); 3561 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3562 I.getType()); 3563 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3564 } 3565 3566 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3567 // FPToSI is never a no-op cast, no need to check 3568 SDValue N = getValue(I.getOperand(0)); 3569 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3570 I.getType()); 3571 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3572 } 3573 3574 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3575 // UIToFP is never a no-op cast, no need to check 3576 SDValue N = getValue(I.getOperand(0)); 3577 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3578 I.getType()); 3579 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3580 } 3581 3582 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3583 // SIToFP is never a no-op cast, no need to check 3584 SDValue N = getValue(I.getOperand(0)); 3585 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3586 I.getType()); 3587 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3588 } 3589 3590 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3591 // What to do depends on the size of the integer and the size of the pointer. 3592 // We can either truncate, zero extend, or no-op, accordingly. 3593 SDValue N = getValue(I.getOperand(0)); 3594 auto &TLI = DAG.getTargetLoweringInfo(); 3595 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3596 I.getType()); 3597 EVT PtrMemVT = 3598 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3599 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3600 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3601 setValue(&I, N); 3602 } 3603 3604 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3605 // What to do depends on the size of the integer and the size of the pointer. 3606 // We can either truncate, zero extend, or no-op, accordingly. 3607 SDValue N = getValue(I.getOperand(0)); 3608 auto &TLI = DAG.getTargetLoweringInfo(); 3609 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3610 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3611 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3612 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3613 setValue(&I, N); 3614 } 3615 3616 void SelectionDAGBuilder::visitBitCast(const User &I) { 3617 SDValue N = getValue(I.getOperand(0)); 3618 SDLoc dl = getCurSDLoc(); 3619 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3620 I.getType()); 3621 3622 // BitCast assures us that source and destination are the same size so this is 3623 // either a BITCAST or a no-op. 3624 if (DestVT != N.getValueType()) 3625 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3626 DestVT, N)); // convert types. 3627 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3628 // might fold any kind of constant expression to an integer constant and that 3629 // is not what we are looking for. Only recognize a bitcast of a genuine 3630 // constant integer as an opaque constant. 3631 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3632 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3633 /*isOpaque*/true)); 3634 else 3635 setValue(&I, N); // noop cast. 3636 } 3637 3638 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3639 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3640 const Value *SV = I.getOperand(0); 3641 SDValue N = getValue(SV); 3642 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3643 3644 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3645 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3646 3647 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3648 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3649 3650 setValue(&I, N); 3651 } 3652 3653 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3654 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3655 SDValue InVec = getValue(I.getOperand(0)); 3656 SDValue InVal = getValue(I.getOperand(1)); 3657 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3658 TLI.getVectorIdxTy(DAG.getDataLayout())); 3659 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3660 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3661 InVec, InVal, InIdx)); 3662 } 3663 3664 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3665 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3666 SDValue InVec = getValue(I.getOperand(0)); 3667 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3668 TLI.getVectorIdxTy(DAG.getDataLayout())); 3669 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3670 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3671 InVec, InIdx)); 3672 } 3673 3674 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3675 SDValue Src1 = getValue(I.getOperand(0)); 3676 SDValue Src2 = getValue(I.getOperand(1)); 3677 ArrayRef<int> Mask; 3678 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3679 Mask = SVI->getShuffleMask(); 3680 else 3681 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3682 SDLoc DL = getCurSDLoc(); 3683 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3684 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3685 EVT SrcVT = Src1.getValueType(); 3686 3687 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3688 VT.isScalableVector()) { 3689 // Canonical splat form of first element of first input vector. 3690 SDValue FirstElt = 3691 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3692 DAG.getVectorIdxConstant(0, DL)); 3693 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3694 return; 3695 } 3696 3697 // For now, we only handle splats for scalable vectors. 3698 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3699 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3700 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3701 3702 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3703 unsigned MaskNumElts = Mask.size(); 3704 3705 if (SrcNumElts == MaskNumElts) { 3706 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3707 return; 3708 } 3709 3710 // Normalize the shuffle vector since mask and vector length don't match. 3711 if (SrcNumElts < MaskNumElts) { 3712 // Mask is longer than the source vectors. We can use concatenate vector to 3713 // make the mask and vectors lengths match. 3714 3715 if (MaskNumElts % SrcNumElts == 0) { 3716 // Mask length is a multiple of the source vector length. 3717 // Check if the shuffle is some kind of concatenation of the input 3718 // vectors. 3719 unsigned NumConcat = MaskNumElts / SrcNumElts; 3720 bool IsConcat = true; 3721 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3722 for (unsigned i = 0; i != MaskNumElts; ++i) { 3723 int Idx = Mask[i]; 3724 if (Idx < 0) 3725 continue; 3726 // Ensure the indices in each SrcVT sized piece are sequential and that 3727 // the same source is used for the whole piece. 3728 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3729 (ConcatSrcs[i / SrcNumElts] >= 0 && 3730 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3731 IsConcat = false; 3732 break; 3733 } 3734 // Remember which source this index came from. 3735 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3736 } 3737 3738 // The shuffle is concatenating multiple vectors together. Just emit 3739 // a CONCAT_VECTORS operation. 3740 if (IsConcat) { 3741 SmallVector<SDValue, 8> ConcatOps; 3742 for (auto Src : ConcatSrcs) { 3743 if (Src < 0) 3744 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3745 else if (Src == 0) 3746 ConcatOps.push_back(Src1); 3747 else 3748 ConcatOps.push_back(Src2); 3749 } 3750 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3751 return; 3752 } 3753 } 3754 3755 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3756 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3757 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3758 PaddedMaskNumElts); 3759 3760 // Pad both vectors with undefs to make them the same length as the mask. 3761 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3762 3763 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3764 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3765 MOps1[0] = Src1; 3766 MOps2[0] = Src2; 3767 3768 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3769 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3770 3771 // Readjust mask for new input vector length. 3772 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3773 for (unsigned i = 0; i != MaskNumElts; ++i) { 3774 int Idx = Mask[i]; 3775 if (Idx >= (int)SrcNumElts) 3776 Idx -= SrcNumElts - PaddedMaskNumElts; 3777 MappedOps[i] = Idx; 3778 } 3779 3780 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3781 3782 // If the concatenated vector was padded, extract a subvector with the 3783 // correct number of elements. 3784 if (MaskNumElts != PaddedMaskNumElts) 3785 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3786 DAG.getVectorIdxConstant(0, DL)); 3787 3788 setValue(&I, Result); 3789 return; 3790 } 3791 3792 if (SrcNumElts > MaskNumElts) { 3793 // Analyze the access pattern of the vector to see if we can extract 3794 // two subvectors and do the shuffle. 3795 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3796 bool CanExtract = true; 3797 for (int Idx : Mask) { 3798 unsigned Input = 0; 3799 if (Idx < 0) 3800 continue; 3801 3802 if (Idx >= (int)SrcNumElts) { 3803 Input = 1; 3804 Idx -= SrcNumElts; 3805 } 3806 3807 // If all the indices come from the same MaskNumElts sized portion of 3808 // the sources we can use extract. Also make sure the extract wouldn't 3809 // extract past the end of the source. 3810 int NewStartIdx = alignDown(Idx, MaskNumElts); 3811 if (NewStartIdx + MaskNumElts > SrcNumElts || 3812 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3813 CanExtract = false; 3814 // Make sure we always update StartIdx as we use it to track if all 3815 // elements are undef. 3816 StartIdx[Input] = NewStartIdx; 3817 } 3818 3819 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3820 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3821 return; 3822 } 3823 if (CanExtract) { 3824 // Extract appropriate subvector and generate a vector shuffle 3825 for (unsigned Input = 0; Input < 2; ++Input) { 3826 SDValue &Src = Input == 0 ? Src1 : Src2; 3827 if (StartIdx[Input] < 0) 3828 Src = DAG.getUNDEF(VT); 3829 else { 3830 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3831 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3832 } 3833 } 3834 3835 // Calculate new mask. 3836 SmallVector<int, 8> MappedOps(Mask); 3837 for (int &Idx : MappedOps) { 3838 if (Idx >= (int)SrcNumElts) 3839 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3840 else if (Idx >= 0) 3841 Idx -= StartIdx[0]; 3842 } 3843 3844 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3845 return; 3846 } 3847 } 3848 3849 // We can't use either concat vectors or extract subvectors so fall back to 3850 // replacing the shuffle with extract and build vector. 3851 // to insert and build vector. 3852 EVT EltVT = VT.getVectorElementType(); 3853 SmallVector<SDValue,8> Ops; 3854 for (int Idx : Mask) { 3855 SDValue Res; 3856 3857 if (Idx < 0) { 3858 Res = DAG.getUNDEF(EltVT); 3859 } else { 3860 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3861 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3862 3863 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3864 DAG.getVectorIdxConstant(Idx, DL)); 3865 } 3866 3867 Ops.push_back(Res); 3868 } 3869 3870 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3871 } 3872 3873 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) { 3874 ArrayRef<unsigned> Indices = I.getIndices(); 3875 const Value *Op0 = I.getOperand(0); 3876 const Value *Op1 = I.getOperand(1); 3877 Type *AggTy = I.getType(); 3878 Type *ValTy = Op1->getType(); 3879 bool IntoUndef = isa<UndefValue>(Op0); 3880 bool FromUndef = isa<UndefValue>(Op1); 3881 3882 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3883 3884 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3885 SmallVector<EVT, 4> AggValueVTs; 3886 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3887 SmallVector<EVT, 4> ValValueVTs; 3888 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3889 3890 unsigned NumAggValues = AggValueVTs.size(); 3891 unsigned NumValValues = ValValueVTs.size(); 3892 SmallVector<SDValue, 4> Values(NumAggValues); 3893 3894 // Ignore an insertvalue that produces an empty object 3895 if (!NumAggValues) { 3896 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3897 return; 3898 } 3899 3900 SDValue Agg = getValue(Op0); 3901 unsigned i = 0; 3902 // Copy the beginning value(s) from the original aggregate. 3903 for (; i != LinearIndex; ++i) 3904 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3905 SDValue(Agg.getNode(), Agg.getResNo() + i); 3906 // Copy values from the inserted value(s). 3907 if (NumValValues) { 3908 SDValue Val = getValue(Op1); 3909 for (; i != LinearIndex + NumValValues; ++i) 3910 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3911 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3912 } 3913 // Copy remaining value(s) from the original aggregate. 3914 for (; i != NumAggValues; ++i) 3915 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3916 SDValue(Agg.getNode(), Agg.getResNo() + i); 3917 3918 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3919 DAG.getVTList(AggValueVTs), Values)); 3920 } 3921 3922 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) { 3923 ArrayRef<unsigned> Indices = I.getIndices(); 3924 const Value *Op0 = I.getOperand(0); 3925 Type *AggTy = Op0->getType(); 3926 Type *ValTy = I.getType(); 3927 bool OutOfUndef = isa<UndefValue>(Op0); 3928 3929 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3930 3931 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3932 SmallVector<EVT, 4> ValValueVTs; 3933 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3934 3935 unsigned NumValValues = ValValueVTs.size(); 3936 3937 // Ignore a extractvalue that produces an empty object 3938 if (!NumValValues) { 3939 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3940 return; 3941 } 3942 3943 SmallVector<SDValue, 4> Values(NumValValues); 3944 3945 SDValue Agg = getValue(Op0); 3946 // Copy out the selected value(s). 3947 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3948 Values[i - LinearIndex] = 3949 OutOfUndef ? 3950 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3951 SDValue(Agg.getNode(), Agg.getResNo() + i); 3952 3953 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3954 DAG.getVTList(ValValueVTs), Values)); 3955 } 3956 3957 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3958 Value *Op0 = I.getOperand(0); 3959 // Note that the pointer operand may be a vector of pointers. Take the scalar 3960 // element which holds a pointer. 3961 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3962 SDValue N = getValue(Op0); 3963 SDLoc dl = getCurSDLoc(); 3964 auto &TLI = DAG.getTargetLoweringInfo(); 3965 3966 // Normalize Vector GEP - all scalar operands should be converted to the 3967 // splat vector. 3968 bool IsVectorGEP = I.getType()->isVectorTy(); 3969 ElementCount VectorElementCount = 3970 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3971 : ElementCount::getFixed(0); 3972 3973 if (IsVectorGEP && !N.getValueType().isVector()) { 3974 LLVMContext &Context = *DAG.getContext(); 3975 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3976 N = DAG.getSplat(VT, dl, N); 3977 } 3978 3979 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3980 GTI != E; ++GTI) { 3981 const Value *Idx = GTI.getOperand(); 3982 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3983 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3984 if (Field) { 3985 // N = N + Offset 3986 uint64_t Offset = 3987 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field); 3988 3989 // In an inbounds GEP with an offset that is nonnegative even when 3990 // interpreted as signed, assume there is no unsigned overflow. 3991 SDNodeFlags Flags; 3992 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3993 Flags.setNoUnsignedWrap(true); 3994 3995 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3996 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3997 } 3998 } else { 3999 // IdxSize is the width of the arithmetic according to IR semantics. 4000 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 4001 // (and fix up the result later). 4002 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 4003 MVT IdxTy = MVT::getIntegerVT(IdxSize); 4004 TypeSize ElementSize = 4005 DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType()); 4006 // We intentionally mask away the high bits here; ElementSize may not 4007 // fit in IdxTy. 4008 APInt ElementMul(IdxSize, ElementSize.getKnownMinValue()); 4009 bool ElementScalable = ElementSize.isScalable(); 4010 4011 // If this is a scalar constant or a splat vector of constants, 4012 // handle it quickly. 4013 const auto *C = dyn_cast<Constant>(Idx); 4014 if (C && isa<VectorType>(C->getType())) 4015 C = C->getSplatValue(); 4016 4017 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 4018 if (CI && CI->isZero()) 4019 continue; 4020 if (CI && !ElementScalable) { 4021 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 4022 LLVMContext &Context = *DAG.getContext(); 4023 SDValue OffsVal; 4024 if (IsVectorGEP) 4025 OffsVal = DAG.getConstant( 4026 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 4027 else 4028 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 4029 4030 // In an inbounds GEP with an offset that is nonnegative even when 4031 // interpreted as signed, assume there is no unsigned overflow. 4032 SDNodeFlags Flags; 4033 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 4034 Flags.setNoUnsignedWrap(true); 4035 4036 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 4037 4038 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 4039 continue; 4040 } 4041 4042 // N = N + Idx * ElementMul; 4043 SDValue IdxN = getValue(Idx); 4044 4045 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 4046 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 4047 VectorElementCount); 4048 IdxN = DAG.getSplat(VT, dl, IdxN); 4049 } 4050 4051 // If the index is smaller or larger than intptr_t, truncate or extend 4052 // it. 4053 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 4054 4055 if (ElementScalable) { 4056 EVT VScaleTy = N.getValueType().getScalarType(); 4057 SDValue VScale = DAG.getNode( 4058 ISD::VSCALE, dl, VScaleTy, 4059 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 4060 if (IsVectorGEP) 4061 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 4062 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 4063 } else { 4064 // If this is a multiply by a power of two, turn it into a shl 4065 // immediately. This is a very common case. 4066 if (ElementMul != 1) { 4067 if (ElementMul.isPowerOf2()) { 4068 unsigned Amt = ElementMul.logBase2(); 4069 IdxN = DAG.getNode(ISD::SHL, dl, 4070 N.getValueType(), IdxN, 4071 DAG.getConstant(Amt, dl, IdxN.getValueType())); 4072 } else { 4073 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 4074 IdxN.getValueType()); 4075 IdxN = DAG.getNode(ISD::MUL, dl, 4076 N.getValueType(), IdxN, Scale); 4077 } 4078 } 4079 } 4080 4081 N = DAG.getNode(ISD::ADD, dl, 4082 N.getValueType(), N, IdxN); 4083 } 4084 } 4085 4086 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 4087 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 4088 if (IsVectorGEP) { 4089 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 4090 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 4091 } 4092 4093 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 4094 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 4095 4096 setValue(&I, N); 4097 } 4098 4099 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 4100 // If this is a fixed sized alloca in the entry block of the function, 4101 // allocate it statically on the stack. 4102 if (FuncInfo.StaticAllocaMap.count(&I)) 4103 return; // getValue will auto-populate this. 4104 4105 SDLoc dl = getCurSDLoc(); 4106 Type *Ty = I.getAllocatedType(); 4107 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4108 auto &DL = DAG.getDataLayout(); 4109 TypeSize TySize = DL.getTypeAllocSize(Ty); 4110 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 4111 4112 SDValue AllocSize = getValue(I.getArraySize()); 4113 4114 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), I.getAddressSpace()); 4115 if (AllocSize.getValueType() != IntPtr) 4116 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 4117 4118 if (TySize.isScalable()) 4119 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4120 DAG.getVScale(dl, IntPtr, 4121 APInt(IntPtr.getScalarSizeInBits(), 4122 TySize.getKnownMinValue()))); 4123 else 4124 AllocSize = 4125 DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4126 DAG.getConstant(TySize.getFixedValue(), dl, IntPtr)); 4127 4128 // Handle alignment. If the requested alignment is less than or equal to 4129 // the stack alignment, ignore it. If the size is greater than or equal to 4130 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4131 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 4132 if (*Alignment <= StackAlign) 4133 Alignment = std::nullopt; 4134 4135 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4136 // Round the size of the allocation up to the stack alignment size 4137 // by add SA-1 to the size. This doesn't overflow because we're computing 4138 // an address inside an alloca. 4139 SDNodeFlags Flags; 4140 Flags.setNoUnsignedWrap(true); 4141 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4142 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4143 4144 // Mask out the low bits for alignment purposes. 4145 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4146 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 4147 4148 SDValue Ops[] = { 4149 getRoot(), AllocSize, 4150 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4151 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4152 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4153 setValue(&I, DSA); 4154 DAG.setRoot(DSA.getValue(1)); 4155 4156 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4157 } 4158 4159 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4160 if (I.isAtomic()) 4161 return visitAtomicLoad(I); 4162 4163 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4164 const Value *SV = I.getOperand(0); 4165 if (TLI.supportSwiftError()) { 4166 // Swifterror values can come from either a function parameter with 4167 // swifterror attribute or an alloca with swifterror attribute. 4168 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4169 if (Arg->hasSwiftErrorAttr()) 4170 return visitLoadFromSwiftError(I); 4171 } 4172 4173 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4174 if (Alloca->isSwiftError()) 4175 return visitLoadFromSwiftError(I); 4176 } 4177 } 4178 4179 SDValue Ptr = getValue(SV); 4180 4181 Type *Ty = I.getType(); 4182 SmallVector<EVT, 4> ValueVTs, MemVTs; 4183 SmallVector<uint64_t, 4> Offsets; 4184 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets, 0); 4185 unsigned NumValues = ValueVTs.size(); 4186 if (NumValues == 0) 4187 return; 4188 4189 Align Alignment = I.getAlign(); 4190 AAMDNodes AAInfo = I.getAAMetadata(); 4191 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4192 bool isVolatile = I.isVolatile(); 4193 MachineMemOperand::Flags MMOFlags = 4194 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 4195 4196 SDValue Root; 4197 bool ConstantMemory = false; 4198 if (isVolatile) 4199 // Serialize volatile loads with other side effects. 4200 Root = getRoot(); 4201 else if (NumValues > MaxParallelChains) 4202 Root = getMemoryRoot(); 4203 else if (AA && 4204 AA->pointsToConstantMemory(MemoryLocation( 4205 SV, 4206 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4207 AAInfo))) { 4208 // Do not serialize (non-volatile) loads of constant memory with anything. 4209 Root = DAG.getEntryNode(); 4210 ConstantMemory = true; 4211 MMOFlags |= MachineMemOperand::MOInvariant; 4212 } else { 4213 // Do not serialize non-volatile loads against each other. 4214 Root = DAG.getRoot(); 4215 } 4216 4217 SDLoc dl = getCurSDLoc(); 4218 4219 if (isVolatile) 4220 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4221 4222 // An aggregate load cannot wrap around the address space, so offsets to its 4223 // parts don't wrap either. 4224 SDNodeFlags Flags; 4225 Flags.setNoUnsignedWrap(true); 4226 4227 SmallVector<SDValue, 4> Values(NumValues); 4228 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4229 EVT PtrVT = Ptr.getValueType(); 4230 4231 unsigned ChainI = 0; 4232 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4233 // Serializing loads here may result in excessive register pressure, and 4234 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4235 // could recover a bit by hoisting nodes upward in the chain by recognizing 4236 // they are side-effect free or do not alias. The optimizer should really 4237 // avoid this case by converting large object/array copies to llvm.memcpy 4238 // (MaxParallelChains should always remain as failsafe). 4239 if (ChainI == MaxParallelChains) { 4240 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4241 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4242 ArrayRef(Chains.data(), ChainI)); 4243 Root = Chain; 4244 ChainI = 0; 4245 } 4246 SDValue A = DAG.getNode(ISD::ADD, dl, 4247 PtrVT, Ptr, 4248 DAG.getConstant(Offsets[i], dl, PtrVT), 4249 Flags); 4250 4251 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4252 MachinePointerInfo(SV, Offsets[i]), Alignment, 4253 MMOFlags, AAInfo, Ranges); 4254 Chains[ChainI] = L.getValue(1); 4255 4256 if (MemVTs[i] != ValueVTs[i]) 4257 L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]); 4258 4259 Values[i] = L; 4260 } 4261 4262 if (!ConstantMemory) { 4263 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4264 ArrayRef(Chains.data(), ChainI)); 4265 if (isVolatile) 4266 DAG.setRoot(Chain); 4267 else 4268 PendingLoads.push_back(Chain); 4269 } 4270 4271 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4272 DAG.getVTList(ValueVTs), Values)); 4273 } 4274 4275 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4276 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4277 "call visitStoreToSwiftError when backend supports swifterror"); 4278 4279 SmallVector<EVT, 4> ValueVTs; 4280 SmallVector<uint64_t, 4> Offsets; 4281 const Value *SrcV = I.getOperand(0); 4282 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4283 SrcV->getType(), ValueVTs, &Offsets, 0); 4284 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4285 "expect a single EVT for swifterror"); 4286 4287 SDValue Src = getValue(SrcV); 4288 // Create a virtual register, then update the virtual register. 4289 Register VReg = 4290 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4291 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4292 // Chain can be getRoot or getControlRoot. 4293 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4294 SDValue(Src.getNode(), Src.getResNo())); 4295 DAG.setRoot(CopyNode); 4296 } 4297 4298 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4299 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4300 "call visitLoadFromSwiftError when backend supports swifterror"); 4301 4302 assert(!I.isVolatile() && 4303 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4304 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4305 "Support volatile, non temporal, invariant for load_from_swift_error"); 4306 4307 const Value *SV = I.getOperand(0); 4308 Type *Ty = I.getType(); 4309 assert( 4310 (!AA || 4311 !AA->pointsToConstantMemory(MemoryLocation( 4312 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4313 I.getAAMetadata()))) && 4314 "load_from_swift_error should not be constant memory"); 4315 4316 SmallVector<EVT, 4> ValueVTs; 4317 SmallVector<uint64_t, 4> Offsets; 4318 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4319 ValueVTs, &Offsets, 0); 4320 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4321 "expect a single EVT for swifterror"); 4322 4323 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4324 SDValue L = DAG.getCopyFromReg( 4325 getRoot(), getCurSDLoc(), 4326 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4327 4328 setValue(&I, L); 4329 } 4330 4331 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4332 if (I.isAtomic()) 4333 return visitAtomicStore(I); 4334 4335 const Value *SrcV = I.getOperand(0); 4336 const Value *PtrV = I.getOperand(1); 4337 4338 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4339 if (TLI.supportSwiftError()) { 4340 // Swifterror values can come from either a function parameter with 4341 // swifterror attribute or an alloca with swifterror attribute. 4342 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4343 if (Arg->hasSwiftErrorAttr()) 4344 return visitStoreToSwiftError(I); 4345 } 4346 4347 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4348 if (Alloca->isSwiftError()) 4349 return visitStoreToSwiftError(I); 4350 } 4351 } 4352 4353 SmallVector<EVT, 4> ValueVTs, MemVTs; 4354 SmallVector<uint64_t, 4> Offsets; 4355 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4356 SrcV->getType(), ValueVTs, &MemVTs, &Offsets, 0); 4357 unsigned NumValues = ValueVTs.size(); 4358 if (NumValues == 0) 4359 return; 4360 4361 // Get the lowered operands. Note that we do this after 4362 // checking if NumResults is zero, because with zero results 4363 // the operands won't have values in the map. 4364 SDValue Src = getValue(SrcV); 4365 SDValue Ptr = getValue(PtrV); 4366 4367 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4368 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4369 SDLoc dl = getCurSDLoc(); 4370 Align Alignment = I.getAlign(); 4371 AAMDNodes AAInfo = I.getAAMetadata(); 4372 4373 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4374 4375 // An aggregate load cannot wrap around the address space, so offsets to its 4376 // parts don't wrap either. 4377 SDNodeFlags Flags; 4378 Flags.setNoUnsignedWrap(true); 4379 4380 unsigned ChainI = 0; 4381 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4382 // See visitLoad comments. 4383 if (ChainI == MaxParallelChains) { 4384 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4385 ArrayRef(Chains.data(), ChainI)); 4386 Root = Chain; 4387 ChainI = 0; 4388 } 4389 SDValue Add = 4390 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags); 4391 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4392 if (MemVTs[i] != ValueVTs[i]) 4393 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4394 SDValue St = 4395 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4396 Alignment, MMOFlags, AAInfo); 4397 Chains[ChainI] = St; 4398 } 4399 4400 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4401 ArrayRef(Chains.data(), ChainI)); 4402 setValue(&I, StoreNode); 4403 DAG.setRoot(StoreNode); 4404 } 4405 4406 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4407 bool IsCompressing) { 4408 SDLoc sdl = getCurSDLoc(); 4409 4410 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4411 MaybeAlign &Alignment) { 4412 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4413 Src0 = I.getArgOperand(0); 4414 Ptr = I.getArgOperand(1); 4415 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4416 Mask = I.getArgOperand(3); 4417 }; 4418 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4419 MaybeAlign &Alignment) { 4420 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4421 Src0 = I.getArgOperand(0); 4422 Ptr = I.getArgOperand(1); 4423 Mask = I.getArgOperand(2); 4424 Alignment = std::nullopt; 4425 }; 4426 4427 Value *PtrOperand, *MaskOperand, *Src0Operand; 4428 MaybeAlign Alignment; 4429 if (IsCompressing) 4430 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4431 else 4432 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4433 4434 SDValue Ptr = getValue(PtrOperand); 4435 SDValue Src0 = getValue(Src0Operand); 4436 SDValue Mask = getValue(MaskOperand); 4437 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4438 4439 EVT VT = Src0.getValueType(); 4440 if (!Alignment) 4441 Alignment = DAG.getEVTAlign(VT); 4442 4443 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4444 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4445 MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata()); 4446 SDValue StoreNode = 4447 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4448 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4449 DAG.setRoot(StoreNode); 4450 setValue(&I, StoreNode); 4451 } 4452 4453 // Get a uniform base for the Gather/Scatter intrinsic. 4454 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4455 // We try to represent it as a base pointer + vector of indices. 4456 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4457 // The first operand of the GEP may be a single pointer or a vector of pointers 4458 // Example: 4459 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4460 // or 4461 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4462 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4463 // 4464 // When the first GEP operand is a single pointer - it is the uniform base we 4465 // are looking for. If first operand of the GEP is a splat vector - we 4466 // extract the splat value and use it as a uniform base. 4467 // In all other cases the function returns 'false'. 4468 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4469 ISD::MemIndexType &IndexType, SDValue &Scale, 4470 SelectionDAGBuilder *SDB, const BasicBlock *CurBB, 4471 uint64_t ElemSize) { 4472 SelectionDAG& DAG = SDB->DAG; 4473 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4474 const DataLayout &DL = DAG.getDataLayout(); 4475 4476 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type"); 4477 4478 // Handle splat constant pointer. 4479 if (auto *C = dyn_cast<Constant>(Ptr)) { 4480 C = C->getSplatValue(); 4481 if (!C) 4482 return false; 4483 4484 Base = SDB->getValue(C); 4485 4486 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); 4487 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4488 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4489 IndexType = ISD::SIGNED_SCALED; 4490 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4491 return true; 4492 } 4493 4494 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4495 if (!GEP || GEP->getParent() != CurBB) 4496 return false; 4497 4498 if (GEP->getNumOperands() != 2) 4499 return false; 4500 4501 const Value *BasePtr = GEP->getPointerOperand(); 4502 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4503 4504 // Make sure the base is scalar and the index is a vector. 4505 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4506 return false; 4507 4508 TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType()); 4509 if (ScaleVal.isScalable()) 4510 return false; 4511 4512 // Target may not support the required addressing mode. 4513 if (ScaleVal != 1 && 4514 !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize)) 4515 return false; 4516 4517 Base = SDB->getValue(BasePtr); 4518 Index = SDB->getValue(IndexVal); 4519 IndexType = ISD::SIGNED_SCALED; 4520 4521 Scale = 4522 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4523 return true; 4524 } 4525 4526 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4527 SDLoc sdl = getCurSDLoc(); 4528 4529 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4530 const Value *Ptr = I.getArgOperand(1); 4531 SDValue Src0 = getValue(I.getArgOperand(0)); 4532 SDValue Mask = getValue(I.getArgOperand(3)); 4533 EVT VT = Src0.getValueType(); 4534 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4535 ->getMaybeAlignValue() 4536 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4537 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4538 4539 SDValue Base; 4540 SDValue Index; 4541 ISD::MemIndexType IndexType; 4542 SDValue Scale; 4543 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4544 I.getParent(), VT.getScalarStoreSize()); 4545 4546 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4547 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4548 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4549 // TODO: Make MachineMemOperands aware of scalable 4550 // vectors. 4551 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata()); 4552 if (!UniformBase) { 4553 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4554 Index = getValue(Ptr); 4555 IndexType = ISD::SIGNED_SCALED; 4556 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4557 } 4558 4559 EVT IdxVT = Index.getValueType(); 4560 EVT EltTy = IdxVT.getVectorElementType(); 4561 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4562 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4563 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4564 } 4565 4566 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4567 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4568 Ops, MMO, IndexType, false); 4569 DAG.setRoot(Scatter); 4570 setValue(&I, Scatter); 4571 } 4572 4573 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4574 SDLoc sdl = getCurSDLoc(); 4575 4576 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4577 MaybeAlign &Alignment) { 4578 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4579 Ptr = I.getArgOperand(0); 4580 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4581 Mask = I.getArgOperand(2); 4582 Src0 = I.getArgOperand(3); 4583 }; 4584 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4585 MaybeAlign &Alignment) { 4586 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4587 Ptr = I.getArgOperand(0); 4588 Alignment = std::nullopt; 4589 Mask = I.getArgOperand(1); 4590 Src0 = I.getArgOperand(2); 4591 }; 4592 4593 Value *PtrOperand, *MaskOperand, *Src0Operand; 4594 MaybeAlign Alignment; 4595 if (IsExpanding) 4596 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4597 else 4598 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4599 4600 SDValue Ptr = getValue(PtrOperand); 4601 SDValue Src0 = getValue(Src0Operand); 4602 SDValue Mask = getValue(MaskOperand); 4603 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4604 4605 EVT VT = Src0.getValueType(); 4606 if (!Alignment) 4607 Alignment = DAG.getEVTAlign(VT); 4608 4609 AAMDNodes AAInfo = I.getAAMetadata(); 4610 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4611 4612 // Do not serialize masked loads of constant memory with anything. 4613 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 4614 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4615 4616 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4617 4618 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4619 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4620 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 4621 4622 SDValue Load = 4623 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4624 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4625 if (AddToChain) 4626 PendingLoads.push_back(Load.getValue(1)); 4627 setValue(&I, Load); 4628 } 4629 4630 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4631 SDLoc sdl = getCurSDLoc(); 4632 4633 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4634 const Value *Ptr = I.getArgOperand(0); 4635 SDValue Src0 = getValue(I.getArgOperand(3)); 4636 SDValue Mask = getValue(I.getArgOperand(2)); 4637 4638 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4639 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4640 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4641 ->getMaybeAlignValue() 4642 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4643 4644 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4645 4646 SDValue Root = DAG.getRoot(); 4647 SDValue Base; 4648 SDValue Index; 4649 ISD::MemIndexType IndexType; 4650 SDValue Scale; 4651 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4652 I.getParent(), VT.getScalarStoreSize()); 4653 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4654 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4655 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4656 // TODO: Make MachineMemOperands aware of scalable 4657 // vectors. 4658 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges); 4659 4660 if (!UniformBase) { 4661 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4662 Index = getValue(Ptr); 4663 IndexType = ISD::SIGNED_SCALED; 4664 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4665 } 4666 4667 EVT IdxVT = Index.getValueType(); 4668 EVT EltTy = IdxVT.getVectorElementType(); 4669 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4670 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4671 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4672 } 4673 4674 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4675 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4676 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4677 4678 PendingLoads.push_back(Gather.getValue(1)); 4679 setValue(&I, Gather); 4680 } 4681 4682 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4683 SDLoc dl = getCurSDLoc(); 4684 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4685 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4686 SyncScope::ID SSID = I.getSyncScopeID(); 4687 4688 SDValue InChain = getRoot(); 4689 4690 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4691 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4692 4693 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4694 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4695 4696 MachineFunction &MF = DAG.getMachineFunction(); 4697 MachineMemOperand *MMO = MF.getMachineMemOperand( 4698 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4699 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4700 FailureOrdering); 4701 4702 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4703 dl, MemVT, VTs, InChain, 4704 getValue(I.getPointerOperand()), 4705 getValue(I.getCompareOperand()), 4706 getValue(I.getNewValOperand()), MMO); 4707 4708 SDValue OutChain = L.getValue(2); 4709 4710 setValue(&I, L); 4711 DAG.setRoot(OutChain); 4712 } 4713 4714 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4715 SDLoc dl = getCurSDLoc(); 4716 ISD::NodeType NT; 4717 switch (I.getOperation()) { 4718 default: llvm_unreachable("Unknown atomicrmw operation"); 4719 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4720 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4721 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4722 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4723 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4724 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4725 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4726 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4727 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4728 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4729 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4730 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4731 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4732 case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break; 4733 case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break; 4734 case AtomicRMWInst::UIncWrap: 4735 NT = ISD::ATOMIC_LOAD_UINC_WRAP; 4736 break; 4737 case AtomicRMWInst::UDecWrap: 4738 NT = ISD::ATOMIC_LOAD_UDEC_WRAP; 4739 break; 4740 } 4741 AtomicOrdering Ordering = I.getOrdering(); 4742 SyncScope::ID SSID = I.getSyncScopeID(); 4743 4744 SDValue InChain = getRoot(); 4745 4746 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4747 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4748 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4749 4750 MachineFunction &MF = DAG.getMachineFunction(); 4751 MachineMemOperand *MMO = MF.getMachineMemOperand( 4752 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4753 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4754 4755 SDValue L = 4756 DAG.getAtomic(NT, dl, MemVT, InChain, 4757 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4758 MMO); 4759 4760 SDValue OutChain = L.getValue(1); 4761 4762 setValue(&I, L); 4763 DAG.setRoot(OutChain); 4764 } 4765 4766 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4767 SDLoc dl = getCurSDLoc(); 4768 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4769 SDValue Ops[3]; 4770 Ops[0] = getRoot(); 4771 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4772 TLI.getFenceOperandTy(DAG.getDataLayout())); 4773 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4774 TLI.getFenceOperandTy(DAG.getDataLayout())); 4775 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops); 4776 setValue(&I, N); 4777 DAG.setRoot(N); 4778 } 4779 4780 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4781 SDLoc dl = getCurSDLoc(); 4782 AtomicOrdering Order = I.getOrdering(); 4783 SyncScope::ID SSID = I.getSyncScopeID(); 4784 4785 SDValue InChain = getRoot(); 4786 4787 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4788 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4789 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4790 4791 if (!TLI.supportsUnalignedAtomics() && 4792 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4793 report_fatal_error("Cannot generate unaligned atomic load"); 4794 4795 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 4796 4797 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4798 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4799 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4800 4801 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4802 4803 SDValue Ptr = getValue(I.getPointerOperand()); 4804 4805 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4806 // TODO: Once this is better exercised by tests, it should be merged with 4807 // the normal path for loads to prevent future divergence. 4808 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4809 if (MemVT != VT) 4810 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4811 4812 setValue(&I, L); 4813 SDValue OutChain = L.getValue(1); 4814 if (!I.isUnordered()) 4815 DAG.setRoot(OutChain); 4816 else 4817 PendingLoads.push_back(OutChain); 4818 return; 4819 } 4820 4821 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4822 Ptr, MMO); 4823 4824 SDValue OutChain = L.getValue(1); 4825 if (MemVT != VT) 4826 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4827 4828 setValue(&I, L); 4829 DAG.setRoot(OutChain); 4830 } 4831 4832 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4833 SDLoc dl = getCurSDLoc(); 4834 4835 AtomicOrdering Ordering = I.getOrdering(); 4836 SyncScope::ID SSID = I.getSyncScopeID(); 4837 4838 SDValue InChain = getRoot(); 4839 4840 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4841 EVT MemVT = 4842 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4843 4844 if (!TLI.supportsUnalignedAtomics() && 4845 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4846 report_fatal_error("Cannot generate unaligned atomic store"); 4847 4848 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4849 4850 MachineFunction &MF = DAG.getMachineFunction(); 4851 MachineMemOperand *MMO = MF.getMachineMemOperand( 4852 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4853 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4854 4855 SDValue Val = getValue(I.getValueOperand()); 4856 if (Val.getValueType() != MemVT) 4857 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4858 SDValue Ptr = getValue(I.getPointerOperand()); 4859 4860 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4861 // TODO: Once this is better exercised by tests, it should be merged with 4862 // the normal path for stores to prevent future divergence. 4863 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4864 setValue(&I, S); 4865 DAG.setRoot(S); 4866 return; 4867 } 4868 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4869 Ptr, Val, MMO); 4870 4871 setValue(&I, OutChain); 4872 DAG.setRoot(OutChain); 4873 } 4874 4875 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4876 /// node. 4877 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4878 unsigned Intrinsic) { 4879 // Ignore the callsite's attributes. A specific call site may be marked with 4880 // readnone, but the lowering code will expect the chain based on the 4881 // definition. 4882 const Function *F = I.getCalledFunction(); 4883 bool HasChain = !F->doesNotAccessMemory(); 4884 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4885 4886 // Build the operand list. 4887 SmallVector<SDValue, 8> Ops; 4888 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4889 if (OnlyLoad) { 4890 // We don't need to serialize loads against other loads. 4891 Ops.push_back(DAG.getRoot()); 4892 } else { 4893 Ops.push_back(getRoot()); 4894 } 4895 } 4896 4897 // Info is set by getTgtMemIntrinsic 4898 TargetLowering::IntrinsicInfo Info; 4899 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4900 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4901 DAG.getMachineFunction(), 4902 Intrinsic); 4903 4904 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4905 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4906 Info.opc == ISD::INTRINSIC_W_CHAIN) 4907 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4908 TLI.getPointerTy(DAG.getDataLayout()))); 4909 4910 // Add all operands of the call to the operand list. 4911 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) { 4912 const Value *Arg = I.getArgOperand(i); 4913 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4914 Ops.push_back(getValue(Arg)); 4915 continue; 4916 } 4917 4918 // Use TargetConstant instead of a regular constant for immarg. 4919 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true); 4920 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4921 assert(CI->getBitWidth() <= 64 && 4922 "large intrinsic immediates not handled"); 4923 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4924 } else { 4925 Ops.push_back( 4926 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4927 } 4928 } 4929 4930 SmallVector<EVT, 4> ValueVTs; 4931 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4932 4933 if (HasChain) 4934 ValueVTs.push_back(MVT::Other); 4935 4936 SDVTList VTs = DAG.getVTList(ValueVTs); 4937 4938 // Propagate fast-math-flags from IR to node(s). 4939 SDNodeFlags Flags; 4940 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 4941 Flags.copyFMF(*FPMO); 4942 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 4943 4944 // Create the node. 4945 SDValue Result; 4946 // In some cases, custom collection of operands from CallInst I may be needed. 4947 TLI.CollectTargetIntrinsicOperands(I, Ops, DAG); 4948 if (IsTgtIntrinsic) { 4949 // This is target intrinsic that touches memory 4950 // 4951 // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic 4952 // didn't yield anything useful. 4953 MachinePointerInfo MPI; 4954 if (Info.ptrVal) 4955 MPI = MachinePointerInfo(Info.ptrVal, Info.offset); 4956 else if (Info.fallbackAddressSpace) 4957 MPI = MachinePointerInfo(*Info.fallbackAddressSpace); 4958 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, 4959 Info.memVT, MPI, Info.align, Info.flags, 4960 Info.size, I.getAAMetadata()); 4961 } else if (!HasChain) { 4962 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4963 } else if (!I.getType()->isVoidTy()) { 4964 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4965 } else { 4966 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4967 } 4968 4969 if (HasChain) { 4970 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4971 if (OnlyLoad) 4972 PendingLoads.push_back(Chain); 4973 else 4974 DAG.setRoot(Chain); 4975 } 4976 4977 if (!I.getType()->isVoidTy()) { 4978 if (!isa<VectorType>(I.getType())) 4979 Result = lowerRangeToAssertZExt(DAG, I, Result); 4980 4981 MaybeAlign Alignment = I.getRetAlign(); 4982 4983 // Insert `assertalign` node if there's an alignment. 4984 if (InsertAssertAlign && Alignment) { 4985 Result = 4986 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 4987 } 4988 4989 setValue(&I, Result); 4990 } 4991 } 4992 4993 /// GetSignificand - Get the significand and build it into a floating-point 4994 /// number with exponent of 1: 4995 /// 4996 /// Op = (Op & 0x007fffff) | 0x3f800000; 4997 /// 4998 /// where Op is the hexadecimal representation of floating point value. 4999 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 5000 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 5001 DAG.getConstant(0x007fffff, dl, MVT::i32)); 5002 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 5003 DAG.getConstant(0x3f800000, dl, MVT::i32)); 5004 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 5005 } 5006 5007 /// GetExponent - Get the exponent: 5008 /// 5009 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 5010 /// 5011 /// where Op is the hexadecimal representation of floating point value. 5012 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 5013 const TargetLowering &TLI, const SDLoc &dl) { 5014 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 5015 DAG.getConstant(0x7f800000, dl, MVT::i32)); 5016 SDValue t1 = DAG.getNode( 5017 ISD::SRL, dl, MVT::i32, t0, 5018 DAG.getConstant(23, dl, 5019 TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout()))); 5020 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 5021 DAG.getConstant(127, dl, MVT::i32)); 5022 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 5023 } 5024 5025 /// getF32Constant - Get 32-bit floating point constant. 5026 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 5027 const SDLoc &dl) { 5028 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 5029 MVT::f32); 5030 } 5031 5032 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 5033 SelectionDAG &DAG) { 5034 // TODO: What fast-math-flags should be set on the floating-point nodes? 5035 5036 // IntegerPartOfX = ((int32_t)(t0); 5037 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 5038 5039 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 5040 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 5041 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 5042 5043 // IntegerPartOfX <<= 23; 5044 IntegerPartOfX = 5045 DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 5046 DAG.getConstant(23, dl, 5047 DAG.getTargetLoweringInfo().getShiftAmountTy( 5048 MVT::i32, DAG.getDataLayout()))); 5049 5050 SDValue TwoToFractionalPartOfX; 5051 if (LimitFloatPrecision <= 6) { 5052 // For floating-point precision of 6: 5053 // 5054 // TwoToFractionalPartOfX = 5055 // 0.997535578f + 5056 // (0.735607626f + 0.252464424f * x) * x; 5057 // 5058 // error 0.0144103317, which is 6 bits 5059 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5060 getF32Constant(DAG, 0x3e814304, dl)); 5061 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5062 getF32Constant(DAG, 0x3f3c50c8, dl)); 5063 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5064 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5065 getF32Constant(DAG, 0x3f7f5e7e, dl)); 5066 } else if (LimitFloatPrecision <= 12) { 5067 // For floating-point precision of 12: 5068 // 5069 // TwoToFractionalPartOfX = 5070 // 0.999892986f + 5071 // (0.696457318f + 5072 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 5073 // 5074 // error 0.000107046256, which is 13 to 14 bits 5075 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5076 getF32Constant(DAG, 0x3da235e3, dl)); 5077 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5078 getF32Constant(DAG, 0x3e65b8f3, dl)); 5079 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5080 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5081 getF32Constant(DAG, 0x3f324b07, dl)); 5082 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5083 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5084 getF32Constant(DAG, 0x3f7ff8fd, dl)); 5085 } else { // LimitFloatPrecision <= 18 5086 // For floating-point precision of 18: 5087 // 5088 // TwoToFractionalPartOfX = 5089 // 0.999999982f + 5090 // (0.693148872f + 5091 // (0.240227044f + 5092 // (0.554906021e-1f + 5093 // (0.961591928e-2f + 5094 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 5095 // error 2.47208000*10^(-7), which is better than 18 bits 5096 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5097 getF32Constant(DAG, 0x3924b03e, dl)); 5098 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5099 getF32Constant(DAG, 0x3ab24b87, dl)); 5100 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5101 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5102 getF32Constant(DAG, 0x3c1d8c17, dl)); 5103 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5104 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5105 getF32Constant(DAG, 0x3d634a1d, dl)); 5106 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5107 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5108 getF32Constant(DAG, 0x3e75fe14, dl)); 5109 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5110 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 5111 getF32Constant(DAG, 0x3f317234, dl)); 5112 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 5113 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 5114 getF32Constant(DAG, 0x3f800000, dl)); 5115 } 5116 5117 // Add the exponent into the result in integer domain. 5118 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 5119 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5120 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 5121 } 5122 5123 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5124 /// limited-precision mode. 5125 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5126 const TargetLowering &TLI, SDNodeFlags Flags) { 5127 if (Op.getValueType() == MVT::f32 && 5128 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5129 5130 // Put the exponent in the right bit position for later addition to the 5131 // final result: 5132 // 5133 // t0 = Op * log2(e) 5134 5135 // TODO: What fast-math-flags should be set here? 5136 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5137 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5138 return getLimitedPrecisionExp2(t0, dl, DAG); 5139 } 5140 5141 // No special expansion. 5142 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5143 } 5144 5145 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5146 /// limited-precision mode. 5147 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5148 const TargetLowering &TLI, SDNodeFlags Flags) { 5149 // TODO: What fast-math-flags should be set on the floating-point nodes? 5150 5151 if (Op.getValueType() == MVT::f32 && 5152 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5153 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5154 5155 // Scale the exponent by log(2). 5156 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5157 SDValue LogOfExponent = 5158 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5159 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5160 5161 // Get the significand and build it into a floating-point number with 5162 // exponent of 1. 5163 SDValue X = GetSignificand(DAG, Op1, dl); 5164 5165 SDValue LogOfMantissa; 5166 if (LimitFloatPrecision <= 6) { 5167 // For floating-point precision of 6: 5168 // 5169 // LogofMantissa = 5170 // -1.1609546f + 5171 // (1.4034025f - 0.23903021f * x) * x; 5172 // 5173 // error 0.0034276066, which is better than 8 bits 5174 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5175 getF32Constant(DAG, 0xbe74c456, dl)); 5176 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5177 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5178 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5179 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5180 getF32Constant(DAG, 0x3f949a29, dl)); 5181 } else if (LimitFloatPrecision <= 12) { 5182 // For floating-point precision of 12: 5183 // 5184 // LogOfMantissa = 5185 // -1.7417939f + 5186 // (2.8212026f + 5187 // (-1.4699568f + 5188 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5189 // 5190 // error 0.000061011436, which is 14 bits 5191 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5192 getF32Constant(DAG, 0xbd67b6d6, dl)); 5193 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5194 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5195 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5196 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5197 getF32Constant(DAG, 0x3fbc278b, dl)); 5198 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5199 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5200 getF32Constant(DAG, 0x40348e95, dl)); 5201 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5202 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5203 getF32Constant(DAG, 0x3fdef31a, dl)); 5204 } else { // LimitFloatPrecision <= 18 5205 // For floating-point precision of 18: 5206 // 5207 // LogOfMantissa = 5208 // -2.1072184f + 5209 // (4.2372794f + 5210 // (-3.7029485f + 5211 // (2.2781945f + 5212 // (-0.87823314f + 5213 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5214 // 5215 // error 0.0000023660568, which is better than 18 bits 5216 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5217 getF32Constant(DAG, 0xbc91e5ac, dl)); 5218 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5219 getF32Constant(DAG, 0x3e4350aa, dl)); 5220 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5221 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5222 getF32Constant(DAG, 0x3f60d3e3, dl)); 5223 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5224 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5225 getF32Constant(DAG, 0x4011cdf0, dl)); 5226 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5227 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5228 getF32Constant(DAG, 0x406cfd1c, dl)); 5229 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5230 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5231 getF32Constant(DAG, 0x408797cb, dl)); 5232 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5233 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5234 getF32Constant(DAG, 0x4006dcab, dl)); 5235 } 5236 5237 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5238 } 5239 5240 // No special expansion. 5241 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5242 } 5243 5244 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5245 /// limited-precision mode. 5246 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5247 const TargetLowering &TLI, SDNodeFlags Flags) { 5248 // TODO: What fast-math-flags should be set on the floating-point nodes? 5249 5250 if (Op.getValueType() == MVT::f32 && 5251 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5252 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5253 5254 // Get the exponent. 5255 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5256 5257 // Get the significand and build it into a floating-point number with 5258 // exponent of 1. 5259 SDValue X = GetSignificand(DAG, Op1, dl); 5260 5261 // Different possible minimax approximations of significand in 5262 // floating-point for various degrees of accuracy over [1,2]. 5263 SDValue Log2ofMantissa; 5264 if (LimitFloatPrecision <= 6) { 5265 // For floating-point precision of 6: 5266 // 5267 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5268 // 5269 // error 0.0049451742, which is more than 7 bits 5270 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5271 getF32Constant(DAG, 0xbeb08fe0, dl)); 5272 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5273 getF32Constant(DAG, 0x40019463, dl)); 5274 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5275 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5276 getF32Constant(DAG, 0x3fd6633d, dl)); 5277 } else if (LimitFloatPrecision <= 12) { 5278 // For floating-point precision of 12: 5279 // 5280 // Log2ofMantissa = 5281 // -2.51285454f + 5282 // (4.07009056f + 5283 // (-2.12067489f + 5284 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5285 // 5286 // error 0.0000876136000, which is better than 13 bits 5287 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5288 getF32Constant(DAG, 0xbda7262e, dl)); 5289 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5290 getF32Constant(DAG, 0x3f25280b, dl)); 5291 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5292 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5293 getF32Constant(DAG, 0x4007b923, dl)); 5294 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5295 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5296 getF32Constant(DAG, 0x40823e2f, dl)); 5297 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5298 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5299 getF32Constant(DAG, 0x4020d29c, dl)); 5300 } else { // LimitFloatPrecision <= 18 5301 // For floating-point precision of 18: 5302 // 5303 // Log2ofMantissa = 5304 // -3.0400495f + 5305 // (6.1129976f + 5306 // (-5.3420409f + 5307 // (3.2865683f + 5308 // (-1.2669343f + 5309 // (0.27515199f - 5310 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5311 // 5312 // error 0.0000018516, which is better than 18 bits 5313 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5314 getF32Constant(DAG, 0xbcd2769e, dl)); 5315 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5316 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5317 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5318 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5319 getF32Constant(DAG, 0x3fa22ae7, dl)); 5320 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5321 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5322 getF32Constant(DAG, 0x40525723, dl)); 5323 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5324 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5325 getF32Constant(DAG, 0x40aaf200, dl)); 5326 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5327 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5328 getF32Constant(DAG, 0x40c39dad, dl)); 5329 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5330 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5331 getF32Constant(DAG, 0x4042902c, dl)); 5332 } 5333 5334 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5335 } 5336 5337 // No special expansion. 5338 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5339 } 5340 5341 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5342 /// limited-precision mode. 5343 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5344 const TargetLowering &TLI, SDNodeFlags Flags) { 5345 // TODO: What fast-math-flags should be set on the floating-point nodes? 5346 5347 if (Op.getValueType() == MVT::f32 && 5348 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5349 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5350 5351 // Scale the exponent by log10(2) [0.30102999f]. 5352 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5353 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5354 getF32Constant(DAG, 0x3e9a209a, dl)); 5355 5356 // Get the significand and build it into a floating-point number with 5357 // exponent of 1. 5358 SDValue X = GetSignificand(DAG, Op1, dl); 5359 5360 SDValue Log10ofMantissa; 5361 if (LimitFloatPrecision <= 6) { 5362 // For floating-point precision of 6: 5363 // 5364 // Log10ofMantissa = 5365 // -0.50419619f + 5366 // (0.60948995f - 0.10380950f * x) * x; 5367 // 5368 // error 0.0014886165, which is 6 bits 5369 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5370 getF32Constant(DAG, 0xbdd49a13, dl)); 5371 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5372 getF32Constant(DAG, 0x3f1c0789, dl)); 5373 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5374 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5375 getF32Constant(DAG, 0x3f011300, dl)); 5376 } else if (LimitFloatPrecision <= 12) { 5377 // For floating-point precision of 12: 5378 // 5379 // Log10ofMantissa = 5380 // -0.64831180f + 5381 // (0.91751397f + 5382 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5383 // 5384 // error 0.00019228036, which is better than 12 bits 5385 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5386 getF32Constant(DAG, 0x3d431f31, dl)); 5387 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5388 getF32Constant(DAG, 0x3ea21fb2, dl)); 5389 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5390 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5391 getF32Constant(DAG, 0x3f6ae232, dl)); 5392 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5393 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5394 getF32Constant(DAG, 0x3f25f7c3, dl)); 5395 } else { // LimitFloatPrecision <= 18 5396 // For floating-point precision of 18: 5397 // 5398 // Log10ofMantissa = 5399 // -0.84299375f + 5400 // (1.5327582f + 5401 // (-1.0688956f + 5402 // (0.49102474f + 5403 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5404 // 5405 // error 0.0000037995730, which is better than 18 bits 5406 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5407 getF32Constant(DAG, 0x3c5d51ce, dl)); 5408 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5409 getF32Constant(DAG, 0x3e00685a, dl)); 5410 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5411 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5412 getF32Constant(DAG, 0x3efb6798, dl)); 5413 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5414 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5415 getF32Constant(DAG, 0x3f88d192, dl)); 5416 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5417 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5418 getF32Constant(DAG, 0x3fc4316c, dl)); 5419 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5420 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5421 getF32Constant(DAG, 0x3f57ce70, dl)); 5422 } 5423 5424 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5425 } 5426 5427 // No special expansion. 5428 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5429 } 5430 5431 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5432 /// limited-precision mode. 5433 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5434 const TargetLowering &TLI, SDNodeFlags Flags) { 5435 if (Op.getValueType() == MVT::f32 && 5436 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5437 return getLimitedPrecisionExp2(Op, dl, DAG); 5438 5439 // No special expansion. 5440 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5441 } 5442 5443 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5444 /// limited-precision mode with x == 10.0f. 5445 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5446 SelectionDAG &DAG, const TargetLowering &TLI, 5447 SDNodeFlags Flags) { 5448 bool IsExp10 = false; 5449 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5450 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5451 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5452 APFloat Ten(10.0f); 5453 IsExp10 = LHSC->isExactlyValue(Ten); 5454 } 5455 } 5456 5457 // TODO: What fast-math-flags should be set on the FMUL node? 5458 if (IsExp10) { 5459 // Put the exponent in the right bit position for later addition to the 5460 // final result: 5461 // 5462 // #define LOG2OF10 3.3219281f 5463 // t0 = Op * LOG2OF10; 5464 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5465 getF32Constant(DAG, 0x40549a78, dl)); 5466 return getLimitedPrecisionExp2(t0, dl, DAG); 5467 } 5468 5469 // No special expansion. 5470 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5471 } 5472 5473 /// ExpandPowI - Expand a llvm.powi intrinsic. 5474 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5475 SelectionDAG &DAG) { 5476 // If RHS is a constant, we can expand this out to a multiplication tree if 5477 // it's beneficial on the target, otherwise we end up lowering to a call to 5478 // __powidf2 (for example). 5479 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5480 unsigned Val = RHSC->getSExtValue(); 5481 5482 // powi(x, 0) -> 1.0 5483 if (Val == 0) 5484 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5485 5486 if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI( 5487 Val, DAG.shouldOptForSize())) { 5488 // Get the exponent as a positive value. 5489 if ((int)Val < 0) 5490 Val = -Val; 5491 // We use the simple binary decomposition method to generate the multiply 5492 // sequence. There are more optimal ways to do this (for example, 5493 // powi(x,15) generates one more multiply than it should), but this has 5494 // the benefit of being both really simple and much better than a libcall. 5495 SDValue Res; // Logically starts equal to 1.0 5496 SDValue CurSquare = LHS; 5497 // TODO: Intrinsics should have fast-math-flags that propagate to these 5498 // nodes. 5499 while (Val) { 5500 if (Val & 1) { 5501 if (Res.getNode()) 5502 Res = 5503 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare); 5504 else 5505 Res = CurSquare; // 1.0*CurSquare. 5506 } 5507 5508 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5509 CurSquare, CurSquare); 5510 Val >>= 1; 5511 } 5512 5513 // If the original was negative, invert the result, producing 1/(x*x*x). 5514 if (RHSC->getSExtValue() < 0) 5515 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5516 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5517 return Res; 5518 } 5519 } 5520 5521 // Otherwise, expand to a libcall. 5522 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5523 } 5524 5525 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5526 SDValue LHS, SDValue RHS, SDValue Scale, 5527 SelectionDAG &DAG, const TargetLowering &TLI) { 5528 EVT VT = LHS.getValueType(); 5529 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5530 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5531 LLVMContext &Ctx = *DAG.getContext(); 5532 5533 // If the type is legal but the operation isn't, this node might survive all 5534 // the way to operation legalization. If we end up there and we do not have 5535 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5536 // node. 5537 5538 // Coax the legalizer into expanding the node during type legalization instead 5539 // by bumping the size by one bit. This will force it to Promote, enabling the 5540 // early expansion and avoiding the need to expand later. 5541 5542 // We don't have to do this if Scale is 0; that can always be expanded, unless 5543 // it's a saturating signed operation. Those can experience true integer 5544 // division overflow, a case which we must avoid. 5545 5546 // FIXME: We wouldn't have to do this (or any of the early 5547 // expansion/promotion) if it was possible to expand a libcall of an 5548 // illegal type during operation legalization. But it's not, so things 5549 // get a bit hacky. 5550 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5551 if ((ScaleInt > 0 || (Saturating && Signed)) && 5552 (TLI.isTypeLegal(VT) || 5553 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5554 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5555 Opcode, VT, ScaleInt); 5556 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5557 EVT PromVT; 5558 if (VT.isScalarInteger()) 5559 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5560 else if (VT.isVector()) { 5561 PromVT = VT.getVectorElementType(); 5562 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5563 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5564 } else 5565 llvm_unreachable("Wrong VT for DIVFIX?"); 5566 LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT); 5567 RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT); 5568 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5569 // For saturating operations, we need to shift up the LHS to get the 5570 // proper saturation width, and then shift down again afterwards. 5571 if (Saturating) 5572 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5573 DAG.getConstant(1, DL, ShiftTy)); 5574 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5575 if (Saturating) 5576 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5577 DAG.getConstant(1, DL, ShiftTy)); 5578 return DAG.getZExtOrTrunc(Res, DL, VT); 5579 } 5580 } 5581 5582 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5583 } 5584 5585 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5586 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5587 static void 5588 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5589 const SDValue &N) { 5590 switch (N.getOpcode()) { 5591 case ISD::CopyFromReg: { 5592 SDValue Op = N.getOperand(1); 5593 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5594 Op.getValueType().getSizeInBits()); 5595 return; 5596 } 5597 case ISD::BITCAST: 5598 case ISD::AssertZext: 5599 case ISD::AssertSext: 5600 case ISD::TRUNCATE: 5601 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5602 return; 5603 case ISD::BUILD_PAIR: 5604 case ISD::BUILD_VECTOR: 5605 case ISD::CONCAT_VECTORS: 5606 for (SDValue Op : N->op_values()) 5607 getUnderlyingArgRegs(Regs, Op); 5608 return; 5609 default: 5610 return; 5611 } 5612 } 5613 5614 /// If the DbgValueInst is a dbg_value of a function argument, create the 5615 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5616 /// instruction selection, they will be inserted to the entry BB. 5617 /// We don't currently support this for variadic dbg_values, as they shouldn't 5618 /// appear for function arguments or in the prologue. 5619 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5620 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5621 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) { 5622 const Argument *Arg = dyn_cast<Argument>(V); 5623 if (!Arg) 5624 return false; 5625 5626 MachineFunction &MF = DAG.getMachineFunction(); 5627 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5628 5629 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind 5630 // we've been asked to pursue. 5631 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr, 5632 bool Indirect) { 5633 if (Reg.isVirtual() && MF.useDebugInstrRef()) { 5634 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF 5635 // pointing at the VReg, which will be patched up later. 5636 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF); 5637 SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg( 5638 /* Reg */ Reg, /* isDef */ false, /* isImp */ false, 5639 /* isKill */ false, /* isDead */ false, 5640 /* isUndef */ false, /* isEarlyClobber */ false, 5641 /* SubReg */ 0, /* isDebug */ true)}); 5642 5643 auto *NewDIExpr = FragExpr; 5644 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into 5645 // the DIExpression. 5646 if (Indirect) 5647 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore); 5648 SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0}); 5649 NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops); 5650 return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr); 5651 } else { 5652 // Create a completely standard DBG_VALUE. 5653 auto &Inst = TII->get(TargetOpcode::DBG_VALUE); 5654 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr); 5655 } 5656 }; 5657 5658 if (Kind == FuncArgumentDbgValueKind::Value) { 5659 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5660 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5661 // the entry block. 5662 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5663 if (!IsInEntryBlock) 5664 return false; 5665 5666 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5667 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5668 // variable that also is a param. 5669 // 5670 // Although, if we are at the top of the entry block already, we can still 5671 // emit using ArgDbgValue. This might catch some situations when the 5672 // dbg.value refers to an argument that isn't used in the entry block, so 5673 // any CopyToReg node would be optimized out and the only way to express 5674 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5675 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5676 // we should only emit as ArgDbgValue if the Variable is an argument to the 5677 // current function, and the dbg.value intrinsic is found in the entry 5678 // block. 5679 bool VariableIsFunctionInputArg = Variable->isParameter() && 5680 !DL->getInlinedAt(); 5681 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5682 if (!IsInPrologue && !VariableIsFunctionInputArg) 5683 return false; 5684 5685 // Here we assume that a function argument on IR level only can be used to 5686 // describe one input parameter on source level. If we for example have 5687 // source code like this 5688 // 5689 // struct A { long x, y; }; 5690 // void foo(struct A a, long b) { 5691 // ... 5692 // b = a.x; 5693 // ... 5694 // } 5695 // 5696 // and IR like this 5697 // 5698 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5699 // entry: 5700 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5701 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5702 // call void @llvm.dbg.value(metadata i32 %b, "b", 5703 // ... 5704 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5705 // ... 5706 // 5707 // then the last dbg.value is describing a parameter "b" using a value that 5708 // is an argument. But since we already has used %a1 to describe a parameter 5709 // we should not handle that last dbg.value here (that would result in an 5710 // incorrect hoisting of the DBG_VALUE to the function entry). 5711 // Notice that we allow one dbg.value per IR level argument, to accommodate 5712 // for the situation with fragments above. 5713 if (VariableIsFunctionInputArg) { 5714 unsigned ArgNo = Arg->getArgNo(); 5715 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5716 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5717 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5718 return false; 5719 FuncInfo.DescribedArgs.set(ArgNo); 5720 } 5721 } 5722 5723 bool IsIndirect = false; 5724 std::optional<MachineOperand> Op; 5725 // Some arguments' frame index is recorded during argument lowering. 5726 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5727 if (FI != std::numeric_limits<int>::max()) 5728 Op = MachineOperand::CreateFI(FI); 5729 5730 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 5731 if (!Op && N.getNode()) { 5732 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5733 Register Reg; 5734 if (ArgRegsAndSizes.size() == 1) 5735 Reg = ArgRegsAndSizes.front().first; 5736 5737 if (Reg && Reg.isVirtual()) { 5738 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5739 Register PR = RegInfo.getLiveInPhysReg(Reg); 5740 if (PR) 5741 Reg = PR; 5742 } 5743 if (Reg) { 5744 Op = MachineOperand::CreateReg(Reg, false); 5745 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5746 } 5747 } 5748 5749 if (!Op && N.getNode()) { 5750 // Check if frame index is available. 5751 SDValue LCandidate = peekThroughBitcasts(N); 5752 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5753 if (FrameIndexSDNode *FINode = 5754 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5755 Op = MachineOperand::CreateFI(FINode->getIndex()); 5756 } 5757 5758 if (!Op) { 5759 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5760 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 5761 SplitRegs) { 5762 unsigned Offset = 0; 5763 for (const auto &RegAndSize : SplitRegs) { 5764 // If the expression is already a fragment, the current register 5765 // offset+size might extend beyond the fragment. In this case, only 5766 // the register bits that are inside the fragment are relevant. 5767 int RegFragmentSizeInBits = RegAndSize.second; 5768 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5769 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5770 // The register is entirely outside the expression fragment, 5771 // so is irrelevant for debug info. 5772 if (Offset >= ExprFragmentSizeInBits) 5773 break; 5774 // The register is partially outside the expression fragment, only 5775 // the low bits within the fragment are relevant for debug info. 5776 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5777 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5778 } 5779 } 5780 5781 auto FragmentExpr = DIExpression::createFragmentExpression( 5782 Expr, Offset, RegFragmentSizeInBits); 5783 Offset += RegAndSize.second; 5784 // If a valid fragment expression cannot be created, the variable's 5785 // correct value cannot be determined and so it is set as Undef. 5786 if (!FragmentExpr) { 5787 SDDbgValue *SDV = DAG.getConstantDbgValue( 5788 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5789 DAG.AddDbgValue(SDV, false); 5790 continue; 5791 } 5792 MachineInstr *NewMI = 5793 MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, 5794 Kind != FuncArgumentDbgValueKind::Value); 5795 FuncInfo.ArgDbgValues.push_back(NewMI); 5796 } 5797 }; 5798 5799 // Check if ValueMap has reg number. 5800 DenseMap<const Value *, Register>::const_iterator 5801 VMI = FuncInfo.ValueMap.find(V); 5802 if (VMI != FuncInfo.ValueMap.end()) { 5803 const auto &TLI = DAG.getTargetLoweringInfo(); 5804 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5805 V->getType(), std::nullopt); 5806 if (RFV.occupiesMultipleRegs()) { 5807 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5808 return true; 5809 } 5810 5811 Op = MachineOperand::CreateReg(VMI->second, false); 5812 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5813 } else if (ArgRegsAndSizes.size() > 1) { 5814 // This was split due to the calling convention, and no virtual register 5815 // mapping exists for the value. 5816 splitMultiRegDbgValue(ArgRegsAndSizes); 5817 return true; 5818 } 5819 } 5820 5821 if (!Op) 5822 return false; 5823 5824 // If the expression refers to the entry value of an Argument, use the 5825 // corresponding livein physical register. As per the Verifier, this is only 5826 // allowed for swiftasync Arguments. 5827 if (Op->isReg() && Expr->isEntryValue()) { 5828 assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync)); 5829 auto OpReg = Op->getReg(); 5830 for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins()) 5831 if (OpReg == VirtReg || OpReg == PhysReg) { 5832 SDDbgValue *SDV = DAG.getVRegDbgValue( 5833 Variable, Expr, PhysReg, 5834 Kind != FuncArgumentDbgValueKind::Value /*is indirect*/, DL, 5835 SDNodeOrder); 5836 DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/); 5837 return true; 5838 } 5839 LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but " 5840 "couldn't find a physical register\n"); 5841 return true; 5842 } 5843 5844 assert(Variable->isValidLocationForIntrinsic(DL) && 5845 "Expected inlined-at fields to agree"); 5846 MachineInstr *NewMI = nullptr; 5847 5848 if (Op->isReg()) 5849 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect); 5850 else 5851 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op, 5852 Variable, Expr); 5853 5854 // Otherwise, use ArgDbgValues. 5855 FuncInfo.ArgDbgValues.push_back(NewMI); 5856 return true; 5857 } 5858 5859 /// Return the appropriate SDDbgValue based on N. 5860 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5861 DILocalVariable *Variable, 5862 DIExpression *Expr, 5863 const DebugLoc &dl, 5864 unsigned DbgSDNodeOrder) { 5865 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5866 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5867 // stack slot locations. 5868 // 5869 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5870 // debug values here after optimization: 5871 // 5872 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5873 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5874 // 5875 // Both describe the direct values of their associated variables. 5876 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5877 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5878 } 5879 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5880 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5881 } 5882 5883 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5884 switch (Intrinsic) { 5885 case Intrinsic::smul_fix: 5886 return ISD::SMULFIX; 5887 case Intrinsic::umul_fix: 5888 return ISD::UMULFIX; 5889 case Intrinsic::smul_fix_sat: 5890 return ISD::SMULFIXSAT; 5891 case Intrinsic::umul_fix_sat: 5892 return ISD::UMULFIXSAT; 5893 case Intrinsic::sdiv_fix: 5894 return ISD::SDIVFIX; 5895 case Intrinsic::udiv_fix: 5896 return ISD::UDIVFIX; 5897 case Intrinsic::sdiv_fix_sat: 5898 return ISD::SDIVFIXSAT; 5899 case Intrinsic::udiv_fix_sat: 5900 return ISD::UDIVFIXSAT; 5901 default: 5902 llvm_unreachable("Unhandled fixed point intrinsic"); 5903 } 5904 } 5905 5906 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5907 const char *FunctionName) { 5908 assert(FunctionName && "FunctionName must not be nullptr"); 5909 SDValue Callee = DAG.getExternalSymbol( 5910 FunctionName, 5911 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5912 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 5913 } 5914 5915 /// Given a @llvm.call.preallocated.setup, return the corresponding 5916 /// preallocated call. 5917 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5918 assert(cast<CallBase>(PreallocatedSetup) 5919 ->getCalledFunction() 5920 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5921 "expected call_preallocated_setup Value"); 5922 for (const auto *U : PreallocatedSetup->users()) { 5923 auto *UseCall = cast<CallBase>(U); 5924 const Function *Fn = UseCall->getCalledFunction(); 5925 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5926 return UseCall; 5927 } 5928 } 5929 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5930 } 5931 5932 /// Lower the call to the specified intrinsic function. 5933 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5934 unsigned Intrinsic) { 5935 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5936 SDLoc sdl = getCurSDLoc(); 5937 DebugLoc dl = getCurDebugLoc(); 5938 SDValue Res; 5939 5940 SDNodeFlags Flags; 5941 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 5942 Flags.copyFMF(*FPOp); 5943 5944 switch (Intrinsic) { 5945 default: 5946 // By default, turn this into a target intrinsic node. 5947 visitTargetIntrinsic(I, Intrinsic); 5948 return; 5949 case Intrinsic::vscale: { 5950 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5951 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1))); 5952 return; 5953 } 5954 case Intrinsic::vastart: visitVAStart(I); return; 5955 case Intrinsic::vaend: visitVAEnd(I); return; 5956 case Intrinsic::vacopy: visitVACopy(I); return; 5957 case Intrinsic::returnaddress: 5958 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5959 TLI.getValueType(DAG.getDataLayout(), I.getType()), 5960 getValue(I.getArgOperand(0)))); 5961 return; 5962 case Intrinsic::addressofreturnaddress: 5963 setValue(&I, 5964 DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5965 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 5966 return; 5967 case Intrinsic::sponentry: 5968 setValue(&I, 5969 DAG.getNode(ISD::SPONENTRY, sdl, 5970 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 5971 return; 5972 case Intrinsic::frameaddress: 5973 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5974 TLI.getFrameIndexTy(DAG.getDataLayout()), 5975 getValue(I.getArgOperand(0)))); 5976 return; 5977 case Intrinsic::read_volatile_register: 5978 case Intrinsic::read_register: { 5979 Value *Reg = I.getArgOperand(0); 5980 SDValue Chain = getRoot(); 5981 SDValue RegName = 5982 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5983 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5984 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5985 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5986 setValue(&I, Res); 5987 DAG.setRoot(Res.getValue(1)); 5988 return; 5989 } 5990 case Intrinsic::write_register: { 5991 Value *Reg = I.getArgOperand(0); 5992 Value *RegValue = I.getArgOperand(1); 5993 SDValue Chain = getRoot(); 5994 SDValue RegName = 5995 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5996 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5997 RegName, getValue(RegValue))); 5998 return; 5999 } 6000 case Intrinsic::memcpy: { 6001 const auto &MCI = cast<MemCpyInst>(I); 6002 SDValue Op1 = getValue(I.getArgOperand(0)); 6003 SDValue Op2 = getValue(I.getArgOperand(1)); 6004 SDValue Op3 = getValue(I.getArgOperand(2)); 6005 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 6006 Align DstAlign = MCI.getDestAlign().valueOrOne(); 6007 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 6008 Align Alignment = std::min(DstAlign, SrcAlign); 6009 bool isVol = MCI.isVolatile(); 6010 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6011 // FIXME: Support passing different dest/src alignments to the memcpy DAG 6012 // node. 6013 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6014 SDValue MC = DAG.getMemcpy( 6015 Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6016 /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)), 6017 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 6018 updateDAGForMaybeTailCall(MC); 6019 return; 6020 } 6021 case Intrinsic::memcpy_inline: { 6022 const auto &MCI = cast<MemCpyInlineInst>(I); 6023 SDValue Dst = getValue(I.getArgOperand(0)); 6024 SDValue Src = getValue(I.getArgOperand(1)); 6025 SDValue Size = getValue(I.getArgOperand(2)); 6026 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 6027 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 6028 Align DstAlign = MCI.getDestAlign().valueOrOne(); 6029 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 6030 Align Alignment = std::min(DstAlign, SrcAlign); 6031 bool isVol = MCI.isVolatile(); 6032 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6033 // FIXME: Support passing different dest/src alignments to the memcpy DAG 6034 // node. 6035 SDValue MC = DAG.getMemcpy( 6036 getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 6037 /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)), 6038 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 6039 updateDAGForMaybeTailCall(MC); 6040 return; 6041 } 6042 case Intrinsic::memset: { 6043 const auto &MSI = cast<MemSetInst>(I); 6044 SDValue Op1 = getValue(I.getArgOperand(0)); 6045 SDValue Op2 = getValue(I.getArgOperand(1)); 6046 SDValue Op3 = getValue(I.getArgOperand(2)); 6047 // @llvm.memset defines 0 and 1 to both mean no alignment. 6048 Align Alignment = MSI.getDestAlign().valueOrOne(); 6049 bool isVol = MSI.isVolatile(); 6050 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6051 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6052 SDValue MS = DAG.getMemset( 6053 Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false, 6054 isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata()); 6055 updateDAGForMaybeTailCall(MS); 6056 return; 6057 } 6058 case Intrinsic::memset_inline: { 6059 const auto &MSII = cast<MemSetInlineInst>(I); 6060 SDValue Dst = getValue(I.getArgOperand(0)); 6061 SDValue Value = getValue(I.getArgOperand(1)); 6062 SDValue Size = getValue(I.getArgOperand(2)); 6063 assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size"); 6064 // @llvm.memset defines 0 and 1 to both mean no alignment. 6065 Align DstAlign = MSII.getDestAlign().valueOrOne(); 6066 bool isVol = MSII.isVolatile(); 6067 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6068 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6069 SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol, 6070 /* AlwaysInline */ true, isTC, 6071 MachinePointerInfo(I.getArgOperand(0)), 6072 I.getAAMetadata()); 6073 updateDAGForMaybeTailCall(MC); 6074 return; 6075 } 6076 case Intrinsic::memmove: { 6077 const auto &MMI = cast<MemMoveInst>(I); 6078 SDValue Op1 = getValue(I.getArgOperand(0)); 6079 SDValue Op2 = getValue(I.getArgOperand(1)); 6080 SDValue Op3 = getValue(I.getArgOperand(2)); 6081 // @llvm.memmove defines 0 and 1 to both mean no alignment. 6082 Align DstAlign = MMI.getDestAlign().valueOrOne(); 6083 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 6084 Align Alignment = std::min(DstAlign, SrcAlign); 6085 bool isVol = MMI.isVolatile(); 6086 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6087 // FIXME: Support passing different dest/src alignments to the memmove DAG 6088 // node. 6089 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6090 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6091 isTC, MachinePointerInfo(I.getArgOperand(0)), 6092 MachinePointerInfo(I.getArgOperand(1)), 6093 I.getAAMetadata(), AA); 6094 updateDAGForMaybeTailCall(MM); 6095 return; 6096 } 6097 case Intrinsic::memcpy_element_unordered_atomic: { 6098 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 6099 SDValue Dst = getValue(MI.getRawDest()); 6100 SDValue Src = getValue(MI.getRawSource()); 6101 SDValue Length = getValue(MI.getLength()); 6102 6103 Type *LengthTy = MI.getLength()->getType(); 6104 unsigned ElemSz = MI.getElementSizeInBytes(); 6105 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6106 SDValue MC = 6107 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6108 isTC, MachinePointerInfo(MI.getRawDest()), 6109 MachinePointerInfo(MI.getRawSource())); 6110 updateDAGForMaybeTailCall(MC); 6111 return; 6112 } 6113 case Intrinsic::memmove_element_unordered_atomic: { 6114 auto &MI = cast<AtomicMemMoveInst>(I); 6115 SDValue Dst = getValue(MI.getRawDest()); 6116 SDValue Src = getValue(MI.getRawSource()); 6117 SDValue Length = getValue(MI.getLength()); 6118 6119 Type *LengthTy = MI.getLength()->getType(); 6120 unsigned ElemSz = MI.getElementSizeInBytes(); 6121 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6122 SDValue MC = 6123 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6124 isTC, MachinePointerInfo(MI.getRawDest()), 6125 MachinePointerInfo(MI.getRawSource())); 6126 updateDAGForMaybeTailCall(MC); 6127 return; 6128 } 6129 case Intrinsic::memset_element_unordered_atomic: { 6130 auto &MI = cast<AtomicMemSetInst>(I); 6131 SDValue Dst = getValue(MI.getRawDest()); 6132 SDValue Val = getValue(MI.getValue()); 6133 SDValue Length = getValue(MI.getLength()); 6134 6135 Type *LengthTy = MI.getLength()->getType(); 6136 unsigned ElemSz = MI.getElementSizeInBytes(); 6137 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6138 SDValue MC = 6139 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz, 6140 isTC, MachinePointerInfo(MI.getRawDest())); 6141 updateDAGForMaybeTailCall(MC); 6142 return; 6143 } 6144 case Intrinsic::call_preallocated_setup: { 6145 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 6146 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6147 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 6148 getRoot(), SrcValue); 6149 setValue(&I, Res); 6150 DAG.setRoot(Res); 6151 return; 6152 } 6153 case Intrinsic::call_preallocated_arg: { 6154 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 6155 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6156 SDValue Ops[3]; 6157 Ops[0] = getRoot(); 6158 Ops[1] = SrcValue; 6159 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 6160 MVT::i32); // arg index 6161 SDValue Res = DAG.getNode( 6162 ISD::PREALLOCATED_ARG, sdl, 6163 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 6164 setValue(&I, Res); 6165 DAG.setRoot(Res.getValue(1)); 6166 return; 6167 } 6168 case Intrinsic::dbg_declare: { 6169 const auto &DI = cast<DbgDeclareInst>(I); 6170 // Debug intrinsics are handled separately in assignment tracking mode. 6171 // Some intrinsics are handled right after Argument lowering. 6172 if (AssignmentTrackingEnabled || 6173 FuncInfo.PreprocessedDbgDeclares.count(&DI)) 6174 return; 6175 // Assume dbg.declare can not currently use DIArgList, i.e. 6176 // it is non-variadic. 6177 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 6178 DILocalVariable *Variable = DI.getVariable(); 6179 DIExpression *Expression = DI.getExpression(); 6180 dropDanglingDebugInfo(Variable, Expression); 6181 assert(Variable && "Missing variable"); 6182 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 6183 << "\n"); 6184 // Check if address has undef value. 6185 const Value *Address = DI.getVariableLocationOp(0); 6186 if (!Address || isa<UndefValue>(Address) || 6187 (Address->use_empty() && !isa<Argument>(Address))) { 6188 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6189 << " (bad/undef/unused-arg address)\n"); 6190 return; 6191 } 6192 6193 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 6194 6195 SDValue &N = NodeMap[Address]; 6196 if (!N.getNode() && isa<Argument>(Address)) 6197 // Check unused arguments map. 6198 N = UnusedArgNodeMap[Address]; 6199 SDDbgValue *SDV; 6200 if (N.getNode()) { 6201 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 6202 Address = BCI->getOperand(0); 6203 // Parameters are handled specially. 6204 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 6205 if (isParameter && FINode) { 6206 // Byval parameter. We have a frame index at this point. 6207 SDV = 6208 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 6209 /*IsIndirect*/ true, dl, SDNodeOrder); 6210 } else if (isa<Argument>(Address)) { 6211 // Address is an argument, so try to emit its dbg value using 6212 // virtual register info from the FuncInfo.ValueMap. 6213 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 6214 FuncArgumentDbgValueKind::Declare, N); 6215 return; 6216 } else { 6217 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 6218 true, dl, SDNodeOrder); 6219 } 6220 DAG.AddDbgValue(SDV, isParameter); 6221 } else { 6222 // If Address is an argument then try to emit its dbg value using 6223 // virtual register info from the FuncInfo.ValueMap. 6224 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 6225 FuncArgumentDbgValueKind::Declare, N)) { 6226 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6227 << " (could not emit func-arg dbg_value)\n"); 6228 } 6229 } 6230 return; 6231 } 6232 case Intrinsic::dbg_label: { 6233 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6234 DILabel *Label = DI.getLabel(); 6235 assert(Label && "Missing label"); 6236 6237 SDDbgLabel *SDV; 6238 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6239 DAG.AddDbgLabel(SDV); 6240 return; 6241 } 6242 case Intrinsic::dbg_assign: { 6243 // Debug intrinsics are handled seperately in assignment tracking mode. 6244 if (AssignmentTrackingEnabled) 6245 return; 6246 // If assignment tracking hasn't been enabled then fall through and treat 6247 // the dbg.assign as a dbg.value. 6248 [[fallthrough]]; 6249 } 6250 case Intrinsic::dbg_value: { 6251 // Debug intrinsics are handled seperately in assignment tracking mode. 6252 if (AssignmentTrackingEnabled) 6253 return; 6254 const DbgValueInst &DI = cast<DbgValueInst>(I); 6255 assert(DI.getVariable() && "Missing variable"); 6256 6257 DILocalVariable *Variable = DI.getVariable(); 6258 DIExpression *Expression = DI.getExpression(); 6259 dropDanglingDebugInfo(Variable, Expression); 6260 6261 if (DI.isKillLocation()) { 6262 handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder); 6263 return; 6264 } 6265 6266 SmallVector<Value *, 4> Values(DI.getValues()); 6267 if (Values.empty()) 6268 return; 6269 6270 bool IsVariadic = DI.hasArgList(); 6271 if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(), 6272 SDNodeOrder, IsVariadic)) 6273 addDanglingDebugInfo(&DI, SDNodeOrder); 6274 return; 6275 } 6276 6277 case Intrinsic::eh_typeid_for: { 6278 // Find the type id for the given typeinfo. 6279 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6280 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6281 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6282 setValue(&I, Res); 6283 return; 6284 } 6285 6286 case Intrinsic::eh_return_i32: 6287 case Intrinsic::eh_return_i64: 6288 DAG.getMachineFunction().setCallsEHReturn(true); 6289 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6290 MVT::Other, 6291 getControlRoot(), 6292 getValue(I.getArgOperand(0)), 6293 getValue(I.getArgOperand(1)))); 6294 return; 6295 case Intrinsic::eh_unwind_init: 6296 DAG.getMachineFunction().setCallsUnwindInit(true); 6297 return; 6298 case Intrinsic::eh_dwarf_cfa: 6299 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6300 TLI.getPointerTy(DAG.getDataLayout()), 6301 getValue(I.getArgOperand(0)))); 6302 return; 6303 case Intrinsic::eh_sjlj_callsite: { 6304 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6305 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0)); 6306 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6307 6308 MMI.setCurrentCallSite(CI->getZExtValue()); 6309 return; 6310 } 6311 case Intrinsic::eh_sjlj_functioncontext: { 6312 // Get and store the index of the function context. 6313 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6314 AllocaInst *FnCtx = 6315 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6316 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6317 MFI.setFunctionContextIndex(FI); 6318 return; 6319 } 6320 case Intrinsic::eh_sjlj_setjmp: { 6321 SDValue Ops[2]; 6322 Ops[0] = getRoot(); 6323 Ops[1] = getValue(I.getArgOperand(0)); 6324 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6325 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6326 setValue(&I, Op.getValue(0)); 6327 DAG.setRoot(Op.getValue(1)); 6328 return; 6329 } 6330 case Intrinsic::eh_sjlj_longjmp: 6331 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6332 getRoot(), getValue(I.getArgOperand(0)))); 6333 return; 6334 case Intrinsic::eh_sjlj_setup_dispatch: 6335 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6336 getRoot())); 6337 return; 6338 case Intrinsic::masked_gather: 6339 visitMaskedGather(I); 6340 return; 6341 case Intrinsic::masked_load: 6342 visitMaskedLoad(I); 6343 return; 6344 case Intrinsic::masked_scatter: 6345 visitMaskedScatter(I); 6346 return; 6347 case Intrinsic::masked_store: 6348 visitMaskedStore(I); 6349 return; 6350 case Intrinsic::masked_expandload: 6351 visitMaskedLoad(I, true /* IsExpanding */); 6352 return; 6353 case Intrinsic::masked_compressstore: 6354 visitMaskedStore(I, true /* IsCompressing */); 6355 return; 6356 case Intrinsic::powi: 6357 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6358 getValue(I.getArgOperand(1)), DAG)); 6359 return; 6360 case Intrinsic::log: 6361 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6362 return; 6363 case Intrinsic::log2: 6364 setValue(&I, 6365 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6366 return; 6367 case Intrinsic::log10: 6368 setValue(&I, 6369 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6370 return; 6371 case Intrinsic::exp: 6372 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6373 return; 6374 case Intrinsic::exp2: 6375 setValue(&I, 6376 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6377 return; 6378 case Intrinsic::pow: 6379 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6380 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6381 return; 6382 case Intrinsic::sqrt: 6383 case Intrinsic::fabs: 6384 case Intrinsic::sin: 6385 case Intrinsic::cos: 6386 case Intrinsic::floor: 6387 case Intrinsic::ceil: 6388 case Intrinsic::trunc: 6389 case Intrinsic::rint: 6390 case Intrinsic::nearbyint: 6391 case Intrinsic::round: 6392 case Intrinsic::roundeven: 6393 case Intrinsic::canonicalize: { 6394 unsigned Opcode; 6395 switch (Intrinsic) { 6396 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6397 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6398 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6399 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6400 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6401 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6402 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6403 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6404 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6405 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6406 case Intrinsic::round: Opcode = ISD::FROUND; break; 6407 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6408 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6409 } 6410 6411 setValue(&I, DAG.getNode(Opcode, sdl, 6412 getValue(I.getArgOperand(0)).getValueType(), 6413 getValue(I.getArgOperand(0)), Flags)); 6414 return; 6415 } 6416 case Intrinsic::lround: 6417 case Intrinsic::llround: 6418 case Intrinsic::lrint: 6419 case Intrinsic::llrint: { 6420 unsigned Opcode; 6421 switch (Intrinsic) { 6422 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6423 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6424 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6425 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6426 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6427 } 6428 6429 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6430 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6431 getValue(I.getArgOperand(0)))); 6432 return; 6433 } 6434 case Intrinsic::minnum: 6435 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6436 getValue(I.getArgOperand(0)).getValueType(), 6437 getValue(I.getArgOperand(0)), 6438 getValue(I.getArgOperand(1)), Flags)); 6439 return; 6440 case Intrinsic::maxnum: 6441 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6442 getValue(I.getArgOperand(0)).getValueType(), 6443 getValue(I.getArgOperand(0)), 6444 getValue(I.getArgOperand(1)), Flags)); 6445 return; 6446 case Intrinsic::minimum: 6447 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6448 getValue(I.getArgOperand(0)).getValueType(), 6449 getValue(I.getArgOperand(0)), 6450 getValue(I.getArgOperand(1)), Flags)); 6451 return; 6452 case Intrinsic::maximum: 6453 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6454 getValue(I.getArgOperand(0)).getValueType(), 6455 getValue(I.getArgOperand(0)), 6456 getValue(I.getArgOperand(1)), Flags)); 6457 return; 6458 case Intrinsic::copysign: 6459 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6460 getValue(I.getArgOperand(0)).getValueType(), 6461 getValue(I.getArgOperand(0)), 6462 getValue(I.getArgOperand(1)), Flags)); 6463 return; 6464 case Intrinsic::ldexp: 6465 setValue(&I, DAG.getNode(ISD::FLDEXP, sdl, 6466 getValue(I.getArgOperand(0)).getValueType(), 6467 getValue(I.getArgOperand(0)), 6468 getValue(I.getArgOperand(1)), Flags)); 6469 return; 6470 case Intrinsic::frexp: { 6471 SmallVector<EVT, 2> ValueVTs; 6472 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 6473 SDVTList VTs = DAG.getVTList(ValueVTs); 6474 setValue(&I, 6475 DAG.getNode(ISD::FFREXP, sdl, VTs, getValue(I.getArgOperand(0)))); 6476 return; 6477 } 6478 case Intrinsic::arithmetic_fence: { 6479 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl, 6480 getValue(I.getArgOperand(0)).getValueType(), 6481 getValue(I.getArgOperand(0)), Flags)); 6482 return; 6483 } 6484 case Intrinsic::fma: 6485 setValue(&I, DAG.getNode( 6486 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6487 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6488 getValue(I.getArgOperand(2)), Flags)); 6489 return; 6490 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6491 case Intrinsic::INTRINSIC: 6492 #include "llvm/IR/ConstrainedOps.def" 6493 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6494 return; 6495 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6496 #include "llvm/IR/VPIntrinsics.def" 6497 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6498 return; 6499 case Intrinsic::fptrunc_round: { 6500 // Get the last argument, the metadata and convert it to an integer in the 6501 // call 6502 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata(); 6503 std::optional<RoundingMode> RoundMode = 6504 convertStrToRoundingMode(cast<MDString>(MD)->getString()); 6505 6506 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6507 6508 // Propagate fast-math-flags from IR to node(s). 6509 SDNodeFlags Flags; 6510 Flags.copyFMF(*cast<FPMathOperator>(&I)); 6511 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 6512 6513 SDValue Result; 6514 Result = DAG.getNode( 6515 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)), 6516 DAG.getTargetConstant((int)*RoundMode, sdl, 6517 TLI.getPointerTy(DAG.getDataLayout()))); 6518 setValue(&I, Result); 6519 6520 return; 6521 } 6522 case Intrinsic::fmuladd: { 6523 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6524 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6525 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6526 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6527 getValue(I.getArgOperand(0)).getValueType(), 6528 getValue(I.getArgOperand(0)), 6529 getValue(I.getArgOperand(1)), 6530 getValue(I.getArgOperand(2)), Flags)); 6531 } else { 6532 // TODO: Intrinsic calls should have fast-math-flags. 6533 SDValue Mul = DAG.getNode( 6534 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6535 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6536 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6537 getValue(I.getArgOperand(0)).getValueType(), 6538 Mul, getValue(I.getArgOperand(2)), Flags); 6539 setValue(&I, Add); 6540 } 6541 return; 6542 } 6543 case Intrinsic::convert_to_fp16: 6544 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6545 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6546 getValue(I.getArgOperand(0)), 6547 DAG.getTargetConstant(0, sdl, 6548 MVT::i32)))); 6549 return; 6550 case Intrinsic::convert_from_fp16: 6551 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6552 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6553 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6554 getValue(I.getArgOperand(0))))); 6555 return; 6556 case Intrinsic::fptosi_sat: { 6557 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6558 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 6559 getValue(I.getArgOperand(0)), 6560 DAG.getValueType(VT.getScalarType()))); 6561 return; 6562 } 6563 case Intrinsic::fptoui_sat: { 6564 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6565 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 6566 getValue(I.getArgOperand(0)), 6567 DAG.getValueType(VT.getScalarType()))); 6568 return; 6569 } 6570 case Intrinsic::set_rounding: 6571 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6572 {getRoot(), getValue(I.getArgOperand(0))}); 6573 setValue(&I, Res); 6574 DAG.setRoot(Res.getValue(0)); 6575 return; 6576 case Intrinsic::is_fpclass: { 6577 const DataLayout DLayout = DAG.getDataLayout(); 6578 EVT DestVT = TLI.getValueType(DLayout, I.getType()); 6579 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType()); 6580 FPClassTest Test = static_cast<FPClassTest>( 6581 cast<ConstantInt>(I.getArgOperand(1))->getZExtValue()); 6582 MachineFunction &MF = DAG.getMachineFunction(); 6583 const Function &F = MF.getFunction(); 6584 SDValue Op = getValue(I.getArgOperand(0)); 6585 SDNodeFlags Flags; 6586 Flags.setNoFPExcept( 6587 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP)); 6588 // If ISD::IS_FPCLASS should be expanded, do it right now, because the 6589 // expansion can use illegal types. Making expansion early allows 6590 // legalizing these types prior to selection. 6591 if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) { 6592 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG); 6593 setValue(&I, Result); 6594 return; 6595 } 6596 6597 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32); 6598 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags); 6599 setValue(&I, V); 6600 return; 6601 } 6602 case Intrinsic::get_fpenv: { 6603 const DataLayout DLayout = DAG.getDataLayout(); 6604 EVT EnvVT = TLI.getValueType(DLayout, I.getType()); 6605 Align TempAlign = DAG.getEVTAlign(EnvVT); 6606 SDValue Chain = getRoot(); 6607 // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node 6608 // and temporary storage in stack. 6609 if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) { 6610 Res = DAG.getNode( 6611 ISD::GET_FPENV, sdl, 6612 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()), 6613 MVT::Other), 6614 Chain); 6615 } else { 6616 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value()); 6617 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex(); 6618 auto MPI = 6619 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI); 6620 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 6621 MPI, MachineMemOperand::MOStore, MemoryLocation::UnknownSize, 6622 TempAlign); 6623 Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO); 6624 Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI); 6625 } 6626 setValue(&I, Res); 6627 DAG.setRoot(Res.getValue(1)); 6628 return; 6629 } 6630 case Intrinsic::set_fpenv: { 6631 const DataLayout DLayout = DAG.getDataLayout(); 6632 SDValue Env = getValue(I.getArgOperand(0)); 6633 EVT EnvVT = Env.getValueType(); 6634 Align TempAlign = DAG.getEVTAlign(EnvVT); 6635 SDValue Chain = getRoot(); 6636 // If SET_FPENV is custom or legal, use it. Otherwise use loading 6637 // environment from memory. 6638 if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) { 6639 Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env); 6640 } else { 6641 // Allocate space in stack, copy environment bits into it and use this 6642 // memory in SET_FPENV_MEM. 6643 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value()); 6644 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex(); 6645 auto MPI = 6646 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI); 6647 Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign, 6648 MachineMemOperand::MOStore); 6649 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 6650 MPI, MachineMemOperand::MOLoad, MemoryLocation::UnknownSize, 6651 TempAlign); 6652 Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO); 6653 } 6654 DAG.setRoot(Chain); 6655 return; 6656 } 6657 case Intrinsic::reset_fpenv: 6658 DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot())); 6659 return; 6660 case Intrinsic::pcmarker: { 6661 SDValue Tmp = getValue(I.getArgOperand(0)); 6662 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6663 return; 6664 } 6665 case Intrinsic::readcyclecounter: { 6666 SDValue Op = getRoot(); 6667 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6668 DAG.getVTList(MVT::i64, MVT::Other), Op); 6669 setValue(&I, Res); 6670 DAG.setRoot(Res.getValue(1)); 6671 return; 6672 } 6673 case Intrinsic::bitreverse: 6674 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6675 getValue(I.getArgOperand(0)).getValueType(), 6676 getValue(I.getArgOperand(0)))); 6677 return; 6678 case Intrinsic::bswap: 6679 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6680 getValue(I.getArgOperand(0)).getValueType(), 6681 getValue(I.getArgOperand(0)))); 6682 return; 6683 case Intrinsic::cttz: { 6684 SDValue Arg = getValue(I.getArgOperand(0)); 6685 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6686 EVT Ty = Arg.getValueType(); 6687 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6688 sdl, Ty, Arg)); 6689 return; 6690 } 6691 case Intrinsic::ctlz: { 6692 SDValue Arg = getValue(I.getArgOperand(0)); 6693 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6694 EVT Ty = Arg.getValueType(); 6695 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6696 sdl, Ty, Arg)); 6697 return; 6698 } 6699 case Intrinsic::ctpop: { 6700 SDValue Arg = getValue(I.getArgOperand(0)); 6701 EVT Ty = Arg.getValueType(); 6702 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6703 return; 6704 } 6705 case Intrinsic::fshl: 6706 case Intrinsic::fshr: { 6707 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6708 SDValue X = getValue(I.getArgOperand(0)); 6709 SDValue Y = getValue(I.getArgOperand(1)); 6710 SDValue Z = getValue(I.getArgOperand(2)); 6711 EVT VT = X.getValueType(); 6712 6713 if (X == Y) { 6714 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6715 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6716 } else { 6717 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6718 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6719 } 6720 return; 6721 } 6722 case Intrinsic::sadd_sat: { 6723 SDValue Op1 = getValue(I.getArgOperand(0)); 6724 SDValue Op2 = getValue(I.getArgOperand(1)); 6725 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6726 return; 6727 } 6728 case Intrinsic::uadd_sat: { 6729 SDValue Op1 = getValue(I.getArgOperand(0)); 6730 SDValue Op2 = getValue(I.getArgOperand(1)); 6731 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6732 return; 6733 } 6734 case Intrinsic::ssub_sat: { 6735 SDValue Op1 = getValue(I.getArgOperand(0)); 6736 SDValue Op2 = getValue(I.getArgOperand(1)); 6737 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6738 return; 6739 } 6740 case Intrinsic::usub_sat: { 6741 SDValue Op1 = getValue(I.getArgOperand(0)); 6742 SDValue Op2 = getValue(I.getArgOperand(1)); 6743 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6744 return; 6745 } 6746 case Intrinsic::sshl_sat: { 6747 SDValue Op1 = getValue(I.getArgOperand(0)); 6748 SDValue Op2 = getValue(I.getArgOperand(1)); 6749 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6750 return; 6751 } 6752 case Intrinsic::ushl_sat: { 6753 SDValue Op1 = getValue(I.getArgOperand(0)); 6754 SDValue Op2 = getValue(I.getArgOperand(1)); 6755 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6756 return; 6757 } 6758 case Intrinsic::smul_fix: 6759 case Intrinsic::umul_fix: 6760 case Intrinsic::smul_fix_sat: 6761 case Intrinsic::umul_fix_sat: { 6762 SDValue Op1 = getValue(I.getArgOperand(0)); 6763 SDValue Op2 = getValue(I.getArgOperand(1)); 6764 SDValue Op3 = getValue(I.getArgOperand(2)); 6765 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6766 Op1.getValueType(), Op1, Op2, Op3)); 6767 return; 6768 } 6769 case Intrinsic::sdiv_fix: 6770 case Intrinsic::udiv_fix: 6771 case Intrinsic::sdiv_fix_sat: 6772 case Intrinsic::udiv_fix_sat: { 6773 SDValue Op1 = getValue(I.getArgOperand(0)); 6774 SDValue Op2 = getValue(I.getArgOperand(1)); 6775 SDValue Op3 = getValue(I.getArgOperand(2)); 6776 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6777 Op1, Op2, Op3, DAG, TLI)); 6778 return; 6779 } 6780 case Intrinsic::smax: { 6781 SDValue Op1 = getValue(I.getArgOperand(0)); 6782 SDValue Op2 = getValue(I.getArgOperand(1)); 6783 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6784 return; 6785 } 6786 case Intrinsic::smin: { 6787 SDValue Op1 = getValue(I.getArgOperand(0)); 6788 SDValue Op2 = getValue(I.getArgOperand(1)); 6789 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6790 return; 6791 } 6792 case Intrinsic::umax: { 6793 SDValue Op1 = getValue(I.getArgOperand(0)); 6794 SDValue Op2 = getValue(I.getArgOperand(1)); 6795 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6796 return; 6797 } 6798 case Intrinsic::umin: { 6799 SDValue Op1 = getValue(I.getArgOperand(0)); 6800 SDValue Op2 = getValue(I.getArgOperand(1)); 6801 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6802 return; 6803 } 6804 case Intrinsic::abs: { 6805 // TODO: Preserve "int min is poison" arg in SDAG? 6806 SDValue Op1 = getValue(I.getArgOperand(0)); 6807 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6808 return; 6809 } 6810 case Intrinsic::stacksave: { 6811 SDValue Op = getRoot(); 6812 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6813 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6814 setValue(&I, Res); 6815 DAG.setRoot(Res.getValue(1)); 6816 return; 6817 } 6818 case Intrinsic::stackrestore: 6819 Res = getValue(I.getArgOperand(0)); 6820 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6821 return; 6822 case Intrinsic::get_dynamic_area_offset: { 6823 SDValue Op = getRoot(); 6824 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6825 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6826 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6827 // target. 6828 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 6829 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6830 " intrinsic!"); 6831 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6832 Op); 6833 DAG.setRoot(Op); 6834 setValue(&I, Res); 6835 return; 6836 } 6837 case Intrinsic::stackguard: { 6838 MachineFunction &MF = DAG.getMachineFunction(); 6839 const Module &M = *MF.getFunction().getParent(); 6840 SDValue Chain = getRoot(); 6841 if (TLI.useLoadStackGuardNode()) { 6842 Res = getLoadStackGuard(DAG, sdl, Chain); 6843 } else { 6844 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6845 const Value *Global = TLI.getSDagStackGuard(M); 6846 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType()); 6847 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6848 MachinePointerInfo(Global, 0), Align, 6849 MachineMemOperand::MOVolatile); 6850 } 6851 if (TLI.useStackGuardXorFP()) 6852 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6853 DAG.setRoot(Chain); 6854 setValue(&I, Res); 6855 return; 6856 } 6857 case Intrinsic::stackprotector: { 6858 // Emit code into the DAG to store the stack guard onto the stack. 6859 MachineFunction &MF = DAG.getMachineFunction(); 6860 MachineFrameInfo &MFI = MF.getFrameInfo(); 6861 SDValue Src, Chain = getRoot(); 6862 6863 if (TLI.useLoadStackGuardNode()) 6864 Src = getLoadStackGuard(DAG, sdl, Chain); 6865 else 6866 Src = getValue(I.getArgOperand(0)); // The guard's value. 6867 6868 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6869 6870 int FI = FuncInfo.StaticAllocaMap[Slot]; 6871 MFI.setStackProtectorIndex(FI); 6872 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6873 6874 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6875 6876 // Store the stack protector onto the stack. 6877 Res = DAG.getStore( 6878 Chain, sdl, Src, FIN, 6879 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 6880 MaybeAlign(), MachineMemOperand::MOVolatile); 6881 setValue(&I, Res); 6882 DAG.setRoot(Res); 6883 return; 6884 } 6885 case Intrinsic::objectsize: 6886 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6887 6888 case Intrinsic::is_constant: 6889 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6890 6891 case Intrinsic::annotation: 6892 case Intrinsic::ptr_annotation: 6893 case Intrinsic::launder_invariant_group: 6894 case Intrinsic::strip_invariant_group: 6895 // Drop the intrinsic, but forward the value 6896 setValue(&I, getValue(I.getOperand(0))); 6897 return; 6898 6899 case Intrinsic::assume: 6900 case Intrinsic::experimental_noalias_scope_decl: 6901 case Intrinsic::var_annotation: 6902 case Intrinsic::sideeffect: 6903 // Discard annotate attributes, noalias scope declarations, assumptions, and 6904 // artificial side-effects. 6905 return; 6906 6907 case Intrinsic::codeview_annotation: { 6908 // Emit a label associated with this metadata. 6909 MachineFunction &MF = DAG.getMachineFunction(); 6910 MCSymbol *Label = 6911 MF.getMMI().getContext().createTempSymbol("annotation", true); 6912 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6913 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6914 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6915 DAG.setRoot(Res); 6916 return; 6917 } 6918 6919 case Intrinsic::init_trampoline: { 6920 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6921 6922 SDValue Ops[6]; 6923 Ops[0] = getRoot(); 6924 Ops[1] = getValue(I.getArgOperand(0)); 6925 Ops[2] = getValue(I.getArgOperand(1)); 6926 Ops[3] = getValue(I.getArgOperand(2)); 6927 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6928 Ops[5] = DAG.getSrcValue(F); 6929 6930 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6931 6932 DAG.setRoot(Res); 6933 return; 6934 } 6935 case Intrinsic::adjust_trampoline: 6936 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6937 TLI.getPointerTy(DAG.getDataLayout()), 6938 getValue(I.getArgOperand(0)))); 6939 return; 6940 case Intrinsic::gcroot: { 6941 assert(DAG.getMachineFunction().getFunction().hasGC() && 6942 "only valid in functions with gc specified, enforced by Verifier"); 6943 assert(GFI && "implied by previous"); 6944 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6945 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6946 6947 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6948 GFI->addStackRoot(FI->getIndex(), TypeMap); 6949 return; 6950 } 6951 case Intrinsic::gcread: 6952 case Intrinsic::gcwrite: 6953 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6954 case Intrinsic::get_rounding: 6955 Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot()); 6956 setValue(&I, Res); 6957 DAG.setRoot(Res.getValue(1)); 6958 return; 6959 6960 case Intrinsic::expect: 6961 // Just replace __builtin_expect(exp, c) with EXP. 6962 setValue(&I, getValue(I.getArgOperand(0))); 6963 return; 6964 6965 case Intrinsic::ubsantrap: 6966 case Intrinsic::debugtrap: 6967 case Intrinsic::trap: { 6968 StringRef TrapFuncName = 6969 I.getAttributes().getFnAttr("trap-func-name").getValueAsString(); 6970 if (TrapFuncName.empty()) { 6971 switch (Intrinsic) { 6972 case Intrinsic::trap: 6973 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 6974 break; 6975 case Intrinsic::debugtrap: 6976 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 6977 break; 6978 case Intrinsic::ubsantrap: 6979 DAG.setRoot(DAG.getNode( 6980 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 6981 DAG.getTargetConstant( 6982 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 6983 MVT::i32))); 6984 break; 6985 default: llvm_unreachable("unknown trap intrinsic"); 6986 } 6987 return; 6988 } 6989 TargetLowering::ArgListTy Args; 6990 if (Intrinsic == Intrinsic::ubsantrap) { 6991 Args.push_back(TargetLoweringBase::ArgListEntry()); 6992 Args[0].Val = I.getArgOperand(0); 6993 Args[0].Node = getValue(Args[0].Val); 6994 Args[0].Ty = Args[0].Val->getType(); 6995 } 6996 6997 TargetLowering::CallLoweringInfo CLI(DAG); 6998 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6999 CallingConv::C, I.getType(), 7000 DAG.getExternalSymbol(TrapFuncName.data(), 7001 TLI.getPointerTy(DAG.getDataLayout())), 7002 std::move(Args)); 7003 7004 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7005 DAG.setRoot(Result.second); 7006 return; 7007 } 7008 7009 case Intrinsic::uadd_with_overflow: 7010 case Intrinsic::sadd_with_overflow: 7011 case Intrinsic::usub_with_overflow: 7012 case Intrinsic::ssub_with_overflow: 7013 case Intrinsic::umul_with_overflow: 7014 case Intrinsic::smul_with_overflow: { 7015 ISD::NodeType Op; 7016 switch (Intrinsic) { 7017 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7018 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 7019 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 7020 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 7021 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 7022 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 7023 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 7024 } 7025 SDValue Op1 = getValue(I.getArgOperand(0)); 7026 SDValue Op2 = getValue(I.getArgOperand(1)); 7027 7028 EVT ResultVT = Op1.getValueType(); 7029 EVT OverflowVT = MVT::i1; 7030 if (ResultVT.isVector()) 7031 OverflowVT = EVT::getVectorVT( 7032 *Context, OverflowVT, ResultVT.getVectorElementCount()); 7033 7034 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 7035 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 7036 return; 7037 } 7038 case Intrinsic::prefetch: { 7039 SDValue Ops[5]; 7040 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 7041 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 7042 Ops[0] = DAG.getRoot(); 7043 Ops[1] = getValue(I.getArgOperand(0)); 7044 Ops[2] = getValue(I.getArgOperand(1)); 7045 Ops[3] = getValue(I.getArgOperand(2)); 7046 Ops[4] = getValue(I.getArgOperand(3)); 7047 SDValue Result = DAG.getMemIntrinsicNode( 7048 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 7049 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 7050 /* align */ std::nullopt, Flags); 7051 7052 // Chain the prefetch in parallell with any pending loads, to stay out of 7053 // the way of later optimizations. 7054 PendingLoads.push_back(Result); 7055 Result = getRoot(); 7056 DAG.setRoot(Result); 7057 return; 7058 } 7059 case Intrinsic::lifetime_start: 7060 case Intrinsic::lifetime_end: { 7061 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 7062 // Stack coloring is not enabled in O0, discard region information. 7063 if (TM.getOptLevel() == CodeGenOpt::None) 7064 return; 7065 7066 const int64_t ObjectSize = 7067 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 7068 Value *const ObjectPtr = I.getArgOperand(1); 7069 SmallVector<const Value *, 4> Allocas; 7070 getUnderlyingObjects(ObjectPtr, Allocas); 7071 7072 for (const Value *Alloca : Allocas) { 7073 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 7074 7075 // Could not find an Alloca. 7076 if (!LifetimeObject) 7077 continue; 7078 7079 // First check that the Alloca is static, otherwise it won't have a 7080 // valid frame index. 7081 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 7082 if (SI == FuncInfo.StaticAllocaMap.end()) 7083 return; 7084 7085 const int FrameIndex = SI->second; 7086 int64_t Offset; 7087 if (GetPointerBaseWithConstantOffset( 7088 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 7089 Offset = -1; // Cannot determine offset from alloca to lifetime object. 7090 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 7091 Offset); 7092 DAG.setRoot(Res); 7093 } 7094 return; 7095 } 7096 case Intrinsic::pseudoprobe: { 7097 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 7098 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 7099 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 7100 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 7101 DAG.setRoot(Res); 7102 return; 7103 } 7104 case Intrinsic::invariant_start: 7105 // Discard region information. 7106 setValue(&I, 7107 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType()))); 7108 return; 7109 case Intrinsic::invariant_end: 7110 // Discard region information. 7111 return; 7112 case Intrinsic::clear_cache: 7113 /// FunctionName may be null. 7114 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 7115 lowerCallToExternalSymbol(I, FunctionName); 7116 return; 7117 case Intrinsic::donothing: 7118 case Intrinsic::seh_try_begin: 7119 case Intrinsic::seh_scope_begin: 7120 case Intrinsic::seh_try_end: 7121 case Intrinsic::seh_scope_end: 7122 // ignore 7123 return; 7124 case Intrinsic::experimental_stackmap: 7125 visitStackmap(I); 7126 return; 7127 case Intrinsic::experimental_patchpoint_void: 7128 case Intrinsic::experimental_patchpoint_i64: 7129 visitPatchpoint(I); 7130 return; 7131 case Intrinsic::experimental_gc_statepoint: 7132 LowerStatepoint(cast<GCStatepointInst>(I)); 7133 return; 7134 case Intrinsic::experimental_gc_result: 7135 visitGCResult(cast<GCResultInst>(I)); 7136 return; 7137 case Intrinsic::experimental_gc_relocate: 7138 visitGCRelocate(cast<GCRelocateInst>(I)); 7139 return; 7140 case Intrinsic::instrprof_cover: 7141 llvm_unreachable("instrprof failed to lower a cover"); 7142 case Intrinsic::instrprof_increment: 7143 llvm_unreachable("instrprof failed to lower an increment"); 7144 case Intrinsic::instrprof_timestamp: 7145 llvm_unreachable("instrprof failed to lower a timestamp"); 7146 case Intrinsic::instrprof_value_profile: 7147 llvm_unreachable("instrprof failed to lower a value profiling call"); 7148 case Intrinsic::localescape: { 7149 MachineFunction &MF = DAG.getMachineFunction(); 7150 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 7151 7152 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 7153 // is the same on all targets. 7154 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) { 7155 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 7156 if (isa<ConstantPointerNull>(Arg)) 7157 continue; // Skip null pointers. They represent a hole in index space. 7158 AllocaInst *Slot = cast<AllocaInst>(Arg); 7159 assert(FuncInfo.StaticAllocaMap.count(Slot) && 7160 "can only escape static allocas"); 7161 int FI = FuncInfo.StaticAllocaMap[Slot]; 7162 MCSymbol *FrameAllocSym = 7163 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7164 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 7165 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 7166 TII->get(TargetOpcode::LOCAL_ESCAPE)) 7167 .addSym(FrameAllocSym) 7168 .addFrameIndex(FI); 7169 } 7170 7171 return; 7172 } 7173 7174 case Intrinsic::localrecover: { 7175 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 7176 MachineFunction &MF = DAG.getMachineFunction(); 7177 7178 // Get the symbol that defines the frame offset. 7179 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 7180 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 7181 unsigned IdxVal = 7182 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 7183 MCSymbol *FrameAllocSym = 7184 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7185 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 7186 7187 Value *FP = I.getArgOperand(1); 7188 SDValue FPVal = getValue(FP); 7189 EVT PtrVT = FPVal.getValueType(); 7190 7191 // Create a MCSymbol for the label to avoid any target lowering 7192 // that would make this PC relative. 7193 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 7194 SDValue OffsetVal = 7195 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 7196 7197 // Add the offset to the FP. 7198 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 7199 setValue(&I, Add); 7200 7201 return; 7202 } 7203 7204 case Intrinsic::eh_exceptionpointer: 7205 case Intrinsic::eh_exceptioncode: { 7206 // Get the exception pointer vreg, copy from it, and resize it to fit. 7207 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 7208 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 7209 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 7210 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 7211 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT); 7212 if (Intrinsic == Intrinsic::eh_exceptioncode) 7213 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32); 7214 setValue(&I, N); 7215 return; 7216 } 7217 case Intrinsic::xray_customevent: { 7218 // Here we want to make sure that the intrinsic behaves as if it has a 7219 // specific calling convention. 7220 const auto &Triple = DAG.getTarget().getTargetTriple(); 7221 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64) 7222 return; 7223 7224 SmallVector<SDValue, 8> Ops; 7225 7226 // We want to say that we always want the arguments in registers. 7227 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 7228 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 7229 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7230 SDValue Chain = getRoot(); 7231 Ops.push_back(LogEntryVal); 7232 Ops.push_back(StrSizeVal); 7233 Ops.push_back(Chain); 7234 7235 // We need to enforce the calling convention for the callsite, so that 7236 // argument ordering is enforced correctly, and that register allocation can 7237 // see that some registers may be assumed clobbered and have to preserve 7238 // them across calls to the intrinsic. 7239 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 7240 sdl, NodeTys, Ops); 7241 SDValue patchableNode = SDValue(MN, 0); 7242 DAG.setRoot(patchableNode); 7243 setValue(&I, patchableNode); 7244 return; 7245 } 7246 case Intrinsic::xray_typedevent: { 7247 // Here we want to make sure that the intrinsic behaves as if it has a 7248 // specific calling convention. 7249 const auto &Triple = DAG.getTarget().getTargetTriple(); 7250 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64) 7251 return; 7252 7253 SmallVector<SDValue, 8> Ops; 7254 7255 // We want to say that we always want the arguments in registers. 7256 // It's unclear to me how manipulating the selection DAG here forces callers 7257 // to provide arguments in registers instead of on the stack. 7258 SDValue LogTypeId = getValue(I.getArgOperand(0)); 7259 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 7260 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 7261 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7262 SDValue Chain = getRoot(); 7263 Ops.push_back(LogTypeId); 7264 Ops.push_back(LogEntryVal); 7265 Ops.push_back(StrSizeVal); 7266 Ops.push_back(Chain); 7267 7268 // We need to enforce the calling convention for the callsite, so that 7269 // argument ordering is enforced correctly, and that register allocation can 7270 // see that some registers may be assumed clobbered and have to preserve 7271 // them across calls to the intrinsic. 7272 MachineSDNode *MN = DAG.getMachineNode( 7273 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops); 7274 SDValue patchableNode = SDValue(MN, 0); 7275 DAG.setRoot(patchableNode); 7276 setValue(&I, patchableNode); 7277 return; 7278 } 7279 case Intrinsic::experimental_deoptimize: 7280 LowerDeoptimizeCall(&I); 7281 return; 7282 case Intrinsic::experimental_stepvector: 7283 visitStepVector(I); 7284 return; 7285 case Intrinsic::vector_reduce_fadd: 7286 case Intrinsic::vector_reduce_fmul: 7287 case Intrinsic::vector_reduce_add: 7288 case Intrinsic::vector_reduce_mul: 7289 case Intrinsic::vector_reduce_and: 7290 case Intrinsic::vector_reduce_or: 7291 case Intrinsic::vector_reduce_xor: 7292 case Intrinsic::vector_reduce_smax: 7293 case Intrinsic::vector_reduce_smin: 7294 case Intrinsic::vector_reduce_umax: 7295 case Intrinsic::vector_reduce_umin: 7296 case Intrinsic::vector_reduce_fmax: 7297 case Intrinsic::vector_reduce_fmin: 7298 case Intrinsic::vector_reduce_fmaximum: 7299 case Intrinsic::vector_reduce_fminimum: 7300 visitVectorReduce(I, Intrinsic); 7301 return; 7302 7303 case Intrinsic::icall_branch_funnel: { 7304 SmallVector<SDValue, 16> Ops; 7305 Ops.push_back(getValue(I.getArgOperand(0))); 7306 7307 int64_t Offset; 7308 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7309 I.getArgOperand(1), Offset, DAG.getDataLayout())); 7310 if (!Base) 7311 report_fatal_error( 7312 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7313 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0)); 7314 7315 struct BranchFunnelTarget { 7316 int64_t Offset; 7317 SDValue Target; 7318 }; 7319 SmallVector<BranchFunnelTarget, 8> Targets; 7320 7321 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) { 7322 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7323 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7324 if (ElemBase != Base) 7325 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7326 "to the same GlobalValue"); 7327 7328 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7329 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7330 if (!GA) 7331 report_fatal_error( 7332 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7333 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7334 GA->getGlobal(), sdl, Val.getValueType(), 7335 GA->getOffset())}); 7336 } 7337 llvm::sort(Targets, 7338 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7339 return T1.Offset < T2.Offset; 7340 }); 7341 7342 for (auto &T : Targets) { 7343 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32)); 7344 Ops.push_back(T.Target); 7345 } 7346 7347 Ops.push_back(DAG.getRoot()); // Chain 7348 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl, 7349 MVT::Other, Ops), 7350 0); 7351 DAG.setRoot(N); 7352 setValue(&I, N); 7353 HasTailCall = true; 7354 return; 7355 } 7356 7357 case Intrinsic::wasm_landingpad_index: 7358 // Information this intrinsic contained has been transferred to 7359 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7360 // delete it now. 7361 return; 7362 7363 case Intrinsic::aarch64_settag: 7364 case Intrinsic::aarch64_settag_zero: { 7365 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7366 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7367 SDValue Val = TSI.EmitTargetCodeForSetTag( 7368 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)), 7369 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7370 ZeroMemory); 7371 DAG.setRoot(Val); 7372 setValue(&I, Val); 7373 return; 7374 } 7375 case Intrinsic::ptrmask: { 7376 SDValue Ptr = getValue(I.getOperand(0)); 7377 SDValue Const = getValue(I.getOperand(1)); 7378 7379 EVT PtrVT = Ptr.getValueType(); 7380 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, 7381 DAG.getZExtOrTrunc(Const, sdl, PtrVT))); 7382 return; 7383 } 7384 case Intrinsic::threadlocal_address: { 7385 setValue(&I, getValue(I.getOperand(0))); 7386 return; 7387 } 7388 case Intrinsic::get_active_lane_mask: { 7389 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7390 SDValue Index = getValue(I.getOperand(0)); 7391 EVT ElementVT = Index.getValueType(); 7392 7393 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) { 7394 visitTargetIntrinsic(I, Intrinsic); 7395 return; 7396 } 7397 7398 SDValue TripCount = getValue(I.getOperand(1)); 7399 EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT, 7400 CCVT.getVectorElementCount()); 7401 7402 SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index); 7403 SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount); 7404 SDValue VectorStep = DAG.getStepVector(sdl, VecTy); 7405 SDValue VectorInduction = DAG.getNode( 7406 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep); 7407 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction, 7408 VectorTripCount, ISD::CondCode::SETULT); 7409 setValue(&I, SetCC); 7410 return; 7411 } 7412 case Intrinsic::experimental_get_vector_length: { 7413 assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 && 7414 "Expected positive VF"); 7415 unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue(); 7416 bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne(); 7417 7418 SDValue Count = getValue(I.getOperand(0)); 7419 EVT CountVT = Count.getValueType(); 7420 7421 if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) { 7422 visitTargetIntrinsic(I, Intrinsic); 7423 return; 7424 } 7425 7426 // Expand to a umin between the trip count and the maximum elements the type 7427 // can hold. 7428 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7429 7430 // Extend the trip count to at least the result VT. 7431 if (CountVT.bitsLT(VT)) { 7432 Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count); 7433 CountVT = VT; 7434 } 7435 7436 SDValue MaxEVL = DAG.getElementCount(sdl, CountVT, 7437 ElementCount::get(VF, IsScalable)); 7438 7439 SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL); 7440 // Clip to the result type if needed. 7441 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin); 7442 7443 setValue(&I, Trunc); 7444 return; 7445 } 7446 case Intrinsic::vector_insert: { 7447 SDValue Vec = getValue(I.getOperand(0)); 7448 SDValue SubVec = getValue(I.getOperand(1)); 7449 SDValue Index = getValue(I.getOperand(2)); 7450 7451 // The intrinsic's index type is i64, but the SDNode requires an index type 7452 // suitable for the target. Convert the index as required. 7453 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7454 if (Index.getValueType() != VectorIdxTy) 7455 Index = DAG.getVectorIdxConstant( 7456 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7457 7458 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7459 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec, 7460 Index)); 7461 return; 7462 } 7463 case Intrinsic::vector_extract: { 7464 SDValue Vec = getValue(I.getOperand(0)); 7465 SDValue Index = getValue(I.getOperand(1)); 7466 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7467 7468 // The intrinsic's index type is i64, but the SDNode requires an index type 7469 // suitable for the target. Convert the index as required. 7470 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7471 if (Index.getValueType() != VectorIdxTy) 7472 Index = DAG.getVectorIdxConstant( 7473 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7474 7475 setValue(&I, 7476 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index)); 7477 return; 7478 } 7479 case Intrinsic::experimental_vector_reverse: 7480 visitVectorReverse(I); 7481 return; 7482 case Intrinsic::experimental_vector_splice: 7483 visitVectorSplice(I); 7484 return; 7485 case Intrinsic::callbr_landingpad: 7486 visitCallBrLandingPad(I); 7487 return; 7488 case Intrinsic::experimental_vector_interleave2: 7489 visitVectorInterleave(I); 7490 return; 7491 case Intrinsic::experimental_vector_deinterleave2: 7492 visitVectorDeinterleave(I); 7493 return; 7494 } 7495 } 7496 7497 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7498 const ConstrainedFPIntrinsic &FPI) { 7499 SDLoc sdl = getCurSDLoc(); 7500 7501 // We do not need to serialize constrained FP intrinsics against 7502 // each other or against (nonvolatile) loads, so they can be 7503 // chained like loads. 7504 SDValue Chain = DAG.getRoot(); 7505 SmallVector<SDValue, 4> Opers; 7506 Opers.push_back(Chain); 7507 if (FPI.isUnaryOp()) { 7508 Opers.push_back(getValue(FPI.getArgOperand(0))); 7509 } else if (FPI.isTernaryOp()) { 7510 Opers.push_back(getValue(FPI.getArgOperand(0))); 7511 Opers.push_back(getValue(FPI.getArgOperand(1))); 7512 Opers.push_back(getValue(FPI.getArgOperand(2))); 7513 } else { 7514 Opers.push_back(getValue(FPI.getArgOperand(0))); 7515 Opers.push_back(getValue(FPI.getArgOperand(1))); 7516 } 7517 7518 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7519 assert(Result.getNode()->getNumValues() == 2); 7520 7521 // Push node to the appropriate list so that future instructions can be 7522 // chained up correctly. 7523 SDValue OutChain = Result.getValue(1); 7524 switch (EB) { 7525 case fp::ExceptionBehavior::ebIgnore: 7526 // The only reason why ebIgnore nodes still need to be chained is that 7527 // they might depend on the current rounding mode, and therefore must 7528 // not be moved across instruction that may change that mode. 7529 [[fallthrough]]; 7530 case fp::ExceptionBehavior::ebMayTrap: 7531 // These must not be moved across calls or instructions that may change 7532 // floating-point exception masks. 7533 PendingConstrainedFP.push_back(OutChain); 7534 break; 7535 case fp::ExceptionBehavior::ebStrict: 7536 // These must not be moved across calls or instructions that may change 7537 // floating-point exception masks or read floating-point exception flags. 7538 // In addition, they cannot be optimized out even if unused. 7539 PendingConstrainedFPStrict.push_back(OutChain); 7540 break; 7541 } 7542 }; 7543 7544 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7545 EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType()); 7546 SDVTList VTs = DAG.getVTList(VT, MVT::Other); 7547 fp::ExceptionBehavior EB = *FPI.getExceptionBehavior(); 7548 7549 SDNodeFlags Flags; 7550 if (EB == fp::ExceptionBehavior::ebIgnore) 7551 Flags.setNoFPExcept(true); 7552 7553 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7554 Flags.copyFMF(*FPOp); 7555 7556 unsigned Opcode; 7557 switch (FPI.getIntrinsicID()) { 7558 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7559 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7560 case Intrinsic::INTRINSIC: \ 7561 Opcode = ISD::STRICT_##DAGN; \ 7562 break; 7563 #include "llvm/IR/ConstrainedOps.def" 7564 case Intrinsic::experimental_constrained_fmuladd: { 7565 Opcode = ISD::STRICT_FMA; 7566 // Break fmuladd into fmul and fadd. 7567 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7568 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 7569 Opers.pop_back(); 7570 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7571 pushOutChain(Mul, EB); 7572 Opcode = ISD::STRICT_FADD; 7573 Opers.clear(); 7574 Opers.push_back(Mul.getValue(1)); 7575 Opers.push_back(Mul.getValue(0)); 7576 Opers.push_back(getValue(FPI.getArgOperand(2))); 7577 } 7578 break; 7579 } 7580 } 7581 7582 // A few strict DAG nodes carry additional operands that are not 7583 // set up by the default code above. 7584 switch (Opcode) { 7585 default: break; 7586 case ISD::STRICT_FP_ROUND: 7587 Opers.push_back( 7588 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7589 break; 7590 case ISD::STRICT_FSETCC: 7591 case ISD::STRICT_FSETCCS: { 7592 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7593 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 7594 if (TM.Options.NoNaNsFPMath) 7595 Condition = getFCmpCodeWithoutNaN(Condition); 7596 Opers.push_back(DAG.getCondCode(Condition)); 7597 break; 7598 } 7599 } 7600 7601 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7602 pushOutChain(Result, EB); 7603 7604 SDValue FPResult = Result.getValue(0); 7605 setValue(&FPI, FPResult); 7606 } 7607 7608 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 7609 std::optional<unsigned> ResOPC; 7610 switch (VPIntrin.getIntrinsicID()) { 7611 case Intrinsic::vp_ctlz: { 7612 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 7613 ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ; 7614 break; 7615 } 7616 case Intrinsic::vp_cttz: { 7617 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 7618 ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ; 7619 break; 7620 } 7621 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \ 7622 case Intrinsic::VPID: \ 7623 ResOPC = ISD::VPSD; \ 7624 break; 7625 #include "llvm/IR/VPIntrinsics.def" 7626 } 7627 7628 if (!ResOPC) 7629 llvm_unreachable( 7630 "Inconsistency: no SDNode available for this VPIntrinsic!"); 7631 7632 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD || 7633 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) { 7634 if (VPIntrin.getFastMathFlags().allowReassoc()) 7635 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD 7636 : ISD::VP_REDUCE_FMUL; 7637 } 7638 7639 return *ResOPC; 7640 } 7641 7642 void SelectionDAGBuilder::visitVPLoad( 7643 const VPIntrinsic &VPIntrin, EVT VT, 7644 const SmallVectorImpl<SDValue> &OpValues) { 7645 SDLoc DL = getCurSDLoc(); 7646 Value *PtrOperand = VPIntrin.getArgOperand(0); 7647 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7648 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7649 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7650 SDValue LD; 7651 // Do not serialize variable-length loads of constant memory with 7652 // anything. 7653 if (!Alignment) 7654 Alignment = DAG.getEVTAlign(VT); 7655 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7656 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7657 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7658 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7659 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7660 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7661 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2], 7662 MMO, false /*IsExpanding */); 7663 if (AddToChain) 7664 PendingLoads.push_back(LD.getValue(1)); 7665 setValue(&VPIntrin, LD); 7666 } 7667 7668 void SelectionDAGBuilder::visitVPGather( 7669 const VPIntrinsic &VPIntrin, EVT VT, 7670 const SmallVectorImpl<SDValue> &OpValues) { 7671 SDLoc DL = getCurSDLoc(); 7672 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7673 Value *PtrOperand = VPIntrin.getArgOperand(0); 7674 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7675 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7676 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7677 SDValue LD; 7678 if (!Alignment) 7679 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7680 unsigned AS = 7681 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7682 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7683 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 7684 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7685 SDValue Base, Index, Scale; 7686 ISD::MemIndexType IndexType; 7687 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7688 this, VPIntrin.getParent(), 7689 VT.getScalarStoreSize()); 7690 if (!UniformBase) { 7691 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7692 Index = getValue(PtrOperand); 7693 IndexType = ISD::SIGNED_SCALED; 7694 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7695 } 7696 EVT IdxVT = Index.getValueType(); 7697 EVT EltTy = IdxVT.getVectorElementType(); 7698 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7699 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7700 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7701 } 7702 LD = DAG.getGatherVP( 7703 DAG.getVTList(VT, MVT::Other), VT, DL, 7704 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO, 7705 IndexType); 7706 PendingLoads.push_back(LD.getValue(1)); 7707 setValue(&VPIntrin, LD); 7708 } 7709 7710 void SelectionDAGBuilder::visitVPStore( 7711 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 7712 SDLoc DL = getCurSDLoc(); 7713 Value *PtrOperand = VPIntrin.getArgOperand(1); 7714 EVT VT = OpValues[0].getValueType(); 7715 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7716 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7717 SDValue ST; 7718 if (!Alignment) 7719 Alignment = DAG.getEVTAlign(VT); 7720 SDValue Ptr = OpValues[1]; 7721 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 7722 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7723 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7724 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7725 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset, 7726 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED, 7727 /* IsTruncating */ false, /*IsCompressing*/ false); 7728 DAG.setRoot(ST); 7729 setValue(&VPIntrin, ST); 7730 } 7731 7732 void SelectionDAGBuilder::visitVPScatter( 7733 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 7734 SDLoc DL = getCurSDLoc(); 7735 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7736 Value *PtrOperand = VPIntrin.getArgOperand(1); 7737 EVT VT = OpValues[0].getValueType(); 7738 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7739 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7740 SDValue ST; 7741 if (!Alignment) 7742 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7743 unsigned AS = 7744 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7745 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7746 MachinePointerInfo(AS), MachineMemOperand::MOStore, 7747 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7748 SDValue Base, Index, Scale; 7749 ISD::MemIndexType IndexType; 7750 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7751 this, VPIntrin.getParent(), 7752 VT.getScalarStoreSize()); 7753 if (!UniformBase) { 7754 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7755 Index = getValue(PtrOperand); 7756 IndexType = ISD::SIGNED_SCALED; 7757 Scale = 7758 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7759 } 7760 EVT IdxVT = Index.getValueType(); 7761 EVT EltTy = IdxVT.getVectorElementType(); 7762 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7763 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7764 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7765 } 7766 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL, 7767 {getMemoryRoot(), OpValues[0], Base, Index, Scale, 7768 OpValues[2], OpValues[3]}, 7769 MMO, IndexType); 7770 DAG.setRoot(ST); 7771 setValue(&VPIntrin, ST); 7772 } 7773 7774 void SelectionDAGBuilder::visitVPStridedLoad( 7775 const VPIntrinsic &VPIntrin, EVT VT, 7776 const SmallVectorImpl<SDValue> &OpValues) { 7777 SDLoc DL = getCurSDLoc(); 7778 Value *PtrOperand = VPIntrin.getArgOperand(0); 7779 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7780 if (!Alignment) 7781 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7782 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7783 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7784 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7785 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7786 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7787 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7788 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7789 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7790 7791 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], 7792 OpValues[2], OpValues[3], MMO, 7793 false /*IsExpanding*/); 7794 7795 if (AddToChain) 7796 PendingLoads.push_back(LD.getValue(1)); 7797 setValue(&VPIntrin, LD); 7798 } 7799 7800 void SelectionDAGBuilder::visitVPStridedStore( 7801 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 7802 SDLoc DL = getCurSDLoc(); 7803 Value *PtrOperand = VPIntrin.getArgOperand(1); 7804 EVT VT = OpValues[0].getValueType(); 7805 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7806 if (!Alignment) 7807 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7808 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7809 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7810 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7811 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7812 7813 SDValue ST = DAG.getStridedStoreVP( 7814 getMemoryRoot(), DL, OpValues[0], OpValues[1], 7815 DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3], 7816 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false, 7817 /*IsCompressing*/ false); 7818 7819 DAG.setRoot(ST); 7820 setValue(&VPIntrin, ST); 7821 } 7822 7823 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) { 7824 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7825 SDLoc DL = getCurSDLoc(); 7826 7827 ISD::CondCode Condition; 7828 CmpInst::Predicate CondCode = VPIntrin.getPredicate(); 7829 bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy(); 7830 if (IsFP) { 7831 // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan) 7832 // flags, but calls that don't return floating-point types can't be 7833 // FPMathOperators, like vp.fcmp. This affects constrained fcmp too. 7834 Condition = getFCmpCondCode(CondCode); 7835 if (TM.Options.NoNaNsFPMath) 7836 Condition = getFCmpCodeWithoutNaN(Condition); 7837 } else { 7838 Condition = getICmpCondCode(CondCode); 7839 } 7840 7841 SDValue Op1 = getValue(VPIntrin.getOperand(0)); 7842 SDValue Op2 = getValue(VPIntrin.getOperand(1)); 7843 // #2 is the condition code 7844 SDValue MaskOp = getValue(VPIntrin.getOperand(3)); 7845 SDValue EVL = getValue(VPIntrin.getOperand(4)); 7846 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7847 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7848 "Unexpected target EVL type"); 7849 EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL); 7850 7851 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7852 VPIntrin.getType()); 7853 setValue(&VPIntrin, 7854 DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL)); 7855 } 7856 7857 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 7858 const VPIntrinsic &VPIntrin) { 7859 SDLoc DL = getCurSDLoc(); 7860 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 7861 7862 auto IID = VPIntrin.getIntrinsicID(); 7863 7864 if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin)) 7865 return visitVPCmp(*CmpI); 7866 7867 SmallVector<EVT, 4> ValueVTs; 7868 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7869 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 7870 SDVTList VTs = DAG.getVTList(ValueVTs); 7871 7872 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID); 7873 7874 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7875 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7876 "Unexpected target EVL type"); 7877 7878 // Request operands. 7879 SmallVector<SDValue, 7> OpValues; 7880 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) { 7881 auto Op = getValue(VPIntrin.getArgOperand(I)); 7882 if (I == EVLParamPos) 7883 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op); 7884 OpValues.push_back(Op); 7885 } 7886 7887 switch (Opcode) { 7888 default: { 7889 SDNodeFlags SDFlags; 7890 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 7891 SDFlags.copyFMF(*FPMO); 7892 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags); 7893 setValue(&VPIntrin, Result); 7894 break; 7895 } 7896 case ISD::VP_LOAD: 7897 visitVPLoad(VPIntrin, ValueVTs[0], OpValues); 7898 break; 7899 case ISD::VP_GATHER: 7900 visitVPGather(VPIntrin, ValueVTs[0], OpValues); 7901 break; 7902 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: 7903 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues); 7904 break; 7905 case ISD::VP_STORE: 7906 visitVPStore(VPIntrin, OpValues); 7907 break; 7908 case ISD::VP_SCATTER: 7909 visitVPScatter(VPIntrin, OpValues); 7910 break; 7911 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: 7912 visitVPStridedStore(VPIntrin, OpValues); 7913 break; 7914 case ISD::VP_FMULADD: { 7915 assert(OpValues.size() == 5 && "Unexpected number of operands"); 7916 SDNodeFlags SDFlags; 7917 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 7918 SDFlags.copyFMF(*FPMO); 7919 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 7920 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) { 7921 setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags)); 7922 } else { 7923 SDValue Mul = DAG.getNode( 7924 ISD::VP_FMUL, DL, VTs, 7925 {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags); 7926 SDValue Add = 7927 DAG.getNode(ISD::VP_FADD, DL, VTs, 7928 {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags); 7929 setValue(&VPIntrin, Add); 7930 } 7931 break; 7932 } 7933 case ISD::VP_INTTOPTR: { 7934 SDValue N = OpValues[0]; 7935 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType()); 7936 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType()); 7937 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 7938 OpValues[2]); 7939 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 7940 OpValues[2]); 7941 setValue(&VPIntrin, N); 7942 break; 7943 } 7944 case ISD::VP_PTRTOINT: { 7945 SDValue N = OpValues[0]; 7946 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7947 VPIntrin.getType()); 7948 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), 7949 VPIntrin.getOperand(0)->getType()); 7950 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 7951 OpValues[2]); 7952 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 7953 OpValues[2]); 7954 setValue(&VPIntrin, N); 7955 break; 7956 } 7957 case ISD::VP_ABS: 7958 case ISD::VP_CTLZ: 7959 case ISD::VP_CTLZ_ZERO_UNDEF: 7960 case ISD::VP_CTTZ: 7961 case ISD::VP_CTTZ_ZERO_UNDEF: { 7962 SDValue Result = 7963 DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]}); 7964 setValue(&VPIntrin, Result); 7965 break; 7966 } 7967 } 7968 } 7969 7970 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 7971 const BasicBlock *EHPadBB, 7972 MCSymbol *&BeginLabel) { 7973 MachineFunction &MF = DAG.getMachineFunction(); 7974 MachineModuleInfo &MMI = MF.getMMI(); 7975 7976 // Insert a label before the invoke call to mark the try range. This can be 7977 // used to detect deletion of the invoke via the MachineModuleInfo. 7978 BeginLabel = MMI.getContext().createTempSymbol(); 7979 7980 // For SjLj, keep track of which landing pads go with which invokes 7981 // so as to maintain the ordering of pads in the LSDA. 7982 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7983 if (CallSiteIndex) { 7984 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7985 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7986 7987 // Now that the call site is handled, stop tracking it. 7988 MMI.setCurrentCallSite(0); 7989 } 7990 7991 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 7992 } 7993 7994 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 7995 const BasicBlock *EHPadBB, 7996 MCSymbol *BeginLabel) { 7997 assert(BeginLabel && "BeginLabel should've been set"); 7998 7999 MachineFunction &MF = DAG.getMachineFunction(); 8000 MachineModuleInfo &MMI = MF.getMMI(); 8001 8002 // Insert a label at the end of the invoke call to mark the try range. This 8003 // can be used to detect deletion of the invoke via the MachineModuleInfo. 8004 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 8005 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 8006 8007 // Inform MachineModuleInfo of range. 8008 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 8009 // There is a platform (e.g. wasm) that uses funclet style IR but does not 8010 // actually use outlined funclets and their LSDA info style. 8011 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 8012 assert(II && "II should've been set"); 8013 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 8014 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 8015 } else if (!isScopedEHPersonality(Pers)) { 8016 assert(EHPadBB); 8017 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 8018 } 8019 8020 return Chain; 8021 } 8022 8023 std::pair<SDValue, SDValue> 8024 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 8025 const BasicBlock *EHPadBB) { 8026 MCSymbol *BeginLabel = nullptr; 8027 8028 if (EHPadBB) { 8029 // Both PendingLoads and PendingExports must be flushed here; 8030 // this call might not return. 8031 (void)getRoot(); 8032 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 8033 CLI.setChain(getRoot()); 8034 } 8035 8036 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8037 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 8038 8039 assert((CLI.IsTailCall || Result.second.getNode()) && 8040 "Non-null chain expected with non-tail call!"); 8041 assert((Result.second.getNode() || !Result.first.getNode()) && 8042 "Null value expected with tail call!"); 8043 8044 if (!Result.second.getNode()) { 8045 // As a special case, a null chain means that a tail call has been emitted 8046 // and the DAG root is already updated. 8047 HasTailCall = true; 8048 8049 // Since there's no actual continuation from this block, nothing can be 8050 // relying on us setting vregs for them. 8051 PendingExports.clear(); 8052 } else { 8053 DAG.setRoot(Result.second); 8054 } 8055 8056 if (EHPadBB) { 8057 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 8058 BeginLabel)); 8059 } 8060 8061 return Result; 8062 } 8063 8064 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 8065 bool isTailCall, 8066 bool isMustTailCall, 8067 const BasicBlock *EHPadBB) { 8068 auto &DL = DAG.getDataLayout(); 8069 FunctionType *FTy = CB.getFunctionType(); 8070 Type *RetTy = CB.getType(); 8071 8072 TargetLowering::ArgListTy Args; 8073 Args.reserve(CB.arg_size()); 8074 8075 const Value *SwiftErrorVal = nullptr; 8076 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8077 8078 if (isTailCall) { 8079 // Avoid emitting tail calls in functions with the disable-tail-calls 8080 // attribute. 8081 auto *Caller = CB.getParent()->getParent(); 8082 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 8083 "true" && !isMustTailCall) 8084 isTailCall = false; 8085 8086 // We can't tail call inside a function with a swifterror argument. Lowering 8087 // does not support this yet. It would have to move into the swifterror 8088 // register before the call. 8089 if (TLI.supportSwiftError() && 8090 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 8091 isTailCall = false; 8092 } 8093 8094 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 8095 TargetLowering::ArgListEntry Entry; 8096 const Value *V = *I; 8097 8098 // Skip empty types 8099 if (V->getType()->isEmptyTy()) 8100 continue; 8101 8102 SDValue ArgNode = getValue(V); 8103 Entry.Node = ArgNode; Entry.Ty = V->getType(); 8104 8105 Entry.setAttributes(&CB, I - CB.arg_begin()); 8106 8107 // Use swifterror virtual register as input to the call. 8108 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 8109 SwiftErrorVal = V; 8110 // We find the virtual register for the actual swifterror argument. 8111 // Instead of using the Value, we use the virtual register instead. 8112 Entry.Node = 8113 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 8114 EVT(TLI.getPointerTy(DL))); 8115 } 8116 8117 Args.push_back(Entry); 8118 8119 // If we have an explicit sret argument that is an Instruction, (i.e., it 8120 // might point to function-local memory), we can't meaningfully tail-call. 8121 if (Entry.IsSRet && isa<Instruction>(V)) 8122 isTailCall = false; 8123 } 8124 8125 // If call site has a cfguardtarget operand bundle, create and add an 8126 // additional ArgListEntry. 8127 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 8128 TargetLowering::ArgListEntry Entry; 8129 Value *V = Bundle->Inputs[0]; 8130 SDValue ArgNode = getValue(V); 8131 Entry.Node = ArgNode; 8132 Entry.Ty = V->getType(); 8133 Entry.IsCFGuardTarget = true; 8134 Args.push_back(Entry); 8135 } 8136 8137 // Check if target-independent constraints permit a tail call here. 8138 // Target-dependent constraints are checked within TLI->LowerCallTo. 8139 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 8140 isTailCall = false; 8141 8142 // Disable tail calls if there is an swifterror argument. Targets have not 8143 // been updated to support tail calls. 8144 if (TLI.supportSwiftError() && SwiftErrorVal) 8145 isTailCall = false; 8146 8147 ConstantInt *CFIType = nullptr; 8148 if (CB.isIndirectCall()) { 8149 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) { 8150 if (!TLI.supportKCFIBundles()) 8151 report_fatal_error( 8152 "Target doesn't support calls with kcfi operand bundles."); 8153 CFIType = cast<ConstantInt>(Bundle->Inputs[0]); 8154 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type"); 8155 } 8156 } 8157 8158 TargetLowering::CallLoweringInfo CLI(DAG); 8159 CLI.setDebugLoc(getCurSDLoc()) 8160 .setChain(getRoot()) 8161 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 8162 .setTailCall(isTailCall) 8163 .setConvergent(CB.isConvergent()) 8164 .setIsPreallocated( 8165 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0) 8166 .setCFIType(CFIType); 8167 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8168 8169 if (Result.first.getNode()) { 8170 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 8171 setValue(&CB, Result.first); 8172 } 8173 8174 // The last element of CLI.InVals has the SDValue for swifterror return. 8175 // Here we copy it to a virtual register and update SwiftErrorMap for 8176 // book-keeping. 8177 if (SwiftErrorVal && TLI.supportSwiftError()) { 8178 // Get the last element of InVals. 8179 SDValue Src = CLI.InVals.back(); 8180 Register VReg = 8181 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 8182 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 8183 DAG.setRoot(CopyNode); 8184 } 8185 } 8186 8187 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 8188 SelectionDAGBuilder &Builder) { 8189 // Check to see if this load can be trivially constant folded, e.g. if the 8190 // input is from a string literal. 8191 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 8192 // Cast pointer to the type we really want to load. 8193 Type *LoadTy = 8194 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 8195 if (LoadVT.isVector()) 8196 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 8197 8198 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 8199 PointerType::getUnqual(LoadTy)); 8200 8201 if (const Constant *LoadCst = 8202 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput), 8203 LoadTy, Builder.DAG.getDataLayout())) 8204 return Builder.getValue(LoadCst); 8205 } 8206 8207 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 8208 // still constant memory, the input chain can be the entry node. 8209 SDValue Root; 8210 bool ConstantMemory = false; 8211 8212 // Do not serialize (non-volatile) loads of constant memory with anything. 8213 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 8214 Root = Builder.DAG.getEntryNode(); 8215 ConstantMemory = true; 8216 } else { 8217 // Do not serialize non-volatile loads against each other. 8218 Root = Builder.DAG.getRoot(); 8219 } 8220 8221 SDValue Ptr = Builder.getValue(PtrVal); 8222 SDValue LoadVal = 8223 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 8224 MachinePointerInfo(PtrVal), Align(1)); 8225 8226 if (!ConstantMemory) 8227 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 8228 return LoadVal; 8229 } 8230 8231 /// Record the value for an instruction that produces an integer result, 8232 /// converting the type where necessary. 8233 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 8234 SDValue Value, 8235 bool IsSigned) { 8236 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8237 I.getType(), true); 8238 Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT); 8239 setValue(&I, Value); 8240 } 8241 8242 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 8243 /// true and lower it. Otherwise return false, and it will be lowered like a 8244 /// normal call. 8245 /// The caller already checked that \p I calls the appropriate LibFunc with a 8246 /// correct prototype. 8247 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 8248 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 8249 const Value *Size = I.getArgOperand(2); 8250 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size)); 8251 if (CSize && CSize->getZExtValue() == 0) { 8252 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8253 I.getType(), true); 8254 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 8255 return true; 8256 } 8257 8258 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8259 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 8260 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 8261 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 8262 if (Res.first.getNode()) { 8263 processIntegerCallValue(I, Res.first, true); 8264 PendingLoads.push_back(Res.second); 8265 return true; 8266 } 8267 8268 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 8269 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 8270 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 8271 return false; 8272 8273 // If the target has a fast compare for the given size, it will return a 8274 // preferred load type for that size. Require that the load VT is legal and 8275 // that the target supports unaligned loads of that type. Otherwise, return 8276 // INVALID. 8277 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 8278 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8279 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 8280 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 8281 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 8282 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 8283 // TODO: Check alignment of src and dest ptrs. 8284 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 8285 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 8286 if (!TLI.isTypeLegal(LVT) || 8287 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 8288 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 8289 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 8290 } 8291 8292 return LVT; 8293 }; 8294 8295 // This turns into unaligned loads. We only do this if the target natively 8296 // supports the MVT we'll be loading or if it is small enough (<= 4) that 8297 // we'll only produce a small number of byte loads. 8298 MVT LoadVT; 8299 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 8300 switch (NumBitsToCompare) { 8301 default: 8302 return false; 8303 case 16: 8304 LoadVT = MVT::i16; 8305 break; 8306 case 32: 8307 LoadVT = MVT::i32; 8308 break; 8309 case 64: 8310 case 128: 8311 case 256: 8312 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 8313 break; 8314 } 8315 8316 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 8317 return false; 8318 8319 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 8320 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 8321 8322 // Bitcast to a wide integer type if the loads are vectors. 8323 if (LoadVT.isVector()) { 8324 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 8325 LoadL = DAG.getBitcast(CmpVT, LoadL); 8326 LoadR = DAG.getBitcast(CmpVT, LoadR); 8327 } 8328 8329 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 8330 processIntegerCallValue(I, Cmp, false); 8331 return true; 8332 } 8333 8334 /// See if we can lower a memchr call into an optimized form. If so, return 8335 /// true and lower it. Otherwise return false, and it will be lowered like a 8336 /// normal call. 8337 /// The caller already checked that \p I calls the appropriate LibFunc with a 8338 /// correct prototype. 8339 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 8340 const Value *Src = I.getArgOperand(0); 8341 const Value *Char = I.getArgOperand(1); 8342 const Value *Length = I.getArgOperand(2); 8343 8344 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8345 std::pair<SDValue, SDValue> Res = 8346 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 8347 getValue(Src), getValue(Char), getValue(Length), 8348 MachinePointerInfo(Src)); 8349 if (Res.first.getNode()) { 8350 setValue(&I, Res.first); 8351 PendingLoads.push_back(Res.second); 8352 return true; 8353 } 8354 8355 return false; 8356 } 8357 8358 /// See if we can lower a mempcpy call into an optimized form. If so, return 8359 /// true and lower it. Otherwise return false, and it will be lowered like a 8360 /// normal call. 8361 /// The caller already checked that \p I calls the appropriate LibFunc with a 8362 /// correct prototype. 8363 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 8364 SDValue Dst = getValue(I.getArgOperand(0)); 8365 SDValue Src = getValue(I.getArgOperand(1)); 8366 SDValue Size = getValue(I.getArgOperand(2)); 8367 8368 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 8369 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 8370 // DAG::getMemcpy needs Alignment to be defined. 8371 Align Alignment = std::min(DstAlign, SrcAlign); 8372 8373 SDLoc sdl = getCurSDLoc(); 8374 8375 // In the mempcpy context we need to pass in a false value for isTailCall 8376 // because the return pointer needs to be adjusted by the size of 8377 // the copied memory. 8378 SDValue Root = getMemoryRoot(); 8379 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, false, false, 8380 /*isTailCall=*/false, 8381 MachinePointerInfo(I.getArgOperand(0)), 8382 MachinePointerInfo(I.getArgOperand(1)), 8383 I.getAAMetadata()); 8384 assert(MC.getNode() != nullptr && 8385 "** memcpy should not be lowered as TailCall in mempcpy context **"); 8386 DAG.setRoot(MC); 8387 8388 // Check if Size needs to be truncated or extended. 8389 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 8390 8391 // Adjust return pointer to point just past the last dst byte. 8392 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 8393 Dst, Size); 8394 setValue(&I, DstPlusSize); 8395 return true; 8396 } 8397 8398 /// See if we can lower a strcpy call into an optimized form. If so, return 8399 /// true and lower it, otherwise return false and it will be lowered like a 8400 /// normal call. 8401 /// The caller already checked that \p I calls the appropriate LibFunc with a 8402 /// correct prototype. 8403 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 8404 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8405 8406 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8407 std::pair<SDValue, SDValue> Res = 8408 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 8409 getValue(Arg0), getValue(Arg1), 8410 MachinePointerInfo(Arg0), 8411 MachinePointerInfo(Arg1), isStpcpy); 8412 if (Res.first.getNode()) { 8413 setValue(&I, Res.first); 8414 DAG.setRoot(Res.second); 8415 return true; 8416 } 8417 8418 return false; 8419 } 8420 8421 /// See if we can lower a strcmp call into an optimized form. If so, return 8422 /// true and lower it, otherwise return false and it will be lowered like a 8423 /// normal call. 8424 /// The caller already checked that \p I calls the appropriate LibFunc with a 8425 /// correct prototype. 8426 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 8427 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8428 8429 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8430 std::pair<SDValue, SDValue> Res = 8431 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 8432 getValue(Arg0), getValue(Arg1), 8433 MachinePointerInfo(Arg0), 8434 MachinePointerInfo(Arg1)); 8435 if (Res.first.getNode()) { 8436 processIntegerCallValue(I, Res.first, true); 8437 PendingLoads.push_back(Res.second); 8438 return true; 8439 } 8440 8441 return false; 8442 } 8443 8444 /// See if we can lower a strlen call into an optimized form. If so, return 8445 /// true and lower it, otherwise return false and it will be lowered like a 8446 /// normal call. 8447 /// The caller already checked that \p I calls the appropriate LibFunc with a 8448 /// correct prototype. 8449 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 8450 const Value *Arg0 = I.getArgOperand(0); 8451 8452 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8453 std::pair<SDValue, SDValue> Res = 8454 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 8455 getValue(Arg0), MachinePointerInfo(Arg0)); 8456 if (Res.first.getNode()) { 8457 processIntegerCallValue(I, Res.first, false); 8458 PendingLoads.push_back(Res.second); 8459 return true; 8460 } 8461 8462 return false; 8463 } 8464 8465 /// See if we can lower a strnlen call into an optimized form. If so, return 8466 /// true and lower it, otherwise return false and it will be lowered like a 8467 /// normal call. 8468 /// The caller already checked that \p I calls the appropriate LibFunc with a 8469 /// correct prototype. 8470 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 8471 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8472 8473 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8474 std::pair<SDValue, SDValue> Res = 8475 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 8476 getValue(Arg0), getValue(Arg1), 8477 MachinePointerInfo(Arg0)); 8478 if (Res.first.getNode()) { 8479 processIntegerCallValue(I, Res.first, false); 8480 PendingLoads.push_back(Res.second); 8481 return true; 8482 } 8483 8484 return false; 8485 } 8486 8487 /// See if we can lower a unary floating-point operation into an SDNode with 8488 /// the specified Opcode. If so, return true and lower it, otherwise return 8489 /// false and it will be lowered like a normal call. 8490 /// The caller already checked that \p I calls the appropriate LibFunc with a 8491 /// correct prototype. 8492 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 8493 unsigned Opcode) { 8494 // We already checked this call's prototype; verify it doesn't modify errno. 8495 if (!I.onlyReadsMemory()) 8496 return false; 8497 8498 SDNodeFlags Flags; 8499 Flags.copyFMF(cast<FPMathOperator>(I)); 8500 8501 SDValue Tmp = getValue(I.getArgOperand(0)); 8502 setValue(&I, 8503 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 8504 return true; 8505 } 8506 8507 /// See if we can lower a binary floating-point operation into an SDNode with 8508 /// the specified Opcode. If so, return true and lower it. Otherwise return 8509 /// false, and it will be lowered like a normal call. 8510 /// The caller already checked that \p I calls the appropriate LibFunc with a 8511 /// correct prototype. 8512 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 8513 unsigned Opcode) { 8514 // We already checked this call's prototype; verify it doesn't modify errno. 8515 if (!I.onlyReadsMemory()) 8516 return false; 8517 8518 SDNodeFlags Flags; 8519 Flags.copyFMF(cast<FPMathOperator>(I)); 8520 8521 SDValue Tmp0 = getValue(I.getArgOperand(0)); 8522 SDValue Tmp1 = getValue(I.getArgOperand(1)); 8523 EVT VT = Tmp0.getValueType(); 8524 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 8525 return true; 8526 } 8527 8528 void SelectionDAGBuilder::visitCall(const CallInst &I) { 8529 // Handle inline assembly differently. 8530 if (I.isInlineAsm()) { 8531 visitInlineAsm(I); 8532 return; 8533 } 8534 8535 diagnoseDontCall(I); 8536 8537 if (Function *F = I.getCalledFunction()) { 8538 if (F->isDeclaration()) { 8539 // Is this an LLVM intrinsic or a target-specific intrinsic? 8540 unsigned IID = F->getIntrinsicID(); 8541 if (!IID) 8542 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 8543 IID = II->getIntrinsicID(F); 8544 8545 if (IID) { 8546 visitIntrinsicCall(I, IID); 8547 return; 8548 } 8549 } 8550 8551 // Check for well-known libc/libm calls. If the function is internal, it 8552 // can't be a library call. Don't do the check if marked as nobuiltin for 8553 // some reason or the call site requires strict floating point semantics. 8554 LibFunc Func; 8555 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 8556 F->hasName() && LibInfo->getLibFunc(*F, Func) && 8557 LibInfo->hasOptimizedCodeGen(Func)) { 8558 switch (Func) { 8559 default: break; 8560 case LibFunc_bcmp: 8561 if (visitMemCmpBCmpCall(I)) 8562 return; 8563 break; 8564 case LibFunc_copysign: 8565 case LibFunc_copysignf: 8566 case LibFunc_copysignl: 8567 // We already checked this call's prototype; verify it doesn't modify 8568 // errno. 8569 if (I.onlyReadsMemory()) { 8570 SDValue LHS = getValue(I.getArgOperand(0)); 8571 SDValue RHS = getValue(I.getArgOperand(1)); 8572 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 8573 LHS.getValueType(), LHS, RHS)); 8574 return; 8575 } 8576 break; 8577 case LibFunc_fabs: 8578 case LibFunc_fabsf: 8579 case LibFunc_fabsl: 8580 if (visitUnaryFloatCall(I, ISD::FABS)) 8581 return; 8582 break; 8583 case LibFunc_fmin: 8584 case LibFunc_fminf: 8585 case LibFunc_fminl: 8586 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 8587 return; 8588 break; 8589 case LibFunc_fmax: 8590 case LibFunc_fmaxf: 8591 case LibFunc_fmaxl: 8592 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 8593 return; 8594 break; 8595 case LibFunc_sin: 8596 case LibFunc_sinf: 8597 case LibFunc_sinl: 8598 if (visitUnaryFloatCall(I, ISD::FSIN)) 8599 return; 8600 break; 8601 case LibFunc_cos: 8602 case LibFunc_cosf: 8603 case LibFunc_cosl: 8604 if (visitUnaryFloatCall(I, ISD::FCOS)) 8605 return; 8606 break; 8607 case LibFunc_sqrt: 8608 case LibFunc_sqrtf: 8609 case LibFunc_sqrtl: 8610 case LibFunc_sqrt_finite: 8611 case LibFunc_sqrtf_finite: 8612 case LibFunc_sqrtl_finite: 8613 if (visitUnaryFloatCall(I, ISD::FSQRT)) 8614 return; 8615 break; 8616 case LibFunc_floor: 8617 case LibFunc_floorf: 8618 case LibFunc_floorl: 8619 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 8620 return; 8621 break; 8622 case LibFunc_nearbyint: 8623 case LibFunc_nearbyintf: 8624 case LibFunc_nearbyintl: 8625 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 8626 return; 8627 break; 8628 case LibFunc_ceil: 8629 case LibFunc_ceilf: 8630 case LibFunc_ceill: 8631 if (visitUnaryFloatCall(I, ISD::FCEIL)) 8632 return; 8633 break; 8634 case LibFunc_rint: 8635 case LibFunc_rintf: 8636 case LibFunc_rintl: 8637 if (visitUnaryFloatCall(I, ISD::FRINT)) 8638 return; 8639 break; 8640 case LibFunc_round: 8641 case LibFunc_roundf: 8642 case LibFunc_roundl: 8643 if (visitUnaryFloatCall(I, ISD::FROUND)) 8644 return; 8645 break; 8646 case LibFunc_trunc: 8647 case LibFunc_truncf: 8648 case LibFunc_truncl: 8649 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 8650 return; 8651 break; 8652 case LibFunc_log2: 8653 case LibFunc_log2f: 8654 case LibFunc_log2l: 8655 if (visitUnaryFloatCall(I, ISD::FLOG2)) 8656 return; 8657 break; 8658 case LibFunc_exp2: 8659 case LibFunc_exp2f: 8660 case LibFunc_exp2l: 8661 if (visitUnaryFloatCall(I, ISD::FEXP2)) 8662 return; 8663 break; 8664 case LibFunc_ldexp: 8665 case LibFunc_ldexpf: 8666 case LibFunc_ldexpl: 8667 if (visitBinaryFloatCall(I, ISD::FLDEXP)) 8668 return; 8669 break; 8670 case LibFunc_memcmp: 8671 if (visitMemCmpBCmpCall(I)) 8672 return; 8673 break; 8674 case LibFunc_mempcpy: 8675 if (visitMemPCpyCall(I)) 8676 return; 8677 break; 8678 case LibFunc_memchr: 8679 if (visitMemChrCall(I)) 8680 return; 8681 break; 8682 case LibFunc_strcpy: 8683 if (visitStrCpyCall(I, false)) 8684 return; 8685 break; 8686 case LibFunc_stpcpy: 8687 if (visitStrCpyCall(I, true)) 8688 return; 8689 break; 8690 case LibFunc_strcmp: 8691 if (visitStrCmpCall(I)) 8692 return; 8693 break; 8694 case LibFunc_strlen: 8695 if (visitStrLenCall(I)) 8696 return; 8697 break; 8698 case LibFunc_strnlen: 8699 if (visitStrNLenCall(I)) 8700 return; 8701 break; 8702 } 8703 } 8704 } 8705 8706 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 8707 // have to do anything here to lower funclet bundles. 8708 // CFGuardTarget bundles are lowered in LowerCallTo. 8709 assert(!I.hasOperandBundlesOtherThan( 8710 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 8711 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 8712 LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) && 8713 "Cannot lower calls with arbitrary operand bundles!"); 8714 8715 SDValue Callee = getValue(I.getCalledOperand()); 8716 8717 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 8718 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 8719 else 8720 // Check if we can potentially perform a tail call. More detailed checking 8721 // is be done within LowerCallTo, after more information about the call is 8722 // known. 8723 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 8724 } 8725 8726 namespace { 8727 8728 /// AsmOperandInfo - This contains information for each constraint that we are 8729 /// lowering. 8730 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 8731 public: 8732 /// CallOperand - If this is the result output operand or a clobber 8733 /// this is null, otherwise it is the incoming operand to the CallInst. 8734 /// This gets modified as the asm is processed. 8735 SDValue CallOperand; 8736 8737 /// AssignedRegs - If this is a register or register class operand, this 8738 /// contains the set of register corresponding to the operand. 8739 RegsForValue AssignedRegs; 8740 8741 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 8742 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 8743 } 8744 8745 /// Whether or not this operand accesses memory 8746 bool hasMemory(const TargetLowering &TLI) const { 8747 // Indirect operand accesses access memory. 8748 if (isIndirect) 8749 return true; 8750 8751 for (const auto &Code : Codes) 8752 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 8753 return true; 8754 8755 return false; 8756 } 8757 }; 8758 8759 8760 } // end anonymous namespace 8761 8762 /// Make sure that the output operand \p OpInfo and its corresponding input 8763 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 8764 /// out). 8765 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 8766 SDISelAsmOperandInfo &MatchingOpInfo, 8767 SelectionDAG &DAG) { 8768 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 8769 return; 8770 8771 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 8772 const auto &TLI = DAG.getTargetLoweringInfo(); 8773 8774 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 8775 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 8776 OpInfo.ConstraintVT); 8777 std::pair<unsigned, const TargetRegisterClass *> InputRC = 8778 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 8779 MatchingOpInfo.ConstraintVT); 8780 if ((OpInfo.ConstraintVT.isInteger() != 8781 MatchingOpInfo.ConstraintVT.isInteger()) || 8782 (MatchRC.second != InputRC.second)) { 8783 // FIXME: error out in a more elegant fashion 8784 report_fatal_error("Unsupported asm: input constraint" 8785 " with a matching output constraint of" 8786 " incompatible type!"); 8787 } 8788 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 8789 } 8790 8791 /// Get a direct memory input to behave well as an indirect operand. 8792 /// This may introduce stores, hence the need for a \p Chain. 8793 /// \return The (possibly updated) chain. 8794 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 8795 SDISelAsmOperandInfo &OpInfo, 8796 SelectionDAG &DAG) { 8797 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8798 8799 // If we don't have an indirect input, put it in the constpool if we can, 8800 // otherwise spill it to a stack slot. 8801 // TODO: This isn't quite right. We need to handle these according to 8802 // the addressing mode that the constraint wants. Also, this may take 8803 // an additional register for the computation and we don't want that 8804 // either. 8805 8806 // If the operand is a float, integer, or vector constant, spill to a 8807 // constant pool entry to get its address. 8808 const Value *OpVal = OpInfo.CallOperandVal; 8809 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 8810 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 8811 OpInfo.CallOperand = DAG.getConstantPool( 8812 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 8813 return Chain; 8814 } 8815 8816 // Otherwise, create a stack slot and emit a store to it before the asm. 8817 Type *Ty = OpVal->getType(); 8818 auto &DL = DAG.getDataLayout(); 8819 uint64_t TySize = DL.getTypeAllocSize(Ty); 8820 MachineFunction &MF = DAG.getMachineFunction(); 8821 int SSFI = MF.getFrameInfo().CreateStackObject( 8822 TySize, DL.getPrefTypeAlign(Ty), false); 8823 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 8824 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 8825 MachinePointerInfo::getFixedStack(MF, SSFI), 8826 TLI.getMemValueType(DL, Ty)); 8827 OpInfo.CallOperand = StackSlot; 8828 8829 return Chain; 8830 } 8831 8832 /// GetRegistersForValue - Assign registers (virtual or physical) for the 8833 /// specified operand. We prefer to assign virtual registers, to allow the 8834 /// register allocator to handle the assignment process. However, if the asm 8835 /// uses features that we can't model on machineinstrs, we have SDISel do the 8836 /// allocation. This produces generally horrible, but correct, code. 8837 /// 8838 /// OpInfo describes the operand 8839 /// RefOpInfo describes the matching operand if any, the operand otherwise 8840 static std::optional<unsigned> 8841 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 8842 SDISelAsmOperandInfo &OpInfo, 8843 SDISelAsmOperandInfo &RefOpInfo) { 8844 LLVMContext &Context = *DAG.getContext(); 8845 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8846 8847 MachineFunction &MF = DAG.getMachineFunction(); 8848 SmallVector<unsigned, 4> Regs; 8849 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8850 8851 // No work to do for memory/address operands. 8852 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8853 OpInfo.ConstraintType == TargetLowering::C_Address) 8854 return std::nullopt; 8855 8856 // If this is a constraint for a single physreg, or a constraint for a 8857 // register class, find it. 8858 unsigned AssignedReg; 8859 const TargetRegisterClass *RC; 8860 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 8861 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 8862 // RC is unset only on failure. Return immediately. 8863 if (!RC) 8864 return std::nullopt; 8865 8866 // Get the actual register value type. This is important, because the user 8867 // may have asked for (e.g.) the AX register in i32 type. We need to 8868 // remember that AX is actually i16 to get the right extension. 8869 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 8870 8871 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) { 8872 // If this is an FP operand in an integer register (or visa versa), or more 8873 // generally if the operand value disagrees with the register class we plan 8874 // to stick it in, fix the operand type. 8875 // 8876 // If this is an input value, the bitcast to the new type is done now. 8877 // Bitcast for output value is done at the end of visitInlineAsm(). 8878 if ((OpInfo.Type == InlineAsm::isOutput || 8879 OpInfo.Type == InlineAsm::isInput) && 8880 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 8881 // Try to convert to the first EVT that the reg class contains. If the 8882 // types are identical size, use a bitcast to convert (e.g. two differing 8883 // vector types). Note: output bitcast is done at the end of 8884 // visitInlineAsm(). 8885 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 8886 // Exclude indirect inputs while they are unsupported because the code 8887 // to perform the load is missing and thus OpInfo.CallOperand still 8888 // refers to the input address rather than the pointed-to value. 8889 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 8890 OpInfo.CallOperand = 8891 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 8892 OpInfo.ConstraintVT = RegVT; 8893 // If the operand is an FP value and we want it in integer registers, 8894 // use the corresponding integer type. This turns an f64 value into 8895 // i64, which can be passed with two i32 values on a 32-bit machine. 8896 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 8897 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 8898 if (OpInfo.Type == InlineAsm::isInput) 8899 OpInfo.CallOperand = 8900 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 8901 OpInfo.ConstraintVT = VT; 8902 } 8903 } 8904 } 8905 8906 // No need to allocate a matching input constraint since the constraint it's 8907 // matching to has already been allocated. 8908 if (OpInfo.isMatchingInputConstraint()) 8909 return std::nullopt; 8910 8911 EVT ValueVT = OpInfo.ConstraintVT; 8912 if (OpInfo.ConstraintVT == MVT::Other) 8913 ValueVT = RegVT; 8914 8915 // Initialize NumRegs. 8916 unsigned NumRegs = 1; 8917 if (OpInfo.ConstraintVT != MVT::Other) 8918 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT); 8919 8920 // If this is a constraint for a specific physical register, like {r17}, 8921 // assign it now. 8922 8923 // If this associated to a specific register, initialize iterator to correct 8924 // place. If virtual, make sure we have enough registers 8925 8926 // Initialize iterator if necessary 8927 TargetRegisterClass::iterator I = RC->begin(); 8928 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8929 8930 // Do not check for single registers. 8931 if (AssignedReg) { 8932 I = std::find(I, RC->end(), AssignedReg); 8933 if (I == RC->end()) { 8934 // RC does not contain the selected register, which indicates a 8935 // mismatch between the register and the required type/bitwidth. 8936 return {AssignedReg}; 8937 } 8938 } 8939 8940 for (; NumRegs; --NumRegs, ++I) { 8941 assert(I != RC->end() && "Ran out of registers to allocate!"); 8942 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8943 Regs.push_back(R); 8944 } 8945 8946 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8947 return std::nullopt; 8948 } 8949 8950 static unsigned 8951 findMatchingInlineAsmOperand(unsigned OperandNo, 8952 const std::vector<SDValue> &AsmNodeOperands) { 8953 // Scan until we find the definition we already emitted of this operand. 8954 unsigned CurOp = InlineAsm::Op_FirstOperand; 8955 for (; OperandNo; --OperandNo) { 8956 // Advance to the next operand. 8957 unsigned OpFlag = 8958 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8959 assert((InlineAsm::isRegDefKind(OpFlag) || 8960 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8961 InlineAsm::isMemKind(OpFlag)) && 8962 "Skipped past definitions?"); 8963 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8964 } 8965 return CurOp; 8966 } 8967 8968 namespace { 8969 8970 class ExtraFlags { 8971 unsigned Flags = 0; 8972 8973 public: 8974 explicit ExtraFlags(const CallBase &Call) { 8975 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8976 if (IA->hasSideEffects()) 8977 Flags |= InlineAsm::Extra_HasSideEffects; 8978 if (IA->isAlignStack()) 8979 Flags |= InlineAsm::Extra_IsAlignStack; 8980 if (Call.isConvergent()) 8981 Flags |= InlineAsm::Extra_IsConvergent; 8982 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8983 } 8984 8985 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8986 // Ideally, we would only check against memory constraints. However, the 8987 // meaning of an Other constraint can be target-specific and we can't easily 8988 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8989 // for Other constraints as well. 8990 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8991 OpInfo.ConstraintType == TargetLowering::C_Other) { 8992 if (OpInfo.Type == InlineAsm::isInput) 8993 Flags |= InlineAsm::Extra_MayLoad; 8994 else if (OpInfo.Type == InlineAsm::isOutput) 8995 Flags |= InlineAsm::Extra_MayStore; 8996 else if (OpInfo.Type == InlineAsm::isClobber) 8997 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8998 } 8999 } 9000 9001 unsigned get() const { return Flags; } 9002 }; 9003 9004 } // end anonymous namespace 9005 9006 static bool isFunction(SDValue Op) { 9007 if (Op && Op.getOpcode() == ISD::GlobalAddress) { 9008 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 9009 auto Fn = dyn_cast_or_null<Function>(GA->getGlobal()); 9010 9011 // In normal "call dllimport func" instruction (non-inlineasm) it force 9012 // indirect access by specifing call opcode. And usually specially print 9013 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can 9014 // not do in this way now. (In fact, this is similar with "Data Access" 9015 // action). So here we ignore dllimport function. 9016 if (Fn && !Fn->hasDLLImportStorageClass()) 9017 return true; 9018 } 9019 } 9020 return false; 9021 } 9022 9023 /// visitInlineAsm - Handle a call to an InlineAsm object. 9024 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 9025 const BasicBlock *EHPadBB) { 9026 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 9027 9028 /// ConstraintOperands - Information about all of the constraints. 9029 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 9030 9031 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9032 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 9033 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 9034 9035 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 9036 // AsmDialect, MayLoad, MayStore). 9037 bool HasSideEffect = IA->hasSideEffects(); 9038 ExtraFlags ExtraInfo(Call); 9039 9040 for (auto &T : TargetConstraints) { 9041 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 9042 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 9043 9044 if (OpInfo.CallOperandVal) 9045 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 9046 9047 if (!HasSideEffect) 9048 HasSideEffect = OpInfo.hasMemory(TLI); 9049 9050 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 9051 // FIXME: Could we compute this on OpInfo rather than T? 9052 9053 // Compute the constraint code and ConstraintType to use. 9054 TLI.ComputeConstraintToUse(T, SDValue()); 9055 9056 if (T.ConstraintType == TargetLowering::C_Immediate && 9057 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 9058 // We've delayed emitting a diagnostic like the "n" constraint because 9059 // inlining could cause an integer showing up. 9060 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 9061 "' expects an integer constant " 9062 "expression"); 9063 9064 ExtraInfo.update(T); 9065 } 9066 9067 // We won't need to flush pending loads if this asm doesn't touch 9068 // memory and is nonvolatile. 9069 SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 9070 9071 bool EmitEHLabels = isa<InvokeInst>(Call); 9072 if (EmitEHLabels) { 9073 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 9074 } 9075 bool IsCallBr = isa<CallBrInst>(Call); 9076 9077 if (IsCallBr || EmitEHLabels) { 9078 // If this is a callbr or invoke we need to flush pending exports since 9079 // inlineasm_br and invoke are terminators. 9080 // We need to do this before nodes are glued to the inlineasm_br node. 9081 Chain = getControlRoot(); 9082 } 9083 9084 MCSymbol *BeginLabel = nullptr; 9085 if (EmitEHLabels) { 9086 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 9087 } 9088 9089 int OpNo = -1; 9090 SmallVector<StringRef> AsmStrs; 9091 IA->collectAsmStrs(AsmStrs); 9092 9093 // Second pass over the constraints: compute which constraint option to use. 9094 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9095 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput) 9096 OpNo++; 9097 9098 // If this is an output operand with a matching input operand, look up the 9099 // matching input. If their types mismatch, e.g. one is an integer, the 9100 // other is floating point, or their sizes are different, flag it as an 9101 // error. 9102 if (OpInfo.hasMatchingInput()) { 9103 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 9104 patchMatchingInput(OpInfo, Input, DAG); 9105 } 9106 9107 // Compute the constraint code and ConstraintType to use. 9108 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 9109 9110 if ((OpInfo.ConstraintType == TargetLowering::C_Memory && 9111 OpInfo.Type == InlineAsm::isClobber) || 9112 OpInfo.ConstraintType == TargetLowering::C_Address) 9113 continue; 9114 9115 // In Linux PIC model, there are 4 cases about value/label addressing: 9116 // 9117 // 1: Function call or Label jmp inside the module. 9118 // 2: Data access (such as global variable, static variable) inside module. 9119 // 3: Function call or Label jmp outside the module. 9120 // 4: Data access (such as global variable) outside the module. 9121 // 9122 // Due to current llvm inline asm architecture designed to not "recognize" 9123 // the asm code, there are quite troubles for us to treat mem addressing 9124 // differently for same value/adress used in different instuctions. 9125 // For example, in pic model, call a func may in plt way or direclty 9126 // pc-related, but lea/mov a function adress may use got. 9127 // 9128 // Here we try to "recognize" function call for the case 1 and case 3 in 9129 // inline asm. And try to adjust the constraint for them. 9130 // 9131 // TODO: Due to current inline asm didn't encourage to jmp to the outsider 9132 // label, so here we don't handle jmp function label now, but we need to 9133 // enhance it (especilly in PIC model) if we meet meaningful requirements. 9134 if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) && 9135 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) && 9136 TM.getCodeModel() != CodeModel::Large) { 9137 OpInfo.isIndirect = false; 9138 OpInfo.ConstraintType = TargetLowering::C_Address; 9139 } 9140 9141 // If this is a memory input, and if the operand is not indirect, do what we 9142 // need to provide an address for the memory input. 9143 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 9144 !OpInfo.isIndirect) { 9145 assert((OpInfo.isMultipleAlternative || 9146 (OpInfo.Type == InlineAsm::isInput)) && 9147 "Can only indirectify direct input operands!"); 9148 9149 // Memory operands really want the address of the value. 9150 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 9151 9152 // There is no longer a Value* corresponding to this operand. 9153 OpInfo.CallOperandVal = nullptr; 9154 9155 // It is now an indirect operand. 9156 OpInfo.isIndirect = true; 9157 } 9158 9159 } 9160 9161 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 9162 std::vector<SDValue> AsmNodeOperands; 9163 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 9164 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 9165 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 9166 9167 // If we have a !srcloc metadata node associated with it, we want to attach 9168 // this to the ultimately generated inline asm machineinstr. To do this, we 9169 // pass in the third operand as this (potentially null) inline asm MDNode. 9170 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 9171 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 9172 9173 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 9174 // bits as operand 3. 9175 AsmNodeOperands.push_back(DAG.getTargetConstant( 9176 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9177 9178 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 9179 // this, assign virtual and physical registers for inputs and otput. 9180 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9181 // Assign Registers. 9182 SDISelAsmOperandInfo &RefOpInfo = 9183 OpInfo.isMatchingInputConstraint() 9184 ? ConstraintOperands[OpInfo.getMatchedOperand()] 9185 : OpInfo; 9186 const auto RegError = 9187 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 9188 if (RegError) { 9189 const MachineFunction &MF = DAG.getMachineFunction(); 9190 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9191 const char *RegName = TRI.getName(*RegError); 9192 emitInlineAsmError(Call, "register '" + Twine(RegName) + 9193 "' allocated for constraint '" + 9194 Twine(OpInfo.ConstraintCode) + 9195 "' does not match required type"); 9196 return; 9197 } 9198 9199 auto DetectWriteToReservedRegister = [&]() { 9200 const MachineFunction &MF = DAG.getMachineFunction(); 9201 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9202 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 9203 if (Register::isPhysicalRegister(Reg) && 9204 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 9205 const char *RegName = TRI.getName(Reg); 9206 emitInlineAsmError(Call, "write to reserved register '" + 9207 Twine(RegName) + "'"); 9208 return true; 9209 } 9210 } 9211 return false; 9212 }; 9213 assert((OpInfo.ConstraintType != TargetLowering::C_Address || 9214 (OpInfo.Type == InlineAsm::isInput && 9215 !OpInfo.isMatchingInputConstraint())) && 9216 "Only address as input operand is allowed."); 9217 9218 switch (OpInfo.Type) { 9219 case InlineAsm::isOutput: 9220 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9221 unsigned ConstraintID = 9222 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9223 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9224 "Failed to convert memory constraint code to constraint id."); 9225 9226 // Add information to the INLINEASM node to know about this output. 9227 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9228 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 9229 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 9230 MVT::i32)); 9231 AsmNodeOperands.push_back(OpInfo.CallOperand); 9232 } else { 9233 // Otherwise, this outputs to a register (directly for C_Register / 9234 // C_RegisterClass, and a target-defined fashion for 9235 // C_Immediate/C_Other). Find a register that we can use. 9236 if (OpInfo.AssignedRegs.Regs.empty()) { 9237 emitInlineAsmError( 9238 Call, "couldn't allocate output register for constraint '" + 9239 Twine(OpInfo.ConstraintCode) + "'"); 9240 return; 9241 } 9242 9243 if (DetectWriteToReservedRegister()) 9244 return; 9245 9246 // Add information to the INLINEASM node to know that this register is 9247 // set. 9248 OpInfo.AssignedRegs.AddInlineAsmOperands( 9249 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 9250 : InlineAsm::Kind_RegDef, 9251 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 9252 } 9253 break; 9254 9255 case InlineAsm::isInput: 9256 case InlineAsm::isLabel: { 9257 SDValue InOperandVal = OpInfo.CallOperand; 9258 9259 if (OpInfo.isMatchingInputConstraint()) { 9260 // If this is required to match an output register we have already set, 9261 // just use its register. 9262 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 9263 AsmNodeOperands); 9264 unsigned OpFlag = 9265 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 9266 if (InlineAsm::isRegDefKind(OpFlag) || 9267 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 9268 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 9269 if (OpInfo.isIndirect) { 9270 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 9271 emitInlineAsmError(Call, "inline asm not supported yet: " 9272 "don't know how to handle tied " 9273 "indirect register inputs"); 9274 return; 9275 } 9276 9277 SmallVector<unsigned, 4> Regs; 9278 MachineFunction &MF = DAG.getMachineFunction(); 9279 MachineRegisterInfo &MRI = MF.getRegInfo(); 9280 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9281 auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]); 9282 Register TiedReg = R->getReg(); 9283 MVT RegVT = R->getSimpleValueType(0); 9284 const TargetRegisterClass *RC = 9285 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg) 9286 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT) 9287 : TRI.getMinimalPhysRegClass(TiedReg); 9288 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 9289 for (unsigned i = 0; i != NumRegs; ++i) 9290 Regs.push_back(MRI.createVirtualRegister(RC)); 9291 9292 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 9293 9294 SDLoc dl = getCurSDLoc(); 9295 // Use the produced MatchedRegs object to 9296 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call); 9297 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 9298 true, OpInfo.getMatchedOperand(), dl, 9299 DAG, AsmNodeOperands); 9300 break; 9301 } 9302 9303 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 9304 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 9305 "Unexpected number of operands"); 9306 // Add information to the INLINEASM node to know about this input. 9307 // See InlineAsm.h isUseOperandTiedToDef. 9308 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 9309 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 9310 OpInfo.getMatchedOperand()); 9311 AsmNodeOperands.push_back(DAG.getTargetConstant( 9312 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9313 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 9314 break; 9315 } 9316 9317 // Treat indirect 'X' constraint as memory. 9318 if (OpInfo.ConstraintType == TargetLowering::C_Other && 9319 OpInfo.isIndirect) 9320 OpInfo.ConstraintType = TargetLowering::C_Memory; 9321 9322 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 9323 OpInfo.ConstraintType == TargetLowering::C_Other) { 9324 std::vector<SDValue> Ops; 9325 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 9326 Ops, DAG); 9327 if (Ops.empty()) { 9328 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 9329 if (isa<ConstantSDNode>(InOperandVal)) { 9330 emitInlineAsmError(Call, "value out of range for constraint '" + 9331 Twine(OpInfo.ConstraintCode) + "'"); 9332 return; 9333 } 9334 9335 emitInlineAsmError(Call, 9336 "invalid operand for inline asm constraint '" + 9337 Twine(OpInfo.ConstraintCode) + "'"); 9338 return; 9339 } 9340 9341 // Add information to the INLINEASM node to know about this input. 9342 unsigned ResOpType = 9343 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 9344 AsmNodeOperands.push_back(DAG.getTargetConstant( 9345 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9346 llvm::append_range(AsmNodeOperands, Ops); 9347 break; 9348 } 9349 9350 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9351 assert((OpInfo.isIndirect || 9352 OpInfo.ConstraintType != TargetLowering::C_Memory) && 9353 "Operand must be indirect to be a mem!"); 9354 assert(InOperandVal.getValueType() == 9355 TLI.getPointerTy(DAG.getDataLayout()) && 9356 "Memory operands expect pointer values"); 9357 9358 unsigned ConstraintID = 9359 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9360 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9361 "Failed to convert memory constraint code to constraint id."); 9362 9363 // Add information to the INLINEASM node to know about this input. 9364 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9365 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 9366 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 9367 getCurSDLoc(), 9368 MVT::i32)); 9369 AsmNodeOperands.push_back(InOperandVal); 9370 break; 9371 } 9372 9373 if (OpInfo.ConstraintType == TargetLowering::C_Address) { 9374 unsigned ConstraintID = 9375 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9376 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9377 "Failed to convert memory constraint code to constraint id."); 9378 9379 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9380 9381 SDValue AsmOp = InOperandVal; 9382 if (isFunction(InOperandVal)) { 9383 auto *GA = cast<GlobalAddressSDNode>(InOperandVal); 9384 ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Func, 1); 9385 AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(), 9386 InOperandVal.getValueType(), 9387 GA->getOffset()); 9388 } 9389 9390 // Add information to the INLINEASM node to know about this input. 9391 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 9392 9393 AsmNodeOperands.push_back( 9394 DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32)); 9395 9396 AsmNodeOperands.push_back(AsmOp); 9397 break; 9398 } 9399 9400 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 9401 OpInfo.ConstraintType == TargetLowering::C_Register) && 9402 "Unknown constraint type!"); 9403 9404 // TODO: Support this. 9405 if (OpInfo.isIndirect) { 9406 emitInlineAsmError( 9407 Call, "Don't know how to handle indirect register inputs yet " 9408 "for constraint '" + 9409 Twine(OpInfo.ConstraintCode) + "'"); 9410 return; 9411 } 9412 9413 // Copy the input into the appropriate registers. 9414 if (OpInfo.AssignedRegs.Regs.empty()) { 9415 emitInlineAsmError(Call, 9416 "couldn't allocate input reg for constraint '" + 9417 Twine(OpInfo.ConstraintCode) + "'"); 9418 return; 9419 } 9420 9421 if (DetectWriteToReservedRegister()) 9422 return; 9423 9424 SDLoc dl = getCurSDLoc(); 9425 9426 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, 9427 &Call); 9428 9429 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 9430 dl, DAG, AsmNodeOperands); 9431 break; 9432 } 9433 case InlineAsm::isClobber: 9434 // Add the clobbered value to the operand list, so that the register 9435 // allocator is aware that the physreg got clobbered. 9436 if (!OpInfo.AssignedRegs.Regs.empty()) 9437 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 9438 false, 0, getCurSDLoc(), DAG, 9439 AsmNodeOperands); 9440 break; 9441 } 9442 } 9443 9444 // Finish up input operands. Set the input chain and add the flag last. 9445 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 9446 if (Glue.getNode()) AsmNodeOperands.push_back(Glue); 9447 9448 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 9449 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 9450 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 9451 Glue = Chain.getValue(1); 9452 9453 // Do additional work to generate outputs. 9454 9455 SmallVector<EVT, 1> ResultVTs; 9456 SmallVector<SDValue, 1> ResultValues; 9457 SmallVector<SDValue, 8> OutChains; 9458 9459 llvm::Type *CallResultType = Call.getType(); 9460 ArrayRef<Type *> ResultTypes; 9461 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 9462 ResultTypes = StructResult->elements(); 9463 else if (!CallResultType->isVoidTy()) 9464 ResultTypes = ArrayRef(CallResultType); 9465 9466 auto CurResultType = ResultTypes.begin(); 9467 auto handleRegAssign = [&](SDValue V) { 9468 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 9469 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 9470 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 9471 ++CurResultType; 9472 // If the type of the inline asm call site return value is different but has 9473 // same size as the type of the asm output bitcast it. One example of this 9474 // is for vectors with different width / number of elements. This can 9475 // happen for register classes that can contain multiple different value 9476 // types. The preg or vreg allocated may not have the same VT as was 9477 // expected. 9478 // 9479 // This can also happen for a return value that disagrees with the register 9480 // class it is put in, eg. a double in a general-purpose register on a 9481 // 32-bit machine. 9482 if (ResultVT != V.getValueType() && 9483 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 9484 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 9485 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 9486 V.getValueType().isInteger()) { 9487 // If a result value was tied to an input value, the computed result 9488 // may have a wider width than the expected result. Extract the 9489 // relevant portion. 9490 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 9491 } 9492 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 9493 ResultVTs.push_back(ResultVT); 9494 ResultValues.push_back(V); 9495 }; 9496 9497 // Deal with output operands. 9498 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9499 if (OpInfo.Type == InlineAsm::isOutput) { 9500 SDValue Val; 9501 // Skip trivial output operands. 9502 if (OpInfo.AssignedRegs.Regs.empty()) 9503 continue; 9504 9505 switch (OpInfo.ConstraintType) { 9506 case TargetLowering::C_Register: 9507 case TargetLowering::C_RegisterClass: 9508 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 9509 Chain, &Glue, &Call); 9510 break; 9511 case TargetLowering::C_Immediate: 9512 case TargetLowering::C_Other: 9513 Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(), 9514 OpInfo, DAG); 9515 break; 9516 case TargetLowering::C_Memory: 9517 break; // Already handled. 9518 case TargetLowering::C_Address: 9519 break; // Silence warning. 9520 case TargetLowering::C_Unknown: 9521 assert(false && "Unexpected unknown constraint"); 9522 } 9523 9524 // Indirect output manifest as stores. Record output chains. 9525 if (OpInfo.isIndirect) { 9526 const Value *Ptr = OpInfo.CallOperandVal; 9527 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 9528 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 9529 MachinePointerInfo(Ptr)); 9530 OutChains.push_back(Store); 9531 } else { 9532 // generate CopyFromRegs to associated registers. 9533 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 9534 if (Val.getOpcode() == ISD::MERGE_VALUES) { 9535 for (const SDValue &V : Val->op_values()) 9536 handleRegAssign(V); 9537 } else 9538 handleRegAssign(Val); 9539 } 9540 } 9541 } 9542 9543 // Set results. 9544 if (!ResultValues.empty()) { 9545 assert(CurResultType == ResultTypes.end() && 9546 "Mismatch in number of ResultTypes"); 9547 assert(ResultValues.size() == ResultTypes.size() && 9548 "Mismatch in number of output operands in asm result"); 9549 9550 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 9551 DAG.getVTList(ResultVTs), ResultValues); 9552 setValue(&Call, V); 9553 } 9554 9555 // Collect store chains. 9556 if (!OutChains.empty()) 9557 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 9558 9559 if (EmitEHLabels) { 9560 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 9561 } 9562 9563 // Only Update Root if inline assembly has a memory effect. 9564 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 9565 EmitEHLabels) 9566 DAG.setRoot(Chain); 9567 } 9568 9569 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 9570 const Twine &Message) { 9571 LLVMContext &Ctx = *DAG.getContext(); 9572 Ctx.emitError(&Call, Message); 9573 9574 // Make sure we leave the DAG in a valid state 9575 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9576 SmallVector<EVT, 1> ValueVTs; 9577 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 9578 9579 if (ValueVTs.empty()) 9580 return; 9581 9582 SmallVector<SDValue, 1> Ops; 9583 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 9584 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 9585 9586 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 9587 } 9588 9589 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 9590 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 9591 MVT::Other, getRoot(), 9592 getValue(I.getArgOperand(0)), 9593 DAG.getSrcValue(I.getArgOperand(0)))); 9594 } 9595 9596 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 9597 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9598 const DataLayout &DL = DAG.getDataLayout(); 9599 SDValue V = DAG.getVAArg( 9600 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 9601 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 9602 DL.getABITypeAlign(I.getType()).value()); 9603 DAG.setRoot(V.getValue(1)); 9604 9605 if (I.getType()->isPointerTy()) 9606 V = DAG.getPtrExtOrTrunc( 9607 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 9608 setValue(&I, V); 9609 } 9610 9611 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 9612 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 9613 MVT::Other, getRoot(), 9614 getValue(I.getArgOperand(0)), 9615 DAG.getSrcValue(I.getArgOperand(0)))); 9616 } 9617 9618 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 9619 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 9620 MVT::Other, getRoot(), 9621 getValue(I.getArgOperand(0)), 9622 getValue(I.getArgOperand(1)), 9623 DAG.getSrcValue(I.getArgOperand(0)), 9624 DAG.getSrcValue(I.getArgOperand(1)))); 9625 } 9626 9627 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 9628 const Instruction &I, 9629 SDValue Op) { 9630 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 9631 if (!Range) 9632 return Op; 9633 9634 ConstantRange CR = getConstantRangeFromMetadata(*Range); 9635 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 9636 return Op; 9637 9638 APInt Lo = CR.getUnsignedMin(); 9639 if (!Lo.isMinValue()) 9640 return Op; 9641 9642 APInt Hi = CR.getUnsignedMax(); 9643 unsigned Bits = std::max(Hi.getActiveBits(), 9644 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 9645 9646 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9647 9648 SDLoc SL = getCurSDLoc(); 9649 9650 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 9651 DAG.getValueType(SmallVT)); 9652 unsigned NumVals = Op.getNode()->getNumValues(); 9653 if (NumVals == 1) 9654 return ZExt; 9655 9656 SmallVector<SDValue, 4> Ops; 9657 9658 Ops.push_back(ZExt); 9659 for (unsigned I = 1; I != NumVals; ++I) 9660 Ops.push_back(Op.getValue(I)); 9661 9662 return DAG.getMergeValues(Ops, SL); 9663 } 9664 9665 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 9666 /// the call being lowered. 9667 /// 9668 /// This is a helper for lowering intrinsics that follow a target calling 9669 /// convention or require stack pointer adjustment. Only a subset of the 9670 /// intrinsic's operands need to participate in the calling convention. 9671 void SelectionDAGBuilder::populateCallLoweringInfo( 9672 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 9673 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 9674 bool IsPatchPoint) { 9675 TargetLowering::ArgListTy Args; 9676 Args.reserve(NumArgs); 9677 9678 // Populate the argument list. 9679 // Attributes for args start at offset 1, after the return attribute. 9680 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 9681 ArgI != ArgE; ++ArgI) { 9682 const Value *V = Call->getOperand(ArgI); 9683 9684 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 9685 9686 TargetLowering::ArgListEntry Entry; 9687 Entry.Node = getValue(V); 9688 Entry.Ty = V->getType(); 9689 Entry.setAttributes(Call, ArgI); 9690 Args.push_back(Entry); 9691 } 9692 9693 CLI.setDebugLoc(getCurSDLoc()) 9694 .setChain(getRoot()) 9695 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 9696 .setDiscardResult(Call->use_empty()) 9697 .setIsPatchPoint(IsPatchPoint) 9698 .setIsPreallocated( 9699 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 9700 } 9701 9702 /// Add a stack map intrinsic call's live variable operands to a stackmap 9703 /// or patchpoint target node's operand list. 9704 /// 9705 /// Constants are converted to TargetConstants purely as an optimization to 9706 /// avoid constant materialization and register allocation. 9707 /// 9708 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 9709 /// generate addess computation nodes, and so FinalizeISel can convert the 9710 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 9711 /// address materialization and register allocation, but may also be required 9712 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 9713 /// alloca in the entry block, then the runtime may assume that the alloca's 9714 /// StackMap location can be read immediately after compilation and that the 9715 /// location is valid at any point during execution (this is similar to the 9716 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 9717 /// only available in a register, then the runtime would need to trap when 9718 /// execution reaches the StackMap in order to read the alloca's location. 9719 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 9720 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 9721 SelectionDAGBuilder &Builder) { 9722 SelectionDAG &DAG = Builder.DAG; 9723 for (unsigned I = StartIdx; I < Call.arg_size(); I++) { 9724 SDValue Op = Builder.getValue(Call.getArgOperand(I)); 9725 9726 // Things on the stack are pointer-typed, meaning that they are already 9727 // legal and can be emitted directly to target nodes. 9728 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) { 9729 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType())); 9730 } else { 9731 // Otherwise emit a target independent node to be legalised. 9732 Ops.push_back(Builder.getValue(Call.getArgOperand(I))); 9733 } 9734 } 9735 } 9736 9737 /// Lower llvm.experimental.stackmap. 9738 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 9739 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>, 9740 // [live variables...]) 9741 9742 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 9743 9744 SDValue Chain, InGlue, Callee; 9745 SmallVector<SDValue, 32> Ops; 9746 9747 SDLoc DL = getCurSDLoc(); 9748 Callee = getValue(CI.getCalledOperand()); 9749 9750 // The stackmap intrinsic only records the live variables (the arguments 9751 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 9752 // intrinsic, this won't be lowered to a function call. This means we don't 9753 // have to worry about calling conventions and target specific lowering code. 9754 // Instead we perform the call lowering right here. 9755 // 9756 // chain, flag = CALLSEQ_START(chain, 0, 0) 9757 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 9758 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 9759 // 9760 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 9761 InGlue = Chain.getValue(1); 9762 9763 // Add the STACKMAP operands, starting with DAG house-keeping. 9764 Ops.push_back(Chain); 9765 Ops.push_back(InGlue); 9766 9767 // Add the <id>, <numShadowBytes> operands. 9768 // 9769 // These do not require legalisation, and can be emitted directly to target 9770 // constant nodes. 9771 SDValue ID = getValue(CI.getArgOperand(0)); 9772 assert(ID.getValueType() == MVT::i64); 9773 SDValue IDConst = DAG.getTargetConstant( 9774 cast<ConstantSDNode>(ID)->getZExtValue(), DL, ID.getValueType()); 9775 Ops.push_back(IDConst); 9776 9777 SDValue Shad = getValue(CI.getArgOperand(1)); 9778 assert(Shad.getValueType() == MVT::i32); 9779 SDValue ShadConst = DAG.getTargetConstant( 9780 cast<ConstantSDNode>(Shad)->getZExtValue(), DL, Shad.getValueType()); 9781 Ops.push_back(ShadConst); 9782 9783 // Add the live variables. 9784 addStackMapLiveVars(CI, 2, DL, Ops, *this); 9785 9786 // Create the STACKMAP node. 9787 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9788 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops); 9789 InGlue = Chain.getValue(1); 9790 9791 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL); 9792 9793 // Stackmaps don't generate values, so nothing goes into the NodeMap. 9794 9795 // Set the root to the target-lowered call chain. 9796 DAG.setRoot(Chain); 9797 9798 // Inform the Frame Information that we have a stackmap in this function. 9799 FuncInfo.MF->getFrameInfo().setHasStackMap(); 9800 } 9801 9802 /// Lower llvm.experimental.patchpoint directly to its target opcode. 9803 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 9804 const BasicBlock *EHPadBB) { 9805 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 9806 // i32 <numBytes>, 9807 // i8* <target>, 9808 // i32 <numArgs>, 9809 // [Args...], 9810 // [live variables...]) 9811 9812 CallingConv::ID CC = CB.getCallingConv(); 9813 bool IsAnyRegCC = CC == CallingConv::AnyReg; 9814 bool HasDef = !CB.getType()->isVoidTy(); 9815 SDLoc dl = getCurSDLoc(); 9816 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 9817 9818 // Handle immediate and symbolic callees. 9819 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 9820 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 9821 /*isTarget=*/true); 9822 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 9823 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 9824 SDLoc(SymbolicCallee), 9825 SymbolicCallee->getValueType(0)); 9826 9827 // Get the real number of arguments participating in the call <numArgs> 9828 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 9829 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 9830 9831 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 9832 // Intrinsics include all meta-operands up to but not including CC. 9833 unsigned NumMetaOpers = PatchPointOpers::CCPos; 9834 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 9835 "Not enough arguments provided to the patchpoint intrinsic"); 9836 9837 // For AnyRegCC the arguments are lowered later on manually. 9838 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 9839 Type *ReturnTy = 9840 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 9841 9842 TargetLowering::CallLoweringInfo CLI(DAG); 9843 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 9844 ReturnTy, true); 9845 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 9846 9847 SDNode *CallEnd = Result.second.getNode(); 9848 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 9849 CallEnd = CallEnd->getOperand(0).getNode(); 9850 9851 /// Get a call instruction from the call sequence chain. 9852 /// Tail calls are not allowed. 9853 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 9854 "Expected a callseq node."); 9855 SDNode *Call = CallEnd->getOperand(0).getNode(); 9856 bool HasGlue = Call->getGluedNode(); 9857 9858 // Replace the target specific call node with the patchable intrinsic. 9859 SmallVector<SDValue, 8> Ops; 9860 9861 // Push the chain. 9862 Ops.push_back(*(Call->op_begin())); 9863 9864 // Optionally, push the glue (if any). 9865 if (HasGlue) 9866 Ops.push_back(*(Call->op_end() - 1)); 9867 9868 // Push the register mask info. 9869 if (HasGlue) 9870 Ops.push_back(*(Call->op_end() - 2)); 9871 else 9872 Ops.push_back(*(Call->op_end() - 1)); 9873 9874 // Add the <id> and <numBytes> constants. 9875 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 9876 Ops.push_back(DAG.getTargetConstant( 9877 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 9878 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 9879 Ops.push_back(DAG.getTargetConstant( 9880 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 9881 MVT::i32)); 9882 9883 // Add the callee. 9884 Ops.push_back(Callee); 9885 9886 // Adjust <numArgs> to account for any arguments that have been passed on the 9887 // stack instead. 9888 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 9889 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 9890 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 9891 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 9892 9893 // Add the calling convention 9894 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 9895 9896 // Add the arguments we omitted previously. The register allocator should 9897 // place these in any free register. 9898 if (IsAnyRegCC) 9899 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 9900 Ops.push_back(getValue(CB.getArgOperand(i))); 9901 9902 // Push the arguments from the call instruction. 9903 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 9904 Ops.append(Call->op_begin() + 2, e); 9905 9906 // Push live variables for the stack map. 9907 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 9908 9909 SDVTList NodeTys; 9910 if (IsAnyRegCC && HasDef) { 9911 // Create the return types based on the intrinsic definition 9912 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9913 SmallVector<EVT, 3> ValueVTs; 9914 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 9915 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 9916 9917 // There is always a chain and a glue type at the end 9918 ValueVTs.push_back(MVT::Other); 9919 ValueVTs.push_back(MVT::Glue); 9920 NodeTys = DAG.getVTList(ValueVTs); 9921 } else 9922 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9923 9924 // Replace the target specific call node with a PATCHPOINT node. 9925 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops); 9926 9927 // Update the NodeMap. 9928 if (HasDef) { 9929 if (IsAnyRegCC) 9930 setValue(&CB, SDValue(PPV.getNode(), 0)); 9931 else 9932 setValue(&CB, Result.first); 9933 } 9934 9935 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 9936 // call sequence. Furthermore the location of the chain and glue can change 9937 // when the AnyReg calling convention is used and the intrinsic returns a 9938 // value. 9939 if (IsAnyRegCC && HasDef) { 9940 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 9941 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)}; 9942 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 9943 } else 9944 DAG.ReplaceAllUsesWith(Call, PPV.getNode()); 9945 DAG.DeleteNode(Call); 9946 9947 // Inform the Frame Information that we have a patchpoint in this function. 9948 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 9949 } 9950 9951 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 9952 unsigned Intrinsic) { 9953 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9954 SDValue Op1 = getValue(I.getArgOperand(0)); 9955 SDValue Op2; 9956 if (I.arg_size() > 1) 9957 Op2 = getValue(I.getArgOperand(1)); 9958 SDLoc dl = getCurSDLoc(); 9959 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 9960 SDValue Res; 9961 SDNodeFlags SDFlags; 9962 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 9963 SDFlags.copyFMF(*FPMO); 9964 9965 switch (Intrinsic) { 9966 case Intrinsic::vector_reduce_fadd: 9967 if (SDFlags.hasAllowReassociation()) 9968 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 9969 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 9970 SDFlags); 9971 else 9972 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 9973 break; 9974 case Intrinsic::vector_reduce_fmul: 9975 if (SDFlags.hasAllowReassociation()) 9976 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 9977 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 9978 SDFlags); 9979 else 9980 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 9981 break; 9982 case Intrinsic::vector_reduce_add: 9983 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 9984 break; 9985 case Intrinsic::vector_reduce_mul: 9986 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 9987 break; 9988 case Intrinsic::vector_reduce_and: 9989 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 9990 break; 9991 case Intrinsic::vector_reduce_or: 9992 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 9993 break; 9994 case Intrinsic::vector_reduce_xor: 9995 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 9996 break; 9997 case Intrinsic::vector_reduce_smax: 9998 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 9999 break; 10000 case Intrinsic::vector_reduce_smin: 10001 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 10002 break; 10003 case Intrinsic::vector_reduce_umax: 10004 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 10005 break; 10006 case Intrinsic::vector_reduce_umin: 10007 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 10008 break; 10009 case Intrinsic::vector_reduce_fmax: 10010 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 10011 break; 10012 case Intrinsic::vector_reduce_fmin: 10013 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 10014 break; 10015 case Intrinsic::vector_reduce_fmaximum: 10016 Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags); 10017 break; 10018 case Intrinsic::vector_reduce_fminimum: 10019 Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags); 10020 break; 10021 default: 10022 llvm_unreachable("Unhandled vector reduce intrinsic"); 10023 } 10024 setValue(&I, Res); 10025 } 10026 10027 /// Returns an AttributeList representing the attributes applied to the return 10028 /// value of the given call. 10029 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 10030 SmallVector<Attribute::AttrKind, 2> Attrs; 10031 if (CLI.RetSExt) 10032 Attrs.push_back(Attribute::SExt); 10033 if (CLI.RetZExt) 10034 Attrs.push_back(Attribute::ZExt); 10035 if (CLI.IsInReg) 10036 Attrs.push_back(Attribute::InReg); 10037 10038 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 10039 Attrs); 10040 } 10041 10042 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 10043 /// implementation, which just calls LowerCall. 10044 /// FIXME: When all targets are 10045 /// migrated to using LowerCall, this hook should be integrated into SDISel. 10046 std::pair<SDValue, SDValue> 10047 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 10048 // Handle the incoming return values from the call. 10049 CLI.Ins.clear(); 10050 Type *OrigRetTy = CLI.RetTy; 10051 SmallVector<EVT, 4> RetTys; 10052 SmallVector<uint64_t, 4> Offsets; 10053 auto &DL = CLI.DAG.getDataLayout(); 10054 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets, 0); 10055 10056 if (CLI.IsPostTypeLegalization) { 10057 // If we are lowering a libcall after legalization, split the return type. 10058 SmallVector<EVT, 4> OldRetTys; 10059 SmallVector<uint64_t, 4> OldOffsets; 10060 RetTys.swap(OldRetTys); 10061 Offsets.swap(OldOffsets); 10062 10063 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 10064 EVT RetVT = OldRetTys[i]; 10065 uint64_t Offset = OldOffsets[i]; 10066 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 10067 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 10068 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 10069 RetTys.append(NumRegs, RegisterVT); 10070 for (unsigned j = 0; j != NumRegs; ++j) 10071 Offsets.push_back(Offset + j * RegisterVTByteSZ); 10072 } 10073 } 10074 10075 SmallVector<ISD::OutputArg, 4> Outs; 10076 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 10077 10078 bool CanLowerReturn = 10079 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 10080 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 10081 10082 SDValue DemoteStackSlot; 10083 int DemoteStackIdx = -100; 10084 if (!CanLowerReturn) { 10085 // FIXME: equivalent assert? 10086 // assert(!CS.hasInAllocaArgument() && 10087 // "sret demotion is incompatible with inalloca"); 10088 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 10089 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 10090 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10091 DemoteStackIdx = 10092 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 10093 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 10094 DL.getAllocaAddrSpace()); 10095 10096 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 10097 ArgListEntry Entry; 10098 Entry.Node = DemoteStackSlot; 10099 Entry.Ty = StackSlotPtrType; 10100 Entry.IsSExt = false; 10101 Entry.IsZExt = false; 10102 Entry.IsInReg = false; 10103 Entry.IsSRet = true; 10104 Entry.IsNest = false; 10105 Entry.IsByVal = false; 10106 Entry.IsByRef = false; 10107 Entry.IsReturned = false; 10108 Entry.IsSwiftSelf = false; 10109 Entry.IsSwiftAsync = false; 10110 Entry.IsSwiftError = false; 10111 Entry.IsCFGuardTarget = false; 10112 Entry.Alignment = Alignment; 10113 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 10114 CLI.NumFixedArgs += 1; 10115 CLI.getArgs()[0].IndirectType = CLI.RetTy; 10116 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 10117 10118 // sret demotion isn't compatible with tail-calls, since the sret argument 10119 // points into the callers stack frame. 10120 CLI.IsTailCall = false; 10121 } else { 10122 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10123 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL); 10124 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 10125 ISD::ArgFlagsTy Flags; 10126 if (NeedsRegBlock) { 10127 Flags.setInConsecutiveRegs(); 10128 if (I == RetTys.size() - 1) 10129 Flags.setInConsecutiveRegsLast(); 10130 } 10131 EVT VT = RetTys[I]; 10132 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10133 CLI.CallConv, VT); 10134 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10135 CLI.CallConv, VT); 10136 for (unsigned i = 0; i != NumRegs; ++i) { 10137 ISD::InputArg MyFlags; 10138 MyFlags.Flags = Flags; 10139 MyFlags.VT = RegisterVT; 10140 MyFlags.ArgVT = VT; 10141 MyFlags.Used = CLI.IsReturnValueUsed; 10142 if (CLI.RetTy->isPointerTy()) { 10143 MyFlags.Flags.setPointer(); 10144 MyFlags.Flags.setPointerAddrSpace( 10145 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 10146 } 10147 if (CLI.RetSExt) 10148 MyFlags.Flags.setSExt(); 10149 if (CLI.RetZExt) 10150 MyFlags.Flags.setZExt(); 10151 if (CLI.IsInReg) 10152 MyFlags.Flags.setInReg(); 10153 CLI.Ins.push_back(MyFlags); 10154 } 10155 } 10156 } 10157 10158 // We push in swifterror return as the last element of CLI.Ins. 10159 ArgListTy &Args = CLI.getArgs(); 10160 if (supportSwiftError()) { 10161 for (const ArgListEntry &Arg : Args) { 10162 if (Arg.IsSwiftError) { 10163 ISD::InputArg MyFlags; 10164 MyFlags.VT = getPointerTy(DL); 10165 MyFlags.ArgVT = EVT(getPointerTy(DL)); 10166 MyFlags.Flags.setSwiftError(); 10167 CLI.Ins.push_back(MyFlags); 10168 } 10169 } 10170 } 10171 10172 // Handle all of the outgoing arguments. 10173 CLI.Outs.clear(); 10174 CLI.OutVals.clear(); 10175 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 10176 SmallVector<EVT, 4> ValueVTs; 10177 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 10178 // FIXME: Split arguments if CLI.IsPostTypeLegalization 10179 Type *FinalType = Args[i].Ty; 10180 if (Args[i].IsByVal) 10181 FinalType = Args[i].IndirectType; 10182 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10183 FinalType, CLI.CallConv, CLI.IsVarArg, DL); 10184 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 10185 ++Value) { 10186 EVT VT = ValueVTs[Value]; 10187 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 10188 SDValue Op = SDValue(Args[i].Node.getNode(), 10189 Args[i].Node.getResNo() + Value); 10190 ISD::ArgFlagsTy Flags; 10191 10192 // Certain targets (such as MIPS), may have a different ABI alignment 10193 // for a type depending on the context. Give the target a chance to 10194 // specify the alignment it wants. 10195 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 10196 Flags.setOrigAlign(OriginalAlignment); 10197 10198 if (Args[i].Ty->isPointerTy()) { 10199 Flags.setPointer(); 10200 Flags.setPointerAddrSpace( 10201 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 10202 } 10203 if (Args[i].IsZExt) 10204 Flags.setZExt(); 10205 if (Args[i].IsSExt) 10206 Flags.setSExt(); 10207 if (Args[i].IsInReg) { 10208 // If we are using vectorcall calling convention, a structure that is 10209 // passed InReg - is surely an HVA 10210 if (CLI.CallConv == CallingConv::X86_VectorCall && 10211 isa<StructType>(FinalType)) { 10212 // The first value of a structure is marked 10213 if (0 == Value) 10214 Flags.setHvaStart(); 10215 Flags.setHva(); 10216 } 10217 // Set InReg Flag 10218 Flags.setInReg(); 10219 } 10220 if (Args[i].IsSRet) 10221 Flags.setSRet(); 10222 if (Args[i].IsSwiftSelf) 10223 Flags.setSwiftSelf(); 10224 if (Args[i].IsSwiftAsync) 10225 Flags.setSwiftAsync(); 10226 if (Args[i].IsSwiftError) 10227 Flags.setSwiftError(); 10228 if (Args[i].IsCFGuardTarget) 10229 Flags.setCFGuardTarget(); 10230 if (Args[i].IsByVal) 10231 Flags.setByVal(); 10232 if (Args[i].IsByRef) 10233 Flags.setByRef(); 10234 if (Args[i].IsPreallocated) { 10235 Flags.setPreallocated(); 10236 // Set the byval flag for CCAssignFn callbacks that don't know about 10237 // preallocated. This way we can know how many bytes we should've 10238 // allocated and how many bytes a callee cleanup function will pop. If 10239 // we port preallocated to more targets, we'll have to add custom 10240 // preallocated handling in the various CC lowering callbacks. 10241 Flags.setByVal(); 10242 } 10243 if (Args[i].IsInAlloca) { 10244 Flags.setInAlloca(); 10245 // Set the byval flag for CCAssignFn callbacks that don't know about 10246 // inalloca. This way we can know how many bytes we should've allocated 10247 // and how many bytes a callee cleanup function will pop. If we port 10248 // inalloca to more targets, we'll have to add custom inalloca handling 10249 // in the various CC lowering callbacks. 10250 Flags.setByVal(); 10251 } 10252 Align MemAlign; 10253 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 10254 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType); 10255 Flags.setByValSize(FrameSize); 10256 10257 // info is not there but there are cases it cannot get right. 10258 if (auto MA = Args[i].Alignment) 10259 MemAlign = *MA; 10260 else 10261 MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL)); 10262 } else if (auto MA = Args[i].Alignment) { 10263 MemAlign = *MA; 10264 } else { 10265 MemAlign = OriginalAlignment; 10266 } 10267 Flags.setMemAlign(MemAlign); 10268 if (Args[i].IsNest) 10269 Flags.setNest(); 10270 if (NeedsRegBlock) 10271 Flags.setInConsecutiveRegs(); 10272 10273 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10274 CLI.CallConv, VT); 10275 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10276 CLI.CallConv, VT); 10277 SmallVector<SDValue, 4> Parts(NumParts); 10278 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 10279 10280 if (Args[i].IsSExt) 10281 ExtendKind = ISD::SIGN_EXTEND; 10282 else if (Args[i].IsZExt) 10283 ExtendKind = ISD::ZERO_EXTEND; 10284 10285 // Conservatively only handle 'returned' on non-vectors that can be lowered, 10286 // for now. 10287 if (Args[i].IsReturned && !Op.getValueType().isVector() && 10288 CanLowerReturn) { 10289 assert((CLI.RetTy == Args[i].Ty || 10290 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 10291 CLI.RetTy->getPointerAddressSpace() == 10292 Args[i].Ty->getPointerAddressSpace())) && 10293 RetTys.size() == NumValues && "unexpected use of 'returned'"); 10294 // Before passing 'returned' to the target lowering code, ensure that 10295 // either the register MVT and the actual EVT are the same size or that 10296 // the return value and argument are extended in the same way; in these 10297 // cases it's safe to pass the argument register value unchanged as the 10298 // return register value (although it's at the target's option whether 10299 // to do so) 10300 // TODO: allow code generation to take advantage of partially preserved 10301 // registers rather than clobbering the entire register when the 10302 // parameter extension method is not compatible with the return 10303 // extension method 10304 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 10305 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 10306 CLI.RetZExt == Args[i].IsZExt)) 10307 Flags.setReturned(); 10308 } 10309 10310 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 10311 CLI.CallConv, ExtendKind); 10312 10313 for (unsigned j = 0; j != NumParts; ++j) { 10314 // if it isn't first piece, alignment must be 1 10315 // For scalable vectors the scalable part is currently handled 10316 // by individual targets, so we just use the known minimum size here. 10317 ISD::OutputArg MyFlags( 10318 Flags, Parts[j].getValueType().getSimpleVT(), VT, 10319 i < CLI.NumFixedArgs, i, 10320 j * Parts[j].getValueType().getStoreSize().getKnownMinValue()); 10321 if (NumParts > 1 && j == 0) 10322 MyFlags.Flags.setSplit(); 10323 else if (j != 0) { 10324 MyFlags.Flags.setOrigAlign(Align(1)); 10325 if (j == NumParts - 1) 10326 MyFlags.Flags.setSplitEnd(); 10327 } 10328 10329 CLI.Outs.push_back(MyFlags); 10330 CLI.OutVals.push_back(Parts[j]); 10331 } 10332 10333 if (NeedsRegBlock && Value == NumValues - 1) 10334 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 10335 } 10336 } 10337 10338 SmallVector<SDValue, 4> InVals; 10339 CLI.Chain = LowerCall(CLI, InVals); 10340 10341 // Update CLI.InVals to use outside of this function. 10342 CLI.InVals = InVals; 10343 10344 // Verify that the target's LowerCall behaved as expected. 10345 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 10346 "LowerCall didn't return a valid chain!"); 10347 assert((!CLI.IsTailCall || InVals.empty()) && 10348 "LowerCall emitted a return value for a tail call!"); 10349 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 10350 "LowerCall didn't emit the correct number of values!"); 10351 10352 // For a tail call, the return value is merely live-out and there aren't 10353 // any nodes in the DAG representing it. Return a special value to 10354 // indicate that a tail call has been emitted and no more Instructions 10355 // should be processed in the current block. 10356 if (CLI.IsTailCall) { 10357 CLI.DAG.setRoot(CLI.Chain); 10358 return std::make_pair(SDValue(), SDValue()); 10359 } 10360 10361 #ifndef NDEBUG 10362 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 10363 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 10364 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 10365 "LowerCall emitted a value with the wrong type!"); 10366 } 10367 #endif 10368 10369 SmallVector<SDValue, 4> ReturnValues; 10370 if (!CanLowerReturn) { 10371 // The instruction result is the result of loading from the 10372 // hidden sret parameter. 10373 SmallVector<EVT, 1> PVTs; 10374 Type *PtrRetTy = 10375 PointerType::get(OrigRetTy->getContext(), DL.getAllocaAddrSpace()); 10376 10377 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 10378 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 10379 EVT PtrVT = PVTs[0]; 10380 10381 unsigned NumValues = RetTys.size(); 10382 ReturnValues.resize(NumValues); 10383 SmallVector<SDValue, 4> Chains(NumValues); 10384 10385 // An aggregate return value cannot wrap around the address space, so 10386 // offsets to its parts don't wrap either. 10387 SDNodeFlags Flags; 10388 Flags.setNoUnsignedWrap(true); 10389 10390 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10391 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 10392 for (unsigned i = 0; i < NumValues; ++i) { 10393 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 10394 CLI.DAG.getConstant(Offsets[i], CLI.DL, 10395 PtrVT), Flags); 10396 SDValue L = CLI.DAG.getLoad( 10397 RetTys[i], CLI.DL, CLI.Chain, Add, 10398 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 10399 DemoteStackIdx, Offsets[i]), 10400 HiddenSRetAlign); 10401 ReturnValues[i] = L; 10402 Chains[i] = L.getValue(1); 10403 } 10404 10405 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 10406 } else { 10407 // Collect the legal value parts into potentially illegal values 10408 // that correspond to the original function's return values. 10409 std::optional<ISD::NodeType> AssertOp; 10410 if (CLI.RetSExt) 10411 AssertOp = ISD::AssertSext; 10412 else if (CLI.RetZExt) 10413 AssertOp = ISD::AssertZext; 10414 unsigned CurReg = 0; 10415 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 10416 EVT VT = RetTys[I]; 10417 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10418 CLI.CallConv, VT); 10419 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10420 CLI.CallConv, VT); 10421 10422 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 10423 NumRegs, RegisterVT, VT, nullptr, 10424 CLI.CallConv, AssertOp)); 10425 CurReg += NumRegs; 10426 } 10427 10428 // For a function returning void, there is no return value. We can't create 10429 // such a node, so we just return a null return value in that case. In 10430 // that case, nothing will actually look at the value. 10431 if (ReturnValues.empty()) 10432 return std::make_pair(SDValue(), CLI.Chain); 10433 } 10434 10435 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 10436 CLI.DAG.getVTList(RetTys), ReturnValues); 10437 return std::make_pair(Res, CLI.Chain); 10438 } 10439 10440 /// Places new result values for the node in Results (their number 10441 /// and types must exactly match those of the original return values of 10442 /// the node), or leaves Results empty, which indicates that the node is not 10443 /// to be custom lowered after all. 10444 void TargetLowering::LowerOperationWrapper(SDNode *N, 10445 SmallVectorImpl<SDValue> &Results, 10446 SelectionDAG &DAG) const { 10447 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 10448 10449 if (!Res.getNode()) 10450 return; 10451 10452 // If the original node has one result, take the return value from 10453 // LowerOperation as is. It might not be result number 0. 10454 if (N->getNumValues() == 1) { 10455 Results.push_back(Res); 10456 return; 10457 } 10458 10459 // If the original node has multiple results, then the return node should 10460 // have the same number of results. 10461 assert((N->getNumValues() == Res->getNumValues()) && 10462 "Lowering returned the wrong number of results!"); 10463 10464 // Places new result values base on N result number. 10465 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 10466 Results.push_back(Res.getValue(I)); 10467 } 10468 10469 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10470 llvm_unreachable("LowerOperation not implemented for this target!"); 10471 } 10472 10473 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, 10474 unsigned Reg, 10475 ISD::NodeType ExtendType) { 10476 SDValue Op = getNonRegisterValue(V); 10477 assert((Op.getOpcode() != ISD::CopyFromReg || 10478 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 10479 "Copy from a reg to the same reg!"); 10480 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 10481 10482 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10483 // If this is an InlineAsm we have to match the registers required, not the 10484 // notional registers required by the type. 10485 10486 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 10487 std::nullopt); // This is not an ABI copy. 10488 SDValue Chain = DAG.getEntryNode(); 10489 10490 if (ExtendType == ISD::ANY_EXTEND) { 10491 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V); 10492 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end()) 10493 ExtendType = PreferredExtendIt->second; 10494 } 10495 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 10496 PendingExports.push_back(Chain); 10497 } 10498 10499 #include "llvm/CodeGen/SelectionDAGISel.h" 10500 10501 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 10502 /// entry block, return true. This includes arguments used by switches, since 10503 /// the switch may expand into multiple basic blocks. 10504 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 10505 // With FastISel active, we may be splitting blocks, so force creation 10506 // of virtual registers for all non-dead arguments. 10507 if (FastISel) 10508 return A->use_empty(); 10509 10510 const BasicBlock &Entry = A->getParent()->front(); 10511 for (const User *U : A->users()) 10512 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 10513 return false; // Use not in entry block. 10514 10515 return true; 10516 } 10517 10518 using ArgCopyElisionMapTy = 10519 DenseMap<const Argument *, 10520 std::pair<const AllocaInst *, const StoreInst *>>; 10521 10522 /// Scan the entry block of the function in FuncInfo for arguments that look 10523 /// like copies into a local alloca. Record any copied arguments in 10524 /// ArgCopyElisionCandidates. 10525 static void 10526 findArgumentCopyElisionCandidates(const DataLayout &DL, 10527 FunctionLoweringInfo *FuncInfo, 10528 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 10529 // Record the state of every static alloca used in the entry block. Argument 10530 // allocas are all used in the entry block, so we need approximately as many 10531 // entries as we have arguments. 10532 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 10533 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 10534 unsigned NumArgs = FuncInfo->Fn->arg_size(); 10535 StaticAllocas.reserve(NumArgs * 2); 10536 10537 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 10538 if (!V) 10539 return nullptr; 10540 V = V->stripPointerCasts(); 10541 const auto *AI = dyn_cast<AllocaInst>(V); 10542 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 10543 return nullptr; 10544 auto Iter = StaticAllocas.insert({AI, Unknown}); 10545 return &Iter.first->second; 10546 }; 10547 10548 // Look for stores of arguments to static allocas. Look through bitcasts and 10549 // GEPs to handle type coercions, as long as the alloca is fully initialized 10550 // by the store. Any non-store use of an alloca escapes it and any subsequent 10551 // unanalyzed store might write it. 10552 // FIXME: Handle structs initialized with multiple stores. 10553 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 10554 // Look for stores, and handle non-store uses conservatively. 10555 const auto *SI = dyn_cast<StoreInst>(&I); 10556 if (!SI) { 10557 // We will look through cast uses, so ignore them completely. 10558 if (I.isCast()) 10559 continue; 10560 // Ignore debug info and pseudo op intrinsics, they don't escape or store 10561 // to allocas. 10562 if (I.isDebugOrPseudoInst()) 10563 continue; 10564 // This is an unknown instruction. Assume it escapes or writes to all 10565 // static alloca operands. 10566 for (const Use &U : I.operands()) { 10567 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 10568 *Info = StaticAllocaInfo::Clobbered; 10569 } 10570 continue; 10571 } 10572 10573 // If the stored value is a static alloca, mark it as escaped. 10574 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 10575 *Info = StaticAllocaInfo::Clobbered; 10576 10577 // Check if the destination is a static alloca. 10578 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 10579 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 10580 if (!Info) 10581 continue; 10582 const AllocaInst *AI = cast<AllocaInst>(Dst); 10583 10584 // Skip allocas that have been initialized or clobbered. 10585 if (*Info != StaticAllocaInfo::Unknown) 10586 continue; 10587 10588 // Check if the stored value is an argument, and that this store fully 10589 // initializes the alloca. 10590 // If the argument type has padding bits we can't directly forward a pointer 10591 // as the upper bits may contain garbage. 10592 // Don't elide copies from the same argument twice. 10593 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 10594 const auto *Arg = dyn_cast<Argument>(Val); 10595 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 10596 Arg->getType()->isEmptyTy() || 10597 DL.getTypeStoreSize(Arg->getType()) != 10598 DL.getTypeAllocSize(AI->getAllocatedType()) || 10599 !DL.typeSizeEqualsStoreSize(Arg->getType()) || 10600 ArgCopyElisionCandidates.count(Arg)) { 10601 *Info = StaticAllocaInfo::Clobbered; 10602 continue; 10603 } 10604 10605 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 10606 << '\n'); 10607 10608 // Mark this alloca and store for argument copy elision. 10609 *Info = StaticAllocaInfo::Elidable; 10610 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 10611 10612 // Stop scanning if we've seen all arguments. This will happen early in -O0 10613 // builds, which is useful, because -O0 builds have large entry blocks and 10614 // many allocas. 10615 if (ArgCopyElisionCandidates.size() == NumArgs) 10616 break; 10617 } 10618 } 10619 10620 /// Try to elide argument copies from memory into a local alloca. Succeeds if 10621 /// ArgVal is a load from a suitable fixed stack object. 10622 static void tryToElideArgumentCopy( 10623 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 10624 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 10625 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 10626 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 10627 ArrayRef<SDValue> ArgVals, bool &ArgHasUses) { 10628 // Check if this is a load from a fixed stack object. 10629 auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]); 10630 if (!LNode) 10631 return; 10632 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 10633 if (!FINode) 10634 return; 10635 10636 // Check that the fixed stack object is the right size and alignment. 10637 // Look at the alignment that the user wrote on the alloca instead of looking 10638 // at the stack object. 10639 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 10640 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 10641 const AllocaInst *AI = ArgCopyIter->second.first; 10642 int FixedIndex = FINode->getIndex(); 10643 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 10644 int OldIndex = AllocaIndex; 10645 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 10646 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 10647 LLVM_DEBUG( 10648 dbgs() << " argument copy elision failed due to bad fixed stack " 10649 "object size\n"); 10650 return; 10651 } 10652 Align RequiredAlignment = AI->getAlign(); 10653 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 10654 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 10655 "greater than stack argument alignment (" 10656 << DebugStr(RequiredAlignment) << " vs " 10657 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 10658 return; 10659 } 10660 10661 // Perform the elision. Delete the old stack object and replace its only use 10662 // in the variable info map. Mark the stack object as mutable. 10663 LLVM_DEBUG({ 10664 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 10665 << " Replacing frame index " << OldIndex << " with " << FixedIndex 10666 << '\n'; 10667 }); 10668 MFI.RemoveStackObject(OldIndex); 10669 MFI.setIsImmutableObjectIndex(FixedIndex, false); 10670 AllocaIndex = FixedIndex; 10671 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 10672 for (SDValue ArgVal : ArgVals) 10673 Chains.push_back(ArgVal.getValue(1)); 10674 10675 // Avoid emitting code for the store implementing the copy. 10676 const StoreInst *SI = ArgCopyIter->second.second; 10677 ElidedArgCopyInstrs.insert(SI); 10678 10679 // Check for uses of the argument again so that we can avoid exporting ArgVal 10680 // if it is't used by anything other than the store. 10681 for (const Value *U : Arg.users()) { 10682 if (U != SI) { 10683 ArgHasUses = true; 10684 break; 10685 } 10686 } 10687 } 10688 10689 void SelectionDAGISel::LowerArguments(const Function &F) { 10690 SelectionDAG &DAG = SDB->DAG; 10691 SDLoc dl = SDB->getCurSDLoc(); 10692 const DataLayout &DL = DAG.getDataLayout(); 10693 SmallVector<ISD::InputArg, 16> Ins; 10694 10695 // In Naked functions we aren't going to save any registers. 10696 if (F.hasFnAttribute(Attribute::Naked)) 10697 return; 10698 10699 if (!FuncInfo->CanLowerReturn) { 10700 // Put in an sret pointer parameter before all the other parameters. 10701 SmallVector<EVT, 1> ValueVTs; 10702 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10703 PointerType::get(F.getContext(), 10704 DAG.getDataLayout().getAllocaAddrSpace()), 10705 ValueVTs); 10706 10707 // NOTE: Assuming that a pointer will never break down to more than one VT 10708 // or one register. 10709 ISD::ArgFlagsTy Flags; 10710 Flags.setSRet(); 10711 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 10712 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 10713 ISD::InputArg::NoArgIndex, 0); 10714 Ins.push_back(RetArg); 10715 } 10716 10717 // Look for stores of arguments to static allocas. Mark such arguments with a 10718 // flag to ask the target to give us the memory location of that argument if 10719 // available. 10720 ArgCopyElisionMapTy ArgCopyElisionCandidates; 10721 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 10722 ArgCopyElisionCandidates); 10723 10724 // Set up the incoming argument description vector. 10725 for (const Argument &Arg : F.args()) { 10726 unsigned ArgNo = Arg.getArgNo(); 10727 SmallVector<EVT, 4> ValueVTs; 10728 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10729 bool isArgValueUsed = !Arg.use_empty(); 10730 unsigned PartBase = 0; 10731 Type *FinalType = Arg.getType(); 10732 if (Arg.hasAttribute(Attribute::ByVal)) 10733 FinalType = Arg.getParamByValType(); 10734 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 10735 FinalType, F.getCallingConv(), F.isVarArg(), DL); 10736 for (unsigned Value = 0, NumValues = ValueVTs.size(); 10737 Value != NumValues; ++Value) { 10738 EVT VT = ValueVTs[Value]; 10739 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 10740 ISD::ArgFlagsTy Flags; 10741 10742 10743 if (Arg.getType()->isPointerTy()) { 10744 Flags.setPointer(); 10745 Flags.setPointerAddrSpace( 10746 cast<PointerType>(Arg.getType())->getAddressSpace()); 10747 } 10748 if (Arg.hasAttribute(Attribute::ZExt)) 10749 Flags.setZExt(); 10750 if (Arg.hasAttribute(Attribute::SExt)) 10751 Flags.setSExt(); 10752 if (Arg.hasAttribute(Attribute::InReg)) { 10753 // If we are using vectorcall calling convention, a structure that is 10754 // passed InReg - is surely an HVA 10755 if (F.getCallingConv() == CallingConv::X86_VectorCall && 10756 isa<StructType>(Arg.getType())) { 10757 // The first value of a structure is marked 10758 if (0 == Value) 10759 Flags.setHvaStart(); 10760 Flags.setHva(); 10761 } 10762 // Set InReg Flag 10763 Flags.setInReg(); 10764 } 10765 if (Arg.hasAttribute(Attribute::StructRet)) 10766 Flags.setSRet(); 10767 if (Arg.hasAttribute(Attribute::SwiftSelf)) 10768 Flags.setSwiftSelf(); 10769 if (Arg.hasAttribute(Attribute::SwiftAsync)) 10770 Flags.setSwiftAsync(); 10771 if (Arg.hasAttribute(Attribute::SwiftError)) 10772 Flags.setSwiftError(); 10773 if (Arg.hasAttribute(Attribute::ByVal)) 10774 Flags.setByVal(); 10775 if (Arg.hasAttribute(Attribute::ByRef)) 10776 Flags.setByRef(); 10777 if (Arg.hasAttribute(Attribute::InAlloca)) { 10778 Flags.setInAlloca(); 10779 // Set the byval flag for CCAssignFn callbacks that don't know about 10780 // inalloca. This way we can know how many bytes we should've allocated 10781 // and how many bytes a callee cleanup function will pop. If we port 10782 // inalloca to more targets, we'll have to add custom inalloca handling 10783 // in the various CC lowering callbacks. 10784 Flags.setByVal(); 10785 } 10786 if (Arg.hasAttribute(Attribute::Preallocated)) { 10787 Flags.setPreallocated(); 10788 // Set the byval flag for CCAssignFn callbacks that don't know about 10789 // preallocated. This way we can know how many bytes we should've 10790 // allocated and how many bytes a callee cleanup function will pop. If 10791 // we port preallocated to more targets, we'll have to add custom 10792 // preallocated handling in the various CC lowering callbacks. 10793 Flags.setByVal(); 10794 } 10795 10796 // Certain targets (such as MIPS), may have a different ABI alignment 10797 // for a type depending on the context. Give the target a chance to 10798 // specify the alignment it wants. 10799 const Align OriginalAlignment( 10800 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 10801 Flags.setOrigAlign(OriginalAlignment); 10802 10803 Align MemAlign; 10804 Type *ArgMemTy = nullptr; 10805 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 10806 Flags.isByRef()) { 10807 if (!ArgMemTy) 10808 ArgMemTy = Arg.getPointeeInMemoryValueType(); 10809 10810 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 10811 10812 // For in-memory arguments, size and alignment should be passed from FE. 10813 // BE will guess if this info is not there but there are cases it cannot 10814 // get right. 10815 if (auto ParamAlign = Arg.getParamStackAlign()) 10816 MemAlign = *ParamAlign; 10817 else if ((ParamAlign = Arg.getParamAlign())) 10818 MemAlign = *ParamAlign; 10819 else 10820 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 10821 if (Flags.isByRef()) 10822 Flags.setByRefSize(MemSize); 10823 else 10824 Flags.setByValSize(MemSize); 10825 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 10826 MemAlign = *ParamAlign; 10827 } else { 10828 MemAlign = OriginalAlignment; 10829 } 10830 Flags.setMemAlign(MemAlign); 10831 10832 if (Arg.hasAttribute(Attribute::Nest)) 10833 Flags.setNest(); 10834 if (NeedsRegBlock) 10835 Flags.setInConsecutiveRegs(); 10836 if (ArgCopyElisionCandidates.count(&Arg)) 10837 Flags.setCopyElisionCandidate(); 10838 if (Arg.hasAttribute(Attribute::Returned)) 10839 Flags.setReturned(); 10840 10841 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 10842 *CurDAG->getContext(), F.getCallingConv(), VT); 10843 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 10844 *CurDAG->getContext(), F.getCallingConv(), VT); 10845 for (unsigned i = 0; i != NumRegs; ++i) { 10846 // For scalable vectors, use the minimum size; individual targets 10847 // are responsible for handling scalable vector arguments and 10848 // return values. 10849 ISD::InputArg MyFlags( 10850 Flags, RegisterVT, VT, isArgValueUsed, ArgNo, 10851 PartBase + i * RegisterVT.getStoreSize().getKnownMinValue()); 10852 if (NumRegs > 1 && i == 0) 10853 MyFlags.Flags.setSplit(); 10854 // if it isn't first piece, alignment must be 1 10855 else if (i > 0) { 10856 MyFlags.Flags.setOrigAlign(Align(1)); 10857 if (i == NumRegs - 1) 10858 MyFlags.Flags.setSplitEnd(); 10859 } 10860 Ins.push_back(MyFlags); 10861 } 10862 if (NeedsRegBlock && Value == NumValues - 1) 10863 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 10864 PartBase += VT.getStoreSize().getKnownMinValue(); 10865 } 10866 } 10867 10868 // Call the target to set up the argument values. 10869 SmallVector<SDValue, 8> InVals; 10870 SDValue NewRoot = TLI->LowerFormalArguments( 10871 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 10872 10873 // Verify that the target's LowerFormalArguments behaved as expected. 10874 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 10875 "LowerFormalArguments didn't return a valid chain!"); 10876 assert(InVals.size() == Ins.size() && 10877 "LowerFormalArguments didn't emit the correct number of values!"); 10878 LLVM_DEBUG({ 10879 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 10880 assert(InVals[i].getNode() && 10881 "LowerFormalArguments emitted a null value!"); 10882 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 10883 "LowerFormalArguments emitted a value with the wrong type!"); 10884 } 10885 }); 10886 10887 // Update the DAG with the new chain value resulting from argument lowering. 10888 DAG.setRoot(NewRoot); 10889 10890 // Set up the argument values. 10891 unsigned i = 0; 10892 if (!FuncInfo->CanLowerReturn) { 10893 // Create a virtual register for the sret pointer, and put in a copy 10894 // from the sret argument into it. 10895 SmallVector<EVT, 1> ValueVTs; 10896 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10897 PointerType::get(F.getContext(), 10898 DAG.getDataLayout().getAllocaAddrSpace()), 10899 ValueVTs); 10900 MVT VT = ValueVTs[0].getSimpleVT(); 10901 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 10902 std::optional<ISD::NodeType> AssertOp; 10903 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 10904 nullptr, F.getCallingConv(), AssertOp); 10905 10906 MachineFunction& MF = SDB->DAG.getMachineFunction(); 10907 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 10908 Register SRetReg = 10909 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 10910 FuncInfo->DemoteRegister = SRetReg; 10911 NewRoot = 10912 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 10913 DAG.setRoot(NewRoot); 10914 10915 // i indexes lowered arguments. Bump it past the hidden sret argument. 10916 ++i; 10917 } 10918 10919 SmallVector<SDValue, 4> Chains; 10920 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 10921 for (const Argument &Arg : F.args()) { 10922 SmallVector<SDValue, 4> ArgValues; 10923 SmallVector<EVT, 4> ValueVTs; 10924 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10925 unsigned NumValues = ValueVTs.size(); 10926 if (NumValues == 0) 10927 continue; 10928 10929 bool ArgHasUses = !Arg.use_empty(); 10930 10931 // Elide the copying store if the target loaded this argument from a 10932 // suitable fixed stack object. 10933 if (Ins[i].Flags.isCopyElisionCandidate()) { 10934 unsigned NumParts = 0; 10935 for (EVT VT : ValueVTs) 10936 NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), 10937 F.getCallingConv(), VT); 10938 10939 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 10940 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 10941 ArrayRef(&InVals[i], NumParts), ArgHasUses); 10942 } 10943 10944 // If this argument is unused then remember its value. It is used to generate 10945 // debugging information. 10946 bool isSwiftErrorArg = 10947 TLI->supportSwiftError() && 10948 Arg.hasAttribute(Attribute::SwiftError); 10949 if (!ArgHasUses && !isSwiftErrorArg) { 10950 SDB->setUnusedArgValue(&Arg, InVals[i]); 10951 10952 // Also remember any frame index for use in FastISel. 10953 if (FrameIndexSDNode *FI = 10954 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 10955 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10956 } 10957 10958 for (unsigned Val = 0; Val != NumValues; ++Val) { 10959 EVT VT = ValueVTs[Val]; 10960 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 10961 F.getCallingConv(), VT); 10962 unsigned NumParts = TLI->getNumRegistersForCallingConv( 10963 *CurDAG->getContext(), F.getCallingConv(), VT); 10964 10965 // Even an apparent 'unused' swifterror argument needs to be returned. So 10966 // we do generate a copy for it that can be used on return from the 10967 // function. 10968 if (ArgHasUses || isSwiftErrorArg) { 10969 std::optional<ISD::NodeType> AssertOp; 10970 if (Arg.hasAttribute(Attribute::SExt)) 10971 AssertOp = ISD::AssertSext; 10972 else if (Arg.hasAttribute(Attribute::ZExt)) 10973 AssertOp = ISD::AssertZext; 10974 10975 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 10976 PartVT, VT, nullptr, 10977 F.getCallingConv(), AssertOp)); 10978 } 10979 10980 i += NumParts; 10981 } 10982 10983 // We don't need to do anything else for unused arguments. 10984 if (ArgValues.empty()) 10985 continue; 10986 10987 // Note down frame index. 10988 if (FrameIndexSDNode *FI = 10989 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 10990 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10991 10992 SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues), 10993 SDB->getCurSDLoc()); 10994 10995 SDB->setValue(&Arg, Res); 10996 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 10997 // We want to associate the argument with the frame index, among 10998 // involved operands, that correspond to the lowest address. The 10999 // getCopyFromParts function, called earlier, is swapping the order of 11000 // the operands to BUILD_PAIR depending on endianness. The result of 11001 // that swapping is that the least significant bits of the argument will 11002 // be in the first operand of the BUILD_PAIR node, and the most 11003 // significant bits will be in the second operand. 11004 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 11005 if (LoadSDNode *LNode = 11006 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 11007 if (FrameIndexSDNode *FI = 11008 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 11009 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11010 } 11011 11012 // Analyses past this point are naive and don't expect an assertion. 11013 if (Res.getOpcode() == ISD::AssertZext) 11014 Res = Res.getOperand(0); 11015 11016 // Update the SwiftErrorVRegDefMap. 11017 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 11018 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 11019 if (Register::isVirtualRegister(Reg)) 11020 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 11021 Reg); 11022 } 11023 11024 // If this argument is live outside of the entry block, insert a copy from 11025 // wherever we got it to the vreg that other BB's will reference it as. 11026 if (Res.getOpcode() == ISD::CopyFromReg) { 11027 // If we can, though, try to skip creating an unnecessary vreg. 11028 // FIXME: This isn't very clean... it would be nice to make this more 11029 // general. 11030 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 11031 if (Register::isVirtualRegister(Reg)) { 11032 FuncInfo->ValueMap[&Arg] = Reg; 11033 continue; 11034 } 11035 } 11036 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 11037 FuncInfo->InitializeRegForValue(&Arg); 11038 SDB->CopyToExportRegsIfNeeded(&Arg); 11039 } 11040 } 11041 11042 if (!Chains.empty()) { 11043 Chains.push_back(NewRoot); 11044 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 11045 } 11046 11047 DAG.setRoot(NewRoot); 11048 11049 assert(i == InVals.size() && "Argument register count mismatch!"); 11050 11051 // If any argument copy elisions occurred and we have debug info, update the 11052 // stale frame indices used in the dbg.declare variable info table. 11053 if (!ArgCopyElisionFrameIndexMap.empty()) { 11054 for (MachineFunction::VariableDbgInfo &VI : 11055 MF->getInStackSlotVariableDbgInfo()) { 11056 auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot()); 11057 if (I != ArgCopyElisionFrameIndexMap.end()) 11058 VI.updateStackSlot(I->second); 11059 } 11060 } 11061 11062 // Finally, if the target has anything special to do, allow it to do so. 11063 emitFunctionEntryCode(); 11064 } 11065 11066 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 11067 /// ensure constants are generated when needed. Remember the virtual registers 11068 /// that need to be added to the Machine PHI nodes as input. We cannot just 11069 /// directly add them, because expansion might result in multiple MBB's for one 11070 /// BB. As such, the start of the BB might correspond to a different MBB than 11071 /// the end. 11072 void 11073 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 11074 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11075 11076 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 11077 11078 // Check PHI nodes in successors that expect a value to be available from this 11079 // block. 11080 for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) { 11081 if (!isa<PHINode>(SuccBB->begin())) continue; 11082 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 11083 11084 // If this terminator has multiple identical successors (common for 11085 // switches), only handle each succ once. 11086 if (!SuccsHandled.insert(SuccMBB).second) 11087 continue; 11088 11089 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 11090 11091 // At this point we know that there is a 1-1 correspondence between LLVM PHI 11092 // nodes and Machine PHI nodes, but the incoming operands have not been 11093 // emitted yet. 11094 for (const PHINode &PN : SuccBB->phis()) { 11095 // Ignore dead phi's. 11096 if (PN.use_empty()) 11097 continue; 11098 11099 // Skip empty types 11100 if (PN.getType()->isEmptyTy()) 11101 continue; 11102 11103 unsigned Reg; 11104 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 11105 11106 if (const auto *C = dyn_cast<Constant>(PHIOp)) { 11107 unsigned &RegOut = ConstantsOut[C]; 11108 if (RegOut == 0) { 11109 RegOut = FuncInfo.CreateRegs(C); 11110 // We need to zero/sign extend ConstantInt phi operands to match 11111 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo. 11112 ISD::NodeType ExtendType = ISD::ANY_EXTEND; 11113 if (auto *CI = dyn_cast<ConstantInt>(C)) 11114 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND 11115 : ISD::ZERO_EXTEND; 11116 CopyValueToVirtualRegister(C, RegOut, ExtendType); 11117 } 11118 Reg = RegOut; 11119 } else { 11120 DenseMap<const Value *, Register>::iterator I = 11121 FuncInfo.ValueMap.find(PHIOp); 11122 if (I != FuncInfo.ValueMap.end()) 11123 Reg = I->second; 11124 else { 11125 assert(isa<AllocaInst>(PHIOp) && 11126 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 11127 "Didn't codegen value into a register!??"); 11128 Reg = FuncInfo.CreateRegs(PHIOp); 11129 CopyValueToVirtualRegister(PHIOp, Reg); 11130 } 11131 } 11132 11133 // Remember that this register needs to added to the machine PHI node as 11134 // the input for this MBB. 11135 SmallVector<EVT, 4> ValueVTs; 11136 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 11137 for (EVT VT : ValueVTs) { 11138 const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 11139 for (unsigned i = 0; i != NumRegisters; ++i) 11140 FuncInfo.PHINodesToUpdate.push_back( 11141 std::make_pair(&*MBBI++, Reg + i)); 11142 Reg += NumRegisters; 11143 } 11144 } 11145 } 11146 11147 ConstantsOut.clear(); 11148 } 11149 11150 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 11151 MachineFunction::iterator I(MBB); 11152 if (++I == FuncInfo.MF->end()) 11153 return nullptr; 11154 return &*I; 11155 } 11156 11157 /// During lowering new call nodes can be created (such as memset, etc.). 11158 /// Those will become new roots of the current DAG, but complications arise 11159 /// when they are tail calls. In such cases, the call lowering will update 11160 /// the root, but the builder still needs to know that a tail call has been 11161 /// lowered in order to avoid generating an additional return. 11162 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 11163 // If the node is null, we do have a tail call. 11164 if (MaybeTC.getNode() != nullptr) 11165 DAG.setRoot(MaybeTC); 11166 else 11167 HasTailCall = true; 11168 } 11169 11170 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 11171 MachineBasicBlock *SwitchMBB, 11172 MachineBasicBlock *DefaultMBB) { 11173 MachineFunction *CurMF = FuncInfo.MF; 11174 MachineBasicBlock *NextMBB = nullptr; 11175 MachineFunction::iterator BBI(W.MBB); 11176 if (++BBI != FuncInfo.MF->end()) 11177 NextMBB = &*BBI; 11178 11179 unsigned Size = W.LastCluster - W.FirstCluster + 1; 11180 11181 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11182 11183 if (Size == 2 && W.MBB == SwitchMBB) { 11184 // If any two of the cases has the same destination, and if one value 11185 // is the same as the other, but has one bit unset that the other has set, 11186 // use bit manipulation to do two compares at once. For example: 11187 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 11188 // TODO: This could be extended to merge any 2 cases in switches with 3 11189 // cases. 11190 // TODO: Handle cases where W.CaseBB != SwitchBB. 11191 CaseCluster &Small = *W.FirstCluster; 11192 CaseCluster &Big = *W.LastCluster; 11193 11194 if (Small.Low == Small.High && Big.Low == Big.High && 11195 Small.MBB == Big.MBB) { 11196 const APInt &SmallValue = Small.Low->getValue(); 11197 const APInt &BigValue = Big.Low->getValue(); 11198 11199 // Check that there is only one bit different. 11200 APInt CommonBit = BigValue ^ SmallValue; 11201 if (CommonBit.isPowerOf2()) { 11202 SDValue CondLHS = getValue(Cond); 11203 EVT VT = CondLHS.getValueType(); 11204 SDLoc DL = getCurSDLoc(); 11205 11206 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 11207 DAG.getConstant(CommonBit, DL, VT)); 11208 SDValue Cond = DAG.getSetCC( 11209 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 11210 ISD::SETEQ); 11211 11212 // Update successor info. 11213 // Both Small and Big will jump to Small.BB, so we sum up the 11214 // probabilities. 11215 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 11216 if (BPI) 11217 addSuccessorWithProb( 11218 SwitchMBB, DefaultMBB, 11219 // The default destination is the first successor in IR. 11220 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 11221 else 11222 addSuccessorWithProb(SwitchMBB, DefaultMBB); 11223 11224 // Insert the true branch. 11225 SDValue BrCond = 11226 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 11227 DAG.getBasicBlock(Small.MBB)); 11228 // Insert the false branch. 11229 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 11230 DAG.getBasicBlock(DefaultMBB)); 11231 11232 DAG.setRoot(BrCond); 11233 return; 11234 } 11235 } 11236 } 11237 11238 if (TM.getOptLevel() != CodeGenOpt::None) { 11239 // Here, we order cases by probability so the most likely case will be 11240 // checked first. However, two clusters can have the same probability in 11241 // which case their relative ordering is non-deterministic. So we use Low 11242 // as a tie-breaker as clusters are guaranteed to never overlap. 11243 llvm::sort(W.FirstCluster, W.LastCluster + 1, 11244 [](const CaseCluster &a, const CaseCluster &b) { 11245 return a.Prob != b.Prob ? 11246 a.Prob > b.Prob : 11247 a.Low->getValue().slt(b.Low->getValue()); 11248 }); 11249 11250 // Rearrange the case blocks so that the last one falls through if possible 11251 // without changing the order of probabilities. 11252 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 11253 --I; 11254 if (I->Prob > W.LastCluster->Prob) 11255 break; 11256 if (I->Kind == CC_Range && I->MBB == NextMBB) { 11257 std::swap(*I, *W.LastCluster); 11258 break; 11259 } 11260 } 11261 } 11262 11263 // Compute total probability. 11264 BranchProbability DefaultProb = W.DefaultProb; 11265 BranchProbability UnhandledProbs = DefaultProb; 11266 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 11267 UnhandledProbs += I->Prob; 11268 11269 MachineBasicBlock *CurMBB = W.MBB; 11270 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 11271 bool FallthroughUnreachable = false; 11272 MachineBasicBlock *Fallthrough; 11273 if (I == W.LastCluster) { 11274 // For the last cluster, fall through to the default destination. 11275 Fallthrough = DefaultMBB; 11276 FallthroughUnreachable = isa<UnreachableInst>( 11277 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 11278 } else { 11279 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 11280 CurMF->insert(BBI, Fallthrough); 11281 // Put Cond in a virtual register to make it available from the new blocks. 11282 ExportFromCurrentBlock(Cond); 11283 } 11284 UnhandledProbs -= I->Prob; 11285 11286 switch (I->Kind) { 11287 case CC_JumpTable: { 11288 // FIXME: Optimize away range check based on pivot comparisons. 11289 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 11290 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 11291 11292 // The jump block hasn't been inserted yet; insert it here. 11293 MachineBasicBlock *JumpMBB = JT->MBB; 11294 CurMF->insert(BBI, JumpMBB); 11295 11296 auto JumpProb = I->Prob; 11297 auto FallthroughProb = UnhandledProbs; 11298 11299 // If the default statement is a target of the jump table, we evenly 11300 // distribute the default probability to successors of CurMBB. Also 11301 // update the probability on the edge from JumpMBB to Fallthrough. 11302 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 11303 SE = JumpMBB->succ_end(); 11304 SI != SE; ++SI) { 11305 if (*SI == DefaultMBB) { 11306 JumpProb += DefaultProb / 2; 11307 FallthroughProb -= DefaultProb / 2; 11308 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 11309 JumpMBB->normalizeSuccProbs(); 11310 break; 11311 } 11312 } 11313 11314 // If the default clause is unreachable, propagate that knowledge into 11315 // JTH->FallthroughUnreachable which will use it to suppress the range 11316 // check. 11317 // 11318 // However, don't do this if we're doing branch target enforcement, 11319 // because a table branch _without_ a range check can be a tempting JOP 11320 // gadget - out-of-bounds inputs that are impossible in correct 11321 // execution become possible again if an attacker can influence the 11322 // control flow. So if an attacker doesn't already have a BTI bypass 11323 // available, we don't want them to be able to get one out of this 11324 // table branch. 11325 if (FallthroughUnreachable) { 11326 Function &CurFunc = CurMF->getFunction(); 11327 bool HasBranchTargetEnforcement = false; 11328 if (CurFunc.hasFnAttribute("branch-target-enforcement")) { 11329 HasBranchTargetEnforcement = 11330 CurFunc.getFnAttribute("branch-target-enforcement") 11331 .getValueAsBool(); 11332 } else { 11333 HasBranchTargetEnforcement = 11334 CurMF->getMMI().getModule()->getModuleFlag( 11335 "branch-target-enforcement"); 11336 } 11337 if (!HasBranchTargetEnforcement) 11338 JTH->FallthroughUnreachable = true; 11339 } 11340 11341 if (!JTH->FallthroughUnreachable) 11342 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 11343 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 11344 CurMBB->normalizeSuccProbs(); 11345 11346 // The jump table header will be inserted in our current block, do the 11347 // range check, and fall through to our fallthrough block. 11348 JTH->HeaderBB = CurMBB; 11349 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 11350 11351 // If we're in the right place, emit the jump table header right now. 11352 if (CurMBB == SwitchMBB) { 11353 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 11354 JTH->Emitted = true; 11355 } 11356 break; 11357 } 11358 case CC_BitTests: { 11359 // FIXME: Optimize away range check based on pivot comparisons. 11360 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 11361 11362 // The bit test blocks haven't been inserted yet; insert them here. 11363 for (BitTestCase &BTC : BTB->Cases) 11364 CurMF->insert(BBI, BTC.ThisBB); 11365 11366 // Fill in fields of the BitTestBlock. 11367 BTB->Parent = CurMBB; 11368 BTB->Default = Fallthrough; 11369 11370 BTB->DefaultProb = UnhandledProbs; 11371 // If the cases in bit test don't form a contiguous range, we evenly 11372 // distribute the probability on the edge to Fallthrough to two 11373 // successors of CurMBB. 11374 if (!BTB->ContiguousRange) { 11375 BTB->Prob += DefaultProb / 2; 11376 BTB->DefaultProb -= DefaultProb / 2; 11377 } 11378 11379 if (FallthroughUnreachable) 11380 BTB->FallthroughUnreachable = true; 11381 11382 // If we're in the right place, emit the bit test header right now. 11383 if (CurMBB == SwitchMBB) { 11384 visitBitTestHeader(*BTB, SwitchMBB); 11385 BTB->Emitted = true; 11386 } 11387 break; 11388 } 11389 case CC_Range: { 11390 const Value *RHS, *LHS, *MHS; 11391 ISD::CondCode CC; 11392 if (I->Low == I->High) { 11393 // Check Cond == I->Low. 11394 CC = ISD::SETEQ; 11395 LHS = Cond; 11396 RHS=I->Low; 11397 MHS = nullptr; 11398 } else { 11399 // Check I->Low <= Cond <= I->High. 11400 CC = ISD::SETLE; 11401 LHS = I->Low; 11402 MHS = Cond; 11403 RHS = I->High; 11404 } 11405 11406 // If Fallthrough is unreachable, fold away the comparison. 11407 if (FallthroughUnreachable) 11408 CC = ISD::SETTRUE; 11409 11410 // The false probability is the sum of all unhandled cases. 11411 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 11412 getCurSDLoc(), I->Prob, UnhandledProbs); 11413 11414 if (CurMBB == SwitchMBB) 11415 visitSwitchCase(CB, SwitchMBB); 11416 else 11417 SL->SwitchCases.push_back(CB); 11418 11419 break; 11420 } 11421 } 11422 CurMBB = Fallthrough; 11423 } 11424 } 11425 11426 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 11427 CaseClusterIt First, 11428 CaseClusterIt Last) { 11429 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 11430 if (X.Prob != CC.Prob) 11431 return X.Prob > CC.Prob; 11432 11433 // Ties are broken by comparing the case value. 11434 return X.Low->getValue().slt(CC.Low->getValue()); 11435 }); 11436 } 11437 11438 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 11439 const SwitchWorkListItem &W, 11440 Value *Cond, 11441 MachineBasicBlock *SwitchMBB) { 11442 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 11443 "Clusters not sorted?"); 11444 11445 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 11446 11447 // Balance the tree based on branch probabilities to create a near-optimal (in 11448 // terms of search time given key frequency) binary search tree. See e.g. Kurt 11449 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 11450 CaseClusterIt LastLeft = W.FirstCluster; 11451 CaseClusterIt FirstRight = W.LastCluster; 11452 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 11453 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 11454 11455 // Move LastLeft and FirstRight towards each other from opposite directions to 11456 // find a partitioning of the clusters which balances the probability on both 11457 // sides. If LeftProb and RightProb are equal, alternate which side is 11458 // taken to ensure 0-probability nodes are distributed evenly. 11459 unsigned I = 0; 11460 while (LastLeft + 1 < FirstRight) { 11461 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 11462 LeftProb += (++LastLeft)->Prob; 11463 else 11464 RightProb += (--FirstRight)->Prob; 11465 I++; 11466 } 11467 11468 while (true) { 11469 // Our binary search tree differs from a typical BST in that ours can have up 11470 // to three values in each leaf. The pivot selection above doesn't take that 11471 // into account, which means the tree might require more nodes and be less 11472 // efficient. We compensate for this here. 11473 11474 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 11475 unsigned NumRight = W.LastCluster - FirstRight + 1; 11476 11477 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 11478 // If one side has less than 3 clusters, and the other has more than 3, 11479 // consider taking a cluster from the other side. 11480 11481 if (NumLeft < NumRight) { 11482 // Consider moving the first cluster on the right to the left side. 11483 CaseCluster &CC = *FirstRight; 11484 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11485 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11486 if (LeftSideRank <= RightSideRank) { 11487 // Moving the cluster to the left does not demote it. 11488 ++LastLeft; 11489 ++FirstRight; 11490 continue; 11491 } 11492 } else { 11493 assert(NumRight < NumLeft); 11494 // Consider moving the last element on the left to the right side. 11495 CaseCluster &CC = *LastLeft; 11496 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11497 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11498 if (RightSideRank <= LeftSideRank) { 11499 // Moving the cluster to the right does not demot it. 11500 --LastLeft; 11501 --FirstRight; 11502 continue; 11503 } 11504 } 11505 } 11506 break; 11507 } 11508 11509 assert(LastLeft + 1 == FirstRight); 11510 assert(LastLeft >= W.FirstCluster); 11511 assert(FirstRight <= W.LastCluster); 11512 11513 // Use the first element on the right as pivot since we will make less-than 11514 // comparisons against it. 11515 CaseClusterIt PivotCluster = FirstRight; 11516 assert(PivotCluster > W.FirstCluster); 11517 assert(PivotCluster <= W.LastCluster); 11518 11519 CaseClusterIt FirstLeft = W.FirstCluster; 11520 CaseClusterIt LastRight = W.LastCluster; 11521 11522 const ConstantInt *Pivot = PivotCluster->Low; 11523 11524 // New blocks will be inserted immediately after the current one. 11525 MachineFunction::iterator BBI(W.MBB); 11526 ++BBI; 11527 11528 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 11529 // we can branch to its destination directly if it's squeezed exactly in 11530 // between the known lower bound and Pivot - 1. 11531 MachineBasicBlock *LeftMBB; 11532 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 11533 FirstLeft->Low == W.GE && 11534 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 11535 LeftMBB = FirstLeft->MBB; 11536 } else { 11537 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11538 FuncInfo.MF->insert(BBI, LeftMBB); 11539 WorkList.push_back( 11540 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 11541 // Put Cond in a virtual register to make it available from the new blocks. 11542 ExportFromCurrentBlock(Cond); 11543 } 11544 11545 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 11546 // single cluster, RHS.Low == Pivot, and we can branch to its destination 11547 // directly if RHS.High equals the current upper bound. 11548 MachineBasicBlock *RightMBB; 11549 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 11550 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 11551 RightMBB = FirstRight->MBB; 11552 } else { 11553 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11554 FuncInfo.MF->insert(BBI, RightMBB); 11555 WorkList.push_back( 11556 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 11557 // Put Cond in a virtual register to make it available from the new blocks. 11558 ExportFromCurrentBlock(Cond); 11559 } 11560 11561 // Create the CaseBlock record that will be used to lower the branch. 11562 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 11563 getCurSDLoc(), LeftProb, RightProb); 11564 11565 if (W.MBB == SwitchMBB) 11566 visitSwitchCase(CB, SwitchMBB); 11567 else 11568 SL->SwitchCases.push_back(CB); 11569 } 11570 11571 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 11572 // from the swith statement. 11573 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 11574 BranchProbability PeeledCaseProb) { 11575 if (PeeledCaseProb == BranchProbability::getOne()) 11576 return BranchProbability::getZero(); 11577 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 11578 11579 uint32_t Numerator = CaseProb.getNumerator(); 11580 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 11581 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 11582 } 11583 11584 // Try to peel the top probability case if it exceeds the threshold. 11585 // Return current MachineBasicBlock for the switch statement if the peeling 11586 // does not occur. 11587 // If the peeling is performed, return the newly created MachineBasicBlock 11588 // for the peeled switch statement. Also update Clusters to remove the peeled 11589 // case. PeeledCaseProb is the BranchProbability for the peeled case. 11590 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 11591 const SwitchInst &SI, CaseClusterVector &Clusters, 11592 BranchProbability &PeeledCaseProb) { 11593 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11594 // Don't perform if there is only one cluster or optimizing for size. 11595 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 11596 TM.getOptLevel() == CodeGenOpt::None || 11597 SwitchMBB->getParent()->getFunction().hasMinSize()) 11598 return SwitchMBB; 11599 11600 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 11601 unsigned PeeledCaseIndex = 0; 11602 bool SwitchPeeled = false; 11603 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 11604 CaseCluster &CC = Clusters[Index]; 11605 if (CC.Prob < TopCaseProb) 11606 continue; 11607 TopCaseProb = CC.Prob; 11608 PeeledCaseIndex = Index; 11609 SwitchPeeled = true; 11610 } 11611 if (!SwitchPeeled) 11612 return SwitchMBB; 11613 11614 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 11615 << TopCaseProb << "\n"); 11616 11617 // Record the MBB for the peeled switch statement. 11618 MachineFunction::iterator BBI(SwitchMBB); 11619 ++BBI; 11620 MachineBasicBlock *PeeledSwitchMBB = 11621 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 11622 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 11623 11624 ExportFromCurrentBlock(SI.getCondition()); 11625 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 11626 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 11627 nullptr, nullptr, TopCaseProb.getCompl()}; 11628 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 11629 11630 Clusters.erase(PeeledCaseIt); 11631 for (CaseCluster &CC : Clusters) { 11632 LLVM_DEBUG( 11633 dbgs() << "Scale the probablity for one cluster, before scaling: " 11634 << CC.Prob << "\n"); 11635 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 11636 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 11637 } 11638 PeeledCaseProb = TopCaseProb; 11639 return PeeledSwitchMBB; 11640 } 11641 11642 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 11643 // Extract cases from the switch. 11644 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11645 CaseClusterVector Clusters; 11646 Clusters.reserve(SI.getNumCases()); 11647 for (auto I : SI.cases()) { 11648 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 11649 const ConstantInt *CaseVal = I.getCaseValue(); 11650 BranchProbability Prob = 11651 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 11652 : BranchProbability(1, SI.getNumCases() + 1); 11653 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 11654 } 11655 11656 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 11657 11658 // Cluster adjacent cases with the same destination. We do this at all 11659 // optimization levels because it's cheap to do and will make codegen faster 11660 // if there are many clusters. 11661 sortAndRangeify(Clusters); 11662 11663 // The branch probablity of the peeled case. 11664 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 11665 MachineBasicBlock *PeeledSwitchMBB = 11666 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 11667 11668 // If there is only the default destination, jump there directly. 11669 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11670 if (Clusters.empty()) { 11671 assert(PeeledSwitchMBB == SwitchMBB); 11672 SwitchMBB->addSuccessor(DefaultMBB); 11673 if (DefaultMBB != NextBlock(SwitchMBB)) { 11674 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 11675 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 11676 } 11677 return; 11678 } 11679 11680 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 11681 SL->findBitTestClusters(Clusters, &SI); 11682 11683 LLVM_DEBUG({ 11684 dbgs() << "Case clusters: "; 11685 for (const CaseCluster &C : Clusters) { 11686 if (C.Kind == CC_JumpTable) 11687 dbgs() << "JT:"; 11688 if (C.Kind == CC_BitTests) 11689 dbgs() << "BT:"; 11690 11691 C.Low->getValue().print(dbgs(), true); 11692 if (C.Low != C.High) { 11693 dbgs() << '-'; 11694 C.High->getValue().print(dbgs(), true); 11695 } 11696 dbgs() << ' '; 11697 } 11698 dbgs() << '\n'; 11699 }); 11700 11701 assert(!Clusters.empty()); 11702 SwitchWorkList WorkList; 11703 CaseClusterIt First = Clusters.begin(); 11704 CaseClusterIt Last = Clusters.end() - 1; 11705 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 11706 // Scale the branchprobability for DefaultMBB if the peel occurs and 11707 // DefaultMBB is not replaced. 11708 if (PeeledCaseProb != BranchProbability::getZero() && 11709 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 11710 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 11711 WorkList.push_back( 11712 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 11713 11714 while (!WorkList.empty()) { 11715 SwitchWorkListItem W = WorkList.pop_back_val(); 11716 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 11717 11718 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 11719 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 11720 // For optimized builds, lower large range as a balanced binary tree. 11721 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 11722 continue; 11723 } 11724 11725 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 11726 } 11727 } 11728 11729 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 11730 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11731 auto DL = getCurSDLoc(); 11732 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11733 setValue(&I, DAG.getStepVector(DL, ResultVT)); 11734 } 11735 11736 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 11737 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11738 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11739 11740 SDLoc DL = getCurSDLoc(); 11741 SDValue V = getValue(I.getOperand(0)); 11742 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 11743 11744 if (VT.isScalableVector()) { 11745 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 11746 return; 11747 } 11748 11749 // Use VECTOR_SHUFFLE for the fixed-length vector 11750 // to maintain existing behavior. 11751 SmallVector<int, 8> Mask; 11752 unsigned NumElts = VT.getVectorMinNumElements(); 11753 for (unsigned i = 0; i != NumElts; ++i) 11754 Mask.push_back(NumElts - 1 - i); 11755 11756 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 11757 } 11758 11759 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) { 11760 auto DL = getCurSDLoc(); 11761 SDValue InVec = getValue(I.getOperand(0)); 11762 EVT OutVT = 11763 InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 11764 11765 unsigned OutNumElts = OutVT.getVectorMinNumElements(); 11766 11767 // ISD Node needs the input vectors split into two equal parts 11768 SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 11769 DAG.getVectorIdxConstant(0, DL)); 11770 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 11771 DAG.getVectorIdxConstant(OutNumElts, DL)); 11772 11773 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 11774 // legalisation and combines. 11775 if (OutVT.isFixedLengthVector()) { 11776 SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 11777 createStrideMask(0, 2, OutNumElts)); 11778 SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 11779 createStrideMask(1, 2, OutNumElts)); 11780 SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc()); 11781 setValue(&I, Res); 11782 return; 11783 } 11784 11785 SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL, 11786 DAG.getVTList(OutVT, OutVT), Lo, Hi); 11787 setValue(&I, Res); 11788 } 11789 11790 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) { 11791 auto DL = getCurSDLoc(); 11792 EVT InVT = getValue(I.getOperand(0)).getValueType(); 11793 SDValue InVec0 = getValue(I.getOperand(0)); 11794 SDValue InVec1 = getValue(I.getOperand(1)); 11795 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11796 EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11797 11798 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 11799 // legalisation and combines. 11800 if (OutVT.isFixedLengthVector()) { 11801 unsigned NumElts = InVT.getVectorMinNumElements(); 11802 SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1); 11803 setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT), 11804 createInterleaveMask(NumElts, 2))); 11805 return; 11806 } 11807 11808 SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, 11809 DAG.getVTList(InVT, InVT), InVec0, InVec1); 11810 Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0), 11811 Res.getValue(1)); 11812 setValue(&I, Res); 11813 } 11814 11815 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 11816 SmallVector<EVT, 4> ValueVTs; 11817 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 11818 ValueVTs); 11819 unsigned NumValues = ValueVTs.size(); 11820 if (NumValues == 0) return; 11821 11822 SmallVector<SDValue, 4> Values(NumValues); 11823 SDValue Op = getValue(I.getOperand(0)); 11824 11825 for (unsigned i = 0; i != NumValues; ++i) 11826 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 11827 SDValue(Op.getNode(), Op.getResNo() + i)); 11828 11829 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 11830 DAG.getVTList(ValueVTs), Values)); 11831 } 11832 11833 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 11834 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11835 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11836 11837 SDLoc DL = getCurSDLoc(); 11838 SDValue V1 = getValue(I.getOperand(0)); 11839 SDValue V2 = getValue(I.getOperand(1)); 11840 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 11841 11842 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 11843 if (VT.isScalableVector()) { 11844 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 11845 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 11846 DAG.getConstant(Imm, DL, IdxVT))); 11847 return; 11848 } 11849 11850 unsigned NumElts = VT.getVectorNumElements(); 11851 11852 uint64_t Idx = (NumElts + Imm) % NumElts; 11853 11854 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 11855 SmallVector<int, 8> Mask; 11856 for (unsigned i = 0; i < NumElts; ++i) 11857 Mask.push_back(Idx + i); 11858 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 11859 } 11860 11861 // Consider the following MIR after SelectionDAG, which produces output in 11862 // phyregs in the first case or virtregs in the second case. 11863 // 11864 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx 11865 // %5:gr32 = COPY $ebx 11866 // %6:gr32 = COPY $edx 11867 // %1:gr32 = COPY %6:gr32 11868 // %0:gr32 = COPY %5:gr32 11869 // 11870 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32 11871 // %1:gr32 = COPY %6:gr32 11872 // %0:gr32 = COPY %5:gr32 11873 // 11874 // Given %0, we'd like to return $ebx in the first case and %5 in the second. 11875 // Given %1, we'd like to return $edx in the first case and %6 in the second. 11876 // 11877 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap 11878 // to a single virtreg (such as %0). The remaining outputs monotonically 11879 // increase in virtreg number from there. If a callbr has no outputs, then it 11880 // should not have a corresponding callbr landingpad; in fact, the callbr 11881 // landingpad would not even be able to refer to such a callbr. 11882 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) { 11883 MachineInstr *MI = MRI.def_begin(Reg)->getParent(); 11884 // There is definitely at least one copy. 11885 assert(MI->getOpcode() == TargetOpcode::COPY && 11886 "start of copy chain MUST be COPY"); 11887 Reg = MI->getOperand(1).getReg(); 11888 MI = MRI.def_begin(Reg)->getParent(); 11889 // There may be an optional second copy. 11890 if (MI->getOpcode() == TargetOpcode::COPY) { 11891 assert(Reg.isVirtual() && "expected COPY of virtual register"); 11892 Reg = MI->getOperand(1).getReg(); 11893 assert(Reg.isPhysical() && "expected COPY of physical register"); 11894 MI = MRI.def_begin(Reg)->getParent(); 11895 } 11896 // The start of the chain must be an INLINEASM_BR. 11897 assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR && 11898 "end of copy chain MUST be INLINEASM_BR"); 11899 return Reg; 11900 } 11901 11902 // We must do this walk rather than the simpler 11903 // setValue(&I, getCopyFromRegs(CBR, CBR->getType())); 11904 // otherwise we will end up with copies of virtregs only valid along direct 11905 // edges. 11906 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) { 11907 SmallVector<EVT, 8> ResultVTs; 11908 SmallVector<SDValue, 8> ResultValues; 11909 const auto *CBR = 11910 cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator()); 11911 11912 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11913 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 11914 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11915 11916 unsigned InitialDef = FuncInfo.ValueMap[CBR]; 11917 SDValue Chain = DAG.getRoot(); 11918 11919 // Re-parse the asm constraints string. 11920 TargetLowering::AsmOperandInfoVector TargetConstraints = 11921 TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR); 11922 for (auto &T : TargetConstraints) { 11923 SDISelAsmOperandInfo OpInfo(T); 11924 if (OpInfo.Type != InlineAsm::isOutput) 11925 continue; 11926 11927 // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the 11928 // individual constraint. 11929 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 11930 11931 switch (OpInfo.ConstraintType) { 11932 case TargetLowering::C_Register: 11933 case TargetLowering::C_RegisterClass: { 11934 // Fill in OpInfo.AssignedRegs.Regs. 11935 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo); 11936 11937 // getRegistersForValue may produce 1 to many registers based on whether 11938 // the OpInfo.ConstraintVT is legal on the target or not. 11939 for (size_t i = 0, e = OpInfo.AssignedRegs.Regs.size(); i != e; ++i) { 11940 Register OriginalDef = FollowCopyChain(MRI, InitialDef++); 11941 if (Register::isPhysicalRegister(OriginalDef)) 11942 FuncInfo.MBB->addLiveIn(OriginalDef); 11943 // Update the assigned registers to use the original defs. 11944 OpInfo.AssignedRegs.Regs[i] = OriginalDef; 11945 } 11946 11947 SDValue V = OpInfo.AssignedRegs.getCopyFromRegs( 11948 DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR); 11949 ResultValues.push_back(V); 11950 ResultVTs.push_back(OpInfo.ConstraintVT); 11951 break; 11952 } 11953 case TargetLowering::C_Other: { 11954 SDValue Flag; 11955 SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 11956 OpInfo, DAG); 11957 ++InitialDef; 11958 ResultValues.push_back(V); 11959 ResultVTs.push_back(OpInfo.ConstraintVT); 11960 break; 11961 } 11962 default: 11963 break; 11964 } 11965 } 11966 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 11967 DAG.getVTList(ResultVTs), ResultValues); 11968 setValue(&I, V); 11969 } 11970