1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This implements routines for translating from LLVM IR into SelectionDAG IR. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "SelectionDAGBuilder.h" 14 #include "SDNodeDbgValue.h" 15 #include "llvm/ADT/APFloat.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/BitVector.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/ADT/SmallPtrSet.h" 20 #include "llvm/ADT/SmallSet.h" 21 #include "llvm/ADT/StringRef.h" 22 #include "llvm/ADT/Twine.h" 23 #include "llvm/Analysis/AliasAnalysis.h" 24 #include "llvm/Analysis/BranchProbabilityInfo.h" 25 #include "llvm/Analysis/ConstantFolding.h" 26 #include "llvm/Analysis/Loads.h" 27 #include "llvm/Analysis/MemoryLocation.h" 28 #include "llvm/Analysis/TargetLibraryInfo.h" 29 #include "llvm/Analysis/ValueTracking.h" 30 #include "llvm/Analysis/VectorUtils.h" 31 #include "llvm/CodeGen/Analysis.h" 32 #include "llvm/CodeGen/AssignmentTrackingAnalysis.h" 33 #include "llvm/CodeGen/CodeGenCommonISel.h" 34 #include "llvm/CodeGen/FunctionLoweringInfo.h" 35 #include "llvm/CodeGen/GCMetadata.h" 36 #include "llvm/CodeGen/MachineBasicBlock.h" 37 #include "llvm/CodeGen/MachineFrameInfo.h" 38 #include "llvm/CodeGen/MachineFunction.h" 39 #include "llvm/CodeGen/MachineInstrBuilder.h" 40 #include "llvm/CodeGen/MachineInstrBundleIterator.h" 41 #include "llvm/CodeGen/MachineMemOperand.h" 42 #include "llvm/CodeGen/MachineModuleInfo.h" 43 #include "llvm/CodeGen/MachineOperand.h" 44 #include "llvm/CodeGen/MachineRegisterInfo.h" 45 #include "llvm/CodeGen/RuntimeLibcalls.h" 46 #include "llvm/CodeGen/SelectionDAG.h" 47 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 48 #include "llvm/CodeGen/StackMaps.h" 49 #include "llvm/CodeGen/SwiftErrorValueTracking.h" 50 #include "llvm/CodeGen/TargetFrameLowering.h" 51 #include "llvm/CodeGen/TargetInstrInfo.h" 52 #include "llvm/CodeGen/TargetOpcodes.h" 53 #include "llvm/CodeGen/TargetRegisterInfo.h" 54 #include "llvm/CodeGen/TargetSubtargetInfo.h" 55 #include "llvm/CodeGen/WinEHFuncInfo.h" 56 #include "llvm/IR/Argument.h" 57 #include "llvm/IR/Attributes.h" 58 #include "llvm/IR/BasicBlock.h" 59 #include "llvm/IR/CFG.h" 60 #include "llvm/IR/CallingConv.h" 61 #include "llvm/IR/Constant.h" 62 #include "llvm/IR/ConstantRange.h" 63 #include "llvm/IR/Constants.h" 64 #include "llvm/IR/DataLayout.h" 65 #include "llvm/IR/DebugInfo.h" 66 #include "llvm/IR/DebugInfoMetadata.h" 67 #include "llvm/IR/DerivedTypes.h" 68 #include "llvm/IR/DiagnosticInfo.h" 69 #include "llvm/IR/EHPersonalities.h" 70 #include "llvm/IR/Function.h" 71 #include "llvm/IR/GetElementPtrTypeIterator.h" 72 #include "llvm/IR/InlineAsm.h" 73 #include "llvm/IR/InstrTypes.h" 74 #include "llvm/IR/Instructions.h" 75 #include "llvm/IR/IntrinsicInst.h" 76 #include "llvm/IR/Intrinsics.h" 77 #include "llvm/IR/IntrinsicsAArch64.h" 78 #include "llvm/IR/IntrinsicsWebAssembly.h" 79 #include "llvm/IR/LLVMContext.h" 80 #include "llvm/IR/Metadata.h" 81 #include "llvm/IR/Module.h" 82 #include "llvm/IR/Operator.h" 83 #include "llvm/IR/PatternMatch.h" 84 #include "llvm/IR/Statepoint.h" 85 #include "llvm/IR/Type.h" 86 #include "llvm/IR/User.h" 87 #include "llvm/IR/Value.h" 88 #include "llvm/MC/MCContext.h" 89 #include "llvm/Support/AtomicOrdering.h" 90 #include "llvm/Support/Casting.h" 91 #include "llvm/Support/CommandLine.h" 92 #include "llvm/Support/Compiler.h" 93 #include "llvm/Support/Debug.h" 94 #include "llvm/Support/MathExtras.h" 95 #include "llvm/Support/raw_ostream.h" 96 #include "llvm/Target/TargetIntrinsicInfo.h" 97 #include "llvm/Target/TargetMachine.h" 98 #include "llvm/Target/TargetOptions.h" 99 #include "llvm/TargetParser/Triple.h" 100 #include "llvm/Transforms/Utils/Local.h" 101 #include <cstddef> 102 #include <iterator> 103 #include <limits> 104 #include <optional> 105 #include <tuple> 106 107 using namespace llvm; 108 using namespace PatternMatch; 109 using namespace SwitchCG; 110 111 #define DEBUG_TYPE "isel" 112 113 /// LimitFloatPrecision - Generate low-precision inline sequences for 114 /// some float libcalls (6, 8 or 12 bits). 115 static unsigned LimitFloatPrecision; 116 117 static cl::opt<bool> 118 InsertAssertAlign("insert-assert-align", cl::init(true), 119 cl::desc("Insert the experimental `assertalign` node."), 120 cl::ReallyHidden); 121 122 static cl::opt<unsigned, true> 123 LimitFPPrecision("limit-float-precision", 124 cl::desc("Generate low-precision inline sequences " 125 "for some float libcalls"), 126 cl::location(LimitFloatPrecision), cl::Hidden, 127 cl::init(0)); 128 129 static cl::opt<unsigned> SwitchPeelThreshold( 130 "switch-peel-threshold", cl::Hidden, cl::init(66), 131 cl::desc("Set the case probability threshold for peeling the case from a " 132 "switch statement. A value greater than 100 will void this " 133 "optimization")); 134 135 // Limit the width of DAG chains. This is important in general to prevent 136 // DAG-based analysis from blowing up. For example, alias analysis and 137 // load clustering may not complete in reasonable time. It is difficult to 138 // recognize and avoid this situation within each individual analysis, and 139 // future analyses are likely to have the same behavior. Limiting DAG width is 140 // the safe approach and will be especially important with global DAGs. 141 // 142 // MaxParallelChains default is arbitrarily high to avoid affecting 143 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 144 // sequence over this should have been converted to llvm.memcpy by the 145 // frontend. It is easy to induce this behavior with .ll code such as: 146 // %buffer = alloca [4096 x i8] 147 // %data = load [4096 x i8]* %argPtr 148 // store [4096 x i8] %data, [4096 x i8]* %buffer 149 static const unsigned MaxParallelChains = 64; 150 151 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 152 const SDValue *Parts, unsigned NumParts, 153 MVT PartVT, EVT ValueVT, const Value *V, 154 std::optional<CallingConv::ID> CC); 155 156 /// getCopyFromParts - Create a value that contains the specified legal parts 157 /// combined into the value they represent. If the parts combine to a type 158 /// larger than ValueVT then AssertOp can be used to specify whether the extra 159 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 160 /// (ISD::AssertSext). 161 static SDValue 162 getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, 163 unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V, 164 std::optional<CallingConv::ID> CC = std::nullopt, 165 std::optional<ISD::NodeType> AssertOp = std::nullopt) { 166 // Let the target assemble the parts if it wants to 167 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 168 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts, 169 PartVT, ValueVT, CC)) 170 return Val; 171 172 if (ValueVT.isVector()) 173 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 174 CC); 175 176 assert(NumParts > 0 && "No parts to assemble!"); 177 SDValue Val = Parts[0]; 178 179 if (NumParts > 1) { 180 // Assemble the value from multiple parts. 181 if (ValueVT.isInteger()) { 182 unsigned PartBits = PartVT.getSizeInBits(); 183 unsigned ValueBits = ValueVT.getSizeInBits(); 184 185 // Assemble the power of 2 part. 186 unsigned RoundParts = llvm::bit_floor(NumParts); 187 unsigned RoundBits = PartBits * RoundParts; 188 EVT RoundVT = RoundBits == ValueBits ? 189 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 190 SDValue Lo, Hi; 191 192 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 193 194 if (RoundParts > 2) { 195 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 196 PartVT, HalfVT, V); 197 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 198 RoundParts / 2, PartVT, HalfVT, V); 199 } else { 200 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 201 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 202 } 203 204 if (DAG.getDataLayout().isBigEndian()) 205 std::swap(Lo, Hi); 206 207 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 208 209 if (RoundParts < NumParts) { 210 // Assemble the trailing non-power-of-2 part. 211 unsigned OddParts = NumParts - RoundParts; 212 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 213 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 214 OddVT, V, CC); 215 216 // Combine the round and odd parts. 217 Lo = Val; 218 if (DAG.getDataLayout().isBigEndian()) 219 std::swap(Lo, Hi); 220 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 221 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 222 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 223 DAG.getConstant(Lo.getValueSizeInBits(), DL, 224 TLI.getShiftAmountTy( 225 TotalVT, DAG.getDataLayout()))); 226 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 227 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 228 } 229 } else if (PartVT.isFloatingPoint()) { 230 // FP split into multiple FP parts (for ppcf128) 231 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 232 "Unexpected split"); 233 SDValue Lo, Hi; 234 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 235 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 236 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 237 std::swap(Lo, Hi); 238 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 239 } else { 240 // FP split into integer parts (soft fp) 241 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 242 !PartVT.isVector() && "Unexpected split"); 243 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 244 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 245 } 246 } 247 248 // There is now one part, held in Val. Correct it to match ValueVT. 249 // PartEVT is the type of the register class that holds the value. 250 // ValueVT is the type of the inline asm operation. 251 EVT PartEVT = Val.getValueType(); 252 253 if (PartEVT == ValueVT) 254 return Val; 255 256 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 257 ValueVT.bitsLT(PartEVT)) { 258 // For an FP value in an integer part, we need to truncate to the right 259 // width first. 260 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 261 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 262 } 263 264 // Handle types that have the same size. 265 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 266 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 267 268 // Handle types with different sizes. 269 if (PartEVT.isInteger() && ValueVT.isInteger()) { 270 if (ValueVT.bitsLT(PartEVT)) { 271 // For a truncate, see if we have any information to 272 // indicate whether the truncated bits will always be 273 // zero or sign-extension. 274 if (AssertOp) 275 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 276 DAG.getValueType(ValueVT)); 277 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 278 } 279 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 280 } 281 282 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 283 // FP_ROUND's are always exact here. 284 if (ValueVT.bitsLT(Val.getValueType())) 285 return DAG.getNode( 286 ISD::FP_ROUND, DL, ValueVT, Val, 287 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 288 289 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 290 } 291 292 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 293 // then truncating. 294 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 295 ValueVT.bitsLT(PartEVT)) { 296 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 297 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 298 } 299 300 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 301 } 302 303 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 304 const Twine &ErrMsg) { 305 const Instruction *I = dyn_cast_or_null<Instruction>(V); 306 if (!V) 307 return Ctx.emitError(ErrMsg); 308 309 const char *AsmError = ", possible invalid constraint for vector type"; 310 if (const CallInst *CI = dyn_cast<CallInst>(I)) 311 if (CI->isInlineAsm()) 312 return Ctx.emitError(I, ErrMsg + AsmError); 313 314 return Ctx.emitError(I, ErrMsg); 315 } 316 317 /// getCopyFromPartsVector - Create a value that contains the specified legal 318 /// parts combined into the value they represent. If the parts combine to a 319 /// type larger than ValueVT then AssertOp can be used to specify whether the 320 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 321 /// ValueVT (ISD::AssertSext). 322 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 323 const SDValue *Parts, unsigned NumParts, 324 MVT PartVT, EVT ValueVT, const Value *V, 325 std::optional<CallingConv::ID> CallConv) { 326 assert(ValueVT.isVector() && "Not a vector value"); 327 assert(NumParts > 0 && "No parts to assemble!"); 328 const bool IsABIRegCopy = CallConv.has_value(); 329 330 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 331 SDValue Val = Parts[0]; 332 333 // Handle a multi-element vector. 334 if (NumParts > 1) { 335 EVT IntermediateVT; 336 MVT RegisterVT; 337 unsigned NumIntermediates; 338 unsigned NumRegs; 339 340 if (IsABIRegCopy) { 341 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 342 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, 343 NumIntermediates, RegisterVT); 344 } else { 345 NumRegs = 346 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 347 NumIntermediates, RegisterVT); 348 } 349 350 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 351 NumParts = NumRegs; // Silence a compiler warning. 352 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 353 assert(RegisterVT.getSizeInBits() == 354 Parts[0].getSimpleValueType().getSizeInBits() && 355 "Part type sizes don't match!"); 356 357 // Assemble the parts into intermediate operands. 358 SmallVector<SDValue, 8> Ops(NumIntermediates); 359 if (NumIntermediates == NumParts) { 360 // If the register was not expanded, truncate or copy the value, 361 // as appropriate. 362 for (unsigned i = 0; i != NumParts; ++i) 363 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 364 PartVT, IntermediateVT, V, CallConv); 365 } else if (NumParts > 0) { 366 // If the intermediate type was expanded, build the intermediate 367 // operands from the parts. 368 assert(NumParts % NumIntermediates == 0 && 369 "Must expand into a divisible number of parts!"); 370 unsigned Factor = NumParts / NumIntermediates; 371 for (unsigned i = 0; i != NumIntermediates; ++i) 372 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 373 PartVT, IntermediateVT, V, CallConv); 374 } 375 376 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 377 // intermediate operands. 378 EVT BuiltVectorTy = 379 IntermediateVT.isVector() 380 ? EVT::getVectorVT( 381 *DAG.getContext(), IntermediateVT.getScalarType(), 382 IntermediateVT.getVectorElementCount() * NumParts) 383 : EVT::getVectorVT(*DAG.getContext(), 384 IntermediateVT.getScalarType(), 385 NumIntermediates); 386 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 387 : ISD::BUILD_VECTOR, 388 DL, BuiltVectorTy, Ops); 389 } 390 391 // There is now one part, held in Val. Correct it to match ValueVT. 392 EVT PartEVT = Val.getValueType(); 393 394 if (PartEVT == ValueVT) 395 return Val; 396 397 if (PartEVT.isVector()) { 398 // Vector/Vector bitcast. 399 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 400 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 401 402 // If the parts vector has more elements than the value vector, then we 403 // have a vector widening case (e.g. <2 x float> -> <4 x float>). 404 // Extract the elements we want. 405 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) { 406 assert((PartEVT.getVectorElementCount().getKnownMinValue() > 407 ValueVT.getVectorElementCount().getKnownMinValue()) && 408 (PartEVT.getVectorElementCount().isScalable() == 409 ValueVT.getVectorElementCount().isScalable()) && 410 "Cannot narrow, it would be a lossy transformation"); 411 PartEVT = 412 EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(), 413 ValueVT.getVectorElementCount()); 414 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val, 415 DAG.getVectorIdxConstant(0, DL)); 416 if (PartEVT == ValueVT) 417 return Val; 418 if (PartEVT.isInteger() && ValueVT.isFloatingPoint()) 419 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 420 } 421 422 // Promoted vector extract 423 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 424 } 425 426 // Trivial bitcast if the types are the same size and the destination 427 // vector type is legal. 428 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 429 TLI.isTypeLegal(ValueVT)) 430 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 431 432 if (ValueVT.getVectorNumElements() != 1) { 433 // Certain ABIs require that vectors are passed as integers. For vectors 434 // are the same size, this is an obvious bitcast. 435 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 436 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 437 } else if (ValueVT.bitsLT(PartEVT)) { 438 const uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 439 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 440 // Drop the extra bits. 441 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 442 return DAG.getBitcast(ValueVT, Val); 443 } 444 445 diagnosePossiblyInvalidConstraint( 446 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 447 return DAG.getUNDEF(ValueVT); 448 } 449 450 // Handle cases such as i8 -> <1 x i1> 451 EVT ValueSVT = ValueVT.getVectorElementType(); 452 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 453 unsigned ValueSize = ValueSVT.getSizeInBits(); 454 if (ValueSize == PartEVT.getSizeInBits()) { 455 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 456 } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) { 457 // It's possible a scalar floating point type gets softened to integer and 458 // then promoted to a larger integer. If PartEVT is the larger integer 459 // we need to truncate it and then bitcast to the FP type. 460 assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types"); 461 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 462 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 463 Val = DAG.getBitcast(ValueSVT, Val); 464 } else { 465 Val = ValueVT.isFloatingPoint() 466 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 467 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 468 } 469 } 470 471 return DAG.getBuildVector(ValueVT, DL, Val); 472 } 473 474 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 475 SDValue Val, SDValue *Parts, unsigned NumParts, 476 MVT PartVT, const Value *V, 477 std::optional<CallingConv::ID> CallConv); 478 479 /// getCopyToParts - Create a series of nodes that contain the specified value 480 /// split into legal parts. If the parts contain more bits than Val, then, for 481 /// integers, ExtendKind can be used to specify how to generate the extra bits. 482 static void 483 getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 484 unsigned NumParts, MVT PartVT, const Value *V, 485 std::optional<CallingConv::ID> CallConv = std::nullopt, 486 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 487 // Let the target split the parts if it wants to 488 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 489 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 490 CallConv)) 491 return; 492 EVT ValueVT = Val.getValueType(); 493 494 // Handle the vector case separately. 495 if (ValueVT.isVector()) 496 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 497 CallConv); 498 499 unsigned OrigNumParts = NumParts; 500 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 501 "Copying to an illegal type!"); 502 503 if (NumParts == 0) 504 return; 505 506 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 507 EVT PartEVT = PartVT; 508 if (PartEVT == ValueVT) { 509 assert(NumParts == 1 && "No-op copy with multiple parts!"); 510 Parts[0] = Val; 511 return; 512 } 513 514 unsigned PartBits = PartVT.getSizeInBits(); 515 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 516 // If the parts cover more bits than the value has, promote the value. 517 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 518 assert(NumParts == 1 && "Do not know what to promote to!"); 519 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 520 } else { 521 if (ValueVT.isFloatingPoint()) { 522 // FP values need to be bitcast, then extended if they are being put 523 // into a larger container. 524 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 525 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 526 } 527 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 528 ValueVT.isInteger() && 529 "Unknown mismatch!"); 530 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 531 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 532 if (PartVT == MVT::x86mmx) 533 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 534 } 535 } else if (PartBits == ValueVT.getSizeInBits()) { 536 // Different types of the same size. 537 assert(NumParts == 1 && PartEVT != ValueVT); 538 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 539 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 540 // If the parts cover less bits than value has, truncate the value. 541 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 542 ValueVT.isInteger() && 543 "Unknown mismatch!"); 544 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 545 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 546 if (PartVT == MVT::x86mmx) 547 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 548 } 549 550 // The value may have changed - recompute ValueVT. 551 ValueVT = Val.getValueType(); 552 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 553 "Failed to tile the value with PartVT!"); 554 555 if (NumParts == 1) { 556 if (PartEVT != ValueVT) { 557 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 558 "scalar-to-vector conversion failed"); 559 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 560 } 561 562 Parts[0] = Val; 563 return; 564 } 565 566 // Expand the value into multiple parts. 567 if (NumParts & (NumParts - 1)) { 568 // The number of parts is not a power of 2. Split off and copy the tail. 569 assert(PartVT.isInteger() && ValueVT.isInteger() && 570 "Do not know what to expand to!"); 571 unsigned RoundParts = llvm::bit_floor(NumParts); 572 unsigned RoundBits = RoundParts * PartBits; 573 unsigned OddParts = NumParts - RoundParts; 574 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 575 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL)); 576 577 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 578 CallConv); 579 580 if (DAG.getDataLayout().isBigEndian()) 581 // The odd parts were reversed by getCopyToParts - unreverse them. 582 std::reverse(Parts + RoundParts, Parts + NumParts); 583 584 NumParts = RoundParts; 585 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 586 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 587 } 588 589 // The number of parts is a power of 2. Repeatedly bisect the value using 590 // EXTRACT_ELEMENT. 591 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 592 EVT::getIntegerVT(*DAG.getContext(), 593 ValueVT.getSizeInBits()), 594 Val); 595 596 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 597 for (unsigned i = 0; i < NumParts; i += StepSize) { 598 unsigned ThisBits = StepSize * PartBits / 2; 599 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 600 SDValue &Part0 = Parts[i]; 601 SDValue &Part1 = Parts[i+StepSize/2]; 602 603 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 604 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 605 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 606 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 607 608 if (ThisBits == PartBits && ThisVT != PartVT) { 609 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 610 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 611 } 612 } 613 } 614 615 if (DAG.getDataLayout().isBigEndian()) 616 std::reverse(Parts, Parts + OrigNumParts); 617 } 618 619 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val, 620 const SDLoc &DL, EVT PartVT) { 621 if (!PartVT.isVector()) 622 return SDValue(); 623 624 EVT ValueVT = Val.getValueType(); 625 ElementCount PartNumElts = PartVT.getVectorElementCount(); 626 ElementCount ValueNumElts = ValueVT.getVectorElementCount(); 627 628 // We only support widening vectors with equivalent element types and 629 // fixed/scalable properties. If a target needs to widen a fixed-length type 630 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below. 631 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) || 632 PartNumElts.isScalable() != ValueNumElts.isScalable() || 633 PartVT.getVectorElementType() != ValueVT.getVectorElementType()) 634 return SDValue(); 635 636 // Widening a scalable vector to another scalable vector is done by inserting 637 // the vector into a larger undef one. 638 if (PartNumElts.isScalable()) 639 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 640 Val, DAG.getVectorIdxConstant(0, DL)); 641 642 EVT ElementVT = PartVT.getVectorElementType(); 643 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 644 // undef elements. 645 SmallVector<SDValue, 16> Ops; 646 DAG.ExtractVectorElements(Val, Ops); 647 SDValue EltUndef = DAG.getUNDEF(ElementVT); 648 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef); 649 650 // FIXME: Use CONCAT for 2x -> 4x. 651 return DAG.getBuildVector(PartVT, DL, Ops); 652 } 653 654 /// getCopyToPartsVector - Create a series of nodes that contain the specified 655 /// value split into legal parts. 656 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 657 SDValue Val, SDValue *Parts, unsigned NumParts, 658 MVT PartVT, const Value *V, 659 std::optional<CallingConv::ID> CallConv) { 660 EVT ValueVT = Val.getValueType(); 661 assert(ValueVT.isVector() && "Not a vector"); 662 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 663 const bool IsABIRegCopy = CallConv.has_value(); 664 665 if (NumParts == 1) { 666 EVT PartEVT = PartVT; 667 if (PartEVT == ValueVT) { 668 // Nothing to do. 669 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 670 // Bitconvert vector->vector case. 671 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 672 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 673 Val = Widened; 674 } else if (PartVT.isVector() && 675 PartEVT.getVectorElementType().bitsGE( 676 ValueVT.getVectorElementType()) && 677 PartEVT.getVectorElementCount() == 678 ValueVT.getVectorElementCount()) { 679 680 // Promoted vector extract 681 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 682 } else if (PartEVT.isVector() && 683 PartEVT.getVectorElementType() != 684 ValueVT.getVectorElementType() && 685 TLI.getTypeAction(*DAG.getContext(), ValueVT) == 686 TargetLowering::TypeWidenVector) { 687 // Combination of widening and promotion. 688 EVT WidenVT = 689 EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(), 690 PartVT.getVectorElementCount()); 691 SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT); 692 Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT); 693 } else { 694 // Don't extract an integer from a float vector. This can happen if the 695 // FP type gets softened to integer and then promoted. The promotion 696 // prevents it from being picked up by the earlier bitcast case. 697 if (ValueVT.getVectorElementCount().isScalar() && 698 (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) { 699 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 700 DAG.getVectorIdxConstant(0, DL)); 701 } else { 702 uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 703 assert(PartVT.getFixedSizeInBits() > ValueSize && 704 "lossy conversion of vector to scalar type"); 705 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 706 Val = DAG.getBitcast(IntermediateType, Val); 707 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 708 } 709 } 710 711 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 712 Parts[0] = Val; 713 return; 714 } 715 716 // Handle a multi-element vector. 717 EVT IntermediateVT; 718 MVT RegisterVT; 719 unsigned NumIntermediates; 720 unsigned NumRegs; 721 if (IsABIRegCopy) { 722 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 723 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates, 724 RegisterVT); 725 } else { 726 NumRegs = 727 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 728 NumIntermediates, RegisterVT); 729 } 730 731 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 732 NumParts = NumRegs; // Silence a compiler warning. 733 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 734 735 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 736 "Mixing scalable and fixed vectors when copying in parts"); 737 738 std::optional<ElementCount> DestEltCnt; 739 740 if (IntermediateVT.isVector()) 741 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 742 else 743 DestEltCnt = ElementCount::getFixed(NumIntermediates); 744 745 EVT BuiltVectorTy = EVT::getVectorVT( 746 *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt); 747 748 if (ValueVT == BuiltVectorTy) { 749 // Nothing to do. 750 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) { 751 // Bitconvert vector->vector case. 752 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 753 } else { 754 if (BuiltVectorTy.getVectorElementType().bitsGT( 755 ValueVT.getVectorElementType())) { 756 // Integer promotion. 757 ValueVT = EVT::getVectorVT(*DAG.getContext(), 758 BuiltVectorTy.getVectorElementType(), 759 ValueVT.getVectorElementCount()); 760 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 761 } 762 763 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) { 764 Val = Widened; 765 } 766 } 767 768 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type"); 769 770 // Split the vector into intermediate operands. 771 SmallVector<SDValue, 8> Ops(NumIntermediates); 772 for (unsigned i = 0; i != NumIntermediates; ++i) { 773 if (IntermediateVT.isVector()) { 774 // This does something sensible for scalable vectors - see the 775 // definition of EXTRACT_SUBVECTOR for further details. 776 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 777 Ops[i] = 778 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 779 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 780 } else { 781 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 782 DAG.getVectorIdxConstant(i, DL)); 783 } 784 } 785 786 // Split the intermediate operands into legal parts. 787 if (NumParts == NumIntermediates) { 788 // If the register was not expanded, promote or copy the value, 789 // as appropriate. 790 for (unsigned i = 0; i != NumParts; ++i) 791 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 792 } else if (NumParts > 0) { 793 // If the intermediate type was expanded, split each the value into 794 // legal parts. 795 assert(NumIntermediates != 0 && "division by zero"); 796 assert(NumParts % NumIntermediates == 0 && 797 "Must expand into a divisible number of parts!"); 798 unsigned Factor = NumParts / NumIntermediates; 799 for (unsigned i = 0; i != NumIntermediates; ++i) 800 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 801 CallConv); 802 } 803 } 804 805 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 806 EVT valuevt, std::optional<CallingConv::ID> CC) 807 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 808 RegCount(1, regs.size()), CallConv(CC) {} 809 810 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 811 const DataLayout &DL, unsigned Reg, Type *Ty, 812 std::optional<CallingConv::ID> CC) { 813 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 814 815 CallConv = CC; 816 817 for (EVT ValueVT : ValueVTs) { 818 unsigned NumRegs = 819 isABIMangled() 820 ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT) 821 : TLI.getNumRegisters(Context, ValueVT); 822 MVT RegisterVT = 823 isABIMangled() 824 ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT) 825 : TLI.getRegisterType(Context, ValueVT); 826 for (unsigned i = 0; i != NumRegs; ++i) 827 Regs.push_back(Reg + i); 828 RegVTs.push_back(RegisterVT); 829 RegCount.push_back(NumRegs); 830 Reg += NumRegs; 831 } 832 } 833 834 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 835 FunctionLoweringInfo &FuncInfo, 836 const SDLoc &dl, SDValue &Chain, 837 SDValue *Glue, const Value *V) const { 838 // A Value with type {} or [0 x %t] needs no registers. 839 if (ValueVTs.empty()) 840 return SDValue(); 841 842 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 843 844 // Assemble the legal parts into the final values. 845 SmallVector<SDValue, 4> Values(ValueVTs.size()); 846 SmallVector<SDValue, 8> Parts; 847 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 848 // Copy the legal parts from the registers. 849 EVT ValueVT = ValueVTs[Value]; 850 unsigned NumRegs = RegCount[Value]; 851 MVT RegisterVT = isABIMangled() 852 ? TLI.getRegisterTypeForCallingConv( 853 *DAG.getContext(), *CallConv, RegVTs[Value]) 854 : RegVTs[Value]; 855 856 Parts.resize(NumRegs); 857 for (unsigned i = 0; i != NumRegs; ++i) { 858 SDValue P; 859 if (!Glue) { 860 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 861 } else { 862 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue); 863 *Glue = P.getValue(2); 864 } 865 866 Chain = P.getValue(1); 867 Parts[i] = P; 868 869 // If the source register was virtual and if we know something about it, 870 // add an assert node. 871 if (!Register::isVirtualRegister(Regs[Part + i]) || 872 !RegisterVT.isInteger()) 873 continue; 874 875 const FunctionLoweringInfo::LiveOutInfo *LOI = 876 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 877 if (!LOI) 878 continue; 879 880 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 881 unsigned NumSignBits = LOI->NumSignBits; 882 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 883 884 if (NumZeroBits == RegSize) { 885 // The current value is a zero. 886 // Explicitly express that as it would be easier for 887 // optimizations to kick in. 888 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 889 continue; 890 } 891 892 // FIXME: We capture more information than the dag can represent. For 893 // now, just use the tightest assertzext/assertsext possible. 894 bool isSExt; 895 EVT FromVT(MVT::Other); 896 if (NumZeroBits) { 897 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 898 isSExt = false; 899 } else if (NumSignBits > 1) { 900 FromVT = 901 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 902 isSExt = true; 903 } else { 904 continue; 905 } 906 // Add an assertion node. 907 assert(FromVT != MVT::Other); 908 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 909 RegisterVT, P, DAG.getValueType(FromVT)); 910 } 911 912 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 913 RegisterVT, ValueVT, V, CallConv); 914 Part += NumRegs; 915 Parts.clear(); 916 } 917 918 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 919 } 920 921 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 922 const SDLoc &dl, SDValue &Chain, SDValue *Glue, 923 const Value *V, 924 ISD::NodeType PreferredExtendType) const { 925 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 926 ISD::NodeType ExtendKind = PreferredExtendType; 927 928 // Get the list of the values's legal parts. 929 unsigned NumRegs = Regs.size(); 930 SmallVector<SDValue, 8> Parts(NumRegs); 931 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 932 unsigned NumParts = RegCount[Value]; 933 934 MVT RegisterVT = isABIMangled() 935 ? TLI.getRegisterTypeForCallingConv( 936 *DAG.getContext(), *CallConv, RegVTs[Value]) 937 : RegVTs[Value]; 938 939 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 940 ExtendKind = ISD::ZERO_EXTEND; 941 942 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 943 NumParts, RegisterVT, V, CallConv, ExtendKind); 944 Part += NumParts; 945 } 946 947 // Copy the parts into the registers. 948 SmallVector<SDValue, 8> Chains(NumRegs); 949 for (unsigned i = 0; i != NumRegs; ++i) { 950 SDValue Part; 951 if (!Glue) { 952 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 953 } else { 954 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue); 955 *Glue = Part.getValue(1); 956 } 957 958 Chains[i] = Part.getValue(0); 959 } 960 961 if (NumRegs == 1 || Glue) 962 // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is 963 // flagged to it. That is the CopyToReg nodes and the user are considered 964 // a single scheduling unit. If we create a TokenFactor and return it as 965 // chain, then the TokenFactor is both a predecessor (operand) of the 966 // user as well as a successor (the TF operands are flagged to the user). 967 // c1, f1 = CopyToReg 968 // c2, f2 = CopyToReg 969 // c3 = TokenFactor c1, c2 970 // ... 971 // = op c3, ..., f2 972 Chain = Chains[NumRegs-1]; 973 else 974 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 975 } 976 977 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 978 unsigned MatchingIdx, const SDLoc &dl, 979 SelectionDAG &DAG, 980 std::vector<SDValue> &Ops) const { 981 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 982 983 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 984 if (HasMatching) 985 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 986 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 987 // Put the register class of the virtual registers in the flag word. That 988 // way, later passes can recompute register class constraints for inline 989 // assembly as well as normal instructions. 990 // Don't do this for tied operands that can use the regclass information 991 // from the def. 992 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 993 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 994 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 995 } 996 997 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 998 Ops.push_back(Res); 999 1000 if (Code == InlineAsm::Kind_Clobber) { 1001 // Clobbers should always have a 1:1 mapping with registers, and may 1002 // reference registers that have illegal (e.g. vector) types. Hence, we 1003 // shouldn't try to apply any sort of splitting logic to them. 1004 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 1005 "No 1:1 mapping from clobbers to regs?"); 1006 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 1007 (void)SP; 1008 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 1009 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 1010 assert( 1011 (Regs[I] != SP || 1012 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 1013 "If we clobbered the stack pointer, MFI should know about it."); 1014 } 1015 return; 1016 } 1017 1018 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 1019 MVT RegisterVT = RegVTs[Value]; 1020 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value], 1021 RegisterVT); 1022 for (unsigned i = 0; i != NumRegs; ++i) { 1023 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 1024 unsigned TheReg = Regs[Reg++]; 1025 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 1026 } 1027 } 1028 } 1029 1030 SmallVector<std::pair<unsigned, TypeSize>, 4> 1031 RegsForValue::getRegsAndSizes() const { 1032 SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec; 1033 unsigned I = 0; 1034 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1035 unsigned RegCount = std::get<0>(CountAndVT); 1036 MVT RegisterVT = std::get<1>(CountAndVT); 1037 TypeSize RegisterSize = RegisterVT.getSizeInBits(); 1038 for (unsigned E = I + RegCount; I != E; ++I) 1039 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1040 } 1041 return OutVec; 1042 } 1043 1044 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1045 AssumptionCache *ac, 1046 const TargetLibraryInfo *li) { 1047 AA = aa; 1048 AC = ac; 1049 GFI = gfi; 1050 LibInfo = li; 1051 Context = DAG.getContext(); 1052 LPadToCallSiteMap.clear(); 1053 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1054 AssignmentTrackingEnabled = isAssignmentTrackingEnabled( 1055 *DAG.getMachineFunction().getFunction().getParent()); 1056 } 1057 1058 void SelectionDAGBuilder::clear() { 1059 NodeMap.clear(); 1060 UnusedArgNodeMap.clear(); 1061 PendingLoads.clear(); 1062 PendingExports.clear(); 1063 PendingConstrainedFP.clear(); 1064 PendingConstrainedFPStrict.clear(); 1065 CurInst = nullptr; 1066 HasTailCall = false; 1067 SDNodeOrder = LowestSDNodeOrder; 1068 StatepointLowering.clear(); 1069 } 1070 1071 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1072 DanglingDebugInfoMap.clear(); 1073 } 1074 1075 // Update DAG root to include dependencies on Pending chains. 1076 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1077 SDValue Root = DAG.getRoot(); 1078 1079 if (Pending.empty()) 1080 return Root; 1081 1082 // Add current root to PendingChains, unless we already indirectly 1083 // depend on it. 1084 if (Root.getOpcode() != ISD::EntryToken) { 1085 unsigned i = 0, e = Pending.size(); 1086 for (; i != e; ++i) { 1087 assert(Pending[i].getNode()->getNumOperands() > 1); 1088 if (Pending[i].getNode()->getOperand(0) == Root) 1089 break; // Don't add the root if we already indirectly depend on it. 1090 } 1091 1092 if (i == e) 1093 Pending.push_back(Root); 1094 } 1095 1096 if (Pending.size() == 1) 1097 Root = Pending[0]; 1098 else 1099 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1100 1101 DAG.setRoot(Root); 1102 Pending.clear(); 1103 return Root; 1104 } 1105 1106 SDValue SelectionDAGBuilder::getMemoryRoot() { 1107 return updateRoot(PendingLoads); 1108 } 1109 1110 SDValue SelectionDAGBuilder::getRoot() { 1111 // Chain up all pending constrained intrinsics together with all 1112 // pending loads, by simply appending them to PendingLoads and 1113 // then calling getMemoryRoot(). 1114 PendingLoads.reserve(PendingLoads.size() + 1115 PendingConstrainedFP.size() + 1116 PendingConstrainedFPStrict.size()); 1117 PendingLoads.append(PendingConstrainedFP.begin(), 1118 PendingConstrainedFP.end()); 1119 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1120 PendingConstrainedFPStrict.end()); 1121 PendingConstrainedFP.clear(); 1122 PendingConstrainedFPStrict.clear(); 1123 return getMemoryRoot(); 1124 } 1125 1126 SDValue SelectionDAGBuilder::getControlRoot() { 1127 // We need to emit pending fpexcept.strict constrained intrinsics, 1128 // so append them to the PendingExports list. 1129 PendingExports.append(PendingConstrainedFPStrict.begin(), 1130 PendingConstrainedFPStrict.end()); 1131 PendingConstrainedFPStrict.clear(); 1132 return updateRoot(PendingExports); 1133 } 1134 1135 void SelectionDAGBuilder::visit(const Instruction &I) { 1136 // Set up outgoing PHI node register values before emitting the terminator. 1137 if (I.isTerminator()) { 1138 HandlePHINodesInSuccessorBlocks(I.getParent()); 1139 } 1140 1141 // Add SDDbgValue nodes for any var locs here. Do so before updating 1142 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1143 if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) { 1144 // Add SDDbgValue nodes for any var locs here. Do so before updating 1145 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1146 for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I); 1147 It != End; ++It) { 1148 auto *Var = FnVarLocs->getDILocalVariable(It->VariableID); 1149 dropDanglingDebugInfo(Var, It->Expr); 1150 SmallVector<Value *> Values(It->Values.location_ops()); 1151 if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder, 1152 It->Values.hasArgList())) 1153 addDanglingDebugInfo(It, SDNodeOrder); 1154 } 1155 } 1156 1157 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1158 if (!isa<DbgInfoIntrinsic>(I)) 1159 ++SDNodeOrder; 1160 1161 CurInst = &I; 1162 1163 // Set inserted listener only if required. 1164 bool NodeInserted = false; 1165 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener; 1166 MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections); 1167 if (PCSectionsMD) { 1168 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>( 1169 DAG, [&](SDNode *) { NodeInserted = true; }); 1170 } 1171 1172 visit(I.getOpcode(), I); 1173 1174 if (!I.isTerminator() && !HasTailCall && 1175 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1176 CopyToExportRegsIfNeeded(&I); 1177 1178 // Handle metadata. 1179 if (PCSectionsMD) { 1180 auto It = NodeMap.find(&I); 1181 if (It != NodeMap.end()) { 1182 DAG.addPCSections(It->second.getNode(), PCSectionsMD); 1183 } else if (NodeInserted) { 1184 // This should not happen; if it does, don't let it go unnoticed so we can 1185 // fix it. Relevant visit*() function is probably missing a setValue(). 1186 errs() << "warning: loosing !pcsections metadata [" 1187 << I.getModule()->getName() << "]\n"; 1188 LLVM_DEBUG(I.dump()); 1189 assert(false); 1190 } 1191 } 1192 1193 CurInst = nullptr; 1194 } 1195 1196 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1197 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1198 } 1199 1200 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1201 // Note: this doesn't use InstVisitor, because it has to work with 1202 // ConstantExpr's in addition to instructions. 1203 switch (Opcode) { 1204 default: llvm_unreachable("Unknown instruction type encountered!"); 1205 // Build the switch statement using the Instruction.def file. 1206 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1207 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1208 #include "llvm/IR/Instruction.def" 1209 } 1210 } 1211 1212 static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG, 1213 DILocalVariable *Variable, 1214 DebugLoc DL, unsigned Order, 1215 RawLocationWrapper Values, 1216 DIExpression *Expression) { 1217 if (!Values.hasArgList()) 1218 return false; 1219 // For variadic dbg_values we will now insert an undef. 1220 // FIXME: We can potentially recover these! 1221 SmallVector<SDDbgOperand, 2> Locs; 1222 for (const Value *V : Values.location_ops()) { 1223 auto *Undef = UndefValue::get(V->getType()); 1224 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1225 } 1226 SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {}, 1227 /*IsIndirect=*/false, DL, Order, 1228 /*IsVariadic=*/true); 1229 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1230 return true; 1231 } 1232 1233 void SelectionDAGBuilder::addDanglingDebugInfo(const VarLocInfo *VarLoc, 1234 unsigned Order) { 1235 if (!handleDanglingVariadicDebugInfo( 1236 DAG, 1237 const_cast<DILocalVariable *>(DAG.getFunctionVarLocs() 1238 ->getVariable(VarLoc->VariableID) 1239 .getVariable()), 1240 VarLoc->DL, Order, VarLoc->Values, VarLoc->Expr)) { 1241 DanglingDebugInfoMap[VarLoc->Values.getVariableLocationOp(0)].emplace_back( 1242 VarLoc, Order); 1243 } 1244 } 1245 1246 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI, 1247 unsigned Order) { 1248 // We treat variadic dbg_values differently at this stage. 1249 if (!handleDanglingVariadicDebugInfo( 1250 DAG, DI->getVariable(), DI->getDebugLoc(), Order, 1251 DI->getWrappedLocation(), DI->getExpression())) { 1252 // TODO: Dangling debug info will eventually either be resolved or produce 1253 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1254 // between the original dbg.value location and its resolved DBG_VALUE, 1255 // which we should ideally fill with an extra Undef DBG_VALUE. 1256 assert(DI->getNumVariableLocationOps() == 1 && 1257 "DbgValueInst without an ArgList should have a single location " 1258 "operand."); 1259 DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, Order); 1260 } 1261 } 1262 1263 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1264 const DIExpression *Expr) { 1265 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1266 DIVariable *DanglingVariable = DDI.getVariable(DAG.getFunctionVarLocs()); 1267 DIExpression *DanglingExpr = DDI.getExpression(); 1268 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1269 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << printDDI(DDI) 1270 << "\n"); 1271 return true; 1272 } 1273 return false; 1274 }; 1275 1276 for (auto &DDIMI : DanglingDebugInfoMap) { 1277 DanglingDebugInfoVector &DDIV = DDIMI.second; 1278 1279 // If debug info is to be dropped, run it through final checks to see 1280 // whether it can be salvaged. 1281 for (auto &DDI : DDIV) 1282 if (isMatchingDbgValue(DDI)) 1283 salvageUnresolvedDbgValue(DDI); 1284 1285 erase_if(DDIV, isMatchingDbgValue); 1286 } 1287 } 1288 1289 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1290 // generate the debug data structures now that we've seen its definition. 1291 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1292 SDValue Val) { 1293 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1294 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1295 return; 1296 1297 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1298 for (auto &DDI : DDIV) { 1299 DebugLoc DL = DDI.getDebugLoc(); 1300 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1301 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1302 DILocalVariable *Variable = DDI.getVariable(DAG.getFunctionVarLocs()); 1303 DIExpression *Expr = DDI.getExpression(); 1304 assert(Variable->isValidLocationForIntrinsic(DL) && 1305 "Expected inlined-at fields to agree"); 1306 SDDbgValue *SDV; 1307 if (Val.getNode()) { 1308 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1309 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1310 // we couldn't resolve it directly when examining the DbgValue intrinsic 1311 // in the first place we should not be more successful here). Unless we 1312 // have some test case that prove this to be correct we should avoid 1313 // calling EmitFuncArgumentDbgValue here. 1314 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL, 1315 FuncArgumentDbgValueKind::Value, Val)) { 1316 LLVM_DEBUG(dbgs() << "Resolve dangling debug info for " << printDDI(DDI) 1317 << "\n"); 1318 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1319 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1320 // inserted after the definition of Val when emitting the instructions 1321 // after ISel. An alternative could be to teach 1322 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1323 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1324 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1325 << ValSDNodeOrder << "\n"); 1326 SDV = getDbgValue(Val, Variable, Expr, DL, 1327 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1328 DAG.AddDbgValue(SDV, false); 1329 } else 1330 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " 1331 << printDDI(DDI) << " in EmitFuncArgumentDbgValue\n"); 1332 } else { 1333 LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(DDI) << "\n"); 1334 auto Undef = UndefValue::get(V->getType()); 1335 auto SDV = 1336 DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder); 1337 DAG.AddDbgValue(SDV, false); 1338 } 1339 } 1340 DDIV.clear(); 1341 } 1342 1343 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1344 // TODO: For the variadic implementation, instead of only checking the fail 1345 // state of `handleDebugValue`, we need know specifically which values were 1346 // invalid, so that we attempt to salvage only those values when processing 1347 // a DIArgList. 1348 Value *V = DDI.getVariableLocationOp(0); 1349 Value *OrigV = V; 1350 DILocalVariable *Var = DDI.getVariable(DAG.getFunctionVarLocs()); 1351 DIExpression *Expr = DDI.getExpression(); 1352 DebugLoc DL = DDI.getDebugLoc(); 1353 unsigned SDOrder = DDI.getSDNodeOrder(); 1354 1355 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1356 // that DW_OP_stack_value is desired. 1357 bool StackValue = true; 1358 1359 // Can this Value can be encoded without any further work? 1360 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) 1361 return; 1362 1363 // Attempt to salvage back through as many instructions as possible. Bail if 1364 // a non-instruction is seen, such as a constant expression or global 1365 // variable. FIXME: Further work could recover those too. 1366 while (isa<Instruction>(V)) { 1367 Instruction &VAsInst = *cast<Instruction>(V); 1368 // Temporary "0", awaiting real implementation. 1369 SmallVector<uint64_t, 16> Ops; 1370 SmallVector<Value *, 4> AdditionalValues; 1371 V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops, 1372 AdditionalValues); 1373 // If we cannot salvage any further, and haven't yet found a suitable debug 1374 // expression, bail out. 1375 if (!V) 1376 break; 1377 1378 // TODO: If AdditionalValues isn't empty, then the salvage can only be 1379 // represented with a DBG_VALUE_LIST, so we give up. When we have support 1380 // here for variadic dbg_values, remove that condition. 1381 if (!AdditionalValues.empty()) 1382 break; 1383 1384 // New value and expr now represent this debuginfo. 1385 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue); 1386 1387 // Some kind of simplification occurred: check whether the operand of the 1388 // salvaged debug expression can be encoded in this DAG. 1389 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) { 1390 LLVM_DEBUG( 1391 dbgs() << "Salvaged debug location info for:\n " << *Var << "\n" 1392 << *OrigV << "\nBy stripping back to:\n " << *V << "\n"); 1393 return; 1394 } 1395 } 1396 1397 // This was the final opportunity to salvage this debug information, and it 1398 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1399 // any earlier variable location. 1400 assert(OrigV && "V shouldn't be null"); 1401 auto *Undef = UndefValue::get(OrigV->getType()); 1402 auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1403 DAG.AddDbgValue(SDV, false); 1404 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << printDDI(DDI) 1405 << "\n"); 1406 } 1407 1408 void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var, 1409 DIExpression *Expr, 1410 DebugLoc DbgLoc, 1411 unsigned Order) { 1412 Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context)); 1413 DIExpression *NewExpr = 1414 const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr)); 1415 handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order, 1416 /*IsVariadic*/ false); 1417 } 1418 1419 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1420 DILocalVariable *Var, 1421 DIExpression *Expr, DebugLoc DbgLoc, 1422 unsigned Order, bool IsVariadic) { 1423 if (Values.empty()) 1424 return true; 1425 SmallVector<SDDbgOperand> LocationOps; 1426 SmallVector<SDNode *> Dependencies; 1427 for (const Value *V : Values) { 1428 // Constant value. 1429 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1430 isa<ConstantPointerNull>(V)) { 1431 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1432 continue; 1433 } 1434 1435 // Look through IntToPtr constants. 1436 if (auto *CE = dyn_cast<ConstantExpr>(V)) 1437 if (CE->getOpcode() == Instruction::IntToPtr) { 1438 LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0))); 1439 continue; 1440 } 1441 1442 // If the Value is a frame index, we can create a FrameIndex debug value 1443 // without relying on the DAG at all. 1444 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1445 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1446 if (SI != FuncInfo.StaticAllocaMap.end()) { 1447 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1448 continue; 1449 } 1450 } 1451 1452 // Do not use getValue() in here; we don't want to generate code at 1453 // this point if it hasn't been done yet. 1454 SDValue N = NodeMap[V]; 1455 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1456 N = UnusedArgNodeMap[V]; 1457 if (N.getNode()) { 1458 // Only emit func arg dbg value for non-variadic dbg.values for now. 1459 if (!IsVariadic && 1460 EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc, 1461 FuncArgumentDbgValueKind::Value, N)) 1462 return true; 1463 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1464 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1465 // describe stack slot locations. 1466 // 1467 // Consider "int x = 0; int *px = &x;". There are two kinds of 1468 // interesting debug values here after optimization: 1469 // 1470 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1471 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1472 // 1473 // Both describe the direct values of their associated variables. 1474 Dependencies.push_back(N.getNode()); 1475 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1476 continue; 1477 } 1478 LocationOps.emplace_back( 1479 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1480 continue; 1481 } 1482 1483 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1484 // Special rules apply for the first dbg.values of parameter variables in a 1485 // function. Identify them by the fact they reference Argument Values, that 1486 // they're parameters, and they are parameters of the current function. We 1487 // need to let them dangle until they get an SDNode. 1488 bool IsParamOfFunc = 1489 isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt(); 1490 if (IsParamOfFunc) 1491 return false; 1492 1493 // The value is not used in this block yet (or it would have an SDNode). 1494 // We still want the value to appear for the user if possible -- if it has 1495 // an associated VReg, we can refer to that instead. 1496 auto VMI = FuncInfo.ValueMap.find(V); 1497 if (VMI != FuncInfo.ValueMap.end()) { 1498 unsigned Reg = VMI->second; 1499 // If this is a PHI node, it may be split up into several MI PHI nodes 1500 // (in FunctionLoweringInfo::set). 1501 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1502 V->getType(), std::nullopt); 1503 if (RFV.occupiesMultipleRegs()) { 1504 // FIXME: We could potentially support variadic dbg_values here. 1505 if (IsVariadic) 1506 return false; 1507 unsigned Offset = 0; 1508 unsigned BitsToDescribe = 0; 1509 if (auto VarSize = Var->getSizeInBits()) 1510 BitsToDescribe = *VarSize; 1511 if (auto Fragment = Expr->getFragmentInfo()) 1512 BitsToDescribe = Fragment->SizeInBits; 1513 for (const auto &RegAndSize : RFV.getRegsAndSizes()) { 1514 // Bail out if all bits are described already. 1515 if (Offset >= BitsToDescribe) 1516 break; 1517 // TODO: handle scalable vectors. 1518 unsigned RegisterSize = RegAndSize.second; 1519 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1520 ? BitsToDescribe - Offset 1521 : RegisterSize; 1522 auto FragmentExpr = DIExpression::createFragmentExpression( 1523 Expr, Offset, FragmentSize); 1524 if (!FragmentExpr) 1525 continue; 1526 SDDbgValue *SDV = DAG.getVRegDbgValue( 1527 Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, SDNodeOrder); 1528 DAG.AddDbgValue(SDV, false); 1529 Offset += RegisterSize; 1530 } 1531 return true; 1532 } 1533 // We can use simple vreg locations for variadic dbg_values as well. 1534 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1535 continue; 1536 } 1537 // We failed to create a SDDbgOperand for V. 1538 return false; 1539 } 1540 1541 // We have created a SDDbgOperand for each Value in Values. 1542 // Should use Order instead of SDNodeOrder? 1543 assert(!LocationOps.empty()); 1544 SDDbgValue *SDV = DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1545 /*IsIndirect=*/false, DbgLoc, 1546 SDNodeOrder, IsVariadic); 1547 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1548 return true; 1549 } 1550 1551 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1552 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1553 for (auto &Pair : DanglingDebugInfoMap) 1554 for (auto &DDI : Pair.second) 1555 salvageUnresolvedDbgValue(DDI); 1556 clearDanglingDebugInfo(); 1557 } 1558 1559 /// getCopyFromRegs - If there was virtual register allocated for the value V 1560 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1561 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1562 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1563 SDValue Result; 1564 1565 if (It != FuncInfo.ValueMap.end()) { 1566 Register InReg = It->second; 1567 1568 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1569 DAG.getDataLayout(), InReg, Ty, 1570 std::nullopt); // This is not an ABI copy. 1571 SDValue Chain = DAG.getEntryNode(); 1572 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1573 V); 1574 resolveDanglingDebugInfo(V, Result); 1575 } 1576 1577 return Result; 1578 } 1579 1580 /// getValue - Return an SDValue for the given Value. 1581 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1582 // If we already have an SDValue for this value, use it. It's important 1583 // to do this first, so that we don't create a CopyFromReg if we already 1584 // have a regular SDValue. 1585 SDValue &N = NodeMap[V]; 1586 if (N.getNode()) return N; 1587 1588 // If there's a virtual register allocated and initialized for this 1589 // value, use it. 1590 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1591 return copyFromReg; 1592 1593 // Otherwise create a new SDValue and remember it. 1594 SDValue Val = getValueImpl(V); 1595 NodeMap[V] = Val; 1596 resolveDanglingDebugInfo(V, Val); 1597 return Val; 1598 } 1599 1600 /// getNonRegisterValue - Return an SDValue for the given Value, but 1601 /// don't look in FuncInfo.ValueMap for a virtual register. 1602 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1603 // If we already have an SDValue for this value, use it. 1604 SDValue &N = NodeMap[V]; 1605 if (N.getNode()) { 1606 if (isIntOrFPConstant(N)) { 1607 // Remove the debug location from the node as the node is about to be used 1608 // in a location which may differ from the original debug location. This 1609 // is relevant to Constant and ConstantFP nodes because they can appear 1610 // as constant expressions inside PHI nodes. 1611 N->setDebugLoc(DebugLoc()); 1612 } 1613 return N; 1614 } 1615 1616 // Otherwise create a new SDValue and remember it. 1617 SDValue Val = getValueImpl(V); 1618 NodeMap[V] = Val; 1619 resolveDanglingDebugInfo(V, Val); 1620 return Val; 1621 } 1622 1623 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1624 /// Create an SDValue for the given value. 1625 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1626 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1627 1628 if (const Constant *C = dyn_cast<Constant>(V)) { 1629 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1630 1631 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1632 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1633 1634 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1635 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1636 1637 if (isa<ConstantPointerNull>(C)) { 1638 unsigned AS = V->getType()->getPointerAddressSpace(); 1639 return DAG.getConstant(0, getCurSDLoc(), 1640 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1641 } 1642 1643 if (match(C, m_VScale())) 1644 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1645 1646 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1647 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1648 1649 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1650 return DAG.getUNDEF(VT); 1651 1652 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1653 visit(CE->getOpcode(), *CE); 1654 SDValue N1 = NodeMap[V]; 1655 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1656 return N1; 1657 } 1658 1659 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1660 SmallVector<SDValue, 4> Constants; 1661 for (const Use &U : C->operands()) { 1662 SDNode *Val = getValue(U).getNode(); 1663 // If the operand is an empty aggregate, there are no values. 1664 if (!Val) continue; 1665 // Add each leaf value from the operand to the Constants list 1666 // to form a flattened list of all the values. 1667 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1668 Constants.push_back(SDValue(Val, i)); 1669 } 1670 1671 return DAG.getMergeValues(Constants, getCurSDLoc()); 1672 } 1673 1674 if (const ConstantDataSequential *CDS = 1675 dyn_cast<ConstantDataSequential>(C)) { 1676 SmallVector<SDValue, 4> Ops; 1677 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1678 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1679 // Add each leaf value from the operand to the Constants list 1680 // to form a flattened list of all the values. 1681 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1682 Ops.push_back(SDValue(Val, i)); 1683 } 1684 1685 if (isa<ArrayType>(CDS->getType())) 1686 return DAG.getMergeValues(Ops, getCurSDLoc()); 1687 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1688 } 1689 1690 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1691 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1692 "Unknown struct or array constant!"); 1693 1694 SmallVector<EVT, 4> ValueVTs; 1695 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1696 unsigned NumElts = ValueVTs.size(); 1697 if (NumElts == 0) 1698 return SDValue(); // empty struct 1699 SmallVector<SDValue, 4> Constants(NumElts); 1700 for (unsigned i = 0; i != NumElts; ++i) { 1701 EVT EltVT = ValueVTs[i]; 1702 if (isa<UndefValue>(C)) 1703 Constants[i] = DAG.getUNDEF(EltVT); 1704 else if (EltVT.isFloatingPoint()) 1705 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1706 else 1707 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1708 } 1709 1710 return DAG.getMergeValues(Constants, getCurSDLoc()); 1711 } 1712 1713 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1714 return DAG.getBlockAddress(BA, VT); 1715 1716 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1717 return getValue(Equiv->getGlobalValue()); 1718 1719 if (const auto *NC = dyn_cast<NoCFIValue>(C)) 1720 return getValue(NC->getGlobalValue()); 1721 1722 VectorType *VecTy = cast<VectorType>(V->getType()); 1723 1724 // Now that we know the number and type of the elements, get that number of 1725 // elements into the Ops array based on what kind of constant it is. 1726 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1727 SmallVector<SDValue, 16> Ops; 1728 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1729 for (unsigned i = 0; i != NumElements; ++i) 1730 Ops.push_back(getValue(CV->getOperand(i))); 1731 1732 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1733 } 1734 1735 if (isa<ConstantAggregateZero>(C)) { 1736 EVT EltVT = 1737 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1738 1739 SDValue Op; 1740 if (EltVT.isFloatingPoint()) 1741 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1742 else 1743 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1744 1745 return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op); 1746 } 1747 1748 llvm_unreachable("Unknown vector constant"); 1749 } 1750 1751 // If this is a static alloca, generate it as the frameindex instead of 1752 // computation. 1753 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1754 DenseMap<const AllocaInst*, int>::iterator SI = 1755 FuncInfo.StaticAllocaMap.find(AI); 1756 if (SI != FuncInfo.StaticAllocaMap.end()) 1757 return DAG.getFrameIndex( 1758 SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType())); 1759 } 1760 1761 // If this is an instruction which fast-isel has deferred, select it now. 1762 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1763 Register InReg = FuncInfo.InitializeRegForValue(Inst); 1764 1765 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1766 Inst->getType(), std::nullopt); 1767 SDValue Chain = DAG.getEntryNode(); 1768 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1769 } 1770 1771 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) 1772 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1773 1774 if (const auto *BB = dyn_cast<BasicBlock>(V)) 1775 return DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 1776 1777 llvm_unreachable("Can't get register for value!"); 1778 } 1779 1780 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1781 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1782 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1783 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1784 bool IsSEH = isAsynchronousEHPersonality(Pers); 1785 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1786 if (!IsSEH) 1787 CatchPadMBB->setIsEHScopeEntry(); 1788 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1789 if (IsMSVCCXX || IsCoreCLR) 1790 CatchPadMBB->setIsEHFuncletEntry(); 1791 } 1792 1793 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1794 // Update machine-CFG edge. 1795 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1796 FuncInfo.MBB->addSuccessor(TargetMBB); 1797 TargetMBB->setIsEHCatchretTarget(true); 1798 DAG.getMachineFunction().setHasEHCatchret(true); 1799 1800 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1801 bool IsSEH = isAsynchronousEHPersonality(Pers); 1802 if (IsSEH) { 1803 // If this is not a fall-through branch or optimizations are switched off, 1804 // emit the branch. 1805 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1806 TM.getOptLevel() == CodeGenOpt::None) 1807 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1808 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1809 return; 1810 } 1811 1812 // Figure out the funclet membership for the catchret's successor. 1813 // This will be used by the FuncletLayout pass to determine how to order the 1814 // BB's. 1815 // A 'catchret' returns to the outer scope's color. 1816 Value *ParentPad = I.getCatchSwitchParentPad(); 1817 const BasicBlock *SuccessorColor; 1818 if (isa<ConstantTokenNone>(ParentPad)) 1819 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1820 else 1821 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1822 assert(SuccessorColor && "No parent funclet for catchret!"); 1823 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1824 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1825 1826 // Create the terminator node. 1827 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1828 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1829 DAG.getBasicBlock(SuccessorColorMBB)); 1830 DAG.setRoot(Ret); 1831 } 1832 1833 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1834 // Don't emit any special code for the cleanuppad instruction. It just marks 1835 // the start of an EH scope/funclet. 1836 FuncInfo.MBB->setIsEHScopeEntry(); 1837 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1838 if (Pers != EHPersonality::Wasm_CXX) { 1839 FuncInfo.MBB->setIsEHFuncletEntry(); 1840 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1841 } 1842 } 1843 1844 // In wasm EH, even though a catchpad may not catch an exception if a tag does 1845 // not match, it is OK to add only the first unwind destination catchpad to the 1846 // successors, because there will be at least one invoke instruction within the 1847 // catch scope that points to the next unwind destination, if one exists, so 1848 // CFGSort cannot mess up with BB sorting order. 1849 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 1850 // call within them, and catchpads only consisting of 'catch (...)' have a 1851 // '__cxa_end_catch' call within them, both of which generate invokes in case 1852 // the next unwind destination exists, i.e., the next unwind destination is not 1853 // the caller.) 1854 // 1855 // Having at most one EH pad successor is also simpler and helps later 1856 // transformations. 1857 // 1858 // For example, 1859 // current: 1860 // invoke void @foo to ... unwind label %catch.dispatch 1861 // catch.dispatch: 1862 // %0 = catchswitch within ... [label %catch.start] unwind label %next 1863 // catch.start: 1864 // ... 1865 // ... in this BB or some other child BB dominated by this BB there will be an 1866 // invoke that points to 'next' BB as an unwind destination 1867 // 1868 // next: ; We don't need to add this to 'current' BB's successor 1869 // ... 1870 static void findWasmUnwindDestinations( 1871 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1872 BranchProbability Prob, 1873 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1874 &UnwindDests) { 1875 while (EHPadBB) { 1876 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1877 if (isa<CleanupPadInst>(Pad)) { 1878 // Stop on cleanup pads. 1879 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1880 UnwindDests.back().first->setIsEHScopeEntry(); 1881 break; 1882 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1883 // Add the catchpad handlers to the possible destinations. We don't 1884 // continue to the unwind destination of the catchswitch for wasm. 1885 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1886 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1887 UnwindDests.back().first->setIsEHScopeEntry(); 1888 } 1889 break; 1890 } else { 1891 continue; 1892 } 1893 } 1894 } 1895 1896 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1897 /// many places it could ultimately go. In the IR, we have a single unwind 1898 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1899 /// This function skips over imaginary basic blocks that hold catchswitch 1900 /// instructions, and finds all the "real" machine 1901 /// basic block destinations. As those destinations may not be successors of 1902 /// EHPadBB, here we also calculate the edge probability to those destinations. 1903 /// The passed-in Prob is the edge probability to EHPadBB. 1904 static void findUnwindDestinations( 1905 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1906 BranchProbability Prob, 1907 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1908 &UnwindDests) { 1909 EHPersonality Personality = 1910 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1911 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1912 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1913 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1914 bool IsSEH = isAsynchronousEHPersonality(Personality); 1915 1916 if (IsWasmCXX) { 1917 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1918 assert(UnwindDests.size() <= 1 && 1919 "There should be at most one unwind destination for wasm"); 1920 return; 1921 } 1922 1923 while (EHPadBB) { 1924 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1925 BasicBlock *NewEHPadBB = nullptr; 1926 if (isa<LandingPadInst>(Pad)) { 1927 // Stop on landingpads. They are not funclets. 1928 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1929 break; 1930 } else if (isa<CleanupPadInst>(Pad)) { 1931 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1932 // personalities. 1933 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1934 UnwindDests.back().first->setIsEHScopeEntry(); 1935 UnwindDests.back().first->setIsEHFuncletEntry(); 1936 break; 1937 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1938 // Add the catchpad handlers to the possible destinations. 1939 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1940 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1941 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1942 if (IsMSVCCXX || IsCoreCLR) 1943 UnwindDests.back().first->setIsEHFuncletEntry(); 1944 if (!IsSEH) 1945 UnwindDests.back().first->setIsEHScopeEntry(); 1946 } 1947 NewEHPadBB = CatchSwitch->getUnwindDest(); 1948 } else { 1949 continue; 1950 } 1951 1952 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1953 if (BPI && NewEHPadBB) 1954 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1955 EHPadBB = NewEHPadBB; 1956 } 1957 } 1958 1959 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1960 // Update successor info. 1961 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1962 auto UnwindDest = I.getUnwindDest(); 1963 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1964 BranchProbability UnwindDestProb = 1965 (BPI && UnwindDest) 1966 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1967 : BranchProbability::getZero(); 1968 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1969 for (auto &UnwindDest : UnwindDests) { 1970 UnwindDest.first->setIsEHPad(); 1971 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1972 } 1973 FuncInfo.MBB->normalizeSuccProbs(); 1974 1975 // Create the terminator node. 1976 SDValue Ret = 1977 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1978 DAG.setRoot(Ret); 1979 } 1980 1981 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1982 report_fatal_error("visitCatchSwitch not yet implemented!"); 1983 } 1984 1985 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1986 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1987 auto &DL = DAG.getDataLayout(); 1988 SDValue Chain = getControlRoot(); 1989 SmallVector<ISD::OutputArg, 8> Outs; 1990 SmallVector<SDValue, 8> OutVals; 1991 1992 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1993 // lower 1994 // 1995 // %val = call <ty> @llvm.experimental.deoptimize() 1996 // ret <ty> %val 1997 // 1998 // differently. 1999 if (I.getParent()->getTerminatingDeoptimizeCall()) { 2000 LowerDeoptimizingReturn(); 2001 return; 2002 } 2003 2004 if (!FuncInfo.CanLowerReturn) { 2005 unsigned DemoteReg = FuncInfo.DemoteRegister; 2006 const Function *F = I.getParent()->getParent(); 2007 2008 // Emit a store of the return value through the virtual register. 2009 // Leave Outs empty so that LowerReturn won't try to load return 2010 // registers the usual way. 2011 SmallVector<EVT, 1> PtrValueVTs; 2012 ComputeValueVTs(TLI, DL, 2013 F->getReturnType()->getPointerTo( 2014 DAG.getDataLayout().getAllocaAddrSpace()), 2015 PtrValueVTs); 2016 2017 SDValue RetPtr = 2018 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]); 2019 SDValue RetOp = getValue(I.getOperand(0)); 2020 2021 SmallVector<EVT, 4> ValueVTs, MemVTs; 2022 SmallVector<uint64_t, 4> Offsets; 2023 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 2024 &Offsets); 2025 unsigned NumValues = ValueVTs.size(); 2026 2027 SmallVector<SDValue, 4> Chains(NumValues); 2028 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 2029 for (unsigned i = 0; i != NumValues; ++i) { 2030 // An aggregate return value cannot wrap around the address space, so 2031 // offsets to its parts don't wrap either. 2032 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 2033 TypeSize::Fixed(Offsets[i])); 2034 2035 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 2036 if (MemVTs[i] != ValueVTs[i]) 2037 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 2038 Chains[i] = DAG.getStore( 2039 Chain, getCurSDLoc(), Val, 2040 // FIXME: better loc info would be nice. 2041 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 2042 commonAlignment(BaseAlign, Offsets[i])); 2043 } 2044 2045 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 2046 MVT::Other, Chains); 2047 } else if (I.getNumOperands() != 0) { 2048 SmallVector<EVT, 4> ValueVTs; 2049 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 2050 unsigned NumValues = ValueVTs.size(); 2051 if (NumValues) { 2052 SDValue RetOp = getValue(I.getOperand(0)); 2053 2054 const Function *F = I.getParent()->getParent(); 2055 2056 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 2057 I.getOperand(0)->getType(), F->getCallingConv(), 2058 /*IsVarArg*/ false, DL); 2059 2060 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 2061 if (F->getAttributes().hasRetAttr(Attribute::SExt)) 2062 ExtendKind = ISD::SIGN_EXTEND; 2063 else if (F->getAttributes().hasRetAttr(Attribute::ZExt)) 2064 ExtendKind = ISD::ZERO_EXTEND; 2065 2066 LLVMContext &Context = F->getContext(); 2067 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg); 2068 2069 for (unsigned j = 0; j != NumValues; ++j) { 2070 EVT VT = ValueVTs[j]; 2071 2072 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 2073 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 2074 2075 CallingConv::ID CC = F->getCallingConv(); 2076 2077 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 2078 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 2079 SmallVector<SDValue, 4> Parts(NumParts); 2080 getCopyToParts(DAG, getCurSDLoc(), 2081 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 2082 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 2083 2084 // 'inreg' on function refers to return value 2085 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2086 if (RetInReg) 2087 Flags.setInReg(); 2088 2089 if (I.getOperand(0)->getType()->isPointerTy()) { 2090 Flags.setPointer(); 2091 Flags.setPointerAddrSpace( 2092 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 2093 } 2094 2095 if (NeedsRegBlock) { 2096 Flags.setInConsecutiveRegs(); 2097 if (j == NumValues - 1) 2098 Flags.setInConsecutiveRegsLast(); 2099 } 2100 2101 // Propagate extension type if any 2102 if (ExtendKind == ISD::SIGN_EXTEND) 2103 Flags.setSExt(); 2104 else if (ExtendKind == ISD::ZERO_EXTEND) 2105 Flags.setZExt(); 2106 2107 for (unsigned i = 0; i < NumParts; ++i) { 2108 Outs.push_back(ISD::OutputArg(Flags, 2109 Parts[i].getValueType().getSimpleVT(), 2110 VT, /*isfixed=*/true, 0, 0)); 2111 OutVals.push_back(Parts[i]); 2112 } 2113 } 2114 } 2115 } 2116 2117 // Push in swifterror virtual register as the last element of Outs. This makes 2118 // sure swifterror virtual register will be returned in the swifterror 2119 // physical register. 2120 const Function *F = I.getParent()->getParent(); 2121 if (TLI.supportSwiftError() && 2122 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2123 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2124 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2125 Flags.setSwiftError(); 2126 Outs.push_back(ISD::OutputArg( 2127 Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)), 2128 /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0)); 2129 // Create SDNode for the swifterror virtual register. 2130 OutVals.push_back( 2131 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2132 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2133 EVT(TLI.getPointerTy(DL)))); 2134 } 2135 2136 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2137 CallingConv::ID CallConv = 2138 DAG.getMachineFunction().getFunction().getCallingConv(); 2139 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2140 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2141 2142 // Verify that the target's LowerReturn behaved as expected. 2143 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2144 "LowerReturn didn't return a valid chain!"); 2145 2146 // Update the DAG with the new chain value resulting from return lowering. 2147 DAG.setRoot(Chain); 2148 } 2149 2150 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2151 /// created for it, emit nodes to copy the value into the virtual 2152 /// registers. 2153 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2154 // Skip empty types 2155 if (V->getType()->isEmptyTy()) 2156 return; 2157 2158 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2159 if (VMI != FuncInfo.ValueMap.end()) { 2160 assert((!V->use_empty() || isa<CallBrInst>(V)) && 2161 "Unused value assigned virtual registers!"); 2162 CopyValueToVirtualRegister(V, VMI->second); 2163 } 2164 } 2165 2166 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2167 /// the current basic block, add it to ValueMap now so that we'll get a 2168 /// CopyTo/FromReg. 2169 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2170 // No need to export constants. 2171 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2172 2173 // Already exported? 2174 if (FuncInfo.isExportedInst(V)) return; 2175 2176 Register Reg = FuncInfo.InitializeRegForValue(V); 2177 CopyValueToVirtualRegister(V, Reg); 2178 } 2179 2180 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2181 const BasicBlock *FromBB) { 2182 // The operands of the setcc have to be in this block. We don't know 2183 // how to export them from some other block. 2184 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2185 // Can export from current BB. 2186 if (VI->getParent() == FromBB) 2187 return true; 2188 2189 // Is already exported, noop. 2190 return FuncInfo.isExportedInst(V); 2191 } 2192 2193 // If this is an argument, we can export it if the BB is the entry block or 2194 // if it is already exported. 2195 if (isa<Argument>(V)) { 2196 if (FromBB->isEntryBlock()) 2197 return true; 2198 2199 // Otherwise, can only export this if it is already exported. 2200 return FuncInfo.isExportedInst(V); 2201 } 2202 2203 // Otherwise, constants can always be exported. 2204 return true; 2205 } 2206 2207 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2208 BranchProbability 2209 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2210 const MachineBasicBlock *Dst) const { 2211 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2212 const BasicBlock *SrcBB = Src->getBasicBlock(); 2213 const BasicBlock *DstBB = Dst->getBasicBlock(); 2214 if (!BPI) { 2215 // If BPI is not available, set the default probability as 1 / N, where N is 2216 // the number of successors. 2217 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2218 return BranchProbability(1, SuccSize); 2219 } 2220 return BPI->getEdgeProbability(SrcBB, DstBB); 2221 } 2222 2223 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2224 MachineBasicBlock *Dst, 2225 BranchProbability Prob) { 2226 if (!FuncInfo.BPI) 2227 Src->addSuccessorWithoutProb(Dst); 2228 else { 2229 if (Prob.isUnknown()) 2230 Prob = getEdgeProbability(Src, Dst); 2231 Src->addSuccessor(Dst, Prob); 2232 } 2233 } 2234 2235 static bool InBlock(const Value *V, const BasicBlock *BB) { 2236 if (const Instruction *I = dyn_cast<Instruction>(V)) 2237 return I->getParent() == BB; 2238 return true; 2239 } 2240 2241 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2242 /// This function emits a branch and is used at the leaves of an OR or an 2243 /// AND operator tree. 2244 void 2245 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2246 MachineBasicBlock *TBB, 2247 MachineBasicBlock *FBB, 2248 MachineBasicBlock *CurBB, 2249 MachineBasicBlock *SwitchBB, 2250 BranchProbability TProb, 2251 BranchProbability FProb, 2252 bool InvertCond) { 2253 const BasicBlock *BB = CurBB->getBasicBlock(); 2254 2255 // If the leaf of the tree is a comparison, merge the condition into 2256 // the caseblock. 2257 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2258 // The operands of the cmp have to be in this block. We don't know 2259 // how to export them from some other block. If this is the first block 2260 // of the sequence, no exporting is needed. 2261 if (CurBB == SwitchBB || 2262 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2263 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2264 ISD::CondCode Condition; 2265 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2266 ICmpInst::Predicate Pred = 2267 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2268 Condition = getICmpCondCode(Pred); 2269 } else { 2270 const FCmpInst *FC = cast<FCmpInst>(Cond); 2271 FCmpInst::Predicate Pred = 2272 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2273 Condition = getFCmpCondCode(Pred); 2274 if (TM.Options.NoNaNsFPMath) 2275 Condition = getFCmpCodeWithoutNaN(Condition); 2276 } 2277 2278 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2279 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2280 SL->SwitchCases.push_back(CB); 2281 return; 2282 } 2283 } 2284 2285 // Create a CaseBlock record representing this branch. 2286 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2287 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2288 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2289 SL->SwitchCases.push_back(CB); 2290 } 2291 2292 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2293 MachineBasicBlock *TBB, 2294 MachineBasicBlock *FBB, 2295 MachineBasicBlock *CurBB, 2296 MachineBasicBlock *SwitchBB, 2297 Instruction::BinaryOps Opc, 2298 BranchProbability TProb, 2299 BranchProbability FProb, 2300 bool InvertCond) { 2301 // Skip over not part of the tree and remember to invert op and operands at 2302 // next level. 2303 Value *NotCond; 2304 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2305 InBlock(NotCond, CurBB->getBasicBlock())) { 2306 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2307 !InvertCond); 2308 return; 2309 } 2310 2311 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2312 const Value *BOpOp0, *BOpOp1; 2313 // Compute the effective opcode for Cond, taking into account whether it needs 2314 // to be inverted, e.g. 2315 // and (not (or A, B)), C 2316 // gets lowered as 2317 // and (and (not A, not B), C) 2318 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2319 if (BOp) { 2320 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2321 ? Instruction::And 2322 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2323 ? Instruction::Or 2324 : (Instruction::BinaryOps)0); 2325 if (InvertCond) { 2326 if (BOpc == Instruction::And) 2327 BOpc = Instruction::Or; 2328 else if (BOpc == Instruction::Or) 2329 BOpc = Instruction::And; 2330 } 2331 } 2332 2333 // If this node is not part of the or/and tree, emit it as a branch. 2334 // Note that all nodes in the tree should have same opcode. 2335 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2336 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2337 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2338 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2339 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2340 TProb, FProb, InvertCond); 2341 return; 2342 } 2343 2344 // Create TmpBB after CurBB. 2345 MachineFunction::iterator BBI(CurBB); 2346 MachineFunction &MF = DAG.getMachineFunction(); 2347 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2348 CurBB->getParent()->insert(++BBI, TmpBB); 2349 2350 if (Opc == Instruction::Or) { 2351 // Codegen X | Y as: 2352 // BB1: 2353 // jmp_if_X TBB 2354 // jmp TmpBB 2355 // TmpBB: 2356 // jmp_if_Y TBB 2357 // jmp FBB 2358 // 2359 2360 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2361 // The requirement is that 2362 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2363 // = TrueProb for original BB. 2364 // Assuming the original probabilities are A and B, one choice is to set 2365 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2366 // A/(1+B) and 2B/(1+B). This choice assumes that 2367 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2368 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2369 // TmpBB, but the math is more complicated. 2370 2371 auto NewTrueProb = TProb / 2; 2372 auto NewFalseProb = TProb / 2 + FProb; 2373 // Emit the LHS condition. 2374 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2375 NewFalseProb, InvertCond); 2376 2377 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2378 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2379 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2380 // Emit the RHS condition into TmpBB. 2381 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2382 Probs[1], InvertCond); 2383 } else { 2384 assert(Opc == Instruction::And && "Unknown merge op!"); 2385 // Codegen X & Y as: 2386 // BB1: 2387 // jmp_if_X TmpBB 2388 // jmp FBB 2389 // TmpBB: 2390 // jmp_if_Y TBB 2391 // jmp FBB 2392 // 2393 // This requires creation of TmpBB after CurBB. 2394 2395 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2396 // The requirement is that 2397 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2398 // = FalseProb for original BB. 2399 // Assuming the original probabilities are A and B, one choice is to set 2400 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2401 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2402 // TrueProb for BB1 * FalseProb for TmpBB. 2403 2404 auto NewTrueProb = TProb + FProb / 2; 2405 auto NewFalseProb = FProb / 2; 2406 // Emit the LHS condition. 2407 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2408 NewFalseProb, InvertCond); 2409 2410 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2411 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2412 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2413 // Emit the RHS condition into TmpBB. 2414 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2415 Probs[1], InvertCond); 2416 } 2417 } 2418 2419 /// If the set of cases should be emitted as a series of branches, return true. 2420 /// If we should emit this as a bunch of and/or'd together conditions, return 2421 /// false. 2422 bool 2423 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2424 if (Cases.size() != 2) return true; 2425 2426 // If this is two comparisons of the same values or'd or and'd together, they 2427 // will get folded into a single comparison, so don't emit two blocks. 2428 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2429 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2430 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2431 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2432 return false; 2433 } 2434 2435 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2436 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2437 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2438 Cases[0].CC == Cases[1].CC && 2439 isa<Constant>(Cases[0].CmpRHS) && 2440 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2441 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2442 return false; 2443 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2444 return false; 2445 } 2446 2447 return true; 2448 } 2449 2450 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2451 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2452 2453 // Update machine-CFG edges. 2454 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2455 2456 if (I.isUnconditional()) { 2457 // Update machine-CFG edges. 2458 BrMBB->addSuccessor(Succ0MBB); 2459 2460 // If this is not a fall-through branch or optimizations are switched off, 2461 // emit the branch. 2462 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2463 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2464 MVT::Other, getControlRoot(), 2465 DAG.getBasicBlock(Succ0MBB))); 2466 2467 return; 2468 } 2469 2470 // If this condition is one of the special cases we handle, do special stuff 2471 // now. 2472 const Value *CondVal = I.getCondition(); 2473 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2474 2475 // If this is a series of conditions that are or'd or and'd together, emit 2476 // this as a sequence of branches instead of setcc's with and/or operations. 2477 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2478 // unpredictable branches, and vector extracts because those jumps are likely 2479 // expensive for any target), this should improve performance. 2480 // For example, instead of something like: 2481 // cmp A, B 2482 // C = seteq 2483 // cmp D, E 2484 // F = setle 2485 // or C, F 2486 // jnz foo 2487 // Emit: 2488 // cmp A, B 2489 // je foo 2490 // cmp D, E 2491 // jle foo 2492 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2493 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2494 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2495 Value *Vec; 2496 const Value *BOp0, *BOp1; 2497 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2498 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2499 Opcode = Instruction::And; 2500 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2501 Opcode = Instruction::Or; 2502 2503 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2504 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2505 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2506 getEdgeProbability(BrMBB, Succ0MBB), 2507 getEdgeProbability(BrMBB, Succ1MBB), 2508 /*InvertCond=*/false); 2509 // If the compares in later blocks need to use values not currently 2510 // exported from this block, export them now. This block should always 2511 // be the first entry. 2512 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2513 2514 // Allow some cases to be rejected. 2515 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2516 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2517 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2518 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2519 } 2520 2521 // Emit the branch for this block. 2522 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2523 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2524 return; 2525 } 2526 2527 // Okay, we decided not to do this, remove any inserted MBB's and clear 2528 // SwitchCases. 2529 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2530 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2531 2532 SL->SwitchCases.clear(); 2533 } 2534 } 2535 2536 // Create a CaseBlock record representing this branch. 2537 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2538 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2539 2540 // Use visitSwitchCase to actually insert the fast branch sequence for this 2541 // cond branch. 2542 visitSwitchCase(CB, BrMBB); 2543 } 2544 2545 /// visitSwitchCase - Emits the necessary code to represent a single node in 2546 /// the binary search tree resulting from lowering a switch instruction. 2547 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2548 MachineBasicBlock *SwitchBB) { 2549 SDValue Cond; 2550 SDValue CondLHS = getValue(CB.CmpLHS); 2551 SDLoc dl = CB.DL; 2552 2553 if (CB.CC == ISD::SETTRUE) { 2554 // Branch or fall through to TrueBB. 2555 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2556 SwitchBB->normalizeSuccProbs(); 2557 if (CB.TrueBB != NextBlock(SwitchBB)) { 2558 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2559 DAG.getBasicBlock(CB.TrueBB))); 2560 } 2561 return; 2562 } 2563 2564 auto &TLI = DAG.getTargetLoweringInfo(); 2565 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2566 2567 // Build the setcc now. 2568 if (!CB.CmpMHS) { 2569 // Fold "(X == true)" to X and "(X == false)" to !X to 2570 // handle common cases produced by branch lowering. 2571 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2572 CB.CC == ISD::SETEQ) 2573 Cond = CondLHS; 2574 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2575 CB.CC == ISD::SETEQ) { 2576 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2577 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2578 } else { 2579 SDValue CondRHS = getValue(CB.CmpRHS); 2580 2581 // If a pointer's DAG type is larger than its memory type then the DAG 2582 // values are zero-extended. This breaks signed comparisons so truncate 2583 // back to the underlying type before doing the compare. 2584 if (CondLHS.getValueType() != MemVT) { 2585 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2586 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2587 } 2588 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2589 } 2590 } else { 2591 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2592 2593 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2594 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2595 2596 SDValue CmpOp = getValue(CB.CmpMHS); 2597 EVT VT = CmpOp.getValueType(); 2598 2599 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2600 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2601 ISD::SETLE); 2602 } else { 2603 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2604 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2605 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2606 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2607 } 2608 } 2609 2610 // Update successor info 2611 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2612 // TrueBB and FalseBB are always different unless the incoming IR is 2613 // degenerate. This only happens when running llc on weird IR. 2614 if (CB.TrueBB != CB.FalseBB) 2615 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2616 SwitchBB->normalizeSuccProbs(); 2617 2618 // If the lhs block is the next block, invert the condition so that we can 2619 // fall through to the lhs instead of the rhs block. 2620 if (CB.TrueBB == NextBlock(SwitchBB)) { 2621 std::swap(CB.TrueBB, CB.FalseBB); 2622 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2623 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2624 } 2625 2626 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2627 MVT::Other, getControlRoot(), Cond, 2628 DAG.getBasicBlock(CB.TrueBB)); 2629 2630 setValue(CurInst, BrCond); 2631 2632 // Insert the false branch. Do this even if it's a fall through branch, 2633 // this makes it easier to do DAG optimizations which require inverting 2634 // the branch condition. 2635 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2636 DAG.getBasicBlock(CB.FalseBB)); 2637 2638 DAG.setRoot(BrCond); 2639 } 2640 2641 /// visitJumpTable - Emit JumpTable node in the current MBB 2642 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2643 // Emit the code for the jump table 2644 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2645 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2646 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2647 JT.Reg, PTy); 2648 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2649 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2650 MVT::Other, Index.getValue(1), 2651 Table, Index); 2652 DAG.setRoot(BrJumpTable); 2653 } 2654 2655 /// visitJumpTableHeader - This function emits necessary code to produce index 2656 /// in the JumpTable from switch case. 2657 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2658 JumpTableHeader &JTH, 2659 MachineBasicBlock *SwitchBB) { 2660 SDLoc dl = getCurSDLoc(); 2661 2662 // Subtract the lowest switch case value from the value being switched on. 2663 SDValue SwitchOp = getValue(JTH.SValue); 2664 EVT VT = SwitchOp.getValueType(); 2665 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2666 DAG.getConstant(JTH.First, dl, VT)); 2667 2668 // The SDNode we just created, which holds the value being switched on minus 2669 // the smallest case value, needs to be copied to a virtual register so it 2670 // can be used as an index into the jump table in a subsequent basic block. 2671 // This value may be smaller or larger than the target's pointer type, and 2672 // therefore require extension or truncating. 2673 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2674 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2675 2676 unsigned JumpTableReg = 2677 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2678 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2679 JumpTableReg, SwitchOp); 2680 JT.Reg = JumpTableReg; 2681 2682 if (!JTH.FallthroughUnreachable) { 2683 // Emit the range check for the jump table, and branch to the default block 2684 // for the switch statement if the value being switched on exceeds the 2685 // largest case in the switch. 2686 SDValue CMP = DAG.getSetCC( 2687 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2688 Sub.getValueType()), 2689 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2690 2691 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2692 MVT::Other, CopyTo, CMP, 2693 DAG.getBasicBlock(JT.Default)); 2694 2695 // Avoid emitting unnecessary branches to the next block. 2696 if (JT.MBB != NextBlock(SwitchBB)) 2697 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2698 DAG.getBasicBlock(JT.MBB)); 2699 2700 DAG.setRoot(BrCond); 2701 } else { 2702 // Avoid emitting unnecessary branches to the next block. 2703 if (JT.MBB != NextBlock(SwitchBB)) 2704 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2705 DAG.getBasicBlock(JT.MBB))); 2706 else 2707 DAG.setRoot(CopyTo); 2708 } 2709 } 2710 2711 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2712 /// variable if there exists one. 2713 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2714 SDValue &Chain) { 2715 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2716 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2717 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2718 MachineFunction &MF = DAG.getMachineFunction(); 2719 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2720 MachineSDNode *Node = 2721 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2722 if (Global) { 2723 MachinePointerInfo MPInfo(Global); 2724 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2725 MachineMemOperand::MODereferenceable; 2726 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2727 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2728 DAG.setNodeMemRefs(Node, {MemRef}); 2729 } 2730 if (PtrTy != PtrMemTy) 2731 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2732 return SDValue(Node, 0); 2733 } 2734 2735 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2736 /// tail spliced into a stack protector check success bb. 2737 /// 2738 /// For a high level explanation of how this fits into the stack protector 2739 /// generation see the comment on the declaration of class 2740 /// StackProtectorDescriptor. 2741 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2742 MachineBasicBlock *ParentBB) { 2743 2744 // First create the loads to the guard/stack slot for the comparison. 2745 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2746 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2747 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2748 2749 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2750 int FI = MFI.getStackProtectorIndex(); 2751 2752 SDValue Guard; 2753 SDLoc dl = getCurSDLoc(); 2754 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2755 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2756 Align Align = 2757 DAG.getDataLayout().getPrefTypeAlign(Type::getInt8PtrTy(M.getContext())); 2758 2759 // Generate code to load the content of the guard slot. 2760 SDValue GuardVal = DAG.getLoad( 2761 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2762 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2763 MachineMemOperand::MOVolatile); 2764 2765 if (TLI.useStackGuardXorFP()) 2766 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2767 2768 // Retrieve guard check function, nullptr if instrumentation is inlined. 2769 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2770 // The target provides a guard check function to validate the guard value. 2771 // Generate a call to that function with the content of the guard slot as 2772 // argument. 2773 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2774 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2775 2776 TargetLowering::ArgListTy Args; 2777 TargetLowering::ArgListEntry Entry; 2778 Entry.Node = GuardVal; 2779 Entry.Ty = FnTy->getParamType(0); 2780 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg)) 2781 Entry.IsInReg = true; 2782 Args.push_back(Entry); 2783 2784 TargetLowering::CallLoweringInfo CLI(DAG); 2785 CLI.setDebugLoc(getCurSDLoc()) 2786 .setChain(DAG.getEntryNode()) 2787 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2788 getValue(GuardCheckFn), std::move(Args)); 2789 2790 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2791 DAG.setRoot(Result.second); 2792 return; 2793 } 2794 2795 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2796 // Otherwise, emit a volatile load to retrieve the stack guard value. 2797 SDValue Chain = DAG.getEntryNode(); 2798 if (TLI.useLoadStackGuardNode()) { 2799 Guard = getLoadStackGuard(DAG, dl, Chain); 2800 } else { 2801 const Value *IRGuard = TLI.getSDagStackGuard(M); 2802 SDValue GuardPtr = getValue(IRGuard); 2803 2804 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2805 MachinePointerInfo(IRGuard, 0), Align, 2806 MachineMemOperand::MOVolatile); 2807 } 2808 2809 // Perform the comparison via a getsetcc. 2810 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2811 *DAG.getContext(), 2812 Guard.getValueType()), 2813 Guard, GuardVal, ISD::SETNE); 2814 2815 // If the guard/stackslot do not equal, branch to failure MBB. 2816 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2817 MVT::Other, GuardVal.getOperand(0), 2818 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2819 // Otherwise branch to success MBB. 2820 SDValue Br = DAG.getNode(ISD::BR, dl, 2821 MVT::Other, BrCond, 2822 DAG.getBasicBlock(SPD.getSuccessMBB())); 2823 2824 DAG.setRoot(Br); 2825 } 2826 2827 /// Codegen the failure basic block for a stack protector check. 2828 /// 2829 /// A failure stack protector machine basic block consists simply of a call to 2830 /// __stack_chk_fail(). 2831 /// 2832 /// For a high level explanation of how this fits into the stack protector 2833 /// generation see the comment on the declaration of class 2834 /// StackProtectorDescriptor. 2835 void 2836 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2837 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2838 TargetLowering::MakeLibCallOptions CallOptions; 2839 CallOptions.setDiscardResult(true); 2840 SDValue Chain = 2841 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2842 std::nullopt, CallOptions, getCurSDLoc()) 2843 .second; 2844 // On PS4/PS5, the "return address" must still be within the calling 2845 // function, even if it's at the very end, so emit an explicit TRAP here. 2846 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2847 if (TM.getTargetTriple().isPS()) 2848 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2849 // WebAssembly needs an unreachable instruction after a non-returning call, 2850 // because the function return type can be different from __stack_chk_fail's 2851 // return type (void). 2852 if (TM.getTargetTriple().isWasm()) 2853 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2854 2855 DAG.setRoot(Chain); 2856 } 2857 2858 /// visitBitTestHeader - This function emits necessary code to produce value 2859 /// suitable for "bit tests" 2860 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2861 MachineBasicBlock *SwitchBB) { 2862 SDLoc dl = getCurSDLoc(); 2863 2864 // Subtract the minimum value. 2865 SDValue SwitchOp = getValue(B.SValue); 2866 EVT VT = SwitchOp.getValueType(); 2867 SDValue RangeSub = 2868 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2869 2870 // Determine the type of the test operands. 2871 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2872 bool UsePtrType = false; 2873 if (!TLI.isTypeLegal(VT)) { 2874 UsePtrType = true; 2875 } else { 2876 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2877 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2878 // Switch table case range are encoded into series of masks. 2879 // Just use pointer type, it's guaranteed to fit. 2880 UsePtrType = true; 2881 break; 2882 } 2883 } 2884 SDValue Sub = RangeSub; 2885 if (UsePtrType) { 2886 VT = TLI.getPointerTy(DAG.getDataLayout()); 2887 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2888 } 2889 2890 B.RegVT = VT.getSimpleVT(); 2891 B.Reg = FuncInfo.CreateReg(B.RegVT); 2892 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2893 2894 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2895 2896 if (!B.FallthroughUnreachable) 2897 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2898 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2899 SwitchBB->normalizeSuccProbs(); 2900 2901 SDValue Root = CopyTo; 2902 if (!B.FallthroughUnreachable) { 2903 // Conditional branch to the default block. 2904 SDValue RangeCmp = DAG.getSetCC(dl, 2905 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2906 RangeSub.getValueType()), 2907 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2908 ISD::SETUGT); 2909 2910 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2911 DAG.getBasicBlock(B.Default)); 2912 } 2913 2914 // Avoid emitting unnecessary branches to the next block. 2915 if (MBB != NextBlock(SwitchBB)) 2916 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2917 2918 DAG.setRoot(Root); 2919 } 2920 2921 /// visitBitTestCase - this function produces one "bit test" 2922 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2923 MachineBasicBlock* NextMBB, 2924 BranchProbability BranchProbToNext, 2925 unsigned Reg, 2926 BitTestCase &B, 2927 MachineBasicBlock *SwitchBB) { 2928 SDLoc dl = getCurSDLoc(); 2929 MVT VT = BB.RegVT; 2930 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2931 SDValue Cmp; 2932 unsigned PopCount = llvm::popcount(B.Mask); 2933 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2934 if (PopCount == 1) { 2935 // Testing for a single bit; just compare the shift count with what it 2936 // would need to be to shift a 1 bit in that position. 2937 Cmp = DAG.getSetCC( 2938 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2939 ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT), 2940 ISD::SETEQ); 2941 } else if (PopCount == BB.Range) { 2942 // There is only one zero bit in the range, test for it directly. 2943 Cmp = DAG.getSetCC( 2944 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2945 ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE); 2946 } else { 2947 // Make desired shift 2948 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2949 DAG.getConstant(1, dl, VT), ShiftOp); 2950 2951 // Emit bit tests and jumps 2952 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2953 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2954 Cmp = DAG.getSetCC( 2955 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2956 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2957 } 2958 2959 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2960 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2961 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2962 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2963 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2964 // one as they are relative probabilities (and thus work more like weights), 2965 // and hence we need to normalize them to let the sum of them become one. 2966 SwitchBB->normalizeSuccProbs(); 2967 2968 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2969 MVT::Other, getControlRoot(), 2970 Cmp, DAG.getBasicBlock(B.TargetBB)); 2971 2972 // Avoid emitting unnecessary branches to the next block. 2973 if (NextMBB != NextBlock(SwitchBB)) 2974 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2975 DAG.getBasicBlock(NextMBB)); 2976 2977 DAG.setRoot(BrAnd); 2978 } 2979 2980 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2981 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2982 2983 // Retrieve successors. Look through artificial IR level blocks like 2984 // catchswitch for successors. 2985 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2986 const BasicBlock *EHPadBB = I.getSuccessor(1); 2987 MachineBasicBlock *EHPadMBB = FuncInfo.MBBMap[EHPadBB]; 2988 2989 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2990 // have to do anything here to lower funclet bundles. 2991 assert(!I.hasOperandBundlesOtherThan( 2992 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 2993 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 2994 LLVMContext::OB_cfguardtarget, 2995 LLVMContext::OB_clang_arc_attachedcall}) && 2996 "Cannot lower invokes with arbitrary operand bundles yet!"); 2997 2998 const Value *Callee(I.getCalledOperand()); 2999 const Function *Fn = dyn_cast<Function>(Callee); 3000 if (isa<InlineAsm>(Callee)) 3001 visitInlineAsm(I, EHPadBB); 3002 else if (Fn && Fn->isIntrinsic()) { 3003 switch (Fn->getIntrinsicID()) { 3004 default: 3005 llvm_unreachable("Cannot invoke this intrinsic"); 3006 case Intrinsic::donothing: 3007 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 3008 case Intrinsic::seh_try_begin: 3009 case Intrinsic::seh_scope_begin: 3010 case Intrinsic::seh_try_end: 3011 case Intrinsic::seh_scope_end: 3012 if (EHPadMBB) 3013 // a block referenced by EH table 3014 // so dtor-funclet not removed by opts 3015 EHPadMBB->setMachineBlockAddressTaken(); 3016 break; 3017 case Intrinsic::experimental_patchpoint_void: 3018 case Intrinsic::experimental_patchpoint_i64: 3019 visitPatchpoint(I, EHPadBB); 3020 break; 3021 case Intrinsic::experimental_gc_statepoint: 3022 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 3023 break; 3024 case Intrinsic::wasm_rethrow: { 3025 // This is usually done in visitTargetIntrinsic, but this intrinsic is 3026 // special because it can be invoked, so we manually lower it to a DAG 3027 // node here. 3028 SmallVector<SDValue, 8> Ops; 3029 Ops.push_back(getRoot()); // inchain 3030 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3031 Ops.push_back( 3032 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 3033 TLI.getPointerTy(DAG.getDataLayout()))); 3034 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 3035 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 3036 break; 3037 } 3038 } 3039 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 3040 // Currently we do not lower any intrinsic calls with deopt operand bundles. 3041 // Eventually we will support lowering the @llvm.experimental.deoptimize 3042 // intrinsic, and right now there are no plans to support other intrinsics 3043 // with deopt state. 3044 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 3045 } else { 3046 LowerCallTo(I, getValue(Callee), false, false, EHPadBB); 3047 } 3048 3049 // If the value of the invoke is used outside of its defining block, make it 3050 // available as a virtual register. 3051 // We already took care of the exported value for the statepoint instruction 3052 // during call to the LowerStatepoint. 3053 if (!isa<GCStatepointInst>(I)) { 3054 CopyToExportRegsIfNeeded(&I); 3055 } 3056 3057 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 3058 BranchProbabilityInfo *BPI = FuncInfo.BPI; 3059 BranchProbability EHPadBBProb = 3060 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 3061 : BranchProbability::getZero(); 3062 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 3063 3064 // Update successor info. 3065 addSuccessorWithProb(InvokeMBB, Return); 3066 for (auto &UnwindDest : UnwindDests) { 3067 UnwindDest.first->setIsEHPad(); 3068 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 3069 } 3070 InvokeMBB->normalizeSuccProbs(); 3071 3072 // Drop into normal successor. 3073 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 3074 DAG.getBasicBlock(Return))); 3075 } 3076 3077 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 3078 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 3079 3080 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3081 // have to do anything here to lower funclet bundles. 3082 assert(!I.hasOperandBundlesOtherThan( 3083 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 3084 "Cannot lower callbrs with arbitrary operand bundles yet!"); 3085 3086 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 3087 visitInlineAsm(I); 3088 CopyToExportRegsIfNeeded(&I); 3089 3090 // Retrieve successors. 3091 SmallPtrSet<BasicBlock *, 8> Dests; 3092 Dests.insert(I.getDefaultDest()); 3093 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 3094 3095 // Update successor info. 3096 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 3097 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 3098 BasicBlock *Dest = I.getIndirectDest(i); 3099 MachineBasicBlock *Target = FuncInfo.MBBMap[Dest]; 3100 Target->setIsInlineAsmBrIndirectTarget(); 3101 Target->setMachineBlockAddressTaken(); 3102 Target->setLabelMustBeEmitted(); 3103 // Don't add duplicate machine successors. 3104 if (Dests.insert(Dest).second) 3105 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 3106 } 3107 CallBrMBB->normalizeSuccProbs(); 3108 3109 // Drop into default successor. 3110 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 3111 MVT::Other, getControlRoot(), 3112 DAG.getBasicBlock(Return))); 3113 } 3114 3115 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 3116 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 3117 } 3118 3119 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 3120 assert(FuncInfo.MBB->isEHPad() && 3121 "Call to landingpad not in landing pad!"); 3122 3123 // If there aren't registers to copy the values into (e.g., during SjLj 3124 // exceptions), then don't bother to create these DAG nodes. 3125 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3126 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 3127 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 3128 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 3129 return; 3130 3131 // If landingpad's return type is token type, we don't create DAG nodes 3132 // for its exception pointer and selector value. The extraction of exception 3133 // pointer or selector value from token type landingpads is not currently 3134 // supported. 3135 if (LP.getType()->isTokenTy()) 3136 return; 3137 3138 SmallVector<EVT, 2> ValueVTs; 3139 SDLoc dl = getCurSDLoc(); 3140 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3141 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3142 3143 // Get the two live-in registers as SDValues. The physregs have already been 3144 // copied into virtual registers. 3145 SDValue Ops[2]; 3146 if (FuncInfo.ExceptionPointerVirtReg) { 3147 Ops[0] = DAG.getZExtOrTrunc( 3148 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3149 FuncInfo.ExceptionPointerVirtReg, 3150 TLI.getPointerTy(DAG.getDataLayout())), 3151 dl, ValueVTs[0]); 3152 } else { 3153 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3154 } 3155 Ops[1] = DAG.getZExtOrTrunc( 3156 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3157 FuncInfo.ExceptionSelectorVirtReg, 3158 TLI.getPointerTy(DAG.getDataLayout())), 3159 dl, ValueVTs[1]); 3160 3161 // Merge into one. 3162 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3163 DAG.getVTList(ValueVTs), Ops); 3164 setValue(&LP, Res); 3165 } 3166 3167 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3168 MachineBasicBlock *Last) { 3169 // Update JTCases. 3170 for (JumpTableBlock &JTB : SL->JTCases) 3171 if (JTB.first.HeaderBB == First) 3172 JTB.first.HeaderBB = Last; 3173 3174 // Update BitTestCases. 3175 for (BitTestBlock &BTB : SL->BitTestCases) 3176 if (BTB.Parent == First) 3177 BTB.Parent = Last; 3178 } 3179 3180 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3181 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3182 3183 // Update machine-CFG edges with unique successors. 3184 SmallSet<BasicBlock*, 32> Done; 3185 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3186 BasicBlock *BB = I.getSuccessor(i); 3187 bool Inserted = Done.insert(BB).second; 3188 if (!Inserted) 3189 continue; 3190 3191 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3192 addSuccessorWithProb(IndirectBrMBB, Succ); 3193 } 3194 IndirectBrMBB->normalizeSuccProbs(); 3195 3196 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3197 MVT::Other, getControlRoot(), 3198 getValue(I.getAddress()))); 3199 } 3200 3201 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3202 if (!DAG.getTarget().Options.TrapUnreachable) 3203 return; 3204 3205 // We may be able to ignore unreachable behind a noreturn call. 3206 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3207 const BasicBlock &BB = *I.getParent(); 3208 if (&I != &BB.front()) { 3209 BasicBlock::const_iterator PredI = 3210 std::prev(BasicBlock::const_iterator(&I)); 3211 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 3212 if (Call->doesNotReturn()) 3213 return; 3214 } 3215 } 3216 } 3217 3218 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3219 } 3220 3221 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3222 SDNodeFlags Flags; 3223 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3224 Flags.copyFMF(*FPOp); 3225 3226 SDValue Op = getValue(I.getOperand(0)); 3227 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3228 Op, Flags); 3229 setValue(&I, UnNodeValue); 3230 } 3231 3232 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3233 SDNodeFlags Flags; 3234 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3235 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3236 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3237 } 3238 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3239 Flags.setExact(ExactOp->isExact()); 3240 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3241 Flags.copyFMF(*FPOp); 3242 3243 SDValue Op1 = getValue(I.getOperand(0)); 3244 SDValue Op2 = getValue(I.getOperand(1)); 3245 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3246 Op1, Op2, Flags); 3247 setValue(&I, BinNodeValue); 3248 } 3249 3250 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3251 SDValue Op1 = getValue(I.getOperand(0)); 3252 SDValue Op2 = getValue(I.getOperand(1)); 3253 3254 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3255 Op1.getValueType(), DAG.getDataLayout()); 3256 3257 // Coerce the shift amount to the right type if we can. This exposes the 3258 // truncate or zext to optimization early. 3259 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3260 assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) && 3261 "Unexpected shift type"); 3262 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy); 3263 } 3264 3265 bool nuw = false; 3266 bool nsw = false; 3267 bool exact = false; 3268 3269 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3270 3271 if (const OverflowingBinaryOperator *OFBinOp = 3272 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3273 nuw = OFBinOp->hasNoUnsignedWrap(); 3274 nsw = OFBinOp->hasNoSignedWrap(); 3275 } 3276 if (const PossiblyExactOperator *ExactOp = 3277 dyn_cast<const PossiblyExactOperator>(&I)) 3278 exact = ExactOp->isExact(); 3279 } 3280 SDNodeFlags Flags; 3281 Flags.setExact(exact); 3282 Flags.setNoSignedWrap(nsw); 3283 Flags.setNoUnsignedWrap(nuw); 3284 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3285 Flags); 3286 setValue(&I, Res); 3287 } 3288 3289 void SelectionDAGBuilder::visitSDiv(const User &I) { 3290 SDValue Op1 = getValue(I.getOperand(0)); 3291 SDValue Op2 = getValue(I.getOperand(1)); 3292 3293 SDNodeFlags Flags; 3294 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3295 cast<PossiblyExactOperator>(&I)->isExact()); 3296 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3297 Op2, Flags)); 3298 } 3299 3300 void SelectionDAGBuilder::visitICmp(const User &I) { 3301 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3302 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3303 predicate = IC->getPredicate(); 3304 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3305 predicate = ICmpInst::Predicate(IC->getPredicate()); 3306 SDValue Op1 = getValue(I.getOperand(0)); 3307 SDValue Op2 = getValue(I.getOperand(1)); 3308 ISD::CondCode Opcode = getICmpCondCode(predicate); 3309 3310 auto &TLI = DAG.getTargetLoweringInfo(); 3311 EVT MemVT = 3312 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3313 3314 // If a pointer's DAG type is larger than its memory type then the DAG values 3315 // are zero-extended. This breaks signed comparisons so truncate back to the 3316 // underlying type before doing the compare. 3317 if (Op1.getValueType() != MemVT) { 3318 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3319 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3320 } 3321 3322 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3323 I.getType()); 3324 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3325 } 3326 3327 void SelectionDAGBuilder::visitFCmp(const User &I) { 3328 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3329 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3330 predicate = FC->getPredicate(); 3331 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3332 predicate = FCmpInst::Predicate(FC->getPredicate()); 3333 SDValue Op1 = getValue(I.getOperand(0)); 3334 SDValue Op2 = getValue(I.getOperand(1)); 3335 3336 ISD::CondCode Condition = getFCmpCondCode(predicate); 3337 auto *FPMO = cast<FPMathOperator>(&I); 3338 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3339 Condition = getFCmpCodeWithoutNaN(Condition); 3340 3341 SDNodeFlags Flags; 3342 Flags.copyFMF(*FPMO); 3343 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3344 3345 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3346 I.getType()); 3347 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3348 } 3349 3350 // Check if the condition of the select has one use or two users that are both 3351 // selects with the same condition. 3352 static bool hasOnlySelectUsers(const Value *Cond) { 3353 return llvm::all_of(Cond->users(), [](const Value *V) { 3354 return isa<SelectInst>(V); 3355 }); 3356 } 3357 3358 void SelectionDAGBuilder::visitSelect(const User &I) { 3359 SmallVector<EVT, 4> ValueVTs; 3360 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3361 ValueVTs); 3362 unsigned NumValues = ValueVTs.size(); 3363 if (NumValues == 0) return; 3364 3365 SmallVector<SDValue, 4> Values(NumValues); 3366 SDValue Cond = getValue(I.getOperand(0)); 3367 SDValue LHSVal = getValue(I.getOperand(1)); 3368 SDValue RHSVal = getValue(I.getOperand(2)); 3369 SmallVector<SDValue, 1> BaseOps(1, Cond); 3370 ISD::NodeType OpCode = 3371 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3372 3373 bool IsUnaryAbs = false; 3374 bool Negate = false; 3375 3376 SDNodeFlags Flags; 3377 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3378 Flags.copyFMF(*FPOp); 3379 3380 // Min/max matching is only viable if all output VTs are the same. 3381 if (all_equal(ValueVTs)) { 3382 EVT VT = ValueVTs[0]; 3383 LLVMContext &Ctx = *DAG.getContext(); 3384 auto &TLI = DAG.getTargetLoweringInfo(); 3385 3386 // We care about the legality of the operation after it has been type 3387 // legalized. 3388 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3389 VT = TLI.getTypeToTransformTo(Ctx, VT); 3390 3391 // If the vselect is legal, assume we want to leave this as a vector setcc + 3392 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3393 // min/max is legal on the scalar type. 3394 bool UseScalarMinMax = VT.isVector() && 3395 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3396 3397 // ValueTracking's select pattern matching does not account for -0.0, 3398 // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that 3399 // -0.0 is less than +0.0. 3400 Value *LHS, *RHS; 3401 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3402 ISD::NodeType Opc = ISD::DELETED_NODE; 3403 switch (SPR.Flavor) { 3404 case SPF_UMAX: Opc = ISD::UMAX; break; 3405 case SPF_UMIN: Opc = ISD::UMIN; break; 3406 case SPF_SMAX: Opc = ISD::SMAX; break; 3407 case SPF_SMIN: Opc = ISD::SMIN; break; 3408 case SPF_FMINNUM: 3409 switch (SPR.NaNBehavior) { 3410 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3411 case SPNB_RETURNS_NAN: break; 3412 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3413 case SPNB_RETURNS_ANY: 3414 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) || 3415 (UseScalarMinMax && 3416 TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()))) 3417 Opc = ISD::FMINNUM; 3418 break; 3419 } 3420 break; 3421 case SPF_FMAXNUM: 3422 switch (SPR.NaNBehavior) { 3423 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3424 case SPNB_RETURNS_NAN: break; 3425 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3426 case SPNB_RETURNS_ANY: 3427 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) || 3428 (UseScalarMinMax && 3429 TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()))) 3430 Opc = ISD::FMAXNUM; 3431 break; 3432 } 3433 break; 3434 case SPF_NABS: 3435 Negate = true; 3436 [[fallthrough]]; 3437 case SPF_ABS: 3438 IsUnaryAbs = true; 3439 Opc = ISD::ABS; 3440 break; 3441 default: break; 3442 } 3443 3444 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3445 (TLI.isOperationLegalOrCustom(Opc, VT) || 3446 (UseScalarMinMax && 3447 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3448 // If the underlying comparison instruction is used by any other 3449 // instruction, the consumed instructions won't be destroyed, so it is 3450 // not profitable to convert to a min/max. 3451 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3452 OpCode = Opc; 3453 LHSVal = getValue(LHS); 3454 RHSVal = getValue(RHS); 3455 BaseOps.clear(); 3456 } 3457 3458 if (IsUnaryAbs) { 3459 OpCode = Opc; 3460 LHSVal = getValue(LHS); 3461 BaseOps.clear(); 3462 } 3463 } 3464 3465 if (IsUnaryAbs) { 3466 for (unsigned i = 0; i != NumValues; ++i) { 3467 SDLoc dl = getCurSDLoc(); 3468 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3469 Values[i] = 3470 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3471 if (Negate) 3472 Values[i] = DAG.getNegative(Values[i], dl, VT); 3473 } 3474 } else { 3475 for (unsigned i = 0; i != NumValues; ++i) { 3476 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3477 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3478 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3479 Values[i] = DAG.getNode( 3480 OpCode, getCurSDLoc(), 3481 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3482 } 3483 } 3484 3485 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3486 DAG.getVTList(ValueVTs), Values)); 3487 } 3488 3489 void SelectionDAGBuilder::visitTrunc(const User &I) { 3490 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3491 SDValue N = getValue(I.getOperand(0)); 3492 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3493 I.getType()); 3494 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3495 } 3496 3497 void SelectionDAGBuilder::visitZExt(const User &I) { 3498 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3499 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3500 SDValue N = getValue(I.getOperand(0)); 3501 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3502 I.getType()); 3503 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3504 } 3505 3506 void SelectionDAGBuilder::visitSExt(const User &I) { 3507 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3508 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3509 SDValue N = getValue(I.getOperand(0)); 3510 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3511 I.getType()); 3512 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3513 } 3514 3515 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3516 // FPTrunc is never a no-op cast, no need to check 3517 SDValue N = getValue(I.getOperand(0)); 3518 SDLoc dl = getCurSDLoc(); 3519 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3520 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3521 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3522 DAG.getTargetConstant( 3523 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3524 } 3525 3526 void SelectionDAGBuilder::visitFPExt(const User &I) { 3527 // FPExt is never a no-op cast, no need to check 3528 SDValue N = getValue(I.getOperand(0)); 3529 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3530 I.getType()); 3531 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3532 } 3533 3534 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3535 // FPToUI is never a no-op cast, no need to check 3536 SDValue N = getValue(I.getOperand(0)); 3537 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3538 I.getType()); 3539 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3540 } 3541 3542 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3543 // FPToSI is never a no-op cast, no need to check 3544 SDValue N = getValue(I.getOperand(0)); 3545 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3546 I.getType()); 3547 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3548 } 3549 3550 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3551 // UIToFP 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::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3556 } 3557 3558 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3559 // SIToFP 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::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3564 } 3565 3566 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3567 // What to do depends on the size of the integer and the size of the pointer. 3568 // We can either truncate, zero extend, or no-op, accordingly. 3569 SDValue N = getValue(I.getOperand(0)); 3570 auto &TLI = DAG.getTargetLoweringInfo(); 3571 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3572 I.getType()); 3573 EVT PtrMemVT = 3574 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3575 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3576 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3577 setValue(&I, N); 3578 } 3579 3580 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3581 // What to do depends on the size of the integer and the size of the pointer. 3582 // We can either truncate, zero extend, or no-op, accordingly. 3583 SDValue N = getValue(I.getOperand(0)); 3584 auto &TLI = DAG.getTargetLoweringInfo(); 3585 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3586 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3587 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3588 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3589 setValue(&I, N); 3590 } 3591 3592 void SelectionDAGBuilder::visitBitCast(const User &I) { 3593 SDValue N = getValue(I.getOperand(0)); 3594 SDLoc dl = getCurSDLoc(); 3595 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3596 I.getType()); 3597 3598 // BitCast assures us that source and destination are the same size so this is 3599 // either a BITCAST or a no-op. 3600 if (DestVT != N.getValueType()) 3601 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3602 DestVT, N)); // convert types. 3603 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3604 // might fold any kind of constant expression to an integer constant and that 3605 // is not what we are looking for. Only recognize a bitcast of a genuine 3606 // constant integer as an opaque constant. 3607 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3608 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3609 /*isOpaque*/true)); 3610 else 3611 setValue(&I, N); // noop cast. 3612 } 3613 3614 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3615 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3616 const Value *SV = I.getOperand(0); 3617 SDValue N = getValue(SV); 3618 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3619 3620 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3621 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3622 3623 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3624 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3625 3626 setValue(&I, N); 3627 } 3628 3629 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3630 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3631 SDValue InVec = getValue(I.getOperand(0)); 3632 SDValue InVal = getValue(I.getOperand(1)); 3633 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3634 TLI.getVectorIdxTy(DAG.getDataLayout())); 3635 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3636 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3637 InVec, InVal, InIdx)); 3638 } 3639 3640 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3641 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3642 SDValue InVec = getValue(I.getOperand(0)); 3643 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3644 TLI.getVectorIdxTy(DAG.getDataLayout())); 3645 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3646 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3647 InVec, InIdx)); 3648 } 3649 3650 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3651 SDValue Src1 = getValue(I.getOperand(0)); 3652 SDValue Src2 = getValue(I.getOperand(1)); 3653 ArrayRef<int> Mask; 3654 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3655 Mask = SVI->getShuffleMask(); 3656 else 3657 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3658 SDLoc DL = getCurSDLoc(); 3659 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3660 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3661 EVT SrcVT = Src1.getValueType(); 3662 3663 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3664 VT.isScalableVector()) { 3665 // Canonical splat form of first element of first input vector. 3666 SDValue FirstElt = 3667 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3668 DAG.getVectorIdxConstant(0, DL)); 3669 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3670 return; 3671 } 3672 3673 // For now, we only handle splats for scalable vectors. 3674 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3675 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3676 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3677 3678 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3679 unsigned MaskNumElts = Mask.size(); 3680 3681 if (SrcNumElts == MaskNumElts) { 3682 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3683 return; 3684 } 3685 3686 // Normalize the shuffle vector since mask and vector length don't match. 3687 if (SrcNumElts < MaskNumElts) { 3688 // Mask is longer than the source vectors. We can use concatenate vector to 3689 // make the mask and vectors lengths match. 3690 3691 if (MaskNumElts % SrcNumElts == 0) { 3692 // Mask length is a multiple of the source vector length. 3693 // Check if the shuffle is some kind of concatenation of the input 3694 // vectors. 3695 unsigned NumConcat = MaskNumElts / SrcNumElts; 3696 bool IsConcat = true; 3697 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3698 for (unsigned i = 0; i != MaskNumElts; ++i) { 3699 int Idx = Mask[i]; 3700 if (Idx < 0) 3701 continue; 3702 // Ensure the indices in each SrcVT sized piece are sequential and that 3703 // the same source is used for the whole piece. 3704 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3705 (ConcatSrcs[i / SrcNumElts] >= 0 && 3706 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3707 IsConcat = false; 3708 break; 3709 } 3710 // Remember which source this index came from. 3711 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3712 } 3713 3714 // The shuffle is concatenating multiple vectors together. Just emit 3715 // a CONCAT_VECTORS operation. 3716 if (IsConcat) { 3717 SmallVector<SDValue, 8> ConcatOps; 3718 for (auto Src : ConcatSrcs) { 3719 if (Src < 0) 3720 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3721 else if (Src == 0) 3722 ConcatOps.push_back(Src1); 3723 else 3724 ConcatOps.push_back(Src2); 3725 } 3726 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3727 return; 3728 } 3729 } 3730 3731 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3732 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3733 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3734 PaddedMaskNumElts); 3735 3736 // Pad both vectors with undefs to make them the same length as the mask. 3737 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3738 3739 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3740 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3741 MOps1[0] = Src1; 3742 MOps2[0] = Src2; 3743 3744 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3745 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3746 3747 // Readjust mask for new input vector length. 3748 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3749 for (unsigned i = 0; i != MaskNumElts; ++i) { 3750 int Idx = Mask[i]; 3751 if (Idx >= (int)SrcNumElts) 3752 Idx -= SrcNumElts - PaddedMaskNumElts; 3753 MappedOps[i] = Idx; 3754 } 3755 3756 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3757 3758 // If the concatenated vector was padded, extract a subvector with the 3759 // correct number of elements. 3760 if (MaskNumElts != PaddedMaskNumElts) 3761 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3762 DAG.getVectorIdxConstant(0, DL)); 3763 3764 setValue(&I, Result); 3765 return; 3766 } 3767 3768 if (SrcNumElts > MaskNumElts) { 3769 // Analyze the access pattern of the vector to see if we can extract 3770 // two subvectors and do the shuffle. 3771 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3772 bool CanExtract = true; 3773 for (int Idx : Mask) { 3774 unsigned Input = 0; 3775 if (Idx < 0) 3776 continue; 3777 3778 if (Idx >= (int)SrcNumElts) { 3779 Input = 1; 3780 Idx -= SrcNumElts; 3781 } 3782 3783 // If all the indices come from the same MaskNumElts sized portion of 3784 // the sources we can use extract. Also make sure the extract wouldn't 3785 // extract past the end of the source. 3786 int NewStartIdx = alignDown(Idx, MaskNumElts); 3787 if (NewStartIdx + MaskNumElts > SrcNumElts || 3788 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3789 CanExtract = false; 3790 // Make sure we always update StartIdx as we use it to track if all 3791 // elements are undef. 3792 StartIdx[Input] = NewStartIdx; 3793 } 3794 3795 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3796 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3797 return; 3798 } 3799 if (CanExtract) { 3800 // Extract appropriate subvector and generate a vector shuffle 3801 for (unsigned Input = 0; Input < 2; ++Input) { 3802 SDValue &Src = Input == 0 ? Src1 : Src2; 3803 if (StartIdx[Input] < 0) 3804 Src = DAG.getUNDEF(VT); 3805 else { 3806 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3807 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3808 } 3809 } 3810 3811 // Calculate new mask. 3812 SmallVector<int, 8> MappedOps(Mask); 3813 for (int &Idx : MappedOps) { 3814 if (Idx >= (int)SrcNumElts) 3815 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3816 else if (Idx >= 0) 3817 Idx -= StartIdx[0]; 3818 } 3819 3820 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3821 return; 3822 } 3823 } 3824 3825 // We can't use either concat vectors or extract subvectors so fall back to 3826 // replacing the shuffle with extract and build vector. 3827 // to insert and build vector. 3828 EVT EltVT = VT.getVectorElementType(); 3829 SmallVector<SDValue,8> Ops; 3830 for (int Idx : Mask) { 3831 SDValue Res; 3832 3833 if (Idx < 0) { 3834 Res = DAG.getUNDEF(EltVT); 3835 } else { 3836 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3837 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3838 3839 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3840 DAG.getVectorIdxConstant(Idx, DL)); 3841 } 3842 3843 Ops.push_back(Res); 3844 } 3845 3846 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3847 } 3848 3849 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) { 3850 ArrayRef<unsigned> Indices = I.getIndices(); 3851 const Value *Op0 = I.getOperand(0); 3852 const Value *Op1 = I.getOperand(1); 3853 Type *AggTy = I.getType(); 3854 Type *ValTy = Op1->getType(); 3855 bool IntoUndef = isa<UndefValue>(Op0); 3856 bool FromUndef = isa<UndefValue>(Op1); 3857 3858 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3859 3860 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3861 SmallVector<EVT, 4> AggValueVTs; 3862 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3863 SmallVector<EVT, 4> ValValueVTs; 3864 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3865 3866 unsigned NumAggValues = AggValueVTs.size(); 3867 unsigned NumValValues = ValValueVTs.size(); 3868 SmallVector<SDValue, 4> Values(NumAggValues); 3869 3870 // Ignore an insertvalue that produces an empty object 3871 if (!NumAggValues) { 3872 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3873 return; 3874 } 3875 3876 SDValue Agg = getValue(Op0); 3877 unsigned i = 0; 3878 // Copy the beginning value(s) from the original aggregate. 3879 for (; i != LinearIndex; ++i) 3880 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3881 SDValue(Agg.getNode(), Agg.getResNo() + i); 3882 // Copy values from the inserted value(s). 3883 if (NumValValues) { 3884 SDValue Val = getValue(Op1); 3885 for (; i != LinearIndex + NumValValues; ++i) 3886 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3887 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3888 } 3889 // Copy remaining value(s) from the original aggregate. 3890 for (; i != NumAggValues; ++i) 3891 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3892 SDValue(Agg.getNode(), Agg.getResNo() + i); 3893 3894 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3895 DAG.getVTList(AggValueVTs), Values)); 3896 } 3897 3898 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) { 3899 ArrayRef<unsigned> Indices = I.getIndices(); 3900 const Value *Op0 = I.getOperand(0); 3901 Type *AggTy = Op0->getType(); 3902 Type *ValTy = I.getType(); 3903 bool OutOfUndef = isa<UndefValue>(Op0); 3904 3905 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3906 3907 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3908 SmallVector<EVT, 4> ValValueVTs; 3909 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3910 3911 unsigned NumValValues = ValValueVTs.size(); 3912 3913 // Ignore a extractvalue that produces an empty object 3914 if (!NumValValues) { 3915 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3916 return; 3917 } 3918 3919 SmallVector<SDValue, 4> Values(NumValValues); 3920 3921 SDValue Agg = getValue(Op0); 3922 // Copy out the selected value(s). 3923 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3924 Values[i - LinearIndex] = 3925 OutOfUndef ? 3926 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3927 SDValue(Agg.getNode(), Agg.getResNo() + i); 3928 3929 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3930 DAG.getVTList(ValValueVTs), Values)); 3931 } 3932 3933 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3934 Value *Op0 = I.getOperand(0); 3935 // Note that the pointer operand may be a vector of pointers. Take the scalar 3936 // element which holds a pointer. 3937 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3938 SDValue N = getValue(Op0); 3939 SDLoc dl = getCurSDLoc(); 3940 auto &TLI = DAG.getTargetLoweringInfo(); 3941 3942 // Normalize Vector GEP - all scalar operands should be converted to the 3943 // splat vector. 3944 bool IsVectorGEP = I.getType()->isVectorTy(); 3945 ElementCount VectorElementCount = 3946 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3947 : ElementCount::getFixed(0); 3948 3949 if (IsVectorGEP && !N.getValueType().isVector()) { 3950 LLVMContext &Context = *DAG.getContext(); 3951 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3952 N = DAG.getSplat(VT, dl, N); 3953 } 3954 3955 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3956 GTI != E; ++GTI) { 3957 const Value *Idx = GTI.getOperand(); 3958 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3959 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3960 if (Field) { 3961 // N = N + Offset 3962 uint64_t Offset = 3963 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field); 3964 3965 // In an inbounds GEP with an offset that is nonnegative even when 3966 // interpreted as signed, assume there is no unsigned overflow. 3967 SDNodeFlags Flags; 3968 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3969 Flags.setNoUnsignedWrap(true); 3970 3971 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3972 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3973 } 3974 } else { 3975 // IdxSize is the width of the arithmetic according to IR semantics. 3976 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3977 // (and fix up the result later). 3978 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3979 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3980 TypeSize ElementSize = 3981 DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType()); 3982 // We intentionally mask away the high bits here; ElementSize may not 3983 // fit in IdxTy. 3984 APInt ElementMul(IdxSize, ElementSize.getKnownMinValue()); 3985 bool ElementScalable = ElementSize.isScalable(); 3986 3987 // If this is a scalar constant or a splat vector of constants, 3988 // handle it quickly. 3989 const auto *C = dyn_cast<Constant>(Idx); 3990 if (C && isa<VectorType>(C->getType())) 3991 C = C->getSplatValue(); 3992 3993 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 3994 if (CI && CI->isZero()) 3995 continue; 3996 if (CI && !ElementScalable) { 3997 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 3998 LLVMContext &Context = *DAG.getContext(); 3999 SDValue OffsVal; 4000 if (IsVectorGEP) 4001 OffsVal = DAG.getConstant( 4002 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 4003 else 4004 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 4005 4006 // In an inbounds GEP with an offset that is nonnegative even when 4007 // interpreted as signed, assume there is no unsigned overflow. 4008 SDNodeFlags Flags; 4009 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 4010 Flags.setNoUnsignedWrap(true); 4011 4012 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 4013 4014 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 4015 continue; 4016 } 4017 4018 // N = N + Idx * ElementMul; 4019 SDValue IdxN = getValue(Idx); 4020 4021 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 4022 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 4023 VectorElementCount); 4024 IdxN = DAG.getSplat(VT, dl, IdxN); 4025 } 4026 4027 // If the index is smaller or larger than intptr_t, truncate or extend 4028 // it. 4029 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 4030 4031 if (ElementScalable) { 4032 EVT VScaleTy = N.getValueType().getScalarType(); 4033 SDValue VScale = DAG.getNode( 4034 ISD::VSCALE, dl, VScaleTy, 4035 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 4036 if (IsVectorGEP) 4037 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 4038 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 4039 } else { 4040 // If this is a multiply by a power of two, turn it into a shl 4041 // immediately. This is a very common case. 4042 if (ElementMul != 1) { 4043 if (ElementMul.isPowerOf2()) { 4044 unsigned Amt = ElementMul.logBase2(); 4045 IdxN = DAG.getNode(ISD::SHL, dl, 4046 N.getValueType(), IdxN, 4047 DAG.getConstant(Amt, dl, IdxN.getValueType())); 4048 } else { 4049 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 4050 IdxN.getValueType()); 4051 IdxN = DAG.getNode(ISD::MUL, dl, 4052 N.getValueType(), IdxN, Scale); 4053 } 4054 } 4055 } 4056 4057 N = DAG.getNode(ISD::ADD, dl, 4058 N.getValueType(), N, IdxN); 4059 } 4060 } 4061 4062 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 4063 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 4064 if (IsVectorGEP) { 4065 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 4066 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 4067 } 4068 4069 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 4070 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 4071 4072 setValue(&I, N); 4073 } 4074 4075 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 4076 // If this is a fixed sized alloca in the entry block of the function, 4077 // allocate it statically on the stack. 4078 if (FuncInfo.StaticAllocaMap.count(&I)) 4079 return; // getValue will auto-populate this. 4080 4081 SDLoc dl = getCurSDLoc(); 4082 Type *Ty = I.getAllocatedType(); 4083 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4084 auto &DL = DAG.getDataLayout(); 4085 TypeSize TySize = DL.getTypeAllocSize(Ty); 4086 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 4087 4088 SDValue AllocSize = getValue(I.getArraySize()); 4089 4090 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), I.getAddressSpace()); 4091 if (AllocSize.getValueType() != IntPtr) 4092 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 4093 4094 if (TySize.isScalable()) 4095 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4096 DAG.getVScale(dl, IntPtr, 4097 APInt(IntPtr.getScalarSizeInBits(), 4098 TySize.getKnownMinValue()))); 4099 else 4100 AllocSize = 4101 DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4102 DAG.getConstant(TySize.getFixedValue(), dl, IntPtr)); 4103 4104 // Handle alignment. If the requested alignment is less than or equal to 4105 // the stack alignment, ignore it. If the size is greater than or equal to 4106 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4107 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 4108 if (*Alignment <= StackAlign) 4109 Alignment = std::nullopt; 4110 4111 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4112 // Round the size of the allocation up to the stack alignment size 4113 // by add SA-1 to the size. This doesn't overflow because we're computing 4114 // an address inside an alloca. 4115 SDNodeFlags Flags; 4116 Flags.setNoUnsignedWrap(true); 4117 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4118 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4119 4120 // Mask out the low bits for alignment purposes. 4121 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4122 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 4123 4124 SDValue Ops[] = { 4125 getRoot(), AllocSize, 4126 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4127 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4128 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4129 setValue(&I, DSA); 4130 DAG.setRoot(DSA.getValue(1)); 4131 4132 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4133 } 4134 4135 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4136 if (I.isAtomic()) 4137 return visitAtomicLoad(I); 4138 4139 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4140 const Value *SV = I.getOperand(0); 4141 if (TLI.supportSwiftError()) { 4142 // Swifterror values can come from either a function parameter with 4143 // swifterror attribute or an alloca with swifterror attribute. 4144 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4145 if (Arg->hasSwiftErrorAttr()) 4146 return visitLoadFromSwiftError(I); 4147 } 4148 4149 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4150 if (Alloca->isSwiftError()) 4151 return visitLoadFromSwiftError(I); 4152 } 4153 } 4154 4155 SDValue Ptr = getValue(SV); 4156 4157 Type *Ty = I.getType(); 4158 SmallVector<EVT, 4> ValueVTs, MemVTs; 4159 SmallVector<uint64_t, 4> Offsets; 4160 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4161 unsigned NumValues = ValueVTs.size(); 4162 if (NumValues == 0) 4163 return; 4164 4165 Align Alignment = I.getAlign(); 4166 AAMDNodes AAInfo = I.getAAMetadata(); 4167 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4168 bool isVolatile = I.isVolatile(); 4169 MachineMemOperand::Flags MMOFlags = 4170 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 4171 4172 SDValue Root; 4173 bool ConstantMemory = false; 4174 if (isVolatile) 4175 // Serialize volatile loads with other side effects. 4176 Root = getRoot(); 4177 else if (NumValues > MaxParallelChains) 4178 Root = getMemoryRoot(); 4179 else if (AA && 4180 AA->pointsToConstantMemory(MemoryLocation( 4181 SV, 4182 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4183 AAInfo))) { 4184 // Do not serialize (non-volatile) loads of constant memory with anything. 4185 Root = DAG.getEntryNode(); 4186 ConstantMemory = true; 4187 MMOFlags |= MachineMemOperand::MOInvariant; 4188 } else { 4189 // Do not serialize non-volatile loads against each other. 4190 Root = DAG.getRoot(); 4191 } 4192 4193 SDLoc dl = getCurSDLoc(); 4194 4195 if (isVolatile) 4196 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4197 4198 // An aggregate load cannot wrap around the address space, so offsets to its 4199 // parts don't wrap either. 4200 SDNodeFlags Flags; 4201 Flags.setNoUnsignedWrap(true); 4202 4203 SmallVector<SDValue, 4> Values(NumValues); 4204 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4205 EVT PtrVT = Ptr.getValueType(); 4206 4207 unsigned ChainI = 0; 4208 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4209 // Serializing loads here may result in excessive register pressure, and 4210 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4211 // could recover a bit by hoisting nodes upward in the chain by recognizing 4212 // they are side-effect free or do not alias. The optimizer should really 4213 // avoid this case by converting large object/array copies to llvm.memcpy 4214 // (MaxParallelChains should always remain as failsafe). 4215 if (ChainI == MaxParallelChains) { 4216 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4217 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4218 ArrayRef(Chains.data(), ChainI)); 4219 Root = Chain; 4220 ChainI = 0; 4221 } 4222 SDValue A = DAG.getNode(ISD::ADD, dl, 4223 PtrVT, Ptr, 4224 DAG.getConstant(Offsets[i], dl, PtrVT), 4225 Flags); 4226 4227 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4228 MachinePointerInfo(SV, Offsets[i]), Alignment, 4229 MMOFlags, AAInfo, Ranges); 4230 Chains[ChainI] = L.getValue(1); 4231 4232 if (MemVTs[i] != ValueVTs[i]) 4233 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4234 4235 Values[i] = L; 4236 } 4237 4238 if (!ConstantMemory) { 4239 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4240 ArrayRef(Chains.data(), ChainI)); 4241 if (isVolatile) 4242 DAG.setRoot(Chain); 4243 else 4244 PendingLoads.push_back(Chain); 4245 } 4246 4247 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4248 DAG.getVTList(ValueVTs), Values)); 4249 } 4250 4251 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4252 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4253 "call visitStoreToSwiftError when backend supports swifterror"); 4254 4255 SmallVector<EVT, 4> ValueVTs; 4256 SmallVector<uint64_t, 4> Offsets; 4257 const Value *SrcV = I.getOperand(0); 4258 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4259 SrcV->getType(), ValueVTs, &Offsets); 4260 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4261 "expect a single EVT for swifterror"); 4262 4263 SDValue Src = getValue(SrcV); 4264 // Create a virtual register, then update the virtual register. 4265 Register VReg = 4266 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4267 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4268 // Chain can be getRoot or getControlRoot. 4269 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4270 SDValue(Src.getNode(), Src.getResNo())); 4271 DAG.setRoot(CopyNode); 4272 } 4273 4274 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4275 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4276 "call visitLoadFromSwiftError when backend supports swifterror"); 4277 4278 assert(!I.isVolatile() && 4279 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4280 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4281 "Support volatile, non temporal, invariant for load_from_swift_error"); 4282 4283 const Value *SV = I.getOperand(0); 4284 Type *Ty = I.getType(); 4285 assert( 4286 (!AA || 4287 !AA->pointsToConstantMemory(MemoryLocation( 4288 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4289 I.getAAMetadata()))) && 4290 "load_from_swift_error should not be constant memory"); 4291 4292 SmallVector<EVT, 4> ValueVTs; 4293 SmallVector<uint64_t, 4> Offsets; 4294 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4295 ValueVTs, &Offsets); 4296 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4297 "expect a single EVT for swifterror"); 4298 4299 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4300 SDValue L = DAG.getCopyFromReg( 4301 getRoot(), getCurSDLoc(), 4302 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4303 4304 setValue(&I, L); 4305 } 4306 4307 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4308 if (I.isAtomic()) 4309 return visitAtomicStore(I); 4310 4311 const Value *SrcV = I.getOperand(0); 4312 const Value *PtrV = I.getOperand(1); 4313 4314 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4315 if (TLI.supportSwiftError()) { 4316 // Swifterror values can come from either a function parameter with 4317 // swifterror attribute or an alloca with swifterror attribute. 4318 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4319 if (Arg->hasSwiftErrorAttr()) 4320 return visitStoreToSwiftError(I); 4321 } 4322 4323 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4324 if (Alloca->isSwiftError()) 4325 return visitStoreToSwiftError(I); 4326 } 4327 } 4328 4329 SmallVector<EVT, 4> ValueVTs, MemVTs; 4330 SmallVector<uint64_t, 4> Offsets; 4331 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4332 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4333 unsigned NumValues = ValueVTs.size(); 4334 if (NumValues == 0) 4335 return; 4336 4337 // Get the lowered operands. Note that we do this after 4338 // checking if NumResults is zero, because with zero results 4339 // the operands won't have values in the map. 4340 SDValue Src = getValue(SrcV); 4341 SDValue Ptr = getValue(PtrV); 4342 4343 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4344 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4345 SDLoc dl = getCurSDLoc(); 4346 Align Alignment = I.getAlign(); 4347 AAMDNodes AAInfo = I.getAAMetadata(); 4348 4349 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4350 4351 // An aggregate load cannot wrap around the address space, so offsets to its 4352 // parts don't wrap either. 4353 SDNodeFlags Flags; 4354 Flags.setNoUnsignedWrap(true); 4355 4356 unsigned ChainI = 0; 4357 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4358 // See visitLoad comments. 4359 if (ChainI == MaxParallelChains) { 4360 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4361 ArrayRef(Chains.data(), ChainI)); 4362 Root = Chain; 4363 ChainI = 0; 4364 } 4365 SDValue Add = 4366 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags); 4367 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4368 if (MemVTs[i] != ValueVTs[i]) 4369 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4370 SDValue St = 4371 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4372 Alignment, MMOFlags, AAInfo); 4373 Chains[ChainI] = St; 4374 } 4375 4376 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4377 ArrayRef(Chains.data(), ChainI)); 4378 setValue(&I, StoreNode); 4379 DAG.setRoot(StoreNode); 4380 } 4381 4382 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4383 bool IsCompressing) { 4384 SDLoc sdl = getCurSDLoc(); 4385 4386 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4387 MaybeAlign &Alignment) { 4388 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4389 Src0 = I.getArgOperand(0); 4390 Ptr = I.getArgOperand(1); 4391 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4392 Mask = I.getArgOperand(3); 4393 }; 4394 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4395 MaybeAlign &Alignment) { 4396 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4397 Src0 = I.getArgOperand(0); 4398 Ptr = I.getArgOperand(1); 4399 Mask = I.getArgOperand(2); 4400 Alignment = std::nullopt; 4401 }; 4402 4403 Value *PtrOperand, *MaskOperand, *Src0Operand; 4404 MaybeAlign Alignment; 4405 if (IsCompressing) 4406 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4407 else 4408 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4409 4410 SDValue Ptr = getValue(PtrOperand); 4411 SDValue Src0 = getValue(Src0Operand); 4412 SDValue Mask = getValue(MaskOperand); 4413 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4414 4415 EVT VT = Src0.getValueType(); 4416 if (!Alignment) 4417 Alignment = DAG.getEVTAlign(VT); 4418 4419 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4420 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4421 MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata()); 4422 SDValue StoreNode = 4423 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4424 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4425 DAG.setRoot(StoreNode); 4426 setValue(&I, StoreNode); 4427 } 4428 4429 // Get a uniform base for the Gather/Scatter intrinsic. 4430 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4431 // We try to represent it as a base pointer + vector of indices. 4432 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4433 // The first operand of the GEP may be a single pointer or a vector of pointers 4434 // Example: 4435 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4436 // or 4437 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4438 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4439 // 4440 // When the first GEP operand is a single pointer - it is the uniform base we 4441 // are looking for. If first operand of the GEP is a splat vector - we 4442 // extract the splat value and use it as a uniform base. 4443 // In all other cases the function returns 'false'. 4444 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4445 ISD::MemIndexType &IndexType, SDValue &Scale, 4446 SelectionDAGBuilder *SDB, const BasicBlock *CurBB, 4447 uint64_t ElemSize) { 4448 SelectionDAG& DAG = SDB->DAG; 4449 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4450 const DataLayout &DL = DAG.getDataLayout(); 4451 4452 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type"); 4453 4454 // Handle splat constant pointer. 4455 if (auto *C = dyn_cast<Constant>(Ptr)) { 4456 C = C->getSplatValue(); 4457 if (!C) 4458 return false; 4459 4460 Base = SDB->getValue(C); 4461 4462 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); 4463 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4464 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4465 IndexType = ISD::SIGNED_SCALED; 4466 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4467 return true; 4468 } 4469 4470 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4471 if (!GEP || GEP->getParent() != CurBB) 4472 return false; 4473 4474 if (GEP->getNumOperands() != 2) 4475 return false; 4476 4477 const Value *BasePtr = GEP->getPointerOperand(); 4478 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4479 4480 // Make sure the base is scalar and the index is a vector. 4481 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4482 return false; 4483 4484 uint64_t ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType()); 4485 4486 // Target may not support the required addressing mode. 4487 if (ScaleVal != 1 && 4488 !TLI.isLegalScaleForGatherScatter(ScaleVal, ElemSize)) 4489 return false; 4490 4491 Base = SDB->getValue(BasePtr); 4492 Index = SDB->getValue(IndexVal); 4493 IndexType = ISD::SIGNED_SCALED; 4494 4495 Scale = 4496 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4497 return true; 4498 } 4499 4500 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4501 SDLoc sdl = getCurSDLoc(); 4502 4503 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4504 const Value *Ptr = I.getArgOperand(1); 4505 SDValue Src0 = getValue(I.getArgOperand(0)); 4506 SDValue Mask = getValue(I.getArgOperand(3)); 4507 EVT VT = Src0.getValueType(); 4508 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4509 ->getMaybeAlignValue() 4510 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4511 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4512 4513 SDValue Base; 4514 SDValue Index; 4515 ISD::MemIndexType IndexType; 4516 SDValue Scale; 4517 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4518 I.getParent(), VT.getScalarStoreSize()); 4519 4520 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4521 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4522 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4523 // TODO: Make MachineMemOperands aware of scalable 4524 // vectors. 4525 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata()); 4526 if (!UniformBase) { 4527 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4528 Index = getValue(Ptr); 4529 IndexType = ISD::SIGNED_SCALED; 4530 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4531 } 4532 4533 EVT IdxVT = Index.getValueType(); 4534 EVT EltTy = IdxVT.getVectorElementType(); 4535 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4536 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4537 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4538 } 4539 4540 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4541 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4542 Ops, MMO, IndexType, false); 4543 DAG.setRoot(Scatter); 4544 setValue(&I, Scatter); 4545 } 4546 4547 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4548 SDLoc sdl = getCurSDLoc(); 4549 4550 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4551 MaybeAlign &Alignment) { 4552 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4553 Ptr = I.getArgOperand(0); 4554 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4555 Mask = I.getArgOperand(2); 4556 Src0 = I.getArgOperand(3); 4557 }; 4558 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4559 MaybeAlign &Alignment) { 4560 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4561 Ptr = I.getArgOperand(0); 4562 Alignment = std::nullopt; 4563 Mask = I.getArgOperand(1); 4564 Src0 = I.getArgOperand(2); 4565 }; 4566 4567 Value *PtrOperand, *MaskOperand, *Src0Operand; 4568 MaybeAlign Alignment; 4569 if (IsExpanding) 4570 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4571 else 4572 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4573 4574 SDValue Ptr = getValue(PtrOperand); 4575 SDValue Src0 = getValue(Src0Operand); 4576 SDValue Mask = getValue(MaskOperand); 4577 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4578 4579 EVT VT = Src0.getValueType(); 4580 if (!Alignment) 4581 Alignment = DAG.getEVTAlign(VT); 4582 4583 AAMDNodes AAInfo = I.getAAMetadata(); 4584 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4585 4586 // Do not serialize masked loads of constant memory with anything. 4587 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 4588 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4589 4590 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4591 4592 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4593 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4594 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 4595 4596 SDValue Load = 4597 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4598 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4599 if (AddToChain) 4600 PendingLoads.push_back(Load.getValue(1)); 4601 setValue(&I, Load); 4602 } 4603 4604 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4605 SDLoc sdl = getCurSDLoc(); 4606 4607 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4608 const Value *Ptr = I.getArgOperand(0); 4609 SDValue Src0 = getValue(I.getArgOperand(3)); 4610 SDValue Mask = getValue(I.getArgOperand(2)); 4611 4612 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4613 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4614 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4615 ->getMaybeAlignValue() 4616 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4617 4618 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4619 4620 SDValue Root = DAG.getRoot(); 4621 SDValue Base; 4622 SDValue Index; 4623 ISD::MemIndexType IndexType; 4624 SDValue Scale; 4625 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4626 I.getParent(), VT.getScalarStoreSize()); 4627 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4628 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4629 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4630 // TODO: Make MachineMemOperands aware of scalable 4631 // vectors. 4632 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges); 4633 4634 if (!UniformBase) { 4635 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4636 Index = getValue(Ptr); 4637 IndexType = ISD::SIGNED_SCALED; 4638 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4639 } 4640 4641 EVT IdxVT = Index.getValueType(); 4642 EVT EltTy = IdxVT.getVectorElementType(); 4643 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4644 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4645 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4646 } 4647 4648 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4649 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4650 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4651 4652 PendingLoads.push_back(Gather.getValue(1)); 4653 setValue(&I, Gather); 4654 } 4655 4656 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4657 SDLoc dl = getCurSDLoc(); 4658 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4659 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4660 SyncScope::ID SSID = I.getSyncScopeID(); 4661 4662 SDValue InChain = getRoot(); 4663 4664 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4665 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4666 4667 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4668 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4669 4670 MachineFunction &MF = DAG.getMachineFunction(); 4671 MachineMemOperand *MMO = MF.getMachineMemOperand( 4672 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4673 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4674 FailureOrdering); 4675 4676 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4677 dl, MemVT, VTs, InChain, 4678 getValue(I.getPointerOperand()), 4679 getValue(I.getCompareOperand()), 4680 getValue(I.getNewValOperand()), MMO); 4681 4682 SDValue OutChain = L.getValue(2); 4683 4684 setValue(&I, L); 4685 DAG.setRoot(OutChain); 4686 } 4687 4688 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4689 SDLoc dl = getCurSDLoc(); 4690 ISD::NodeType NT; 4691 switch (I.getOperation()) { 4692 default: llvm_unreachable("Unknown atomicrmw operation"); 4693 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4694 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4695 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4696 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4697 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4698 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4699 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4700 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4701 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4702 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4703 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4704 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4705 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4706 case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break; 4707 case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break; 4708 case AtomicRMWInst::UIncWrap: 4709 NT = ISD::ATOMIC_LOAD_UINC_WRAP; 4710 break; 4711 case AtomicRMWInst::UDecWrap: 4712 NT = ISD::ATOMIC_LOAD_UDEC_WRAP; 4713 break; 4714 } 4715 AtomicOrdering Ordering = I.getOrdering(); 4716 SyncScope::ID SSID = I.getSyncScopeID(); 4717 4718 SDValue InChain = getRoot(); 4719 4720 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4721 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4722 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4723 4724 MachineFunction &MF = DAG.getMachineFunction(); 4725 MachineMemOperand *MMO = MF.getMachineMemOperand( 4726 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4727 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4728 4729 SDValue L = 4730 DAG.getAtomic(NT, dl, MemVT, InChain, 4731 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4732 MMO); 4733 4734 SDValue OutChain = L.getValue(1); 4735 4736 setValue(&I, L); 4737 DAG.setRoot(OutChain); 4738 } 4739 4740 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4741 SDLoc dl = getCurSDLoc(); 4742 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4743 SDValue Ops[3]; 4744 Ops[0] = getRoot(); 4745 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4746 TLI.getFenceOperandTy(DAG.getDataLayout())); 4747 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4748 TLI.getFenceOperandTy(DAG.getDataLayout())); 4749 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops); 4750 setValue(&I, N); 4751 DAG.setRoot(N); 4752 } 4753 4754 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4755 SDLoc dl = getCurSDLoc(); 4756 AtomicOrdering Order = I.getOrdering(); 4757 SyncScope::ID SSID = I.getSyncScopeID(); 4758 4759 SDValue InChain = getRoot(); 4760 4761 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4762 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4763 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4764 4765 if (!TLI.supportsUnalignedAtomics() && 4766 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4767 report_fatal_error("Cannot generate unaligned atomic load"); 4768 4769 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 4770 4771 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4772 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4773 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4774 4775 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4776 4777 SDValue Ptr = getValue(I.getPointerOperand()); 4778 4779 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4780 // TODO: Once this is better exercised by tests, it should be merged with 4781 // the normal path for loads to prevent future divergence. 4782 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4783 if (MemVT != VT) 4784 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4785 4786 setValue(&I, L); 4787 SDValue OutChain = L.getValue(1); 4788 if (!I.isUnordered()) 4789 DAG.setRoot(OutChain); 4790 else 4791 PendingLoads.push_back(OutChain); 4792 return; 4793 } 4794 4795 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4796 Ptr, MMO); 4797 4798 SDValue OutChain = L.getValue(1); 4799 if (MemVT != VT) 4800 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4801 4802 setValue(&I, L); 4803 DAG.setRoot(OutChain); 4804 } 4805 4806 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4807 SDLoc dl = getCurSDLoc(); 4808 4809 AtomicOrdering Ordering = I.getOrdering(); 4810 SyncScope::ID SSID = I.getSyncScopeID(); 4811 4812 SDValue InChain = getRoot(); 4813 4814 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4815 EVT MemVT = 4816 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4817 4818 if (!TLI.supportsUnalignedAtomics() && 4819 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4820 report_fatal_error("Cannot generate unaligned atomic store"); 4821 4822 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4823 4824 MachineFunction &MF = DAG.getMachineFunction(); 4825 MachineMemOperand *MMO = MF.getMachineMemOperand( 4826 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4827 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4828 4829 SDValue Val = getValue(I.getValueOperand()); 4830 if (Val.getValueType() != MemVT) 4831 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4832 SDValue Ptr = getValue(I.getPointerOperand()); 4833 4834 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4835 // TODO: Once this is better exercised by tests, it should be merged with 4836 // the normal path for stores to prevent future divergence. 4837 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4838 setValue(&I, S); 4839 DAG.setRoot(S); 4840 return; 4841 } 4842 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4843 Ptr, Val, MMO); 4844 4845 setValue(&I, OutChain); 4846 DAG.setRoot(OutChain); 4847 } 4848 4849 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4850 /// node. 4851 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4852 unsigned Intrinsic) { 4853 // Ignore the callsite's attributes. A specific call site may be marked with 4854 // readnone, but the lowering code will expect the chain based on the 4855 // definition. 4856 const Function *F = I.getCalledFunction(); 4857 bool HasChain = !F->doesNotAccessMemory(); 4858 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4859 4860 // Build the operand list. 4861 SmallVector<SDValue, 8> Ops; 4862 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4863 if (OnlyLoad) { 4864 // We don't need to serialize loads against other loads. 4865 Ops.push_back(DAG.getRoot()); 4866 } else { 4867 Ops.push_back(getRoot()); 4868 } 4869 } 4870 4871 // Info is set by getTgtMemIntrinsic 4872 TargetLowering::IntrinsicInfo Info; 4873 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4874 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4875 DAG.getMachineFunction(), 4876 Intrinsic); 4877 4878 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4879 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4880 Info.opc == ISD::INTRINSIC_W_CHAIN) 4881 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4882 TLI.getPointerTy(DAG.getDataLayout()))); 4883 4884 // Add all operands of the call to the operand list. 4885 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) { 4886 const Value *Arg = I.getArgOperand(i); 4887 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4888 Ops.push_back(getValue(Arg)); 4889 continue; 4890 } 4891 4892 // Use TargetConstant instead of a regular constant for immarg. 4893 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true); 4894 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4895 assert(CI->getBitWidth() <= 64 && 4896 "large intrinsic immediates not handled"); 4897 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4898 } else { 4899 Ops.push_back( 4900 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4901 } 4902 } 4903 4904 SmallVector<EVT, 4> ValueVTs; 4905 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4906 4907 if (HasChain) 4908 ValueVTs.push_back(MVT::Other); 4909 4910 SDVTList VTs = DAG.getVTList(ValueVTs); 4911 4912 // Propagate fast-math-flags from IR to node(s). 4913 SDNodeFlags Flags; 4914 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 4915 Flags.copyFMF(*FPMO); 4916 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 4917 4918 // Create the node. 4919 SDValue Result; 4920 // In some cases, custom collection of operands from CallInst I may be needed. 4921 TLI.CollectTargetIntrinsicOperands(I, Ops, DAG); 4922 if (IsTgtIntrinsic) { 4923 // This is target intrinsic that touches memory 4924 // 4925 // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic 4926 // didn't yield anything useful. 4927 MachinePointerInfo MPI; 4928 if (Info.ptrVal) 4929 MPI = MachinePointerInfo(Info.ptrVal, Info.offset); 4930 else if (Info.fallbackAddressSpace) 4931 MPI = MachinePointerInfo(*Info.fallbackAddressSpace); 4932 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, 4933 Info.memVT, MPI, Info.align, Info.flags, 4934 Info.size, I.getAAMetadata()); 4935 } else if (!HasChain) { 4936 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4937 } else if (!I.getType()->isVoidTy()) { 4938 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4939 } else { 4940 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4941 } 4942 4943 if (HasChain) { 4944 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4945 if (OnlyLoad) 4946 PendingLoads.push_back(Chain); 4947 else 4948 DAG.setRoot(Chain); 4949 } 4950 4951 if (!I.getType()->isVoidTy()) { 4952 if (!isa<VectorType>(I.getType())) 4953 Result = lowerRangeToAssertZExt(DAG, I, Result); 4954 4955 MaybeAlign Alignment = I.getRetAlign(); 4956 4957 // Insert `assertalign` node if there's an alignment. 4958 if (InsertAssertAlign && Alignment) { 4959 Result = 4960 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 4961 } 4962 4963 setValue(&I, Result); 4964 } 4965 } 4966 4967 /// GetSignificand - Get the significand and build it into a floating-point 4968 /// number with exponent of 1: 4969 /// 4970 /// Op = (Op & 0x007fffff) | 0x3f800000; 4971 /// 4972 /// where Op is the hexadecimal representation of floating point value. 4973 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4974 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4975 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4976 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4977 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4978 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4979 } 4980 4981 /// GetExponent - Get the exponent: 4982 /// 4983 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4984 /// 4985 /// where Op is the hexadecimal representation of floating point value. 4986 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4987 const TargetLowering &TLI, const SDLoc &dl) { 4988 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4989 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4990 SDValue t1 = DAG.getNode( 4991 ISD::SRL, dl, MVT::i32, t0, 4992 DAG.getConstant(23, dl, 4993 TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout()))); 4994 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4995 DAG.getConstant(127, dl, MVT::i32)); 4996 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4997 } 4998 4999 /// getF32Constant - Get 32-bit floating point constant. 5000 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 5001 const SDLoc &dl) { 5002 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 5003 MVT::f32); 5004 } 5005 5006 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 5007 SelectionDAG &DAG) { 5008 // TODO: What fast-math-flags should be set on the floating-point nodes? 5009 5010 // IntegerPartOfX = ((int32_t)(t0); 5011 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 5012 5013 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 5014 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 5015 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 5016 5017 // IntegerPartOfX <<= 23; 5018 IntegerPartOfX = 5019 DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 5020 DAG.getConstant(23, dl, 5021 DAG.getTargetLoweringInfo().getShiftAmountTy( 5022 MVT::i32, DAG.getDataLayout()))); 5023 5024 SDValue TwoToFractionalPartOfX; 5025 if (LimitFloatPrecision <= 6) { 5026 // For floating-point precision of 6: 5027 // 5028 // TwoToFractionalPartOfX = 5029 // 0.997535578f + 5030 // (0.735607626f + 0.252464424f * x) * x; 5031 // 5032 // error 0.0144103317, which is 6 bits 5033 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5034 getF32Constant(DAG, 0x3e814304, dl)); 5035 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5036 getF32Constant(DAG, 0x3f3c50c8, dl)); 5037 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5038 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5039 getF32Constant(DAG, 0x3f7f5e7e, dl)); 5040 } else if (LimitFloatPrecision <= 12) { 5041 // For floating-point precision of 12: 5042 // 5043 // TwoToFractionalPartOfX = 5044 // 0.999892986f + 5045 // (0.696457318f + 5046 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 5047 // 5048 // error 0.000107046256, which is 13 to 14 bits 5049 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5050 getF32Constant(DAG, 0x3da235e3, dl)); 5051 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5052 getF32Constant(DAG, 0x3e65b8f3, dl)); 5053 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5054 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5055 getF32Constant(DAG, 0x3f324b07, dl)); 5056 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5057 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5058 getF32Constant(DAG, 0x3f7ff8fd, dl)); 5059 } else { // LimitFloatPrecision <= 18 5060 // For floating-point precision of 18: 5061 // 5062 // TwoToFractionalPartOfX = 5063 // 0.999999982f + 5064 // (0.693148872f + 5065 // (0.240227044f + 5066 // (0.554906021e-1f + 5067 // (0.961591928e-2f + 5068 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 5069 // error 2.47208000*10^(-7), which is better than 18 bits 5070 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5071 getF32Constant(DAG, 0x3924b03e, dl)); 5072 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5073 getF32Constant(DAG, 0x3ab24b87, dl)); 5074 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5075 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5076 getF32Constant(DAG, 0x3c1d8c17, dl)); 5077 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5078 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5079 getF32Constant(DAG, 0x3d634a1d, dl)); 5080 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5081 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5082 getF32Constant(DAG, 0x3e75fe14, dl)); 5083 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5084 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 5085 getF32Constant(DAG, 0x3f317234, dl)); 5086 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 5087 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 5088 getF32Constant(DAG, 0x3f800000, dl)); 5089 } 5090 5091 // Add the exponent into the result in integer domain. 5092 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 5093 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5094 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 5095 } 5096 5097 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5098 /// limited-precision mode. 5099 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5100 const TargetLowering &TLI, SDNodeFlags Flags) { 5101 if (Op.getValueType() == MVT::f32 && 5102 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5103 5104 // Put the exponent in the right bit position for later addition to the 5105 // final result: 5106 // 5107 // t0 = Op * log2(e) 5108 5109 // TODO: What fast-math-flags should be set here? 5110 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5111 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5112 return getLimitedPrecisionExp2(t0, dl, DAG); 5113 } 5114 5115 // No special expansion. 5116 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5117 } 5118 5119 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5120 /// limited-precision mode. 5121 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5122 const TargetLowering &TLI, SDNodeFlags Flags) { 5123 // TODO: What fast-math-flags should be set on the floating-point nodes? 5124 5125 if (Op.getValueType() == MVT::f32 && 5126 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5127 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5128 5129 // Scale the exponent by log(2). 5130 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5131 SDValue LogOfExponent = 5132 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5133 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5134 5135 // Get the significand and build it into a floating-point number with 5136 // exponent of 1. 5137 SDValue X = GetSignificand(DAG, Op1, dl); 5138 5139 SDValue LogOfMantissa; 5140 if (LimitFloatPrecision <= 6) { 5141 // For floating-point precision of 6: 5142 // 5143 // LogofMantissa = 5144 // -1.1609546f + 5145 // (1.4034025f - 0.23903021f * x) * x; 5146 // 5147 // error 0.0034276066, which is better than 8 bits 5148 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5149 getF32Constant(DAG, 0xbe74c456, dl)); 5150 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5151 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5152 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5153 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5154 getF32Constant(DAG, 0x3f949a29, dl)); 5155 } else if (LimitFloatPrecision <= 12) { 5156 // For floating-point precision of 12: 5157 // 5158 // LogOfMantissa = 5159 // -1.7417939f + 5160 // (2.8212026f + 5161 // (-1.4699568f + 5162 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5163 // 5164 // error 0.000061011436, which is 14 bits 5165 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5166 getF32Constant(DAG, 0xbd67b6d6, dl)); 5167 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5168 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5169 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5170 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5171 getF32Constant(DAG, 0x3fbc278b, dl)); 5172 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5173 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5174 getF32Constant(DAG, 0x40348e95, dl)); 5175 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5176 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5177 getF32Constant(DAG, 0x3fdef31a, dl)); 5178 } else { // LimitFloatPrecision <= 18 5179 // For floating-point precision of 18: 5180 // 5181 // LogOfMantissa = 5182 // -2.1072184f + 5183 // (4.2372794f + 5184 // (-3.7029485f + 5185 // (2.2781945f + 5186 // (-0.87823314f + 5187 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5188 // 5189 // error 0.0000023660568, which is better than 18 bits 5190 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5191 getF32Constant(DAG, 0xbc91e5ac, dl)); 5192 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5193 getF32Constant(DAG, 0x3e4350aa, dl)); 5194 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5195 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5196 getF32Constant(DAG, 0x3f60d3e3, dl)); 5197 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5198 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5199 getF32Constant(DAG, 0x4011cdf0, dl)); 5200 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5201 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5202 getF32Constant(DAG, 0x406cfd1c, dl)); 5203 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5204 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5205 getF32Constant(DAG, 0x408797cb, dl)); 5206 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5207 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5208 getF32Constant(DAG, 0x4006dcab, dl)); 5209 } 5210 5211 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5212 } 5213 5214 // No special expansion. 5215 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5216 } 5217 5218 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5219 /// limited-precision mode. 5220 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5221 const TargetLowering &TLI, SDNodeFlags Flags) { 5222 // TODO: What fast-math-flags should be set on the floating-point nodes? 5223 5224 if (Op.getValueType() == MVT::f32 && 5225 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5226 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5227 5228 // Get the exponent. 5229 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5230 5231 // Get the significand and build it into a floating-point number with 5232 // exponent of 1. 5233 SDValue X = GetSignificand(DAG, Op1, dl); 5234 5235 // Different possible minimax approximations of significand in 5236 // floating-point for various degrees of accuracy over [1,2]. 5237 SDValue Log2ofMantissa; 5238 if (LimitFloatPrecision <= 6) { 5239 // For floating-point precision of 6: 5240 // 5241 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5242 // 5243 // error 0.0049451742, which is more than 7 bits 5244 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5245 getF32Constant(DAG, 0xbeb08fe0, dl)); 5246 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5247 getF32Constant(DAG, 0x40019463, dl)); 5248 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5249 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5250 getF32Constant(DAG, 0x3fd6633d, dl)); 5251 } else if (LimitFloatPrecision <= 12) { 5252 // For floating-point precision of 12: 5253 // 5254 // Log2ofMantissa = 5255 // -2.51285454f + 5256 // (4.07009056f + 5257 // (-2.12067489f + 5258 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5259 // 5260 // error 0.0000876136000, which is better than 13 bits 5261 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5262 getF32Constant(DAG, 0xbda7262e, dl)); 5263 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5264 getF32Constant(DAG, 0x3f25280b, dl)); 5265 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5266 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5267 getF32Constant(DAG, 0x4007b923, dl)); 5268 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5269 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5270 getF32Constant(DAG, 0x40823e2f, dl)); 5271 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5272 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5273 getF32Constant(DAG, 0x4020d29c, dl)); 5274 } else { // LimitFloatPrecision <= 18 5275 // For floating-point precision of 18: 5276 // 5277 // Log2ofMantissa = 5278 // -3.0400495f + 5279 // (6.1129976f + 5280 // (-5.3420409f + 5281 // (3.2865683f + 5282 // (-1.2669343f + 5283 // (0.27515199f - 5284 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5285 // 5286 // error 0.0000018516, which is better than 18 bits 5287 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5288 getF32Constant(DAG, 0xbcd2769e, dl)); 5289 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5290 getF32Constant(DAG, 0x3e8ce0b9, 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, 0x3fa22ae7, 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, 0x40525723, dl)); 5297 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5298 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5299 getF32Constant(DAG, 0x40aaf200, dl)); 5300 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5301 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5302 getF32Constant(DAG, 0x40c39dad, dl)); 5303 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5304 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5305 getF32Constant(DAG, 0x4042902c, dl)); 5306 } 5307 5308 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5309 } 5310 5311 // No special expansion. 5312 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5313 } 5314 5315 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5316 /// limited-precision mode. 5317 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5318 const TargetLowering &TLI, SDNodeFlags Flags) { 5319 // TODO: What fast-math-flags should be set on the floating-point nodes? 5320 5321 if (Op.getValueType() == MVT::f32 && 5322 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5323 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5324 5325 // Scale the exponent by log10(2) [0.30102999f]. 5326 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5327 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5328 getF32Constant(DAG, 0x3e9a209a, dl)); 5329 5330 // Get the significand and build it into a floating-point number with 5331 // exponent of 1. 5332 SDValue X = GetSignificand(DAG, Op1, dl); 5333 5334 SDValue Log10ofMantissa; 5335 if (LimitFloatPrecision <= 6) { 5336 // For floating-point precision of 6: 5337 // 5338 // Log10ofMantissa = 5339 // -0.50419619f + 5340 // (0.60948995f - 0.10380950f * x) * x; 5341 // 5342 // error 0.0014886165, which is 6 bits 5343 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5344 getF32Constant(DAG, 0xbdd49a13, dl)); 5345 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5346 getF32Constant(DAG, 0x3f1c0789, dl)); 5347 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5348 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5349 getF32Constant(DAG, 0x3f011300, dl)); 5350 } else if (LimitFloatPrecision <= 12) { 5351 // For floating-point precision of 12: 5352 // 5353 // Log10ofMantissa = 5354 // -0.64831180f + 5355 // (0.91751397f + 5356 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5357 // 5358 // error 0.00019228036, which is better than 12 bits 5359 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5360 getF32Constant(DAG, 0x3d431f31, dl)); 5361 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5362 getF32Constant(DAG, 0x3ea21fb2, dl)); 5363 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5364 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5365 getF32Constant(DAG, 0x3f6ae232, dl)); 5366 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5367 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5368 getF32Constant(DAG, 0x3f25f7c3, dl)); 5369 } else { // LimitFloatPrecision <= 18 5370 // For floating-point precision of 18: 5371 // 5372 // Log10ofMantissa = 5373 // -0.84299375f + 5374 // (1.5327582f + 5375 // (-1.0688956f + 5376 // (0.49102474f + 5377 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5378 // 5379 // error 0.0000037995730, which is better than 18 bits 5380 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5381 getF32Constant(DAG, 0x3c5d51ce, dl)); 5382 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5383 getF32Constant(DAG, 0x3e00685a, dl)); 5384 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5385 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5386 getF32Constant(DAG, 0x3efb6798, dl)); 5387 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5388 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5389 getF32Constant(DAG, 0x3f88d192, dl)); 5390 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5391 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5392 getF32Constant(DAG, 0x3fc4316c, dl)); 5393 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5394 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5395 getF32Constant(DAG, 0x3f57ce70, dl)); 5396 } 5397 5398 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5399 } 5400 5401 // No special expansion. 5402 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5403 } 5404 5405 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5406 /// limited-precision mode. 5407 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5408 const TargetLowering &TLI, SDNodeFlags Flags) { 5409 if (Op.getValueType() == MVT::f32 && 5410 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5411 return getLimitedPrecisionExp2(Op, dl, DAG); 5412 5413 // No special expansion. 5414 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5415 } 5416 5417 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5418 /// limited-precision mode with x == 10.0f. 5419 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5420 SelectionDAG &DAG, const TargetLowering &TLI, 5421 SDNodeFlags Flags) { 5422 bool IsExp10 = false; 5423 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5424 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5425 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5426 APFloat Ten(10.0f); 5427 IsExp10 = LHSC->isExactlyValue(Ten); 5428 } 5429 } 5430 5431 // TODO: What fast-math-flags should be set on the FMUL node? 5432 if (IsExp10) { 5433 // Put the exponent in the right bit position for later addition to the 5434 // final result: 5435 // 5436 // #define LOG2OF10 3.3219281f 5437 // t0 = Op * LOG2OF10; 5438 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5439 getF32Constant(DAG, 0x40549a78, dl)); 5440 return getLimitedPrecisionExp2(t0, dl, DAG); 5441 } 5442 5443 // No special expansion. 5444 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5445 } 5446 5447 /// ExpandPowI - Expand a llvm.powi intrinsic. 5448 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5449 SelectionDAG &DAG) { 5450 // If RHS is a constant, we can expand this out to a multiplication tree if 5451 // it's beneficial on the target, otherwise we end up lowering to a call to 5452 // __powidf2 (for example). 5453 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5454 int Val = RHSC->getSExtValue(); 5455 5456 // powi(x, 0) -> 1.0 5457 if (Val == 0) 5458 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5459 5460 if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI( 5461 Val, DAG.shouldOptForSize())) { 5462 // We use the simple binary decomposition method to generate the multiply 5463 // sequence. There are more optimal ways to do this (for example, 5464 // powi(x,15) generates one more multiply than it should), but this has 5465 // the benefit of being both really simple and much better than a libcall. 5466 SDValue Res; // Logically starts equal to 1.0 5467 SDValue CurSquare = LHS; 5468 // TODO: Intrinsics should have fast-math-flags that propagate to these 5469 // nodes. 5470 while (Val) { 5471 if (Val & 1) { 5472 if (Res.getNode()) 5473 Res = 5474 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare); 5475 else 5476 Res = CurSquare; // 1.0*CurSquare. 5477 } 5478 5479 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5480 CurSquare, CurSquare); 5481 // Use logic right shift 5482 Val = int(unsigned(Val) >> 1); 5483 } 5484 5485 // If the original was negative, invert the result, producing 1/(x*x*x). 5486 if (RHSC->getSExtValue() < 0) 5487 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5488 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5489 return Res; 5490 } 5491 } 5492 5493 // Otherwise, expand to a libcall. 5494 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5495 } 5496 5497 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5498 SDValue LHS, SDValue RHS, SDValue Scale, 5499 SelectionDAG &DAG, const TargetLowering &TLI) { 5500 EVT VT = LHS.getValueType(); 5501 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5502 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5503 LLVMContext &Ctx = *DAG.getContext(); 5504 5505 // If the type is legal but the operation isn't, this node might survive all 5506 // the way to operation legalization. If we end up there and we do not have 5507 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5508 // node. 5509 5510 // Coax the legalizer into expanding the node during type legalization instead 5511 // by bumping the size by one bit. This will force it to Promote, enabling the 5512 // early expansion and avoiding the need to expand later. 5513 5514 // We don't have to do this if Scale is 0; that can always be expanded, unless 5515 // it's a saturating signed operation. Those can experience true integer 5516 // division overflow, a case which we must avoid. 5517 5518 // FIXME: We wouldn't have to do this (or any of the early 5519 // expansion/promotion) if it was possible to expand a libcall of an 5520 // illegal type during operation legalization. But it's not, so things 5521 // get a bit hacky. 5522 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5523 if ((ScaleInt > 0 || (Saturating && Signed)) && 5524 (TLI.isTypeLegal(VT) || 5525 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5526 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5527 Opcode, VT, ScaleInt); 5528 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5529 EVT PromVT; 5530 if (VT.isScalarInteger()) 5531 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5532 else if (VT.isVector()) { 5533 PromVT = VT.getVectorElementType(); 5534 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5535 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5536 } else 5537 llvm_unreachable("Wrong VT for DIVFIX?"); 5538 if (Signed) { 5539 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5540 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5541 } else { 5542 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5543 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5544 } 5545 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5546 // For saturating operations, we need to shift up the LHS to get the 5547 // proper saturation width, and then shift down again afterwards. 5548 if (Saturating) 5549 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5550 DAG.getConstant(1, DL, ShiftTy)); 5551 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5552 if (Saturating) 5553 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5554 DAG.getConstant(1, DL, ShiftTy)); 5555 return DAG.getZExtOrTrunc(Res, DL, VT); 5556 } 5557 } 5558 5559 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5560 } 5561 5562 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5563 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5564 static void 5565 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5566 const SDValue &N) { 5567 switch (N.getOpcode()) { 5568 case ISD::CopyFromReg: { 5569 SDValue Op = N.getOperand(1); 5570 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5571 Op.getValueType().getSizeInBits()); 5572 return; 5573 } 5574 case ISD::BITCAST: 5575 case ISD::AssertZext: 5576 case ISD::AssertSext: 5577 case ISD::TRUNCATE: 5578 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5579 return; 5580 case ISD::BUILD_PAIR: 5581 case ISD::BUILD_VECTOR: 5582 case ISD::CONCAT_VECTORS: 5583 for (SDValue Op : N->op_values()) 5584 getUnderlyingArgRegs(Regs, Op); 5585 return; 5586 default: 5587 return; 5588 } 5589 } 5590 5591 /// If the DbgValueInst is a dbg_value of a function argument, create the 5592 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5593 /// instruction selection, they will be inserted to the entry BB. 5594 /// We don't currently support this for variadic dbg_values, as they shouldn't 5595 /// appear for function arguments or in the prologue. 5596 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5597 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5598 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) { 5599 const Argument *Arg = dyn_cast<Argument>(V); 5600 if (!Arg) 5601 return false; 5602 5603 MachineFunction &MF = DAG.getMachineFunction(); 5604 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5605 5606 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind 5607 // we've been asked to pursue. 5608 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr, 5609 bool Indirect) { 5610 if (Reg.isVirtual() && MF.useDebugInstrRef()) { 5611 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF 5612 // pointing at the VReg, which will be patched up later. 5613 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF); 5614 SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg( 5615 /* Reg */ Reg, /* isDef */ false, /* isImp */ false, 5616 /* isKill */ false, /* isDead */ false, 5617 /* isUndef */ false, /* isEarlyClobber */ false, 5618 /* SubReg */ 0, /* isDebug */ true)}); 5619 5620 auto *NewDIExpr = FragExpr; 5621 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into 5622 // the DIExpression. 5623 if (Indirect) 5624 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore); 5625 SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0}); 5626 NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops); 5627 return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr); 5628 } else { 5629 // Create a completely standard DBG_VALUE. 5630 auto &Inst = TII->get(TargetOpcode::DBG_VALUE); 5631 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr); 5632 } 5633 }; 5634 5635 if (Kind == FuncArgumentDbgValueKind::Value) { 5636 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5637 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5638 // the entry block. 5639 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5640 if (!IsInEntryBlock) 5641 return false; 5642 5643 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5644 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5645 // variable that also is a param. 5646 // 5647 // Although, if we are at the top of the entry block already, we can still 5648 // emit using ArgDbgValue. This might catch some situations when the 5649 // dbg.value refers to an argument that isn't used in the entry block, so 5650 // any CopyToReg node would be optimized out and the only way to express 5651 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5652 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5653 // we should only emit as ArgDbgValue if the Variable is an argument to the 5654 // current function, and the dbg.value intrinsic is found in the entry 5655 // block. 5656 bool VariableIsFunctionInputArg = Variable->isParameter() && 5657 !DL->getInlinedAt(); 5658 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5659 if (!IsInPrologue && !VariableIsFunctionInputArg) 5660 return false; 5661 5662 // Here we assume that a function argument on IR level only can be used to 5663 // describe one input parameter on source level. If we for example have 5664 // source code like this 5665 // 5666 // struct A { long x, y; }; 5667 // void foo(struct A a, long b) { 5668 // ... 5669 // b = a.x; 5670 // ... 5671 // } 5672 // 5673 // and IR like this 5674 // 5675 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5676 // entry: 5677 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5678 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5679 // call void @llvm.dbg.value(metadata i32 %b, "b", 5680 // ... 5681 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5682 // ... 5683 // 5684 // then the last dbg.value is describing a parameter "b" using a value that 5685 // is an argument. But since we already has used %a1 to describe a parameter 5686 // we should not handle that last dbg.value here (that would result in an 5687 // incorrect hoisting of the DBG_VALUE to the function entry). 5688 // Notice that we allow one dbg.value per IR level argument, to accommodate 5689 // for the situation with fragments above. 5690 if (VariableIsFunctionInputArg) { 5691 unsigned ArgNo = Arg->getArgNo(); 5692 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5693 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5694 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5695 return false; 5696 FuncInfo.DescribedArgs.set(ArgNo); 5697 } 5698 } 5699 5700 bool IsIndirect = false; 5701 std::optional<MachineOperand> Op; 5702 // Some arguments' frame index is recorded during argument lowering. 5703 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5704 if (FI != std::numeric_limits<int>::max()) 5705 Op = MachineOperand::CreateFI(FI); 5706 5707 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 5708 if (!Op && N.getNode()) { 5709 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5710 Register Reg; 5711 if (ArgRegsAndSizes.size() == 1) 5712 Reg = ArgRegsAndSizes.front().first; 5713 5714 if (Reg && Reg.isVirtual()) { 5715 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5716 Register PR = RegInfo.getLiveInPhysReg(Reg); 5717 if (PR) 5718 Reg = PR; 5719 } 5720 if (Reg) { 5721 Op = MachineOperand::CreateReg(Reg, false); 5722 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5723 } 5724 } 5725 5726 if (!Op && N.getNode()) { 5727 // Check if frame index is available. 5728 SDValue LCandidate = peekThroughBitcasts(N); 5729 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5730 if (FrameIndexSDNode *FINode = 5731 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5732 Op = MachineOperand::CreateFI(FINode->getIndex()); 5733 } 5734 5735 if (!Op) { 5736 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5737 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 5738 SplitRegs) { 5739 unsigned Offset = 0; 5740 for (const auto &RegAndSize : SplitRegs) { 5741 // If the expression is already a fragment, the current register 5742 // offset+size might extend beyond the fragment. In this case, only 5743 // the register bits that are inside the fragment are relevant. 5744 int RegFragmentSizeInBits = RegAndSize.second; 5745 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5746 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5747 // The register is entirely outside the expression fragment, 5748 // so is irrelevant for debug info. 5749 if (Offset >= ExprFragmentSizeInBits) 5750 break; 5751 // The register is partially outside the expression fragment, only 5752 // the low bits within the fragment are relevant for debug info. 5753 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5754 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5755 } 5756 } 5757 5758 auto FragmentExpr = DIExpression::createFragmentExpression( 5759 Expr, Offset, RegFragmentSizeInBits); 5760 Offset += RegAndSize.second; 5761 // If a valid fragment expression cannot be created, the variable's 5762 // correct value cannot be determined and so it is set as Undef. 5763 if (!FragmentExpr) { 5764 SDDbgValue *SDV = DAG.getConstantDbgValue( 5765 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5766 DAG.AddDbgValue(SDV, false); 5767 continue; 5768 } 5769 MachineInstr *NewMI = 5770 MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, 5771 Kind != FuncArgumentDbgValueKind::Value); 5772 FuncInfo.ArgDbgValues.push_back(NewMI); 5773 } 5774 }; 5775 5776 // Check if ValueMap has reg number. 5777 DenseMap<const Value *, Register>::const_iterator 5778 VMI = FuncInfo.ValueMap.find(V); 5779 if (VMI != FuncInfo.ValueMap.end()) { 5780 const auto &TLI = DAG.getTargetLoweringInfo(); 5781 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5782 V->getType(), std::nullopt); 5783 if (RFV.occupiesMultipleRegs()) { 5784 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5785 return true; 5786 } 5787 5788 Op = MachineOperand::CreateReg(VMI->second, false); 5789 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5790 } else if (ArgRegsAndSizes.size() > 1) { 5791 // This was split due to the calling convention, and no virtual register 5792 // mapping exists for the value. 5793 splitMultiRegDbgValue(ArgRegsAndSizes); 5794 return true; 5795 } 5796 } 5797 5798 if (!Op) 5799 return false; 5800 5801 assert(Variable->isValidLocationForIntrinsic(DL) && 5802 "Expected inlined-at fields to agree"); 5803 MachineInstr *NewMI = nullptr; 5804 5805 if (Op->isReg()) 5806 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect); 5807 else 5808 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op, 5809 Variable, Expr); 5810 5811 // Otherwise, use ArgDbgValues. 5812 FuncInfo.ArgDbgValues.push_back(NewMI); 5813 return true; 5814 } 5815 5816 /// Return the appropriate SDDbgValue based on N. 5817 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5818 DILocalVariable *Variable, 5819 DIExpression *Expr, 5820 const DebugLoc &dl, 5821 unsigned DbgSDNodeOrder) { 5822 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5823 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5824 // stack slot locations. 5825 // 5826 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5827 // debug values here after optimization: 5828 // 5829 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5830 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5831 // 5832 // Both describe the direct values of their associated variables. 5833 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5834 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5835 } 5836 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5837 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5838 } 5839 5840 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5841 switch (Intrinsic) { 5842 case Intrinsic::smul_fix: 5843 return ISD::SMULFIX; 5844 case Intrinsic::umul_fix: 5845 return ISD::UMULFIX; 5846 case Intrinsic::smul_fix_sat: 5847 return ISD::SMULFIXSAT; 5848 case Intrinsic::umul_fix_sat: 5849 return ISD::UMULFIXSAT; 5850 case Intrinsic::sdiv_fix: 5851 return ISD::SDIVFIX; 5852 case Intrinsic::udiv_fix: 5853 return ISD::UDIVFIX; 5854 case Intrinsic::sdiv_fix_sat: 5855 return ISD::SDIVFIXSAT; 5856 case Intrinsic::udiv_fix_sat: 5857 return ISD::UDIVFIXSAT; 5858 default: 5859 llvm_unreachable("Unhandled fixed point intrinsic"); 5860 } 5861 } 5862 5863 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5864 const char *FunctionName) { 5865 assert(FunctionName && "FunctionName must not be nullptr"); 5866 SDValue Callee = DAG.getExternalSymbol( 5867 FunctionName, 5868 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5869 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 5870 } 5871 5872 /// Given a @llvm.call.preallocated.setup, return the corresponding 5873 /// preallocated call. 5874 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5875 assert(cast<CallBase>(PreallocatedSetup) 5876 ->getCalledFunction() 5877 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5878 "expected call_preallocated_setup Value"); 5879 for (const auto *U : PreallocatedSetup->users()) { 5880 auto *UseCall = cast<CallBase>(U); 5881 const Function *Fn = UseCall->getCalledFunction(); 5882 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5883 return UseCall; 5884 } 5885 } 5886 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5887 } 5888 5889 /// Lower the call to the specified intrinsic function. 5890 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5891 unsigned Intrinsic) { 5892 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5893 SDLoc sdl = getCurSDLoc(); 5894 DebugLoc dl = getCurDebugLoc(); 5895 SDValue Res; 5896 5897 SDNodeFlags Flags; 5898 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 5899 Flags.copyFMF(*FPOp); 5900 5901 switch (Intrinsic) { 5902 default: 5903 // By default, turn this into a target intrinsic node. 5904 visitTargetIntrinsic(I, Intrinsic); 5905 return; 5906 case Intrinsic::vscale: { 5907 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5908 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1))); 5909 return; 5910 } 5911 case Intrinsic::vastart: visitVAStart(I); return; 5912 case Intrinsic::vaend: visitVAEnd(I); return; 5913 case Intrinsic::vacopy: visitVACopy(I); return; 5914 case Intrinsic::returnaddress: 5915 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5916 TLI.getValueType(DAG.getDataLayout(), I.getType()), 5917 getValue(I.getArgOperand(0)))); 5918 return; 5919 case Intrinsic::addressofreturnaddress: 5920 setValue(&I, 5921 DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5922 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 5923 return; 5924 case Intrinsic::sponentry: 5925 setValue(&I, 5926 DAG.getNode(ISD::SPONENTRY, sdl, 5927 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 5928 return; 5929 case Intrinsic::frameaddress: 5930 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5931 TLI.getFrameIndexTy(DAG.getDataLayout()), 5932 getValue(I.getArgOperand(0)))); 5933 return; 5934 case Intrinsic::read_volatile_register: 5935 case Intrinsic::read_register: { 5936 Value *Reg = I.getArgOperand(0); 5937 SDValue Chain = getRoot(); 5938 SDValue RegName = 5939 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5940 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5941 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5942 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5943 setValue(&I, Res); 5944 DAG.setRoot(Res.getValue(1)); 5945 return; 5946 } 5947 case Intrinsic::write_register: { 5948 Value *Reg = I.getArgOperand(0); 5949 Value *RegValue = I.getArgOperand(1); 5950 SDValue Chain = getRoot(); 5951 SDValue RegName = 5952 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5953 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5954 RegName, getValue(RegValue))); 5955 return; 5956 } 5957 case Intrinsic::memcpy: { 5958 const auto &MCI = cast<MemCpyInst>(I); 5959 SDValue Op1 = getValue(I.getArgOperand(0)); 5960 SDValue Op2 = getValue(I.getArgOperand(1)); 5961 SDValue Op3 = getValue(I.getArgOperand(2)); 5962 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5963 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5964 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5965 Align Alignment = std::min(DstAlign, SrcAlign); 5966 bool isVol = MCI.isVolatile(); 5967 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5968 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5969 // node. 5970 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5971 SDValue MC = DAG.getMemcpy( 5972 Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5973 /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)), 5974 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 5975 updateDAGForMaybeTailCall(MC); 5976 return; 5977 } 5978 case Intrinsic::memcpy_inline: { 5979 const auto &MCI = cast<MemCpyInlineInst>(I); 5980 SDValue Dst = getValue(I.getArgOperand(0)); 5981 SDValue Src = getValue(I.getArgOperand(1)); 5982 SDValue Size = getValue(I.getArgOperand(2)); 5983 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 5984 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 5985 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5986 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5987 Align Alignment = std::min(DstAlign, SrcAlign); 5988 bool isVol = MCI.isVolatile(); 5989 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5990 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5991 // node. 5992 SDValue MC = DAG.getMemcpy( 5993 getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 5994 /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)), 5995 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 5996 updateDAGForMaybeTailCall(MC); 5997 return; 5998 } 5999 case Intrinsic::memset: { 6000 const auto &MSI = cast<MemSetInst>(I); 6001 SDValue Op1 = getValue(I.getArgOperand(0)); 6002 SDValue Op2 = getValue(I.getArgOperand(1)); 6003 SDValue Op3 = getValue(I.getArgOperand(2)); 6004 // @llvm.memset defines 0 and 1 to both mean no alignment. 6005 Align Alignment = MSI.getDestAlign().valueOrOne(); 6006 bool isVol = MSI.isVolatile(); 6007 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6008 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6009 SDValue MS = DAG.getMemset( 6010 Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false, 6011 isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata()); 6012 updateDAGForMaybeTailCall(MS); 6013 return; 6014 } 6015 case Intrinsic::memset_inline: { 6016 const auto &MSII = cast<MemSetInlineInst>(I); 6017 SDValue Dst = getValue(I.getArgOperand(0)); 6018 SDValue Value = getValue(I.getArgOperand(1)); 6019 SDValue Size = getValue(I.getArgOperand(2)); 6020 assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size"); 6021 // @llvm.memset defines 0 and 1 to both mean no alignment. 6022 Align DstAlign = MSII.getDestAlign().valueOrOne(); 6023 bool isVol = MSII.isVolatile(); 6024 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6025 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6026 SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol, 6027 /* AlwaysInline */ true, isTC, 6028 MachinePointerInfo(I.getArgOperand(0)), 6029 I.getAAMetadata()); 6030 updateDAGForMaybeTailCall(MC); 6031 return; 6032 } 6033 case Intrinsic::memmove: { 6034 const auto &MMI = cast<MemMoveInst>(I); 6035 SDValue Op1 = getValue(I.getArgOperand(0)); 6036 SDValue Op2 = getValue(I.getArgOperand(1)); 6037 SDValue Op3 = getValue(I.getArgOperand(2)); 6038 // @llvm.memmove defines 0 and 1 to both mean no alignment. 6039 Align DstAlign = MMI.getDestAlign().valueOrOne(); 6040 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 6041 Align Alignment = std::min(DstAlign, SrcAlign); 6042 bool isVol = MMI.isVolatile(); 6043 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6044 // FIXME: Support passing different dest/src alignments to the memmove DAG 6045 // node. 6046 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6047 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6048 isTC, MachinePointerInfo(I.getArgOperand(0)), 6049 MachinePointerInfo(I.getArgOperand(1)), 6050 I.getAAMetadata(), AA); 6051 updateDAGForMaybeTailCall(MM); 6052 return; 6053 } 6054 case Intrinsic::memcpy_element_unordered_atomic: { 6055 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 6056 SDValue Dst = getValue(MI.getRawDest()); 6057 SDValue Src = getValue(MI.getRawSource()); 6058 SDValue Length = getValue(MI.getLength()); 6059 6060 Type *LengthTy = MI.getLength()->getType(); 6061 unsigned ElemSz = MI.getElementSizeInBytes(); 6062 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6063 SDValue MC = 6064 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6065 isTC, MachinePointerInfo(MI.getRawDest()), 6066 MachinePointerInfo(MI.getRawSource())); 6067 updateDAGForMaybeTailCall(MC); 6068 return; 6069 } 6070 case Intrinsic::memmove_element_unordered_atomic: { 6071 auto &MI = cast<AtomicMemMoveInst>(I); 6072 SDValue Dst = getValue(MI.getRawDest()); 6073 SDValue Src = getValue(MI.getRawSource()); 6074 SDValue Length = getValue(MI.getLength()); 6075 6076 Type *LengthTy = MI.getLength()->getType(); 6077 unsigned ElemSz = MI.getElementSizeInBytes(); 6078 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6079 SDValue MC = 6080 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6081 isTC, MachinePointerInfo(MI.getRawDest()), 6082 MachinePointerInfo(MI.getRawSource())); 6083 updateDAGForMaybeTailCall(MC); 6084 return; 6085 } 6086 case Intrinsic::memset_element_unordered_atomic: { 6087 auto &MI = cast<AtomicMemSetInst>(I); 6088 SDValue Dst = getValue(MI.getRawDest()); 6089 SDValue Val = getValue(MI.getValue()); 6090 SDValue Length = getValue(MI.getLength()); 6091 6092 Type *LengthTy = MI.getLength()->getType(); 6093 unsigned ElemSz = MI.getElementSizeInBytes(); 6094 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6095 SDValue MC = 6096 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz, 6097 isTC, MachinePointerInfo(MI.getRawDest())); 6098 updateDAGForMaybeTailCall(MC); 6099 return; 6100 } 6101 case Intrinsic::call_preallocated_setup: { 6102 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 6103 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6104 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 6105 getRoot(), SrcValue); 6106 setValue(&I, Res); 6107 DAG.setRoot(Res); 6108 return; 6109 } 6110 case Intrinsic::call_preallocated_arg: { 6111 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 6112 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6113 SDValue Ops[3]; 6114 Ops[0] = getRoot(); 6115 Ops[1] = SrcValue; 6116 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 6117 MVT::i32); // arg index 6118 SDValue Res = DAG.getNode( 6119 ISD::PREALLOCATED_ARG, sdl, 6120 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 6121 setValue(&I, Res); 6122 DAG.setRoot(Res.getValue(1)); 6123 return; 6124 } 6125 case Intrinsic::dbg_declare: { 6126 // Debug intrinsics are handled separately in assignment tracking mode. 6127 if (AssignmentTrackingEnabled) 6128 return; 6129 // Assume dbg.declare can not currently use DIArgList, i.e. 6130 // it is non-variadic. 6131 const auto &DI = cast<DbgVariableIntrinsic>(I); 6132 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 6133 DILocalVariable *Variable = DI.getVariable(); 6134 DIExpression *Expression = DI.getExpression(); 6135 dropDanglingDebugInfo(Variable, Expression); 6136 assert(Variable && "Missing variable"); 6137 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 6138 << "\n"); 6139 // Check if address has undef value. 6140 const Value *Address = DI.getVariableLocationOp(0); 6141 if (!Address || isa<UndefValue>(Address) || 6142 (Address->use_empty() && !isa<Argument>(Address))) { 6143 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6144 << " (bad/undef/unused-arg address)\n"); 6145 return; 6146 } 6147 6148 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 6149 6150 // Check if this variable can be described by a frame index, typically 6151 // either as a static alloca or a byval parameter. 6152 int FI = std::numeric_limits<int>::max(); 6153 if (const auto *AI = 6154 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 6155 if (AI->isStaticAlloca()) { 6156 auto I = FuncInfo.StaticAllocaMap.find(AI); 6157 if (I != FuncInfo.StaticAllocaMap.end()) 6158 FI = I->second; 6159 } 6160 } else if (const auto *Arg = dyn_cast<Argument>( 6161 Address->stripInBoundsConstantOffsets())) { 6162 FI = FuncInfo.getArgumentFrameIndex(Arg); 6163 } 6164 6165 // llvm.dbg.declare is handled as a frame index in the MachineFunction 6166 // variable table. 6167 if (FI != std::numeric_limits<int>::max()) { 6168 LLVM_DEBUG(dbgs() << "Skipping " << DI 6169 << " (variable info stashed in MF side table)\n"); 6170 return; 6171 } 6172 6173 SDValue &N = NodeMap[Address]; 6174 if (!N.getNode() && isa<Argument>(Address)) 6175 // Check unused arguments map. 6176 N = UnusedArgNodeMap[Address]; 6177 SDDbgValue *SDV; 6178 if (N.getNode()) { 6179 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 6180 Address = BCI->getOperand(0); 6181 // Parameters are handled specially. 6182 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 6183 if (isParameter && FINode) { 6184 // Byval parameter. We have a frame index at this point. 6185 SDV = 6186 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 6187 /*IsIndirect*/ true, dl, SDNodeOrder); 6188 } else if (isa<Argument>(Address)) { 6189 // Address is an argument, so try to emit its dbg value using 6190 // virtual register info from the FuncInfo.ValueMap. 6191 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 6192 FuncArgumentDbgValueKind::Declare, N); 6193 return; 6194 } else { 6195 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 6196 true, dl, SDNodeOrder); 6197 } 6198 DAG.AddDbgValue(SDV, isParameter); 6199 } else { 6200 // If Address is an argument then try to emit its dbg value using 6201 // virtual register info from the FuncInfo.ValueMap. 6202 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 6203 FuncArgumentDbgValueKind::Declare, N)) { 6204 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6205 << " (could not emit func-arg dbg_value)\n"); 6206 } 6207 } 6208 return; 6209 } 6210 case Intrinsic::dbg_label: { 6211 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6212 DILabel *Label = DI.getLabel(); 6213 assert(Label && "Missing label"); 6214 6215 SDDbgLabel *SDV; 6216 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6217 DAG.AddDbgLabel(SDV); 6218 return; 6219 } 6220 case Intrinsic::dbg_assign: { 6221 // Debug intrinsics are handled seperately in assignment tracking mode. 6222 if (AssignmentTrackingEnabled) 6223 return; 6224 // If assignment tracking hasn't been enabled then fall through and treat 6225 // the dbg.assign as a dbg.value. 6226 [[fallthrough]]; 6227 } 6228 case Intrinsic::dbg_value: { 6229 // Debug intrinsics are handled seperately in assignment tracking mode. 6230 if (AssignmentTrackingEnabled) 6231 return; 6232 const DbgValueInst &DI = cast<DbgValueInst>(I); 6233 assert(DI.getVariable() && "Missing variable"); 6234 6235 DILocalVariable *Variable = DI.getVariable(); 6236 DIExpression *Expression = DI.getExpression(); 6237 dropDanglingDebugInfo(Variable, Expression); 6238 6239 if (DI.isKillLocation()) { 6240 handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder); 6241 return; 6242 } 6243 6244 SmallVector<Value *, 4> Values(DI.getValues()); 6245 if (Values.empty()) 6246 return; 6247 6248 bool IsVariadic = DI.hasArgList(); 6249 if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(), 6250 SDNodeOrder, IsVariadic)) 6251 addDanglingDebugInfo(&DI, SDNodeOrder); 6252 return; 6253 } 6254 6255 case Intrinsic::eh_typeid_for: { 6256 // Find the type id for the given typeinfo. 6257 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6258 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6259 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6260 setValue(&I, Res); 6261 return; 6262 } 6263 6264 case Intrinsic::eh_return_i32: 6265 case Intrinsic::eh_return_i64: 6266 DAG.getMachineFunction().setCallsEHReturn(true); 6267 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6268 MVT::Other, 6269 getControlRoot(), 6270 getValue(I.getArgOperand(0)), 6271 getValue(I.getArgOperand(1)))); 6272 return; 6273 case Intrinsic::eh_unwind_init: 6274 DAG.getMachineFunction().setCallsUnwindInit(true); 6275 return; 6276 case Intrinsic::eh_dwarf_cfa: 6277 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6278 TLI.getPointerTy(DAG.getDataLayout()), 6279 getValue(I.getArgOperand(0)))); 6280 return; 6281 case Intrinsic::eh_sjlj_callsite: { 6282 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6283 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0)); 6284 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6285 6286 MMI.setCurrentCallSite(CI->getZExtValue()); 6287 return; 6288 } 6289 case Intrinsic::eh_sjlj_functioncontext: { 6290 // Get and store the index of the function context. 6291 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6292 AllocaInst *FnCtx = 6293 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6294 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6295 MFI.setFunctionContextIndex(FI); 6296 return; 6297 } 6298 case Intrinsic::eh_sjlj_setjmp: { 6299 SDValue Ops[2]; 6300 Ops[0] = getRoot(); 6301 Ops[1] = getValue(I.getArgOperand(0)); 6302 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6303 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6304 setValue(&I, Op.getValue(0)); 6305 DAG.setRoot(Op.getValue(1)); 6306 return; 6307 } 6308 case Intrinsic::eh_sjlj_longjmp: 6309 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6310 getRoot(), getValue(I.getArgOperand(0)))); 6311 return; 6312 case Intrinsic::eh_sjlj_setup_dispatch: 6313 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6314 getRoot())); 6315 return; 6316 case Intrinsic::masked_gather: 6317 visitMaskedGather(I); 6318 return; 6319 case Intrinsic::masked_load: 6320 visitMaskedLoad(I); 6321 return; 6322 case Intrinsic::masked_scatter: 6323 visitMaskedScatter(I); 6324 return; 6325 case Intrinsic::masked_store: 6326 visitMaskedStore(I); 6327 return; 6328 case Intrinsic::masked_expandload: 6329 visitMaskedLoad(I, true /* IsExpanding */); 6330 return; 6331 case Intrinsic::masked_compressstore: 6332 visitMaskedStore(I, true /* IsCompressing */); 6333 return; 6334 case Intrinsic::powi: 6335 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6336 getValue(I.getArgOperand(1)), DAG)); 6337 return; 6338 case Intrinsic::log: 6339 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6340 return; 6341 case Intrinsic::log2: 6342 setValue(&I, 6343 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6344 return; 6345 case Intrinsic::log10: 6346 setValue(&I, 6347 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6348 return; 6349 case Intrinsic::exp: 6350 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6351 return; 6352 case Intrinsic::exp2: 6353 setValue(&I, 6354 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6355 return; 6356 case Intrinsic::pow: 6357 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6358 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6359 return; 6360 case Intrinsic::sqrt: 6361 case Intrinsic::fabs: 6362 case Intrinsic::sin: 6363 case Intrinsic::cos: 6364 case Intrinsic::floor: 6365 case Intrinsic::ceil: 6366 case Intrinsic::trunc: 6367 case Intrinsic::rint: 6368 case Intrinsic::nearbyint: 6369 case Intrinsic::round: 6370 case Intrinsic::roundeven: 6371 case Intrinsic::canonicalize: { 6372 unsigned Opcode; 6373 switch (Intrinsic) { 6374 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6375 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6376 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6377 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6378 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6379 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6380 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6381 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6382 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6383 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6384 case Intrinsic::round: Opcode = ISD::FROUND; break; 6385 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6386 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6387 } 6388 6389 setValue(&I, DAG.getNode(Opcode, sdl, 6390 getValue(I.getArgOperand(0)).getValueType(), 6391 getValue(I.getArgOperand(0)), Flags)); 6392 return; 6393 } 6394 case Intrinsic::lround: 6395 case Intrinsic::llround: 6396 case Intrinsic::lrint: 6397 case Intrinsic::llrint: { 6398 unsigned Opcode; 6399 switch (Intrinsic) { 6400 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6401 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6402 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6403 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6404 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6405 } 6406 6407 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6408 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6409 getValue(I.getArgOperand(0)))); 6410 return; 6411 } 6412 case Intrinsic::minnum: 6413 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6414 getValue(I.getArgOperand(0)).getValueType(), 6415 getValue(I.getArgOperand(0)), 6416 getValue(I.getArgOperand(1)), Flags)); 6417 return; 6418 case Intrinsic::maxnum: 6419 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6420 getValue(I.getArgOperand(0)).getValueType(), 6421 getValue(I.getArgOperand(0)), 6422 getValue(I.getArgOperand(1)), Flags)); 6423 return; 6424 case Intrinsic::minimum: 6425 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6426 getValue(I.getArgOperand(0)).getValueType(), 6427 getValue(I.getArgOperand(0)), 6428 getValue(I.getArgOperand(1)), Flags)); 6429 return; 6430 case Intrinsic::maximum: 6431 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6432 getValue(I.getArgOperand(0)).getValueType(), 6433 getValue(I.getArgOperand(0)), 6434 getValue(I.getArgOperand(1)), Flags)); 6435 return; 6436 case Intrinsic::copysign: 6437 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6438 getValue(I.getArgOperand(0)).getValueType(), 6439 getValue(I.getArgOperand(0)), 6440 getValue(I.getArgOperand(1)), Flags)); 6441 return; 6442 case Intrinsic::arithmetic_fence: { 6443 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl, 6444 getValue(I.getArgOperand(0)).getValueType(), 6445 getValue(I.getArgOperand(0)), Flags)); 6446 return; 6447 } 6448 case Intrinsic::fma: 6449 setValue(&I, DAG.getNode( 6450 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6451 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6452 getValue(I.getArgOperand(2)), Flags)); 6453 return; 6454 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6455 case Intrinsic::INTRINSIC: 6456 #include "llvm/IR/ConstrainedOps.def" 6457 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6458 return; 6459 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6460 #include "llvm/IR/VPIntrinsics.def" 6461 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6462 return; 6463 case Intrinsic::fptrunc_round: { 6464 // Get the last argument, the metadata and convert it to an integer in the 6465 // call 6466 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata(); 6467 std::optional<RoundingMode> RoundMode = 6468 convertStrToRoundingMode(cast<MDString>(MD)->getString()); 6469 6470 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6471 6472 // Propagate fast-math-flags from IR to node(s). 6473 SDNodeFlags Flags; 6474 Flags.copyFMF(*cast<FPMathOperator>(&I)); 6475 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 6476 6477 SDValue Result; 6478 Result = DAG.getNode( 6479 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)), 6480 DAG.getTargetConstant((int)*RoundMode, sdl, 6481 TLI.getPointerTy(DAG.getDataLayout()))); 6482 setValue(&I, Result); 6483 6484 return; 6485 } 6486 case Intrinsic::fmuladd: { 6487 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6488 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6489 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6490 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6491 getValue(I.getArgOperand(0)).getValueType(), 6492 getValue(I.getArgOperand(0)), 6493 getValue(I.getArgOperand(1)), 6494 getValue(I.getArgOperand(2)), Flags)); 6495 } else { 6496 // TODO: Intrinsic calls should have fast-math-flags. 6497 SDValue Mul = DAG.getNode( 6498 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6499 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6500 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6501 getValue(I.getArgOperand(0)).getValueType(), 6502 Mul, getValue(I.getArgOperand(2)), Flags); 6503 setValue(&I, Add); 6504 } 6505 return; 6506 } 6507 case Intrinsic::convert_to_fp16: 6508 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6509 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6510 getValue(I.getArgOperand(0)), 6511 DAG.getTargetConstant(0, sdl, 6512 MVT::i32)))); 6513 return; 6514 case Intrinsic::convert_from_fp16: 6515 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6516 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6517 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6518 getValue(I.getArgOperand(0))))); 6519 return; 6520 case Intrinsic::fptosi_sat: { 6521 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6522 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 6523 getValue(I.getArgOperand(0)), 6524 DAG.getValueType(VT.getScalarType()))); 6525 return; 6526 } 6527 case Intrinsic::fptoui_sat: { 6528 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6529 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 6530 getValue(I.getArgOperand(0)), 6531 DAG.getValueType(VT.getScalarType()))); 6532 return; 6533 } 6534 case Intrinsic::set_rounding: 6535 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6536 {getRoot(), getValue(I.getArgOperand(0))}); 6537 setValue(&I, Res); 6538 DAG.setRoot(Res.getValue(0)); 6539 return; 6540 case Intrinsic::is_fpclass: { 6541 const DataLayout DLayout = DAG.getDataLayout(); 6542 EVT DestVT = TLI.getValueType(DLayout, I.getType()); 6543 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType()); 6544 FPClassTest Test = static_cast<FPClassTest>( 6545 cast<ConstantInt>(I.getArgOperand(1))->getZExtValue()); 6546 MachineFunction &MF = DAG.getMachineFunction(); 6547 const Function &F = MF.getFunction(); 6548 SDValue Op = getValue(I.getArgOperand(0)); 6549 SDNodeFlags Flags; 6550 Flags.setNoFPExcept( 6551 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP)); 6552 // If ISD::IS_FPCLASS should be expanded, do it right now, because the 6553 // expansion can use illegal types. Making expansion early allows 6554 // legalizing these types prior to selection. 6555 if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) { 6556 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG); 6557 setValue(&I, Result); 6558 return; 6559 } 6560 6561 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32); 6562 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags); 6563 setValue(&I, V); 6564 return; 6565 } 6566 case Intrinsic::pcmarker: { 6567 SDValue Tmp = getValue(I.getArgOperand(0)); 6568 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6569 return; 6570 } 6571 case Intrinsic::readcyclecounter: { 6572 SDValue Op = getRoot(); 6573 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6574 DAG.getVTList(MVT::i64, MVT::Other), Op); 6575 setValue(&I, Res); 6576 DAG.setRoot(Res.getValue(1)); 6577 return; 6578 } 6579 case Intrinsic::bitreverse: 6580 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6581 getValue(I.getArgOperand(0)).getValueType(), 6582 getValue(I.getArgOperand(0)))); 6583 return; 6584 case Intrinsic::bswap: 6585 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6586 getValue(I.getArgOperand(0)).getValueType(), 6587 getValue(I.getArgOperand(0)))); 6588 return; 6589 case Intrinsic::cttz: { 6590 SDValue Arg = getValue(I.getArgOperand(0)); 6591 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6592 EVT Ty = Arg.getValueType(); 6593 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6594 sdl, Ty, Arg)); 6595 return; 6596 } 6597 case Intrinsic::ctlz: { 6598 SDValue Arg = getValue(I.getArgOperand(0)); 6599 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6600 EVT Ty = Arg.getValueType(); 6601 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6602 sdl, Ty, Arg)); 6603 return; 6604 } 6605 case Intrinsic::ctpop: { 6606 SDValue Arg = getValue(I.getArgOperand(0)); 6607 EVT Ty = Arg.getValueType(); 6608 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6609 return; 6610 } 6611 case Intrinsic::fshl: 6612 case Intrinsic::fshr: { 6613 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6614 SDValue X = getValue(I.getArgOperand(0)); 6615 SDValue Y = getValue(I.getArgOperand(1)); 6616 SDValue Z = getValue(I.getArgOperand(2)); 6617 EVT VT = X.getValueType(); 6618 6619 if (X == Y) { 6620 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6621 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6622 } else { 6623 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6624 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6625 } 6626 return; 6627 } 6628 case Intrinsic::sadd_sat: { 6629 SDValue Op1 = getValue(I.getArgOperand(0)); 6630 SDValue Op2 = getValue(I.getArgOperand(1)); 6631 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6632 return; 6633 } 6634 case Intrinsic::uadd_sat: { 6635 SDValue Op1 = getValue(I.getArgOperand(0)); 6636 SDValue Op2 = getValue(I.getArgOperand(1)); 6637 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6638 return; 6639 } 6640 case Intrinsic::ssub_sat: { 6641 SDValue Op1 = getValue(I.getArgOperand(0)); 6642 SDValue Op2 = getValue(I.getArgOperand(1)); 6643 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6644 return; 6645 } 6646 case Intrinsic::usub_sat: { 6647 SDValue Op1 = getValue(I.getArgOperand(0)); 6648 SDValue Op2 = getValue(I.getArgOperand(1)); 6649 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6650 return; 6651 } 6652 case Intrinsic::sshl_sat: { 6653 SDValue Op1 = getValue(I.getArgOperand(0)); 6654 SDValue Op2 = getValue(I.getArgOperand(1)); 6655 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6656 return; 6657 } 6658 case Intrinsic::ushl_sat: { 6659 SDValue Op1 = getValue(I.getArgOperand(0)); 6660 SDValue Op2 = getValue(I.getArgOperand(1)); 6661 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6662 return; 6663 } 6664 case Intrinsic::smul_fix: 6665 case Intrinsic::umul_fix: 6666 case Intrinsic::smul_fix_sat: 6667 case Intrinsic::umul_fix_sat: { 6668 SDValue Op1 = getValue(I.getArgOperand(0)); 6669 SDValue Op2 = getValue(I.getArgOperand(1)); 6670 SDValue Op3 = getValue(I.getArgOperand(2)); 6671 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6672 Op1.getValueType(), Op1, Op2, Op3)); 6673 return; 6674 } 6675 case Intrinsic::sdiv_fix: 6676 case Intrinsic::udiv_fix: 6677 case Intrinsic::sdiv_fix_sat: 6678 case Intrinsic::udiv_fix_sat: { 6679 SDValue Op1 = getValue(I.getArgOperand(0)); 6680 SDValue Op2 = getValue(I.getArgOperand(1)); 6681 SDValue Op3 = getValue(I.getArgOperand(2)); 6682 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6683 Op1, Op2, Op3, DAG, TLI)); 6684 return; 6685 } 6686 case Intrinsic::smax: { 6687 SDValue Op1 = getValue(I.getArgOperand(0)); 6688 SDValue Op2 = getValue(I.getArgOperand(1)); 6689 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6690 return; 6691 } 6692 case Intrinsic::smin: { 6693 SDValue Op1 = getValue(I.getArgOperand(0)); 6694 SDValue Op2 = getValue(I.getArgOperand(1)); 6695 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6696 return; 6697 } 6698 case Intrinsic::umax: { 6699 SDValue Op1 = getValue(I.getArgOperand(0)); 6700 SDValue Op2 = getValue(I.getArgOperand(1)); 6701 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6702 return; 6703 } 6704 case Intrinsic::umin: { 6705 SDValue Op1 = getValue(I.getArgOperand(0)); 6706 SDValue Op2 = getValue(I.getArgOperand(1)); 6707 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6708 return; 6709 } 6710 case Intrinsic::abs: { 6711 // TODO: Preserve "int min is poison" arg in SDAG? 6712 SDValue Op1 = getValue(I.getArgOperand(0)); 6713 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6714 return; 6715 } 6716 case Intrinsic::stacksave: { 6717 SDValue Op = getRoot(); 6718 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6719 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6720 setValue(&I, Res); 6721 DAG.setRoot(Res.getValue(1)); 6722 return; 6723 } 6724 case Intrinsic::stackrestore: 6725 Res = getValue(I.getArgOperand(0)); 6726 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6727 return; 6728 case Intrinsic::get_dynamic_area_offset: { 6729 SDValue Op = getRoot(); 6730 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6731 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6732 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6733 // target. 6734 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 6735 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6736 " intrinsic!"); 6737 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6738 Op); 6739 DAG.setRoot(Op); 6740 setValue(&I, Res); 6741 return; 6742 } 6743 case Intrinsic::stackguard: { 6744 MachineFunction &MF = DAG.getMachineFunction(); 6745 const Module &M = *MF.getFunction().getParent(); 6746 SDValue Chain = getRoot(); 6747 if (TLI.useLoadStackGuardNode()) { 6748 Res = getLoadStackGuard(DAG, sdl, Chain); 6749 } else { 6750 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6751 const Value *Global = TLI.getSDagStackGuard(M); 6752 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType()); 6753 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6754 MachinePointerInfo(Global, 0), Align, 6755 MachineMemOperand::MOVolatile); 6756 } 6757 if (TLI.useStackGuardXorFP()) 6758 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6759 DAG.setRoot(Chain); 6760 setValue(&I, Res); 6761 return; 6762 } 6763 case Intrinsic::stackprotector: { 6764 // Emit code into the DAG to store the stack guard onto the stack. 6765 MachineFunction &MF = DAG.getMachineFunction(); 6766 MachineFrameInfo &MFI = MF.getFrameInfo(); 6767 SDValue Src, Chain = getRoot(); 6768 6769 if (TLI.useLoadStackGuardNode()) 6770 Src = getLoadStackGuard(DAG, sdl, Chain); 6771 else 6772 Src = getValue(I.getArgOperand(0)); // The guard's value. 6773 6774 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6775 6776 int FI = FuncInfo.StaticAllocaMap[Slot]; 6777 MFI.setStackProtectorIndex(FI); 6778 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6779 6780 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6781 6782 // Store the stack protector onto the stack. 6783 Res = DAG.getStore( 6784 Chain, sdl, Src, FIN, 6785 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 6786 MaybeAlign(), MachineMemOperand::MOVolatile); 6787 setValue(&I, Res); 6788 DAG.setRoot(Res); 6789 return; 6790 } 6791 case Intrinsic::objectsize: 6792 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6793 6794 case Intrinsic::is_constant: 6795 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6796 6797 case Intrinsic::annotation: 6798 case Intrinsic::ptr_annotation: 6799 case Intrinsic::launder_invariant_group: 6800 case Intrinsic::strip_invariant_group: 6801 // Drop the intrinsic, but forward the value 6802 setValue(&I, getValue(I.getOperand(0))); 6803 return; 6804 6805 case Intrinsic::assume: 6806 case Intrinsic::experimental_noalias_scope_decl: 6807 case Intrinsic::var_annotation: 6808 case Intrinsic::sideeffect: 6809 // Discard annotate attributes, noalias scope declarations, assumptions, and 6810 // artificial side-effects. 6811 return; 6812 6813 case Intrinsic::codeview_annotation: { 6814 // Emit a label associated with this metadata. 6815 MachineFunction &MF = DAG.getMachineFunction(); 6816 MCSymbol *Label = 6817 MF.getMMI().getContext().createTempSymbol("annotation", true); 6818 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6819 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6820 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6821 DAG.setRoot(Res); 6822 return; 6823 } 6824 6825 case Intrinsic::init_trampoline: { 6826 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6827 6828 SDValue Ops[6]; 6829 Ops[0] = getRoot(); 6830 Ops[1] = getValue(I.getArgOperand(0)); 6831 Ops[2] = getValue(I.getArgOperand(1)); 6832 Ops[3] = getValue(I.getArgOperand(2)); 6833 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6834 Ops[5] = DAG.getSrcValue(F); 6835 6836 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6837 6838 DAG.setRoot(Res); 6839 return; 6840 } 6841 case Intrinsic::adjust_trampoline: 6842 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6843 TLI.getPointerTy(DAG.getDataLayout()), 6844 getValue(I.getArgOperand(0)))); 6845 return; 6846 case Intrinsic::gcroot: { 6847 assert(DAG.getMachineFunction().getFunction().hasGC() && 6848 "only valid in functions with gc specified, enforced by Verifier"); 6849 assert(GFI && "implied by previous"); 6850 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6851 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6852 6853 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6854 GFI->addStackRoot(FI->getIndex(), TypeMap); 6855 return; 6856 } 6857 case Intrinsic::gcread: 6858 case Intrinsic::gcwrite: 6859 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6860 case Intrinsic::get_rounding: 6861 Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot()); 6862 setValue(&I, Res); 6863 DAG.setRoot(Res.getValue(1)); 6864 return; 6865 6866 case Intrinsic::expect: 6867 // Just replace __builtin_expect(exp, c) with EXP. 6868 setValue(&I, getValue(I.getArgOperand(0))); 6869 return; 6870 6871 case Intrinsic::ubsantrap: 6872 case Intrinsic::debugtrap: 6873 case Intrinsic::trap: { 6874 StringRef TrapFuncName = 6875 I.getAttributes().getFnAttr("trap-func-name").getValueAsString(); 6876 if (TrapFuncName.empty()) { 6877 switch (Intrinsic) { 6878 case Intrinsic::trap: 6879 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 6880 break; 6881 case Intrinsic::debugtrap: 6882 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 6883 break; 6884 case Intrinsic::ubsantrap: 6885 DAG.setRoot(DAG.getNode( 6886 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 6887 DAG.getTargetConstant( 6888 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 6889 MVT::i32))); 6890 break; 6891 default: llvm_unreachable("unknown trap intrinsic"); 6892 } 6893 return; 6894 } 6895 TargetLowering::ArgListTy Args; 6896 if (Intrinsic == Intrinsic::ubsantrap) { 6897 Args.push_back(TargetLoweringBase::ArgListEntry()); 6898 Args[0].Val = I.getArgOperand(0); 6899 Args[0].Node = getValue(Args[0].Val); 6900 Args[0].Ty = Args[0].Val->getType(); 6901 } 6902 6903 TargetLowering::CallLoweringInfo CLI(DAG); 6904 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6905 CallingConv::C, I.getType(), 6906 DAG.getExternalSymbol(TrapFuncName.data(), 6907 TLI.getPointerTy(DAG.getDataLayout())), 6908 std::move(Args)); 6909 6910 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6911 DAG.setRoot(Result.second); 6912 return; 6913 } 6914 6915 case Intrinsic::uadd_with_overflow: 6916 case Intrinsic::sadd_with_overflow: 6917 case Intrinsic::usub_with_overflow: 6918 case Intrinsic::ssub_with_overflow: 6919 case Intrinsic::umul_with_overflow: 6920 case Intrinsic::smul_with_overflow: { 6921 ISD::NodeType Op; 6922 switch (Intrinsic) { 6923 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6924 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6925 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6926 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6927 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6928 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6929 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6930 } 6931 SDValue Op1 = getValue(I.getArgOperand(0)); 6932 SDValue Op2 = getValue(I.getArgOperand(1)); 6933 6934 EVT ResultVT = Op1.getValueType(); 6935 EVT OverflowVT = MVT::i1; 6936 if (ResultVT.isVector()) 6937 OverflowVT = EVT::getVectorVT( 6938 *Context, OverflowVT, ResultVT.getVectorElementCount()); 6939 6940 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6941 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6942 return; 6943 } 6944 case Intrinsic::prefetch: { 6945 SDValue Ops[5]; 6946 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6947 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6948 Ops[0] = DAG.getRoot(); 6949 Ops[1] = getValue(I.getArgOperand(0)); 6950 Ops[2] = getValue(I.getArgOperand(1)); 6951 Ops[3] = getValue(I.getArgOperand(2)); 6952 Ops[4] = getValue(I.getArgOperand(3)); 6953 SDValue Result = DAG.getMemIntrinsicNode( 6954 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 6955 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 6956 /* align */ std::nullopt, Flags); 6957 6958 // Chain the prefetch in parallell with any pending loads, to stay out of 6959 // the way of later optimizations. 6960 PendingLoads.push_back(Result); 6961 Result = getRoot(); 6962 DAG.setRoot(Result); 6963 return; 6964 } 6965 case Intrinsic::lifetime_start: 6966 case Intrinsic::lifetime_end: { 6967 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6968 // Stack coloring is not enabled in O0, discard region information. 6969 if (TM.getOptLevel() == CodeGenOpt::None) 6970 return; 6971 6972 const int64_t ObjectSize = 6973 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6974 Value *const ObjectPtr = I.getArgOperand(1); 6975 SmallVector<const Value *, 4> Allocas; 6976 getUnderlyingObjects(ObjectPtr, Allocas); 6977 6978 for (const Value *Alloca : Allocas) { 6979 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 6980 6981 // Could not find an Alloca. 6982 if (!LifetimeObject) 6983 continue; 6984 6985 // First check that the Alloca is static, otherwise it won't have a 6986 // valid frame index. 6987 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6988 if (SI == FuncInfo.StaticAllocaMap.end()) 6989 return; 6990 6991 const int FrameIndex = SI->second; 6992 int64_t Offset; 6993 if (GetPointerBaseWithConstantOffset( 6994 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6995 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6996 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6997 Offset); 6998 DAG.setRoot(Res); 6999 } 7000 return; 7001 } 7002 case Intrinsic::pseudoprobe: { 7003 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 7004 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 7005 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 7006 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 7007 DAG.setRoot(Res); 7008 return; 7009 } 7010 case Intrinsic::invariant_start: 7011 // Discard region information. 7012 setValue(&I, 7013 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType()))); 7014 return; 7015 case Intrinsic::invariant_end: 7016 // Discard region information. 7017 return; 7018 case Intrinsic::clear_cache: 7019 /// FunctionName may be null. 7020 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 7021 lowerCallToExternalSymbol(I, FunctionName); 7022 return; 7023 case Intrinsic::donothing: 7024 case Intrinsic::seh_try_begin: 7025 case Intrinsic::seh_scope_begin: 7026 case Intrinsic::seh_try_end: 7027 case Intrinsic::seh_scope_end: 7028 // ignore 7029 return; 7030 case Intrinsic::experimental_stackmap: 7031 visitStackmap(I); 7032 return; 7033 case Intrinsic::experimental_patchpoint_void: 7034 case Intrinsic::experimental_patchpoint_i64: 7035 visitPatchpoint(I); 7036 return; 7037 case Intrinsic::experimental_gc_statepoint: 7038 LowerStatepoint(cast<GCStatepointInst>(I)); 7039 return; 7040 case Intrinsic::experimental_gc_result: 7041 visitGCResult(cast<GCResultInst>(I)); 7042 return; 7043 case Intrinsic::experimental_gc_relocate: 7044 visitGCRelocate(cast<GCRelocateInst>(I)); 7045 return; 7046 case Intrinsic::instrprof_cover: 7047 llvm_unreachable("instrprof failed to lower a cover"); 7048 case Intrinsic::instrprof_increment: 7049 llvm_unreachable("instrprof failed to lower an increment"); 7050 case Intrinsic::instrprof_timestamp: 7051 llvm_unreachable("instrprof failed to lower a timestamp"); 7052 case Intrinsic::instrprof_value_profile: 7053 llvm_unreachable("instrprof failed to lower a value profiling call"); 7054 case Intrinsic::localescape: { 7055 MachineFunction &MF = DAG.getMachineFunction(); 7056 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 7057 7058 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 7059 // is the same on all targets. 7060 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) { 7061 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 7062 if (isa<ConstantPointerNull>(Arg)) 7063 continue; // Skip null pointers. They represent a hole in index space. 7064 AllocaInst *Slot = cast<AllocaInst>(Arg); 7065 assert(FuncInfo.StaticAllocaMap.count(Slot) && 7066 "can only escape static allocas"); 7067 int FI = FuncInfo.StaticAllocaMap[Slot]; 7068 MCSymbol *FrameAllocSym = 7069 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7070 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 7071 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 7072 TII->get(TargetOpcode::LOCAL_ESCAPE)) 7073 .addSym(FrameAllocSym) 7074 .addFrameIndex(FI); 7075 } 7076 7077 return; 7078 } 7079 7080 case Intrinsic::localrecover: { 7081 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 7082 MachineFunction &MF = DAG.getMachineFunction(); 7083 7084 // Get the symbol that defines the frame offset. 7085 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 7086 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 7087 unsigned IdxVal = 7088 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 7089 MCSymbol *FrameAllocSym = 7090 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7091 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 7092 7093 Value *FP = I.getArgOperand(1); 7094 SDValue FPVal = getValue(FP); 7095 EVT PtrVT = FPVal.getValueType(); 7096 7097 // Create a MCSymbol for the label to avoid any target lowering 7098 // that would make this PC relative. 7099 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 7100 SDValue OffsetVal = 7101 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 7102 7103 // Add the offset to the FP. 7104 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 7105 setValue(&I, Add); 7106 7107 return; 7108 } 7109 7110 case Intrinsic::eh_exceptionpointer: 7111 case Intrinsic::eh_exceptioncode: { 7112 // Get the exception pointer vreg, copy from it, and resize it to fit. 7113 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 7114 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 7115 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 7116 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 7117 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT); 7118 if (Intrinsic == Intrinsic::eh_exceptioncode) 7119 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32); 7120 setValue(&I, N); 7121 return; 7122 } 7123 case Intrinsic::xray_customevent: { 7124 // Here we want to make sure that the intrinsic behaves as if it has a 7125 // specific calling convention, and only for x86_64. 7126 // FIXME: Support other platforms later. 7127 const auto &Triple = DAG.getTarget().getTargetTriple(); 7128 if (Triple.getArch() != Triple::x86_64) 7129 return; 7130 7131 SmallVector<SDValue, 8> Ops; 7132 7133 // We want to say that we always want the arguments in registers. 7134 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 7135 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 7136 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7137 SDValue Chain = getRoot(); 7138 Ops.push_back(LogEntryVal); 7139 Ops.push_back(StrSizeVal); 7140 Ops.push_back(Chain); 7141 7142 // We need to enforce the calling convention for the callsite, so that 7143 // argument ordering is enforced correctly, and that register allocation can 7144 // see that some registers may be assumed clobbered and have to preserve 7145 // them across calls to the intrinsic. 7146 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 7147 sdl, NodeTys, Ops); 7148 SDValue patchableNode = SDValue(MN, 0); 7149 DAG.setRoot(patchableNode); 7150 setValue(&I, patchableNode); 7151 return; 7152 } 7153 case Intrinsic::xray_typedevent: { 7154 // Here we want to make sure that the intrinsic behaves as if it has a 7155 // specific calling convention, and only for x86_64. 7156 // FIXME: Support other platforms later. 7157 const auto &Triple = DAG.getTarget().getTargetTriple(); 7158 if (Triple.getArch() != Triple::x86_64) 7159 return; 7160 7161 SmallVector<SDValue, 8> Ops; 7162 7163 // We want to say that we always want the arguments in registers. 7164 // It's unclear to me how manipulating the selection DAG here forces callers 7165 // to provide arguments in registers instead of on the stack. 7166 SDValue LogTypeId = getValue(I.getArgOperand(0)); 7167 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 7168 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 7169 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7170 SDValue Chain = getRoot(); 7171 Ops.push_back(LogTypeId); 7172 Ops.push_back(LogEntryVal); 7173 Ops.push_back(StrSizeVal); 7174 Ops.push_back(Chain); 7175 7176 // We need to enforce the calling convention for the callsite, so that 7177 // argument ordering is enforced correctly, and that register allocation can 7178 // see that some registers may be assumed clobbered and have to preserve 7179 // them across calls to the intrinsic. 7180 MachineSDNode *MN = DAG.getMachineNode( 7181 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops); 7182 SDValue patchableNode = SDValue(MN, 0); 7183 DAG.setRoot(patchableNode); 7184 setValue(&I, patchableNode); 7185 return; 7186 } 7187 case Intrinsic::experimental_deoptimize: 7188 LowerDeoptimizeCall(&I); 7189 return; 7190 case Intrinsic::experimental_stepvector: 7191 visitStepVector(I); 7192 return; 7193 case Intrinsic::vector_reduce_fadd: 7194 case Intrinsic::vector_reduce_fmul: 7195 case Intrinsic::vector_reduce_add: 7196 case Intrinsic::vector_reduce_mul: 7197 case Intrinsic::vector_reduce_and: 7198 case Intrinsic::vector_reduce_or: 7199 case Intrinsic::vector_reduce_xor: 7200 case Intrinsic::vector_reduce_smax: 7201 case Intrinsic::vector_reduce_smin: 7202 case Intrinsic::vector_reduce_umax: 7203 case Intrinsic::vector_reduce_umin: 7204 case Intrinsic::vector_reduce_fmax: 7205 case Intrinsic::vector_reduce_fmin: 7206 visitVectorReduce(I, Intrinsic); 7207 return; 7208 7209 case Intrinsic::icall_branch_funnel: { 7210 SmallVector<SDValue, 16> Ops; 7211 Ops.push_back(getValue(I.getArgOperand(0))); 7212 7213 int64_t Offset; 7214 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7215 I.getArgOperand(1), Offset, DAG.getDataLayout())); 7216 if (!Base) 7217 report_fatal_error( 7218 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7219 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0)); 7220 7221 struct BranchFunnelTarget { 7222 int64_t Offset; 7223 SDValue Target; 7224 }; 7225 SmallVector<BranchFunnelTarget, 8> Targets; 7226 7227 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) { 7228 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7229 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7230 if (ElemBase != Base) 7231 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7232 "to the same GlobalValue"); 7233 7234 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7235 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7236 if (!GA) 7237 report_fatal_error( 7238 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7239 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7240 GA->getGlobal(), sdl, Val.getValueType(), 7241 GA->getOffset())}); 7242 } 7243 llvm::sort(Targets, 7244 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7245 return T1.Offset < T2.Offset; 7246 }); 7247 7248 for (auto &T : Targets) { 7249 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32)); 7250 Ops.push_back(T.Target); 7251 } 7252 7253 Ops.push_back(DAG.getRoot()); // Chain 7254 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl, 7255 MVT::Other, Ops), 7256 0); 7257 DAG.setRoot(N); 7258 setValue(&I, N); 7259 HasTailCall = true; 7260 return; 7261 } 7262 7263 case Intrinsic::wasm_landingpad_index: 7264 // Information this intrinsic contained has been transferred to 7265 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7266 // delete it now. 7267 return; 7268 7269 case Intrinsic::aarch64_settag: 7270 case Intrinsic::aarch64_settag_zero: { 7271 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7272 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7273 SDValue Val = TSI.EmitTargetCodeForSetTag( 7274 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)), 7275 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7276 ZeroMemory); 7277 DAG.setRoot(Val); 7278 setValue(&I, Val); 7279 return; 7280 } 7281 case Intrinsic::ptrmask: { 7282 SDValue Ptr = getValue(I.getOperand(0)); 7283 SDValue Const = getValue(I.getOperand(1)); 7284 7285 EVT PtrVT = Ptr.getValueType(); 7286 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, 7287 DAG.getZExtOrTrunc(Const, sdl, PtrVT))); 7288 return; 7289 } 7290 case Intrinsic::threadlocal_address: { 7291 setValue(&I, getValue(I.getOperand(0))); 7292 return; 7293 } 7294 case Intrinsic::get_active_lane_mask: { 7295 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7296 SDValue Index = getValue(I.getOperand(0)); 7297 EVT ElementVT = Index.getValueType(); 7298 7299 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) { 7300 visitTargetIntrinsic(I, Intrinsic); 7301 return; 7302 } 7303 7304 SDValue TripCount = getValue(I.getOperand(1)); 7305 auto VecTy = CCVT.changeVectorElementType(ElementVT); 7306 7307 SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index); 7308 SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount); 7309 SDValue VectorStep = DAG.getStepVector(sdl, VecTy); 7310 SDValue VectorInduction = DAG.getNode( 7311 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep); 7312 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction, 7313 VectorTripCount, ISD::CondCode::SETULT); 7314 setValue(&I, SetCC); 7315 return; 7316 } 7317 case Intrinsic::vector_insert: { 7318 SDValue Vec = getValue(I.getOperand(0)); 7319 SDValue SubVec = getValue(I.getOperand(1)); 7320 SDValue Index = getValue(I.getOperand(2)); 7321 7322 // The intrinsic's index type is i64, but the SDNode requires an index type 7323 // suitable for the target. Convert the index as required. 7324 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7325 if (Index.getValueType() != VectorIdxTy) 7326 Index = DAG.getVectorIdxConstant( 7327 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7328 7329 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7330 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec, 7331 Index)); 7332 return; 7333 } 7334 case Intrinsic::vector_extract: { 7335 SDValue Vec = getValue(I.getOperand(0)); 7336 SDValue Index = getValue(I.getOperand(1)); 7337 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7338 7339 // The intrinsic's index type is i64, but the SDNode requires an index type 7340 // suitable for the target. Convert the index as required. 7341 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7342 if (Index.getValueType() != VectorIdxTy) 7343 Index = DAG.getVectorIdxConstant( 7344 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7345 7346 setValue(&I, 7347 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index)); 7348 return; 7349 } 7350 case Intrinsic::experimental_vector_reverse: 7351 visitVectorReverse(I); 7352 return; 7353 case Intrinsic::experimental_vector_splice: 7354 visitVectorSplice(I); 7355 return; 7356 case Intrinsic::callbr_landingpad: 7357 visitCallBrLandingPad(I); 7358 return; 7359 case Intrinsic::experimental_vector_interleave2: 7360 visitVectorInterleave(I); 7361 return; 7362 case Intrinsic::experimental_vector_deinterleave2: 7363 visitVectorDeinterleave(I); 7364 return; 7365 } 7366 } 7367 7368 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7369 const ConstrainedFPIntrinsic &FPI) { 7370 SDLoc sdl = getCurSDLoc(); 7371 7372 // We do not need to serialize constrained FP intrinsics against 7373 // each other or against (nonvolatile) loads, so they can be 7374 // chained like loads. 7375 SDValue Chain = DAG.getRoot(); 7376 SmallVector<SDValue, 4> Opers; 7377 Opers.push_back(Chain); 7378 if (FPI.isUnaryOp()) { 7379 Opers.push_back(getValue(FPI.getArgOperand(0))); 7380 } else if (FPI.isTernaryOp()) { 7381 Opers.push_back(getValue(FPI.getArgOperand(0))); 7382 Opers.push_back(getValue(FPI.getArgOperand(1))); 7383 Opers.push_back(getValue(FPI.getArgOperand(2))); 7384 } else { 7385 Opers.push_back(getValue(FPI.getArgOperand(0))); 7386 Opers.push_back(getValue(FPI.getArgOperand(1))); 7387 } 7388 7389 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7390 assert(Result.getNode()->getNumValues() == 2); 7391 7392 // Push node to the appropriate list so that future instructions can be 7393 // chained up correctly. 7394 SDValue OutChain = Result.getValue(1); 7395 switch (EB) { 7396 case fp::ExceptionBehavior::ebIgnore: 7397 // The only reason why ebIgnore nodes still need to be chained is that 7398 // they might depend on the current rounding mode, and therefore must 7399 // not be moved across instruction that may change that mode. 7400 [[fallthrough]]; 7401 case fp::ExceptionBehavior::ebMayTrap: 7402 // These must not be moved across calls or instructions that may change 7403 // floating-point exception masks. 7404 PendingConstrainedFP.push_back(OutChain); 7405 break; 7406 case fp::ExceptionBehavior::ebStrict: 7407 // These must not be moved across calls or instructions that may change 7408 // floating-point exception masks or read floating-point exception flags. 7409 // In addition, they cannot be optimized out even if unused. 7410 PendingConstrainedFPStrict.push_back(OutChain); 7411 break; 7412 } 7413 }; 7414 7415 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7416 EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType()); 7417 SDVTList VTs = DAG.getVTList(VT, MVT::Other); 7418 fp::ExceptionBehavior EB = *FPI.getExceptionBehavior(); 7419 7420 SDNodeFlags Flags; 7421 if (EB == fp::ExceptionBehavior::ebIgnore) 7422 Flags.setNoFPExcept(true); 7423 7424 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7425 Flags.copyFMF(*FPOp); 7426 7427 unsigned Opcode; 7428 switch (FPI.getIntrinsicID()) { 7429 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7430 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7431 case Intrinsic::INTRINSIC: \ 7432 Opcode = ISD::STRICT_##DAGN; \ 7433 break; 7434 #include "llvm/IR/ConstrainedOps.def" 7435 case Intrinsic::experimental_constrained_fmuladd: { 7436 Opcode = ISD::STRICT_FMA; 7437 // Break fmuladd into fmul and fadd. 7438 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7439 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 7440 Opers.pop_back(); 7441 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7442 pushOutChain(Mul, EB); 7443 Opcode = ISD::STRICT_FADD; 7444 Opers.clear(); 7445 Opers.push_back(Mul.getValue(1)); 7446 Opers.push_back(Mul.getValue(0)); 7447 Opers.push_back(getValue(FPI.getArgOperand(2))); 7448 } 7449 break; 7450 } 7451 } 7452 7453 // A few strict DAG nodes carry additional operands that are not 7454 // set up by the default code above. 7455 switch (Opcode) { 7456 default: break; 7457 case ISD::STRICT_FP_ROUND: 7458 Opers.push_back( 7459 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7460 break; 7461 case ISD::STRICT_FSETCC: 7462 case ISD::STRICT_FSETCCS: { 7463 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7464 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 7465 if (TM.Options.NoNaNsFPMath) 7466 Condition = getFCmpCodeWithoutNaN(Condition); 7467 Opers.push_back(DAG.getCondCode(Condition)); 7468 break; 7469 } 7470 } 7471 7472 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7473 pushOutChain(Result, EB); 7474 7475 SDValue FPResult = Result.getValue(0); 7476 setValue(&FPI, FPResult); 7477 } 7478 7479 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 7480 std::optional<unsigned> ResOPC; 7481 switch (VPIntrin.getIntrinsicID()) { 7482 case Intrinsic::vp_ctlz: { 7483 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 7484 ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ; 7485 break; 7486 } 7487 case Intrinsic::vp_cttz: { 7488 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 7489 ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ; 7490 break; 7491 } 7492 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \ 7493 case Intrinsic::VPID: \ 7494 ResOPC = ISD::VPSD; \ 7495 break; 7496 #include "llvm/IR/VPIntrinsics.def" 7497 } 7498 7499 if (!ResOPC) 7500 llvm_unreachable( 7501 "Inconsistency: no SDNode available for this VPIntrinsic!"); 7502 7503 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD || 7504 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) { 7505 if (VPIntrin.getFastMathFlags().allowReassoc()) 7506 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD 7507 : ISD::VP_REDUCE_FMUL; 7508 } 7509 7510 return *ResOPC; 7511 } 7512 7513 void SelectionDAGBuilder::visitVPLoad( 7514 const VPIntrinsic &VPIntrin, EVT VT, 7515 const SmallVectorImpl<SDValue> &OpValues) { 7516 SDLoc DL = getCurSDLoc(); 7517 Value *PtrOperand = VPIntrin.getArgOperand(0); 7518 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7519 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7520 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7521 SDValue LD; 7522 // Do not serialize variable-length loads of constant memory with 7523 // anything. 7524 if (!Alignment) 7525 Alignment = DAG.getEVTAlign(VT); 7526 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7527 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7528 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7529 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7530 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7531 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7532 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2], 7533 MMO, false /*IsExpanding */); 7534 if (AddToChain) 7535 PendingLoads.push_back(LD.getValue(1)); 7536 setValue(&VPIntrin, LD); 7537 } 7538 7539 void SelectionDAGBuilder::visitVPGather( 7540 const VPIntrinsic &VPIntrin, EVT VT, 7541 const SmallVectorImpl<SDValue> &OpValues) { 7542 SDLoc DL = getCurSDLoc(); 7543 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7544 Value *PtrOperand = VPIntrin.getArgOperand(0); 7545 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7546 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7547 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7548 SDValue LD; 7549 if (!Alignment) 7550 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7551 unsigned AS = 7552 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7553 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7554 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 7555 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7556 SDValue Base, Index, Scale; 7557 ISD::MemIndexType IndexType; 7558 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7559 this, VPIntrin.getParent(), 7560 VT.getScalarStoreSize()); 7561 if (!UniformBase) { 7562 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7563 Index = getValue(PtrOperand); 7564 IndexType = ISD::SIGNED_SCALED; 7565 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7566 } 7567 EVT IdxVT = Index.getValueType(); 7568 EVT EltTy = IdxVT.getVectorElementType(); 7569 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7570 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7571 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7572 } 7573 LD = DAG.getGatherVP( 7574 DAG.getVTList(VT, MVT::Other), VT, DL, 7575 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO, 7576 IndexType); 7577 PendingLoads.push_back(LD.getValue(1)); 7578 setValue(&VPIntrin, LD); 7579 } 7580 7581 void SelectionDAGBuilder::visitVPStore( 7582 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 7583 SDLoc DL = getCurSDLoc(); 7584 Value *PtrOperand = VPIntrin.getArgOperand(1); 7585 EVT VT = OpValues[0].getValueType(); 7586 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7587 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7588 SDValue ST; 7589 if (!Alignment) 7590 Alignment = DAG.getEVTAlign(VT); 7591 SDValue Ptr = OpValues[1]; 7592 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 7593 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7594 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7595 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7596 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset, 7597 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED, 7598 /* IsTruncating */ false, /*IsCompressing*/ false); 7599 DAG.setRoot(ST); 7600 setValue(&VPIntrin, ST); 7601 } 7602 7603 void SelectionDAGBuilder::visitVPScatter( 7604 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 7605 SDLoc DL = getCurSDLoc(); 7606 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7607 Value *PtrOperand = VPIntrin.getArgOperand(1); 7608 EVT VT = OpValues[0].getValueType(); 7609 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7610 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7611 SDValue ST; 7612 if (!Alignment) 7613 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7614 unsigned AS = 7615 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7616 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7617 MachinePointerInfo(AS), MachineMemOperand::MOStore, 7618 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7619 SDValue Base, Index, Scale; 7620 ISD::MemIndexType IndexType; 7621 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7622 this, VPIntrin.getParent(), 7623 VT.getScalarStoreSize()); 7624 if (!UniformBase) { 7625 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7626 Index = getValue(PtrOperand); 7627 IndexType = ISD::SIGNED_SCALED; 7628 Scale = 7629 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7630 } 7631 EVT IdxVT = Index.getValueType(); 7632 EVT EltTy = IdxVT.getVectorElementType(); 7633 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7634 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7635 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7636 } 7637 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL, 7638 {getMemoryRoot(), OpValues[0], Base, Index, Scale, 7639 OpValues[2], OpValues[3]}, 7640 MMO, IndexType); 7641 DAG.setRoot(ST); 7642 setValue(&VPIntrin, ST); 7643 } 7644 7645 void SelectionDAGBuilder::visitVPStridedLoad( 7646 const VPIntrinsic &VPIntrin, EVT VT, 7647 const SmallVectorImpl<SDValue> &OpValues) { 7648 SDLoc DL = getCurSDLoc(); 7649 Value *PtrOperand = VPIntrin.getArgOperand(0); 7650 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7651 if (!Alignment) 7652 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7653 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7654 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 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 7662 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], 7663 OpValues[2], OpValues[3], MMO, 7664 false /*IsExpanding*/); 7665 7666 if (AddToChain) 7667 PendingLoads.push_back(LD.getValue(1)); 7668 setValue(&VPIntrin, LD); 7669 } 7670 7671 void SelectionDAGBuilder::visitVPStridedStore( 7672 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 7673 SDLoc DL = getCurSDLoc(); 7674 Value *PtrOperand = VPIntrin.getArgOperand(1); 7675 EVT VT = OpValues[0].getValueType(); 7676 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7677 if (!Alignment) 7678 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7679 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7680 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7681 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7682 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7683 7684 SDValue ST = DAG.getStridedStoreVP( 7685 getMemoryRoot(), DL, OpValues[0], OpValues[1], 7686 DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3], 7687 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false, 7688 /*IsCompressing*/ false); 7689 7690 DAG.setRoot(ST); 7691 setValue(&VPIntrin, ST); 7692 } 7693 7694 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) { 7695 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7696 SDLoc DL = getCurSDLoc(); 7697 7698 ISD::CondCode Condition; 7699 CmpInst::Predicate CondCode = VPIntrin.getPredicate(); 7700 bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy(); 7701 if (IsFP) { 7702 // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan) 7703 // flags, but calls that don't return floating-point types can't be 7704 // FPMathOperators, like vp.fcmp. This affects constrained fcmp too. 7705 Condition = getFCmpCondCode(CondCode); 7706 if (TM.Options.NoNaNsFPMath) 7707 Condition = getFCmpCodeWithoutNaN(Condition); 7708 } else { 7709 Condition = getICmpCondCode(CondCode); 7710 } 7711 7712 SDValue Op1 = getValue(VPIntrin.getOperand(0)); 7713 SDValue Op2 = getValue(VPIntrin.getOperand(1)); 7714 // #2 is the condition code 7715 SDValue MaskOp = getValue(VPIntrin.getOperand(3)); 7716 SDValue EVL = getValue(VPIntrin.getOperand(4)); 7717 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7718 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7719 "Unexpected target EVL type"); 7720 EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL); 7721 7722 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7723 VPIntrin.getType()); 7724 setValue(&VPIntrin, 7725 DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL)); 7726 } 7727 7728 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 7729 const VPIntrinsic &VPIntrin) { 7730 SDLoc DL = getCurSDLoc(); 7731 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 7732 7733 auto IID = VPIntrin.getIntrinsicID(); 7734 7735 if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin)) 7736 return visitVPCmp(*CmpI); 7737 7738 SmallVector<EVT, 4> ValueVTs; 7739 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7740 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 7741 SDVTList VTs = DAG.getVTList(ValueVTs); 7742 7743 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID); 7744 7745 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7746 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7747 "Unexpected target EVL type"); 7748 7749 // Request operands. 7750 SmallVector<SDValue, 7> OpValues; 7751 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) { 7752 auto Op = getValue(VPIntrin.getArgOperand(I)); 7753 if (I == EVLParamPos) 7754 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op); 7755 OpValues.push_back(Op); 7756 } 7757 7758 switch (Opcode) { 7759 default: { 7760 SDNodeFlags SDFlags; 7761 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 7762 SDFlags.copyFMF(*FPMO); 7763 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags); 7764 setValue(&VPIntrin, Result); 7765 break; 7766 } 7767 case ISD::VP_LOAD: 7768 visitVPLoad(VPIntrin, ValueVTs[0], OpValues); 7769 break; 7770 case ISD::VP_GATHER: 7771 visitVPGather(VPIntrin, ValueVTs[0], OpValues); 7772 break; 7773 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: 7774 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues); 7775 break; 7776 case ISD::VP_STORE: 7777 visitVPStore(VPIntrin, OpValues); 7778 break; 7779 case ISD::VP_SCATTER: 7780 visitVPScatter(VPIntrin, OpValues); 7781 break; 7782 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: 7783 visitVPStridedStore(VPIntrin, OpValues); 7784 break; 7785 case ISD::VP_FMULADD: { 7786 assert(OpValues.size() == 5 && "Unexpected number of operands"); 7787 SDNodeFlags SDFlags; 7788 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 7789 SDFlags.copyFMF(*FPMO); 7790 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 7791 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) { 7792 setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags)); 7793 } else { 7794 SDValue Mul = DAG.getNode( 7795 ISD::VP_FMUL, DL, VTs, 7796 {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags); 7797 SDValue Add = 7798 DAG.getNode(ISD::VP_FADD, DL, VTs, 7799 {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags); 7800 setValue(&VPIntrin, Add); 7801 } 7802 break; 7803 } 7804 case ISD::VP_INTTOPTR: { 7805 SDValue N = OpValues[0]; 7806 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType()); 7807 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType()); 7808 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 7809 OpValues[2]); 7810 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 7811 OpValues[2]); 7812 setValue(&VPIntrin, N); 7813 break; 7814 } 7815 case ISD::VP_PTRTOINT: { 7816 SDValue N = OpValues[0]; 7817 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7818 VPIntrin.getType()); 7819 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), 7820 VPIntrin.getOperand(0)->getType()); 7821 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 7822 OpValues[2]); 7823 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 7824 OpValues[2]); 7825 setValue(&VPIntrin, N); 7826 break; 7827 } 7828 case ISD::VP_ABS: 7829 case ISD::VP_CTLZ: 7830 case ISD::VP_CTLZ_ZERO_UNDEF: 7831 case ISD::VP_CTTZ: 7832 case ISD::VP_CTTZ_ZERO_UNDEF: { 7833 SDValue Result = 7834 DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]}); 7835 setValue(&VPIntrin, Result); 7836 break; 7837 } 7838 } 7839 } 7840 7841 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 7842 const BasicBlock *EHPadBB, 7843 MCSymbol *&BeginLabel) { 7844 MachineFunction &MF = DAG.getMachineFunction(); 7845 MachineModuleInfo &MMI = MF.getMMI(); 7846 7847 // Insert a label before the invoke call to mark the try range. This can be 7848 // used to detect deletion of the invoke via the MachineModuleInfo. 7849 BeginLabel = MMI.getContext().createTempSymbol(); 7850 7851 // For SjLj, keep track of which landing pads go with which invokes 7852 // so as to maintain the ordering of pads in the LSDA. 7853 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7854 if (CallSiteIndex) { 7855 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7856 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7857 7858 // Now that the call site is handled, stop tracking it. 7859 MMI.setCurrentCallSite(0); 7860 } 7861 7862 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 7863 } 7864 7865 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 7866 const BasicBlock *EHPadBB, 7867 MCSymbol *BeginLabel) { 7868 assert(BeginLabel && "BeginLabel should've been set"); 7869 7870 MachineFunction &MF = DAG.getMachineFunction(); 7871 MachineModuleInfo &MMI = MF.getMMI(); 7872 7873 // Insert a label at the end of the invoke call to mark the try range. This 7874 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7875 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7876 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 7877 7878 // Inform MachineModuleInfo of range. 7879 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7880 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7881 // actually use outlined funclets and their LSDA info style. 7882 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7883 assert(II && "II should've been set"); 7884 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 7885 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 7886 } else if (!isScopedEHPersonality(Pers)) { 7887 assert(EHPadBB); 7888 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7889 } 7890 7891 return Chain; 7892 } 7893 7894 std::pair<SDValue, SDValue> 7895 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7896 const BasicBlock *EHPadBB) { 7897 MCSymbol *BeginLabel = nullptr; 7898 7899 if (EHPadBB) { 7900 // Both PendingLoads and PendingExports must be flushed here; 7901 // this call might not return. 7902 (void)getRoot(); 7903 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 7904 CLI.setChain(getRoot()); 7905 } 7906 7907 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7908 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7909 7910 assert((CLI.IsTailCall || Result.second.getNode()) && 7911 "Non-null chain expected with non-tail call!"); 7912 assert((Result.second.getNode() || !Result.first.getNode()) && 7913 "Null value expected with tail call!"); 7914 7915 if (!Result.second.getNode()) { 7916 // As a special case, a null chain means that a tail call has been emitted 7917 // and the DAG root is already updated. 7918 HasTailCall = true; 7919 7920 // Since there's no actual continuation from this block, nothing can be 7921 // relying on us setting vregs for them. 7922 PendingExports.clear(); 7923 } else { 7924 DAG.setRoot(Result.second); 7925 } 7926 7927 if (EHPadBB) { 7928 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 7929 BeginLabel)); 7930 } 7931 7932 return Result; 7933 } 7934 7935 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 7936 bool isTailCall, 7937 bool isMustTailCall, 7938 const BasicBlock *EHPadBB) { 7939 auto &DL = DAG.getDataLayout(); 7940 FunctionType *FTy = CB.getFunctionType(); 7941 Type *RetTy = CB.getType(); 7942 7943 TargetLowering::ArgListTy Args; 7944 Args.reserve(CB.arg_size()); 7945 7946 const Value *SwiftErrorVal = nullptr; 7947 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7948 7949 if (isTailCall) { 7950 // Avoid emitting tail calls in functions with the disable-tail-calls 7951 // attribute. 7952 auto *Caller = CB.getParent()->getParent(); 7953 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7954 "true" && !isMustTailCall) 7955 isTailCall = false; 7956 7957 // We can't tail call inside a function with a swifterror argument. Lowering 7958 // does not support this yet. It would have to move into the swifterror 7959 // register before the call. 7960 if (TLI.supportSwiftError() && 7961 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7962 isTailCall = false; 7963 } 7964 7965 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 7966 TargetLowering::ArgListEntry Entry; 7967 const Value *V = *I; 7968 7969 // Skip empty types 7970 if (V->getType()->isEmptyTy()) 7971 continue; 7972 7973 SDValue ArgNode = getValue(V); 7974 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7975 7976 Entry.setAttributes(&CB, I - CB.arg_begin()); 7977 7978 // Use swifterror virtual register as input to the call. 7979 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7980 SwiftErrorVal = V; 7981 // We find the virtual register for the actual swifterror argument. 7982 // Instead of using the Value, we use the virtual register instead. 7983 Entry.Node = 7984 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 7985 EVT(TLI.getPointerTy(DL))); 7986 } 7987 7988 Args.push_back(Entry); 7989 7990 // If we have an explicit sret argument that is an Instruction, (i.e., it 7991 // might point to function-local memory), we can't meaningfully tail-call. 7992 if (Entry.IsSRet && isa<Instruction>(V)) 7993 isTailCall = false; 7994 } 7995 7996 // If call site has a cfguardtarget operand bundle, create and add an 7997 // additional ArgListEntry. 7998 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7999 TargetLowering::ArgListEntry Entry; 8000 Value *V = Bundle->Inputs[0]; 8001 SDValue ArgNode = getValue(V); 8002 Entry.Node = ArgNode; 8003 Entry.Ty = V->getType(); 8004 Entry.IsCFGuardTarget = true; 8005 Args.push_back(Entry); 8006 } 8007 8008 // Check if target-independent constraints permit a tail call here. 8009 // Target-dependent constraints are checked within TLI->LowerCallTo. 8010 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 8011 isTailCall = false; 8012 8013 // Disable tail calls if there is an swifterror argument. Targets have not 8014 // been updated to support tail calls. 8015 if (TLI.supportSwiftError() && SwiftErrorVal) 8016 isTailCall = false; 8017 8018 ConstantInt *CFIType = nullptr; 8019 if (CB.isIndirectCall()) { 8020 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) { 8021 if (!TLI.supportKCFIBundles()) 8022 report_fatal_error( 8023 "Target doesn't support calls with kcfi operand bundles."); 8024 CFIType = cast<ConstantInt>(Bundle->Inputs[0]); 8025 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type"); 8026 } 8027 } 8028 8029 TargetLowering::CallLoweringInfo CLI(DAG); 8030 CLI.setDebugLoc(getCurSDLoc()) 8031 .setChain(getRoot()) 8032 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 8033 .setTailCall(isTailCall) 8034 .setConvergent(CB.isConvergent()) 8035 .setIsPreallocated( 8036 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0) 8037 .setCFIType(CFIType); 8038 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8039 8040 if (Result.first.getNode()) { 8041 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 8042 setValue(&CB, Result.first); 8043 } 8044 8045 // The last element of CLI.InVals has the SDValue for swifterror return. 8046 // Here we copy it to a virtual register and update SwiftErrorMap for 8047 // book-keeping. 8048 if (SwiftErrorVal && TLI.supportSwiftError()) { 8049 // Get the last element of InVals. 8050 SDValue Src = CLI.InVals.back(); 8051 Register VReg = 8052 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 8053 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 8054 DAG.setRoot(CopyNode); 8055 } 8056 } 8057 8058 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 8059 SelectionDAGBuilder &Builder) { 8060 // Check to see if this load can be trivially constant folded, e.g. if the 8061 // input is from a string literal. 8062 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 8063 // Cast pointer to the type we really want to load. 8064 Type *LoadTy = 8065 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 8066 if (LoadVT.isVector()) 8067 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 8068 8069 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 8070 PointerType::getUnqual(LoadTy)); 8071 8072 if (const Constant *LoadCst = 8073 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput), 8074 LoadTy, Builder.DAG.getDataLayout())) 8075 return Builder.getValue(LoadCst); 8076 } 8077 8078 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 8079 // still constant memory, the input chain can be the entry node. 8080 SDValue Root; 8081 bool ConstantMemory = false; 8082 8083 // Do not serialize (non-volatile) loads of constant memory with anything. 8084 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 8085 Root = Builder.DAG.getEntryNode(); 8086 ConstantMemory = true; 8087 } else { 8088 // Do not serialize non-volatile loads against each other. 8089 Root = Builder.DAG.getRoot(); 8090 } 8091 8092 SDValue Ptr = Builder.getValue(PtrVal); 8093 SDValue LoadVal = 8094 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 8095 MachinePointerInfo(PtrVal), Align(1)); 8096 8097 if (!ConstantMemory) 8098 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 8099 return LoadVal; 8100 } 8101 8102 /// Record the value for an instruction that produces an integer result, 8103 /// converting the type where necessary. 8104 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 8105 SDValue Value, 8106 bool IsSigned) { 8107 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8108 I.getType(), true); 8109 if (IsSigned) 8110 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 8111 else 8112 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 8113 setValue(&I, Value); 8114 } 8115 8116 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 8117 /// true and lower it. Otherwise return false, and it will be lowered like a 8118 /// normal call. 8119 /// The caller already checked that \p I calls the appropriate LibFunc with a 8120 /// correct prototype. 8121 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 8122 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 8123 const Value *Size = I.getArgOperand(2); 8124 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size)); 8125 if (CSize && CSize->getZExtValue() == 0) { 8126 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8127 I.getType(), true); 8128 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 8129 return true; 8130 } 8131 8132 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8133 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 8134 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 8135 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 8136 if (Res.first.getNode()) { 8137 processIntegerCallValue(I, Res.first, true); 8138 PendingLoads.push_back(Res.second); 8139 return true; 8140 } 8141 8142 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 8143 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 8144 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 8145 return false; 8146 8147 // If the target has a fast compare for the given size, it will return a 8148 // preferred load type for that size. Require that the load VT is legal and 8149 // that the target supports unaligned loads of that type. Otherwise, return 8150 // INVALID. 8151 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 8152 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8153 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 8154 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 8155 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 8156 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 8157 // TODO: Check alignment of src and dest ptrs. 8158 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 8159 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 8160 if (!TLI.isTypeLegal(LVT) || 8161 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 8162 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 8163 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 8164 } 8165 8166 return LVT; 8167 }; 8168 8169 // This turns into unaligned loads. We only do this if the target natively 8170 // supports the MVT we'll be loading or if it is small enough (<= 4) that 8171 // we'll only produce a small number of byte loads. 8172 MVT LoadVT; 8173 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 8174 switch (NumBitsToCompare) { 8175 default: 8176 return false; 8177 case 16: 8178 LoadVT = MVT::i16; 8179 break; 8180 case 32: 8181 LoadVT = MVT::i32; 8182 break; 8183 case 64: 8184 case 128: 8185 case 256: 8186 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 8187 break; 8188 } 8189 8190 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 8191 return false; 8192 8193 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 8194 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 8195 8196 // Bitcast to a wide integer type if the loads are vectors. 8197 if (LoadVT.isVector()) { 8198 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 8199 LoadL = DAG.getBitcast(CmpVT, LoadL); 8200 LoadR = DAG.getBitcast(CmpVT, LoadR); 8201 } 8202 8203 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 8204 processIntegerCallValue(I, Cmp, false); 8205 return true; 8206 } 8207 8208 /// See if we can lower a memchr call into an optimized form. If so, return 8209 /// true and lower it. Otherwise return false, and it will be lowered like a 8210 /// normal call. 8211 /// The caller already checked that \p I calls the appropriate LibFunc with a 8212 /// correct prototype. 8213 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 8214 const Value *Src = I.getArgOperand(0); 8215 const Value *Char = I.getArgOperand(1); 8216 const Value *Length = I.getArgOperand(2); 8217 8218 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8219 std::pair<SDValue, SDValue> Res = 8220 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 8221 getValue(Src), getValue(Char), getValue(Length), 8222 MachinePointerInfo(Src)); 8223 if (Res.first.getNode()) { 8224 setValue(&I, Res.first); 8225 PendingLoads.push_back(Res.second); 8226 return true; 8227 } 8228 8229 return false; 8230 } 8231 8232 /// See if we can lower a mempcpy call into an optimized form. If so, return 8233 /// true and lower it. Otherwise return false, and it will be lowered like a 8234 /// normal call. 8235 /// The caller already checked that \p I calls the appropriate LibFunc with a 8236 /// correct prototype. 8237 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 8238 SDValue Dst = getValue(I.getArgOperand(0)); 8239 SDValue Src = getValue(I.getArgOperand(1)); 8240 SDValue Size = getValue(I.getArgOperand(2)); 8241 8242 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 8243 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 8244 // DAG::getMemcpy needs Alignment to be defined. 8245 Align Alignment = std::min(DstAlign, SrcAlign); 8246 8247 bool isVol = false; 8248 SDLoc sdl = getCurSDLoc(); 8249 8250 // In the mempcpy context we need to pass in a false value for isTailCall 8251 // because the return pointer needs to be adjusted by the size of 8252 // the copied memory. 8253 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 8254 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false, 8255 /*isTailCall=*/false, 8256 MachinePointerInfo(I.getArgOperand(0)), 8257 MachinePointerInfo(I.getArgOperand(1)), 8258 I.getAAMetadata()); 8259 assert(MC.getNode() != nullptr && 8260 "** memcpy should not be lowered as TailCall in mempcpy context **"); 8261 DAG.setRoot(MC); 8262 8263 // Check if Size needs to be truncated or extended. 8264 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 8265 8266 // Adjust return pointer to point just past the last dst byte. 8267 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 8268 Dst, Size); 8269 setValue(&I, DstPlusSize); 8270 return true; 8271 } 8272 8273 /// See if we can lower a strcpy call into an optimized form. If so, return 8274 /// true and lower it, otherwise return false and it will be lowered like a 8275 /// normal call. 8276 /// The caller already checked that \p I calls the appropriate LibFunc with a 8277 /// correct prototype. 8278 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 8279 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8280 8281 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8282 std::pair<SDValue, SDValue> Res = 8283 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 8284 getValue(Arg0), getValue(Arg1), 8285 MachinePointerInfo(Arg0), 8286 MachinePointerInfo(Arg1), isStpcpy); 8287 if (Res.first.getNode()) { 8288 setValue(&I, Res.first); 8289 DAG.setRoot(Res.second); 8290 return true; 8291 } 8292 8293 return false; 8294 } 8295 8296 /// See if we can lower a strcmp call into an optimized form. If so, return 8297 /// true and lower it, otherwise return false and it will be lowered like a 8298 /// normal call. 8299 /// The caller already checked that \p I calls the appropriate LibFunc with a 8300 /// correct prototype. 8301 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 8302 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8303 8304 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8305 std::pair<SDValue, SDValue> Res = 8306 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 8307 getValue(Arg0), getValue(Arg1), 8308 MachinePointerInfo(Arg0), 8309 MachinePointerInfo(Arg1)); 8310 if (Res.first.getNode()) { 8311 processIntegerCallValue(I, Res.first, true); 8312 PendingLoads.push_back(Res.second); 8313 return true; 8314 } 8315 8316 return false; 8317 } 8318 8319 /// See if we can lower a strlen call into an optimized form. If so, return 8320 /// true and lower it, otherwise return false and it will be lowered like a 8321 /// normal call. 8322 /// The caller already checked that \p I calls the appropriate LibFunc with a 8323 /// correct prototype. 8324 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 8325 const Value *Arg0 = I.getArgOperand(0); 8326 8327 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8328 std::pair<SDValue, SDValue> Res = 8329 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 8330 getValue(Arg0), MachinePointerInfo(Arg0)); 8331 if (Res.first.getNode()) { 8332 processIntegerCallValue(I, Res.first, false); 8333 PendingLoads.push_back(Res.second); 8334 return true; 8335 } 8336 8337 return false; 8338 } 8339 8340 /// See if we can lower a strnlen call into an optimized form. If so, return 8341 /// true and lower it, otherwise return false and it will be lowered like a 8342 /// normal call. 8343 /// The caller already checked that \p I calls the appropriate LibFunc with a 8344 /// correct prototype. 8345 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 8346 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8347 8348 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8349 std::pair<SDValue, SDValue> Res = 8350 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 8351 getValue(Arg0), getValue(Arg1), 8352 MachinePointerInfo(Arg0)); 8353 if (Res.first.getNode()) { 8354 processIntegerCallValue(I, Res.first, false); 8355 PendingLoads.push_back(Res.second); 8356 return true; 8357 } 8358 8359 return false; 8360 } 8361 8362 /// See if we can lower a unary floating-point operation into an SDNode with 8363 /// the specified Opcode. If so, return true and lower it, otherwise return 8364 /// false and it will be lowered like a normal call. 8365 /// The caller already checked that \p I calls the appropriate LibFunc with a 8366 /// correct prototype. 8367 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 8368 unsigned Opcode) { 8369 // We already checked this call's prototype; verify it doesn't modify errno. 8370 if (!I.onlyReadsMemory()) 8371 return false; 8372 8373 SDNodeFlags Flags; 8374 Flags.copyFMF(cast<FPMathOperator>(I)); 8375 8376 SDValue Tmp = getValue(I.getArgOperand(0)); 8377 setValue(&I, 8378 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 8379 return true; 8380 } 8381 8382 /// See if we can lower a binary floating-point operation into an SDNode with 8383 /// the specified Opcode. If so, return true and lower it. Otherwise return 8384 /// false, and it will be lowered like a normal call. 8385 /// The caller already checked that \p I calls the appropriate LibFunc with a 8386 /// correct prototype. 8387 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 8388 unsigned Opcode) { 8389 // We already checked this call's prototype; verify it doesn't modify errno. 8390 if (!I.onlyReadsMemory()) 8391 return false; 8392 8393 SDNodeFlags Flags; 8394 Flags.copyFMF(cast<FPMathOperator>(I)); 8395 8396 SDValue Tmp0 = getValue(I.getArgOperand(0)); 8397 SDValue Tmp1 = getValue(I.getArgOperand(1)); 8398 EVT VT = Tmp0.getValueType(); 8399 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 8400 return true; 8401 } 8402 8403 void SelectionDAGBuilder::visitCall(const CallInst &I) { 8404 // Handle inline assembly differently. 8405 if (I.isInlineAsm()) { 8406 visitInlineAsm(I); 8407 return; 8408 } 8409 8410 diagnoseDontCall(I); 8411 8412 if (Function *F = I.getCalledFunction()) { 8413 if (F->isDeclaration()) { 8414 // Is this an LLVM intrinsic or a target-specific intrinsic? 8415 unsigned IID = F->getIntrinsicID(); 8416 if (!IID) 8417 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 8418 IID = II->getIntrinsicID(F); 8419 8420 if (IID) { 8421 visitIntrinsicCall(I, IID); 8422 return; 8423 } 8424 } 8425 8426 // Check for well-known libc/libm calls. If the function is internal, it 8427 // can't be a library call. Don't do the check if marked as nobuiltin for 8428 // some reason or the call site requires strict floating point semantics. 8429 LibFunc Func; 8430 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 8431 F->hasName() && LibInfo->getLibFunc(*F, Func) && 8432 LibInfo->hasOptimizedCodeGen(Func)) { 8433 switch (Func) { 8434 default: break; 8435 case LibFunc_bcmp: 8436 if (visitMemCmpBCmpCall(I)) 8437 return; 8438 break; 8439 case LibFunc_copysign: 8440 case LibFunc_copysignf: 8441 case LibFunc_copysignl: 8442 // We already checked this call's prototype; verify it doesn't modify 8443 // errno. 8444 if (I.onlyReadsMemory()) { 8445 SDValue LHS = getValue(I.getArgOperand(0)); 8446 SDValue RHS = getValue(I.getArgOperand(1)); 8447 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 8448 LHS.getValueType(), LHS, RHS)); 8449 return; 8450 } 8451 break; 8452 case LibFunc_fabs: 8453 case LibFunc_fabsf: 8454 case LibFunc_fabsl: 8455 if (visitUnaryFloatCall(I, ISD::FABS)) 8456 return; 8457 break; 8458 case LibFunc_fmin: 8459 case LibFunc_fminf: 8460 case LibFunc_fminl: 8461 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 8462 return; 8463 break; 8464 case LibFunc_fmax: 8465 case LibFunc_fmaxf: 8466 case LibFunc_fmaxl: 8467 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 8468 return; 8469 break; 8470 case LibFunc_sin: 8471 case LibFunc_sinf: 8472 case LibFunc_sinl: 8473 if (visitUnaryFloatCall(I, ISD::FSIN)) 8474 return; 8475 break; 8476 case LibFunc_cos: 8477 case LibFunc_cosf: 8478 case LibFunc_cosl: 8479 if (visitUnaryFloatCall(I, ISD::FCOS)) 8480 return; 8481 break; 8482 case LibFunc_sqrt: 8483 case LibFunc_sqrtf: 8484 case LibFunc_sqrtl: 8485 case LibFunc_sqrt_finite: 8486 case LibFunc_sqrtf_finite: 8487 case LibFunc_sqrtl_finite: 8488 if (visitUnaryFloatCall(I, ISD::FSQRT)) 8489 return; 8490 break; 8491 case LibFunc_floor: 8492 case LibFunc_floorf: 8493 case LibFunc_floorl: 8494 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 8495 return; 8496 break; 8497 case LibFunc_nearbyint: 8498 case LibFunc_nearbyintf: 8499 case LibFunc_nearbyintl: 8500 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 8501 return; 8502 break; 8503 case LibFunc_ceil: 8504 case LibFunc_ceilf: 8505 case LibFunc_ceill: 8506 if (visitUnaryFloatCall(I, ISD::FCEIL)) 8507 return; 8508 break; 8509 case LibFunc_rint: 8510 case LibFunc_rintf: 8511 case LibFunc_rintl: 8512 if (visitUnaryFloatCall(I, ISD::FRINT)) 8513 return; 8514 break; 8515 case LibFunc_round: 8516 case LibFunc_roundf: 8517 case LibFunc_roundl: 8518 if (visitUnaryFloatCall(I, ISD::FROUND)) 8519 return; 8520 break; 8521 case LibFunc_trunc: 8522 case LibFunc_truncf: 8523 case LibFunc_truncl: 8524 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 8525 return; 8526 break; 8527 case LibFunc_log2: 8528 case LibFunc_log2f: 8529 case LibFunc_log2l: 8530 if (visitUnaryFloatCall(I, ISD::FLOG2)) 8531 return; 8532 break; 8533 case LibFunc_exp2: 8534 case LibFunc_exp2f: 8535 case LibFunc_exp2l: 8536 if (visitUnaryFloatCall(I, ISD::FEXP2)) 8537 return; 8538 break; 8539 case LibFunc_memcmp: 8540 if (visitMemCmpBCmpCall(I)) 8541 return; 8542 break; 8543 case LibFunc_mempcpy: 8544 if (visitMemPCpyCall(I)) 8545 return; 8546 break; 8547 case LibFunc_memchr: 8548 if (visitMemChrCall(I)) 8549 return; 8550 break; 8551 case LibFunc_strcpy: 8552 if (visitStrCpyCall(I, false)) 8553 return; 8554 break; 8555 case LibFunc_stpcpy: 8556 if (visitStrCpyCall(I, true)) 8557 return; 8558 break; 8559 case LibFunc_strcmp: 8560 if (visitStrCmpCall(I)) 8561 return; 8562 break; 8563 case LibFunc_strlen: 8564 if (visitStrLenCall(I)) 8565 return; 8566 break; 8567 case LibFunc_strnlen: 8568 if (visitStrNLenCall(I)) 8569 return; 8570 break; 8571 } 8572 } 8573 } 8574 8575 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 8576 // have to do anything here to lower funclet bundles. 8577 // CFGuardTarget bundles are lowered in LowerCallTo. 8578 assert(!I.hasOperandBundlesOtherThan( 8579 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 8580 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 8581 LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) && 8582 "Cannot lower calls with arbitrary operand bundles!"); 8583 8584 SDValue Callee = getValue(I.getCalledOperand()); 8585 8586 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 8587 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 8588 else 8589 // Check if we can potentially perform a tail call. More detailed checking 8590 // is be done within LowerCallTo, after more information about the call is 8591 // known. 8592 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 8593 } 8594 8595 namespace { 8596 8597 /// AsmOperandInfo - This contains information for each constraint that we are 8598 /// lowering. 8599 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 8600 public: 8601 /// CallOperand - If this is the result output operand or a clobber 8602 /// this is null, otherwise it is the incoming operand to the CallInst. 8603 /// This gets modified as the asm is processed. 8604 SDValue CallOperand; 8605 8606 /// AssignedRegs - If this is a register or register class operand, this 8607 /// contains the set of register corresponding to the operand. 8608 RegsForValue AssignedRegs; 8609 8610 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 8611 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 8612 } 8613 8614 /// Whether or not this operand accesses memory 8615 bool hasMemory(const TargetLowering &TLI) const { 8616 // Indirect operand accesses access memory. 8617 if (isIndirect) 8618 return true; 8619 8620 for (const auto &Code : Codes) 8621 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 8622 return true; 8623 8624 return false; 8625 } 8626 }; 8627 8628 8629 } // end anonymous namespace 8630 8631 /// Make sure that the output operand \p OpInfo and its corresponding input 8632 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 8633 /// out). 8634 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 8635 SDISelAsmOperandInfo &MatchingOpInfo, 8636 SelectionDAG &DAG) { 8637 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 8638 return; 8639 8640 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 8641 const auto &TLI = DAG.getTargetLoweringInfo(); 8642 8643 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 8644 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 8645 OpInfo.ConstraintVT); 8646 std::pair<unsigned, const TargetRegisterClass *> InputRC = 8647 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 8648 MatchingOpInfo.ConstraintVT); 8649 if ((OpInfo.ConstraintVT.isInteger() != 8650 MatchingOpInfo.ConstraintVT.isInteger()) || 8651 (MatchRC.second != InputRC.second)) { 8652 // FIXME: error out in a more elegant fashion 8653 report_fatal_error("Unsupported asm: input constraint" 8654 " with a matching output constraint of" 8655 " incompatible type!"); 8656 } 8657 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 8658 } 8659 8660 /// Get a direct memory input to behave well as an indirect operand. 8661 /// This may introduce stores, hence the need for a \p Chain. 8662 /// \return The (possibly updated) chain. 8663 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 8664 SDISelAsmOperandInfo &OpInfo, 8665 SelectionDAG &DAG) { 8666 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8667 8668 // If we don't have an indirect input, put it in the constpool if we can, 8669 // otherwise spill it to a stack slot. 8670 // TODO: This isn't quite right. We need to handle these according to 8671 // the addressing mode that the constraint wants. Also, this may take 8672 // an additional register for the computation and we don't want that 8673 // either. 8674 8675 // If the operand is a float, integer, or vector constant, spill to a 8676 // constant pool entry to get its address. 8677 const Value *OpVal = OpInfo.CallOperandVal; 8678 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 8679 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 8680 OpInfo.CallOperand = DAG.getConstantPool( 8681 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 8682 return Chain; 8683 } 8684 8685 // Otherwise, create a stack slot and emit a store to it before the asm. 8686 Type *Ty = OpVal->getType(); 8687 auto &DL = DAG.getDataLayout(); 8688 uint64_t TySize = DL.getTypeAllocSize(Ty); 8689 MachineFunction &MF = DAG.getMachineFunction(); 8690 int SSFI = MF.getFrameInfo().CreateStackObject( 8691 TySize, DL.getPrefTypeAlign(Ty), false); 8692 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 8693 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 8694 MachinePointerInfo::getFixedStack(MF, SSFI), 8695 TLI.getMemValueType(DL, Ty)); 8696 OpInfo.CallOperand = StackSlot; 8697 8698 return Chain; 8699 } 8700 8701 /// GetRegistersForValue - Assign registers (virtual or physical) for the 8702 /// specified operand. We prefer to assign virtual registers, to allow the 8703 /// register allocator to handle the assignment process. However, if the asm 8704 /// uses features that we can't model on machineinstrs, we have SDISel do the 8705 /// allocation. This produces generally horrible, but correct, code. 8706 /// 8707 /// OpInfo describes the operand 8708 /// RefOpInfo describes the matching operand if any, the operand otherwise 8709 static std::optional<unsigned> 8710 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 8711 SDISelAsmOperandInfo &OpInfo, 8712 SDISelAsmOperandInfo &RefOpInfo) { 8713 LLVMContext &Context = *DAG.getContext(); 8714 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8715 8716 MachineFunction &MF = DAG.getMachineFunction(); 8717 SmallVector<unsigned, 4> Regs; 8718 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8719 8720 // No work to do for memory/address operands. 8721 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8722 OpInfo.ConstraintType == TargetLowering::C_Address) 8723 return std::nullopt; 8724 8725 // If this is a constraint for a single physreg, or a constraint for a 8726 // register class, find it. 8727 unsigned AssignedReg; 8728 const TargetRegisterClass *RC; 8729 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 8730 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 8731 // RC is unset only on failure. Return immediately. 8732 if (!RC) 8733 return std::nullopt; 8734 8735 // Get the actual register value type. This is important, because the user 8736 // may have asked for (e.g.) the AX register in i32 type. We need to 8737 // remember that AX is actually i16 to get the right extension. 8738 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 8739 8740 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) { 8741 // If this is an FP operand in an integer register (or visa versa), or more 8742 // generally if the operand value disagrees with the register class we plan 8743 // to stick it in, fix the operand type. 8744 // 8745 // If this is an input value, the bitcast to the new type is done now. 8746 // Bitcast for output value is done at the end of visitInlineAsm(). 8747 if ((OpInfo.Type == InlineAsm::isOutput || 8748 OpInfo.Type == InlineAsm::isInput) && 8749 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 8750 // Try to convert to the first EVT that the reg class contains. If the 8751 // types are identical size, use a bitcast to convert (e.g. two differing 8752 // vector types). Note: output bitcast is done at the end of 8753 // visitInlineAsm(). 8754 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 8755 // Exclude indirect inputs while they are unsupported because the code 8756 // to perform the load is missing and thus OpInfo.CallOperand still 8757 // refers to the input address rather than the pointed-to value. 8758 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 8759 OpInfo.CallOperand = 8760 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 8761 OpInfo.ConstraintVT = RegVT; 8762 // If the operand is an FP value and we want it in integer registers, 8763 // use the corresponding integer type. This turns an f64 value into 8764 // i64, which can be passed with two i32 values on a 32-bit machine. 8765 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 8766 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 8767 if (OpInfo.Type == InlineAsm::isInput) 8768 OpInfo.CallOperand = 8769 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 8770 OpInfo.ConstraintVT = VT; 8771 } 8772 } 8773 } 8774 8775 // No need to allocate a matching input constraint since the constraint it's 8776 // matching to has already been allocated. 8777 if (OpInfo.isMatchingInputConstraint()) 8778 return std::nullopt; 8779 8780 EVT ValueVT = OpInfo.ConstraintVT; 8781 if (OpInfo.ConstraintVT == MVT::Other) 8782 ValueVT = RegVT; 8783 8784 // Initialize NumRegs. 8785 unsigned NumRegs = 1; 8786 if (OpInfo.ConstraintVT != MVT::Other) 8787 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT); 8788 8789 // If this is a constraint for a specific physical register, like {r17}, 8790 // assign it now. 8791 8792 // If this associated to a specific register, initialize iterator to correct 8793 // place. If virtual, make sure we have enough registers 8794 8795 // Initialize iterator if necessary 8796 TargetRegisterClass::iterator I = RC->begin(); 8797 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8798 8799 // Do not check for single registers. 8800 if (AssignedReg) { 8801 I = std::find(I, RC->end(), AssignedReg); 8802 if (I == RC->end()) { 8803 // RC does not contain the selected register, which indicates a 8804 // mismatch between the register and the required type/bitwidth. 8805 return {AssignedReg}; 8806 } 8807 } 8808 8809 for (; NumRegs; --NumRegs, ++I) { 8810 assert(I != RC->end() && "Ran out of registers to allocate!"); 8811 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8812 Regs.push_back(R); 8813 } 8814 8815 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8816 return std::nullopt; 8817 } 8818 8819 static unsigned 8820 findMatchingInlineAsmOperand(unsigned OperandNo, 8821 const std::vector<SDValue> &AsmNodeOperands) { 8822 // Scan until we find the definition we already emitted of this operand. 8823 unsigned CurOp = InlineAsm::Op_FirstOperand; 8824 for (; OperandNo; --OperandNo) { 8825 // Advance to the next operand. 8826 unsigned OpFlag = 8827 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8828 assert((InlineAsm::isRegDefKind(OpFlag) || 8829 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8830 InlineAsm::isMemKind(OpFlag)) && 8831 "Skipped past definitions?"); 8832 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8833 } 8834 return CurOp; 8835 } 8836 8837 namespace { 8838 8839 class ExtraFlags { 8840 unsigned Flags = 0; 8841 8842 public: 8843 explicit ExtraFlags(const CallBase &Call) { 8844 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8845 if (IA->hasSideEffects()) 8846 Flags |= InlineAsm::Extra_HasSideEffects; 8847 if (IA->isAlignStack()) 8848 Flags |= InlineAsm::Extra_IsAlignStack; 8849 if (Call.isConvergent()) 8850 Flags |= InlineAsm::Extra_IsConvergent; 8851 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8852 } 8853 8854 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8855 // Ideally, we would only check against memory constraints. However, the 8856 // meaning of an Other constraint can be target-specific and we can't easily 8857 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8858 // for Other constraints as well. 8859 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8860 OpInfo.ConstraintType == TargetLowering::C_Other) { 8861 if (OpInfo.Type == InlineAsm::isInput) 8862 Flags |= InlineAsm::Extra_MayLoad; 8863 else if (OpInfo.Type == InlineAsm::isOutput) 8864 Flags |= InlineAsm::Extra_MayStore; 8865 else if (OpInfo.Type == InlineAsm::isClobber) 8866 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8867 } 8868 } 8869 8870 unsigned get() const { return Flags; } 8871 }; 8872 8873 } // end anonymous namespace 8874 8875 static bool isFunction(SDValue Op) { 8876 if (Op && Op.getOpcode() == ISD::GlobalAddress) { 8877 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 8878 auto Fn = dyn_cast_or_null<Function>(GA->getGlobal()); 8879 8880 // In normal "call dllimport func" instruction (non-inlineasm) it force 8881 // indirect access by specifing call opcode. And usually specially print 8882 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can 8883 // not do in this way now. (In fact, this is similar with "Data Access" 8884 // action). So here we ignore dllimport function. 8885 if (Fn && !Fn->hasDLLImportStorageClass()) 8886 return true; 8887 } 8888 } 8889 return false; 8890 } 8891 8892 /// visitInlineAsm - Handle a call to an InlineAsm object. 8893 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 8894 const BasicBlock *EHPadBB) { 8895 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8896 8897 /// ConstraintOperands - Information about all of the constraints. 8898 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 8899 8900 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8901 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8902 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 8903 8904 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8905 // AsmDialect, MayLoad, MayStore). 8906 bool HasSideEffect = IA->hasSideEffects(); 8907 ExtraFlags ExtraInfo(Call); 8908 8909 for (auto &T : TargetConstraints) { 8910 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8911 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8912 8913 if (OpInfo.CallOperandVal) 8914 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8915 8916 if (!HasSideEffect) 8917 HasSideEffect = OpInfo.hasMemory(TLI); 8918 8919 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8920 // FIXME: Could we compute this on OpInfo rather than T? 8921 8922 // Compute the constraint code and ConstraintType to use. 8923 TLI.ComputeConstraintToUse(T, SDValue()); 8924 8925 if (T.ConstraintType == TargetLowering::C_Immediate && 8926 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8927 // We've delayed emitting a diagnostic like the "n" constraint because 8928 // inlining could cause an integer showing up. 8929 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 8930 "' expects an integer constant " 8931 "expression"); 8932 8933 ExtraInfo.update(T); 8934 } 8935 8936 // We won't need to flush pending loads if this asm doesn't touch 8937 // memory and is nonvolatile. 8938 SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8939 8940 bool EmitEHLabels = isa<InvokeInst>(Call); 8941 if (EmitEHLabels) { 8942 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 8943 } 8944 bool IsCallBr = isa<CallBrInst>(Call); 8945 8946 if (IsCallBr || EmitEHLabels) { 8947 // If this is a callbr or invoke we need to flush pending exports since 8948 // inlineasm_br and invoke are terminators. 8949 // We need to do this before nodes are glued to the inlineasm_br node. 8950 Chain = getControlRoot(); 8951 } 8952 8953 MCSymbol *BeginLabel = nullptr; 8954 if (EmitEHLabels) { 8955 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 8956 } 8957 8958 int OpNo = -1; 8959 SmallVector<StringRef> AsmStrs; 8960 IA->collectAsmStrs(AsmStrs); 8961 8962 // Second pass over the constraints: compute which constraint option to use. 8963 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8964 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput) 8965 OpNo++; 8966 8967 // If this is an output operand with a matching input operand, look up the 8968 // matching input. If their types mismatch, e.g. one is an integer, the 8969 // other is floating point, or their sizes are different, flag it as an 8970 // error. 8971 if (OpInfo.hasMatchingInput()) { 8972 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8973 patchMatchingInput(OpInfo, Input, DAG); 8974 } 8975 8976 // Compute the constraint code and ConstraintType to use. 8977 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8978 8979 if ((OpInfo.ConstraintType == TargetLowering::C_Memory && 8980 OpInfo.Type == InlineAsm::isClobber) || 8981 OpInfo.ConstraintType == TargetLowering::C_Address) 8982 continue; 8983 8984 // In Linux PIC model, there are 4 cases about value/label addressing: 8985 // 8986 // 1: Function call or Label jmp inside the module. 8987 // 2: Data access (such as global variable, static variable) inside module. 8988 // 3: Function call or Label jmp outside the module. 8989 // 4: Data access (such as global variable) outside the module. 8990 // 8991 // Due to current llvm inline asm architecture designed to not "recognize" 8992 // the asm code, there are quite troubles for us to treat mem addressing 8993 // differently for same value/adress used in different instuctions. 8994 // For example, in pic model, call a func may in plt way or direclty 8995 // pc-related, but lea/mov a function adress may use got. 8996 // 8997 // Here we try to "recognize" function call for the case 1 and case 3 in 8998 // inline asm. And try to adjust the constraint for them. 8999 // 9000 // TODO: Due to current inline asm didn't encourage to jmp to the outsider 9001 // label, so here we don't handle jmp function label now, but we need to 9002 // enhance it (especilly in PIC model) if we meet meaningful requirements. 9003 if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) && 9004 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) && 9005 TM.getCodeModel() != CodeModel::Large) { 9006 OpInfo.isIndirect = false; 9007 OpInfo.ConstraintType = TargetLowering::C_Address; 9008 } 9009 9010 // If this is a memory input, and if the operand is not indirect, do what we 9011 // need to provide an address for the memory input. 9012 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 9013 !OpInfo.isIndirect) { 9014 assert((OpInfo.isMultipleAlternative || 9015 (OpInfo.Type == InlineAsm::isInput)) && 9016 "Can only indirectify direct input operands!"); 9017 9018 // Memory operands really want the address of the value. 9019 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 9020 9021 // There is no longer a Value* corresponding to this operand. 9022 OpInfo.CallOperandVal = nullptr; 9023 9024 // It is now an indirect operand. 9025 OpInfo.isIndirect = true; 9026 } 9027 9028 } 9029 9030 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 9031 std::vector<SDValue> AsmNodeOperands; 9032 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 9033 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 9034 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 9035 9036 // If we have a !srcloc metadata node associated with it, we want to attach 9037 // this to the ultimately generated inline asm machineinstr. To do this, we 9038 // pass in the third operand as this (potentially null) inline asm MDNode. 9039 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 9040 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 9041 9042 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 9043 // bits as operand 3. 9044 AsmNodeOperands.push_back(DAG.getTargetConstant( 9045 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9046 9047 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 9048 // this, assign virtual and physical registers for inputs and otput. 9049 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9050 // Assign Registers. 9051 SDISelAsmOperandInfo &RefOpInfo = 9052 OpInfo.isMatchingInputConstraint() 9053 ? ConstraintOperands[OpInfo.getMatchedOperand()] 9054 : OpInfo; 9055 const auto RegError = 9056 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 9057 if (RegError) { 9058 const MachineFunction &MF = DAG.getMachineFunction(); 9059 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9060 const char *RegName = TRI.getName(*RegError); 9061 emitInlineAsmError(Call, "register '" + Twine(RegName) + 9062 "' allocated for constraint '" + 9063 Twine(OpInfo.ConstraintCode) + 9064 "' does not match required type"); 9065 return; 9066 } 9067 9068 auto DetectWriteToReservedRegister = [&]() { 9069 const MachineFunction &MF = DAG.getMachineFunction(); 9070 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9071 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 9072 if (Register::isPhysicalRegister(Reg) && 9073 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 9074 const char *RegName = TRI.getName(Reg); 9075 emitInlineAsmError(Call, "write to reserved register '" + 9076 Twine(RegName) + "'"); 9077 return true; 9078 } 9079 } 9080 return false; 9081 }; 9082 assert((OpInfo.ConstraintType != TargetLowering::C_Address || 9083 (OpInfo.Type == InlineAsm::isInput && 9084 !OpInfo.isMatchingInputConstraint())) && 9085 "Only address as input operand is allowed."); 9086 9087 switch (OpInfo.Type) { 9088 case InlineAsm::isOutput: 9089 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9090 unsigned ConstraintID = 9091 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9092 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9093 "Failed to convert memory constraint code to constraint id."); 9094 9095 // Add information to the INLINEASM node to know about this output. 9096 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9097 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 9098 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 9099 MVT::i32)); 9100 AsmNodeOperands.push_back(OpInfo.CallOperand); 9101 } else { 9102 // Otherwise, this outputs to a register (directly for C_Register / 9103 // C_RegisterClass, and a target-defined fashion for 9104 // C_Immediate/C_Other). Find a register that we can use. 9105 if (OpInfo.AssignedRegs.Regs.empty()) { 9106 emitInlineAsmError( 9107 Call, "couldn't allocate output register for constraint '" + 9108 Twine(OpInfo.ConstraintCode) + "'"); 9109 return; 9110 } 9111 9112 if (DetectWriteToReservedRegister()) 9113 return; 9114 9115 // Add information to the INLINEASM node to know that this register is 9116 // set. 9117 OpInfo.AssignedRegs.AddInlineAsmOperands( 9118 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 9119 : InlineAsm::Kind_RegDef, 9120 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 9121 } 9122 break; 9123 9124 case InlineAsm::isInput: 9125 case InlineAsm::isLabel: { 9126 SDValue InOperandVal = OpInfo.CallOperand; 9127 9128 if (OpInfo.isMatchingInputConstraint()) { 9129 // If this is required to match an output register we have already set, 9130 // just use its register. 9131 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 9132 AsmNodeOperands); 9133 unsigned OpFlag = 9134 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 9135 if (InlineAsm::isRegDefKind(OpFlag) || 9136 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 9137 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 9138 if (OpInfo.isIndirect) { 9139 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 9140 emitInlineAsmError(Call, "inline asm not supported yet: " 9141 "don't know how to handle tied " 9142 "indirect register inputs"); 9143 return; 9144 } 9145 9146 SmallVector<unsigned, 4> Regs; 9147 MachineFunction &MF = DAG.getMachineFunction(); 9148 MachineRegisterInfo &MRI = MF.getRegInfo(); 9149 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9150 auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]); 9151 Register TiedReg = R->getReg(); 9152 MVT RegVT = R->getSimpleValueType(0); 9153 const TargetRegisterClass *RC = 9154 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg) 9155 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT) 9156 : TRI.getMinimalPhysRegClass(TiedReg); 9157 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 9158 for (unsigned i = 0; i != NumRegs; ++i) 9159 Regs.push_back(MRI.createVirtualRegister(RC)); 9160 9161 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 9162 9163 SDLoc dl = getCurSDLoc(); 9164 // Use the produced MatchedRegs object to 9165 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call); 9166 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 9167 true, OpInfo.getMatchedOperand(), dl, 9168 DAG, AsmNodeOperands); 9169 break; 9170 } 9171 9172 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 9173 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 9174 "Unexpected number of operands"); 9175 // Add information to the INLINEASM node to know about this input. 9176 // See InlineAsm.h isUseOperandTiedToDef. 9177 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 9178 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 9179 OpInfo.getMatchedOperand()); 9180 AsmNodeOperands.push_back(DAG.getTargetConstant( 9181 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9182 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 9183 break; 9184 } 9185 9186 // Treat indirect 'X' constraint as memory. 9187 if (OpInfo.ConstraintType == TargetLowering::C_Other && 9188 OpInfo.isIndirect) 9189 OpInfo.ConstraintType = TargetLowering::C_Memory; 9190 9191 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 9192 OpInfo.ConstraintType == TargetLowering::C_Other) { 9193 std::vector<SDValue> Ops; 9194 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 9195 Ops, DAG); 9196 if (Ops.empty()) { 9197 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 9198 if (isa<ConstantSDNode>(InOperandVal)) { 9199 emitInlineAsmError(Call, "value out of range for constraint '" + 9200 Twine(OpInfo.ConstraintCode) + "'"); 9201 return; 9202 } 9203 9204 emitInlineAsmError(Call, 9205 "invalid operand for inline asm constraint '" + 9206 Twine(OpInfo.ConstraintCode) + "'"); 9207 return; 9208 } 9209 9210 // Add information to the INLINEASM node to know about this input. 9211 unsigned ResOpType = 9212 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 9213 AsmNodeOperands.push_back(DAG.getTargetConstant( 9214 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9215 llvm::append_range(AsmNodeOperands, Ops); 9216 break; 9217 } 9218 9219 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9220 assert((OpInfo.isIndirect || 9221 OpInfo.ConstraintType != TargetLowering::C_Memory) && 9222 "Operand must be indirect to be a mem!"); 9223 assert(InOperandVal.getValueType() == 9224 TLI.getPointerTy(DAG.getDataLayout()) && 9225 "Memory operands expect pointer values"); 9226 9227 unsigned ConstraintID = 9228 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9229 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9230 "Failed to convert memory constraint code to constraint id."); 9231 9232 // Add information to the INLINEASM node to know about this input. 9233 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9234 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 9235 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 9236 getCurSDLoc(), 9237 MVT::i32)); 9238 AsmNodeOperands.push_back(InOperandVal); 9239 break; 9240 } 9241 9242 if (OpInfo.ConstraintType == TargetLowering::C_Address) { 9243 assert(InOperandVal.getValueType() == 9244 TLI.getPointerTy(DAG.getDataLayout()) && 9245 "Address operands expect pointer values"); 9246 9247 unsigned ConstraintID = 9248 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9249 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9250 "Failed to convert memory constraint code to constraint id."); 9251 9252 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9253 9254 SDValue AsmOp = InOperandVal; 9255 if (isFunction(InOperandVal)) { 9256 auto *GA = cast<GlobalAddressSDNode>(InOperandVal); 9257 ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Func, 1); 9258 AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(), 9259 InOperandVal.getValueType(), 9260 GA->getOffset()); 9261 } 9262 9263 // Add information to the INLINEASM node to know about this input. 9264 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 9265 9266 AsmNodeOperands.push_back( 9267 DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32)); 9268 9269 AsmNodeOperands.push_back(AsmOp); 9270 break; 9271 } 9272 9273 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 9274 OpInfo.ConstraintType == TargetLowering::C_Register) && 9275 "Unknown constraint type!"); 9276 9277 // TODO: Support this. 9278 if (OpInfo.isIndirect) { 9279 emitInlineAsmError( 9280 Call, "Don't know how to handle indirect register inputs yet " 9281 "for constraint '" + 9282 Twine(OpInfo.ConstraintCode) + "'"); 9283 return; 9284 } 9285 9286 // Copy the input into the appropriate registers. 9287 if (OpInfo.AssignedRegs.Regs.empty()) { 9288 emitInlineAsmError(Call, 9289 "couldn't allocate input reg for constraint '" + 9290 Twine(OpInfo.ConstraintCode) + "'"); 9291 return; 9292 } 9293 9294 if (DetectWriteToReservedRegister()) 9295 return; 9296 9297 SDLoc dl = getCurSDLoc(); 9298 9299 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, 9300 &Call); 9301 9302 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 9303 dl, DAG, AsmNodeOperands); 9304 break; 9305 } 9306 case InlineAsm::isClobber: 9307 // Add the clobbered value to the operand list, so that the register 9308 // allocator is aware that the physreg got clobbered. 9309 if (!OpInfo.AssignedRegs.Regs.empty()) 9310 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 9311 false, 0, getCurSDLoc(), DAG, 9312 AsmNodeOperands); 9313 break; 9314 } 9315 } 9316 9317 // Finish up input operands. Set the input chain and add the flag last. 9318 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 9319 if (Glue.getNode()) AsmNodeOperands.push_back(Glue); 9320 9321 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 9322 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 9323 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 9324 Glue = Chain.getValue(1); 9325 9326 // Do additional work to generate outputs. 9327 9328 SmallVector<EVT, 1> ResultVTs; 9329 SmallVector<SDValue, 1> ResultValues; 9330 SmallVector<SDValue, 8> OutChains; 9331 9332 llvm::Type *CallResultType = Call.getType(); 9333 ArrayRef<Type *> ResultTypes; 9334 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 9335 ResultTypes = StructResult->elements(); 9336 else if (!CallResultType->isVoidTy()) 9337 ResultTypes = ArrayRef(CallResultType); 9338 9339 auto CurResultType = ResultTypes.begin(); 9340 auto handleRegAssign = [&](SDValue V) { 9341 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 9342 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 9343 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 9344 ++CurResultType; 9345 // If the type of the inline asm call site return value is different but has 9346 // same size as the type of the asm output bitcast it. One example of this 9347 // is for vectors with different width / number of elements. This can 9348 // happen for register classes that can contain multiple different value 9349 // types. The preg or vreg allocated may not have the same VT as was 9350 // expected. 9351 // 9352 // This can also happen for a return value that disagrees with the register 9353 // class it is put in, eg. a double in a general-purpose register on a 9354 // 32-bit machine. 9355 if (ResultVT != V.getValueType() && 9356 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 9357 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 9358 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 9359 V.getValueType().isInteger()) { 9360 // If a result value was tied to an input value, the computed result 9361 // may have a wider width than the expected result. Extract the 9362 // relevant portion. 9363 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 9364 } 9365 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 9366 ResultVTs.push_back(ResultVT); 9367 ResultValues.push_back(V); 9368 }; 9369 9370 // Deal with output operands. 9371 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9372 if (OpInfo.Type == InlineAsm::isOutput) { 9373 SDValue Val; 9374 // Skip trivial output operands. 9375 if (OpInfo.AssignedRegs.Regs.empty()) 9376 continue; 9377 9378 switch (OpInfo.ConstraintType) { 9379 case TargetLowering::C_Register: 9380 case TargetLowering::C_RegisterClass: 9381 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 9382 Chain, &Glue, &Call); 9383 break; 9384 case TargetLowering::C_Immediate: 9385 case TargetLowering::C_Other: 9386 Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(), 9387 OpInfo, DAG); 9388 break; 9389 case TargetLowering::C_Memory: 9390 break; // Already handled. 9391 case TargetLowering::C_Address: 9392 break; // Silence warning. 9393 case TargetLowering::C_Unknown: 9394 assert(false && "Unexpected unknown constraint"); 9395 } 9396 9397 // Indirect output manifest as stores. Record output chains. 9398 if (OpInfo.isIndirect) { 9399 const Value *Ptr = OpInfo.CallOperandVal; 9400 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 9401 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 9402 MachinePointerInfo(Ptr)); 9403 OutChains.push_back(Store); 9404 } else { 9405 // generate CopyFromRegs to associated registers. 9406 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 9407 if (Val.getOpcode() == ISD::MERGE_VALUES) { 9408 for (const SDValue &V : Val->op_values()) 9409 handleRegAssign(V); 9410 } else 9411 handleRegAssign(Val); 9412 } 9413 } 9414 } 9415 9416 // Set results. 9417 if (!ResultValues.empty()) { 9418 assert(CurResultType == ResultTypes.end() && 9419 "Mismatch in number of ResultTypes"); 9420 assert(ResultValues.size() == ResultTypes.size() && 9421 "Mismatch in number of output operands in asm result"); 9422 9423 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 9424 DAG.getVTList(ResultVTs), ResultValues); 9425 setValue(&Call, V); 9426 } 9427 9428 // Collect store chains. 9429 if (!OutChains.empty()) 9430 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 9431 9432 if (EmitEHLabels) { 9433 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 9434 } 9435 9436 // Only Update Root if inline assembly has a memory effect. 9437 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 9438 EmitEHLabels) 9439 DAG.setRoot(Chain); 9440 } 9441 9442 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 9443 const Twine &Message) { 9444 LLVMContext &Ctx = *DAG.getContext(); 9445 Ctx.emitError(&Call, Message); 9446 9447 // Make sure we leave the DAG in a valid state 9448 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9449 SmallVector<EVT, 1> ValueVTs; 9450 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 9451 9452 if (ValueVTs.empty()) 9453 return; 9454 9455 SmallVector<SDValue, 1> Ops; 9456 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 9457 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 9458 9459 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 9460 } 9461 9462 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 9463 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 9464 MVT::Other, getRoot(), 9465 getValue(I.getArgOperand(0)), 9466 DAG.getSrcValue(I.getArgOperand(0)))); 9467 } 9468 9469 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 9470 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9471 const DataLayout &DL = DAG.getDataLayout(); 9472 SDValue V = DAG.getVAArg( 9473 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 9474 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 9475 DL.getABITypeAlign(I.getType()).value()); 9476 DAG.setRoot(V.getValue(1)); 9477 9478 if (I.getType()->isPointerTy()) 9479 V = DAG.getPtrExtOrTrunc( 9480 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 9481 setValue(&I, V); 9482 } 9483 9484 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 9485 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 9486 MVT::Other, getRoot(), 9487 getValue(I.getArgOperand(0)), 9488 DAG.getSrcValue(I.getArgOperand(0)))); 9489 } 9490 9491 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 9492 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 9493 MVT::Other, getRoot(), 9494 getValue(I.getArgOperand(0)), 9495 getValue(I.getArgOperand(1)), 9496 DAG.getSrcValue(I.getArgOperand(0)), 9497 DAG.getSrcValue(I.getArgOperand(1)))); 9498 } 9499 9500 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 9501 const Instruction &I, 9502 SDValue Op) { 9503 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 9504 if (!Range) 9505 return Op; 9506 9507 ConstantRange CR = getConstantRangeFromMetadata(*Range); 9508 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 9509 return Op; 9510 9511 APInt Lo = CR.getUnsignedMin(); 9512 if (!Lo.isMinValue()) 9513 return Op; 9514 9515 APInt Hi = CR.getUnsignedMax(); 9516 unsigned Bits = std::max(Hi.getActiveBits(), 9517 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 9518 9519 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9520 9521 SDLoc SL = getCurSDLoc(); 9522 9523 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 9524 DAG.getValueType(SmallVT)); 9525 unsigned NumVals = Op.getNode()->getNumValues(); 9526 if (NumVals == 1) 9527 return ZExt; 9528 9529 SmallVector<SDValue, 4> Ops; 9530 9531 Ops.push_back(ZExt); 9532 for (unsigned I = 1; I != NumVals; ++I) 9533 Ops.push_back(Op.getValue(I)); 9534 9535 return DAG.getMergeValues(Ops, SL); 9536 } 9537 9538 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 9539 /// the call being lowered. 9540 /// 9541 /// This is a helper for lowering intrinsics that follow a target calling 9542 /// convention or require stack pointer adjustment. Only a subset of the 9543 /// intrinsic's operands need to participate in the calling convention. 9544 void SelectionDAGBuilder::populateCallLoweringInfo( 9545 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 9546 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 9547 bool IsPatchPoint) { 9548 TargetLowering::ArgListTy Args; 9549 Args.reserve(NumArgs); 9550 9551 // Populate the argument list. 9552 // Attributes for args start at offset 1, after the return attribute. 9553 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 9554 ArgI != ArgE; ++ArgI) { 9555 const Value *V = Call->getOperand(ArgI); 9556 9557 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 9558 9559 TargetLowering::ArgListEntry Entry; 9560 Entry.Node = getValue(V); 9561 Entry.Ty = V->getType(); 9562 Entry.setAttributes(Call, ArgI); 9563 Args.push_back(Entry); 9564 } 9565 9566 CLI.setDebugLoc(getCurSDLoc()) 9567 .setChain(getRoot()) 9568 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 9569 .setDiscardResult(Call->use_empty()) 9570 .setIsPatchPoint(IsPatchPoint) 9571 .setIsPreallocated( 9572 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 9573 } 9574 9575 /// Add a stack map intrinsic call's live variable operands to a stackmap 9576 /// or patchpoint target node's operand list. 9577 /// 9578 /// Constants are converted to TargetConstants purely as an optimization to 9579 /// avoid constant materialization and register allocation. 9580 /// 9581 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 9582 /// generate addess computation nodes, and so FinalizeISel can convert the 9583 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 9584 /// address materialization and register allocation, but may also be required 9585 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 9586 /// alloca in the entry block, then the runtime may assume that the alloca's 9587 /// StackMap location can be read immediately after compilation and that the 9588 /// location is valid at any point during execution (this is similar to the 9589 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 9590 /// only available in a register, then the runtime would need to trap when 9591 /// execution reaches the StackMap in order to read the alloca's location. 9592 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 9593 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 9594 SelectionDAGBuilder &Builder) { 9595 SelectionDAG &DAG = Builder.DAG; 9596 for (unsigned I = StartIdx; I < Call.arg_size(); I++) { 9597 SDValue Op = Builder.getValue(Call.getArgOperand(I)); 9598 9599 // Things on the stack are pointer-typed, meaning that they are already 9600 // legal and can be emitted directly to target nodes. 9601 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) { 9602 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType())); 9603 } else { 9604 // Otherwise emit a target independent node to be legalised. 9605 Ops.push_back(Builder.getValue(Call.getArgOperand(I))); 9606 } 9607 } 9608 } 9609 9610 /// Lower llvm.experimental.stackmap. 9611 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 9612 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>, 9613 // [live variables...]) 9614 9615 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 9616 9617 SDValue Chain, InGlue, Callee; 9618 SmallVector<SDValue, 32> Ops; 9619 9620 SDLoc DL = getCurSDLoc(); 9621 Callee = getValue(CI.getCalledOperand()); 9622 9623 // The stackmap intrinsic only records the live variables (the arguments 9624 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 9625 // intrinsic, this won't be lowered to a function call. This means we don't 9626 // have to worry about calling conventions and target specific lowering code. 9627 // Instead we perform the call lowering right here. 9628 // 9629 // chain, flag = CALLSEQ_START(chain, 0, 0) 9630 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 9631 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 9632 // 9633 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 9634 InGlue = Chain.getValue(1); 9635 9636 // Add the STACKMAP operands, starting with DAG house-keeping. 9637 Ops.push_back(Chain); 9638 Ops.push_back(InGlue); 9639 9640 // Add the <id>, <numShadowBytes> operands. 9641 // 9642 // These do not require legalisation, and can be emitted directly to target 9643 // constant nodes. 9644 SDValue ID = getValue(CI.getArgOperand(0)); 9645 assert(ID.getValueType() == MVT::i64); 9646 SDValue IDConst = DAG.getTargetConstant( 9647 cast<ConstantSDNode>(ID)->getZExtValue(), DL, ID.getValueType()); 9648 Ops.push_back(IDConst); 9649 9650 SDValue Shad = getValue(CI.getArgOperand(1)); 9651 assert(Shad.getValueType() == MVT::i32); 9652 SDValue ShadConst = DAG.getTargetConstant( 9653 cast<ConstantSDNode>(Shad)->getZExtValue(), DL, Shad.getValueType()); 9654 Ops.push_back(ShadConst); 9655 9656 // Add the live variables. 9657 addStackMapLiveVars(CI, 2, DL, Ops, *this); 9658 9659 // Create the STACKMAP node. 9660 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9661 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops); 9662 InGlue = Chain.getValue(1); 9663 9664 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL); 9665 9666 // Stackmaps don't generate values, so nothing goes into the NodeMap. 9667 9668 // Set the root to the target-lowered call chain. 9669 DAG.setRoot(Chain); 9670 9671 // Inform the Frame Information that we have a stackmap in this function. 9672 FuncInfo.MF->getFrameInfo().setHasStackMap(); 9673 } 9674 9675 /// Lower llvm.experimental.patchpoint directly to its target opcode. 9676 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 9677 const BasicBlock *EHPadBB) { 9678 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 9679 // i32 <numBytes>, 9680 // i8* <target>, 9681 // i32 <numArgs>, 9682 // [Args...], 9683 // [live variables...]) 9684 9685 CallingConv::ID CC = CB.getCallingConv(); 9686 bool IsAnyRegCC = CC == CallingConv::AnyReg; 9687 bool HasDef = !CB.getType()->isVoidTy(); 9688 SDLoc dl = getCurSDLoc(); 9689 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 9690 9691 // Handle immediate and symbolic callees. 9692 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 9693 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 9694 /*isTarget=*/true); 9695 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 9696 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 9697 SDLoc(SymbolicCallee), 9698 SymbolicCallee->getValueType(0)); 9699 9700 // Get the real number of arguments participating in the call <numArgs> 9701 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 9702 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 9703 9704 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 9705 // Intrinsics include all meta-operands up to but not including CC. 9706 unsigned NumMetaOpers = PatchPointOpers::CCPos; 9707 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 9708 "Not enough arguments provided to the patchpoint intrinsic"); 9709 9710 // For AnyRegCC the arguments are lowered later on manually. 9711 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 9712 Type *ReturnTy = 9713 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 9714 9715 TargetLowering::CallLoweringInfo CLI(DAG); 9716 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 9717 ReturnTy, true); 9718 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 9719 9720 SDNode *CallEnd = Result.second.getNode(); 9721 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 9722 CallEnd = CallEnd->getOperand(0).getNode(); 9723 9724 /// Get a call instruction from the call sequence chain. 9725 /// Tail calls are not allowed. 9726 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 9727 "Expected a callseq node."); 9728 SDNode *Call = CallEnd->getOperand(0).getNode(); 9729 bool HasGlue = Call->getGluedNode(); 9730 9731 // Replace the target specific call node with the patchable intrinsic. 9732 SmallVector<SDValue, 8> Ops; 9733 9734 // Push the chain. 9735 Ops.push_back(*(Call->op_begin())); 9736 9737 // Optionally, push the glue (if any). 9738 if (HasGlue) 9739 Ops.push_back(*(Call->op_end() - 1)); 9740 9741 // Push the register mask info. 9742 if (HasGlue) 9743 Ops.push_back(*(Call->op_end() - 2)); 9744 else 9745 Ops.push_back(*(Call->op_end() - 1)); 9746 9747 // Add the <id> and <numBytes> constants. 9748 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 9749 Ops.push_back(DAG.getTargetConstant( 9750 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 9751 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 9752 Ops.push_back(DAG.getTargetConstant( 9753 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 9754 MVT::i32)); 9755 9756 // Add the callee. 9757 Ops.push_back(Callee); 9758 9759 // Adjust <numArgs> to account for any arguments that have been passed on the 9760 // stack instead. 9761 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 9762 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 9763 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 9764 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 9765 9766 // Add the calling convention 9767 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 9768 9769 // Add the arguments we omitted previously. The register allocator should 9770 // place these in any free register. 9771 if (IsAnyRegCC) 9772 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 9773 Ops.push_back(getValue(CB.getArgOperand(i))); 9774 9775 // Push the arguments from the call instruction. 9776 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 9777 Ops.append(Call->op_begin() + 2, e); 9778 9779 // Push live variables for the stack map. 9780 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 9781 9782 SDVTList NodeTys; 9783 if (IsAnyRegCC && HasDef) { 9784 // Create the return types based on the intrinsic definition 9785 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9786 SmallVector<EVT, 3> ValueVTs; 9787 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 9788 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 9789 9790 // There is always a chain and a glue type at the end 9791 ValueVTs.push_back(MVT::Other); 9792 ValueVTs.push_back(MVT::Glue); 9793 NodeTys = DAG.getVTList(ValueVTs); 9794 } else 9795 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9796 9797 // Replace the target specific call node with a PATCHPOINT node. 9798 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops); 9799 9800 // Update the NodeMap. 9801 if (HasDef) { 9802 if (IsAnyRegCC) 9803 setValue(&CB, SDValue(PPV.getNode(), 0)); 9804 else 9805 setValue(&CB, Result.first); 9806 } 9807 9808 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 9809 // call sequence. Furthermore the location of the chain and glue can change 9810 // when the AnyReg calling convention is used and the intrinsic returns a 9811 // value. 9812 if (IsAnyRegCC && HasDef) { 9813 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 9814 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)}; 9815 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 9816 } else 9817 DAG.ReplaceAllUsesWith(Call, PPV.getNode()); 9818 DAG.DeleteNode(Call); 9819 9820 // Inform the Frame Information that we have a patchpoint in this function. 9821 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 9822 } 9823 9824 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 9825 unsigned Intrinsic) { 9826 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9827 SDValue Op1 = getValue(I.getArgOperand(0)); 9828 SDValue Op2; 9829 if (I.arg_size() > 1) 9830 Op2 = getValue(I.getArgOperand(1)); 9831 SDLoc dl = getCurSDLoc(); 9832 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 9833 SDValue Res; 9834 SDNodeFlags SDFlags; 9835 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 9836 SDFlags.copyFMF(*FPMO); 9837 9838 switch (Intrinsic) { 9839 case Intrinsic::vector_reduce_fadd: 9840 if (SDFlags.hasAllowReassociation()) 9841 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 9842 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 9843 SDFlags); 9844 else 9845 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 9846 break; 9847 case Intrinsic::vector_reduce_fmul: 9848 if (SDFlags.hasAllowReassociation()) 9849 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 9850 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 9851 SDFlags); 9852 else 9853 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 9854 break; 9855 case Intrinsic::vector_reduce_add: 9856 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 9857 break; 9858 case Intrinsic::vector_reduce_mul: 9859 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 9860 break; 9861 case Intrinsic::vector_reduce_and: 9862 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 9863 break; 9864 case Intrinsic::vector_reduce_or: 9865 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 9866 break; 9867 case Intrinsic::vector_reduce_xor: 9868 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 9869 break; 9870 case Intrinsic::vector_reduce_smax: 9871 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 9872 break; 9873 case Intrinsic::vector_reduce_smin: 9874 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 9875 break; 9876 case Intrinsic::vector_reduce_umax: 9877 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 9878 break; 9879 case Intrinsic::vector_reduce_umin: 9880 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 9881 break; 9882 case Intrinsic::vector_reduce_fmax: 9883 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 9884 break; 9885 case Intrinsic::vector_reduce_fmin: 9886 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 9887 break; 9888 default: 9889 llvm_unreachable("Unhandled vector reduce intrinsic"); 9890 } 9891 setValue(&I, Res); 9892 } 9893 9894 /// Returns an AttributeList representing the attributes applied to the return 9895 /// value of the given call. 9896 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9897 SmallVector<Attribute::AttrKind, 2> Attrs; 9898 if (CLI.RetSExt) 9899 Attrs.push_back(Attribute::SExt); 9900 if (CLI.RetZExt) 9901 Attrs.push_back(Attribute::ZExt); 9902 if (CLI.IsInReg) 9903 Attrs.push_back(Attribute::InReg); 9904 9905 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9906 Attrs); 9907 } 9908 9909 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9910 /// implementation, which just calls LowerCall. 9911 /// FIXME: When all targets are 9912 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9913 std::pair<SDValue, SDValue> 9914 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9915 // Handle the incoming return values from the call. 9916 CLI.Ins.clear(); 9917 Type *OrigRetTy = CLI.RetTy; 9918 SmallVector<EVT, 4> RetTys; 9919 SmallVector<uint64_t, 4> Offsets; 9920 auto &DL = CLI.DAG.getDataLayout(); 9921 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 9922 9923 if (CLI.IsPostTypeLegalization) { 9924 // If we are lowering a libcall after legalization, split the return type. 9925 SmallVector<EVT, 4> OldRetTys; 9926 SmallVector<uint64_t, 4> OldOffsets; 9927 RetTys.swap(OldRetTys); 9928 Offsets.swap(OldOffsets); 9929 9930 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9931 EVT RetVT = OldRetTys[i]; 9932 uint64_t Offset = OldOffsets[i]; 9933 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9934 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9935 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9936 RetTys.append(NumRegs, RegisterVT); 9937 for (unsigned j = 0; j != NumRegs; ++j) 9938 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9939 } 9940 } 9941 9942 SmallVector<ISD::OutputArg, 4> Outs; 9943 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9944 9945 bool CanLowerReturn = 9946 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9947 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9948 9949 SDValue DemoteStackSlot; 9950 int DemoteStackIdx = -100; 9951 if (!CanLowerReturn) { 9952 // FIXME: equivalent assert? 9953 // assert(!CS.hasInAllocaArgument() && 9954 // "sret demotion is incompatible with inalloca"); 9955 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9956 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 9957 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9958 DemoteStackIdx = 9959 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 9960 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9961 DL.getAllocaAddrSpace()); 9962 9963 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9964 ArgListEntry Entry; 9965 Entry.Node = DemoteStackSlot; 9966 Entry.Ty = StackSlotPtrType; 9967 Entry.IsSExt = false; 9968 Entry.IsZExt = false; 9969 Entry.IsInReg = false; 9970 Entry.IsSRet = true; 9971 Entry.IsNest = false; 9972 Entry.IsByVal = false; 9973 Entry.IsByRef = false; 9974 Entry.IsReturned = false; 9975 Entry.IsSwiftSelf = false; 9976 Entry.IsSwiftAsync = false; 9977 Entry.IsSwiftError = false; 9978 Entry.IsCFGuardTarget = false; 9979 Entry.Alignment = Alignment; 9980 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9981 CLI.NumFixedArgs += 1; 9982 CLI.getArgs()[0].IndirectType = CLI.RetTy; 9983 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9984 9985 // sret demotion isn't compatible with tail-calls, since the sret argument 9986 // points into the callers stack frame. 9987 CLI.IsTailCall = false; 9988 } else { 9989 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9990 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL); 9991 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9992 ISD::ArgFlagsTy Flags; 9993 if (NeedsRegBlock) { 9994 Flags.setInConsecutiveRegs(); 9995 if (I == RetTys.size() - 1) 9996 Flags.setInConsecutiveRegsLast(); 9997 } 9998 EVT VT = RetTys[I]; 9999 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10000 CLI.CallConv, VT); 10001 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10002 CLI.CallConv, VT); 10003 for (unsigned i = 0; i != NumRegs; ++i) { 10004 ISD::InputArg MyFlags; 10005 MyFlags.Flags = Flags; 10006 MyFlags.VT = RegisterVT; 10007 MyFlags.ArgVT = VT; 10008 MyFlags.Used = CLI.IsReturnValueUsed; 10009 if (CLI.RetTy->isPointerTy()) { 10010 MyFlags.Flags.setPointer(); 10011 MyFlags.Flags.setPointerAddrSpace( 10012 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 10013 } 10014 if (CLI.RetSExt) 10015 MyFlags.Flags.setSExt(); 10016 if (CLI.RetZExt) 10017 MyFlags.Flags.setZExt(); 10018 if (CLI.IsInReg) 10019 MyFlags.Flags.setInReg(); 10020 CLI.Ins.push_back(MyFlags); 10021 } 10022 } 10023 } 10024 10025 // We push in swifterror return as the last element of CLI.Ins. 10026 ArgListTy &Args = CLI.getArgs(); 10027 if (supportSwiftError()) { 10028 for (const ArgListEntry &Arg : Args) { 10029 if (Arg.IsSwiftError) { 10030 ISD::InputArg MyFlags; 10031 MyFlags.VT = getPointerTy(DL); 10032 MyFlags.ArgVT = EVT(getPointerTy(DL)); 10033 MyFlags.Flags.setSwiftError(); 10034 CLI.Ins.push_back(MyFlags); 10035 } 10036 } 10037 } 10038 10039 // Handle all of the outgoing arguments. 10040 CLI.Outs.clear(); 10041 CLI.OutVals.clear(); 10042 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 10043 SmallVector<EVT, 4> ValueVTs; 10044 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 10045 // FIXME: Split arguments if CLI.IsPostTypeLegalization 10046 Type *FinalType = Args[i].Ty; 10047 if (Args[i].IsByVal) 10048 FinalType = Args[i].IndirectType; 10049 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10050 FinalType, CLI.CallConv, CLI.IsVarArg, DL); 10051 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 10052 ++Value) { 10053 EVT VT = ValueVTs[Value]; 10054 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 10055 SDValue Op = SDValue(Args[i].Node.getNode(), 10056 Args[i].Node.getResNo() + Value); 10057 ISD::ArgFlagsTy Flags; 10058 10059 // Certain targets (such as MIPS), may have a different ABI alignment 10060 // for a type depending on the context. Give the target a chance to 10061 // specify the alignment it wants. 10062 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 10063 Flags.setOrigAlign(OriginalAlignment); 10064 10065 if (Args[i].Ty->isPointerTy()) { 10066 Flags.setPointer(); 10067 Flags.setPointerAddrSpace( 10068 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 10069 } 10070 if (Args[i].IsZExt) 10071 Flags.setZExt(); 10072 if (Args[i].IsSExt) 10073 Flags.setSExt(); 10074 if (Args[i].IsInReg) { 10075 // If we are using vectorcall calling convention, a structure that is 10076 // passed InReg - is surely an HVA 10077 if (CLI.CallConv == CallingConv::X86_VectorCall && 10078 isa<StructType>(FinalType)) { 10079 // The first value of a structure is marked 10080 if (0 == Value) 10081 Flags.setHvaStart(); 10082 Flags.setHva(); 10083 } 10084 // Set InReg Flag 10085 Flags.setInReg(); 10086 } 10087 if (Args[i].IsSRet) 10088 Flags.setSRet(); 10089 if (Args[i].IsSwiftSelf) 10090 Flags.setSwiftSelf(); 10091 if (Args[i].IsSwiftAsync) 10092 Flags.setSwiftAsync(); 10093 if (Args[i].IsSwiftError) 10094 Flags.setSwiftError(); 10095 if (Args[i].IsCFGuardTarget) 10096 Flags.setCFGuardTarget(); 10097 if (Args[i].IsByVal) 10098 Flags.setByVal(); 10099 if (Args[i].IsByRef) 10100 Flags.setByRef(); 10101 if (Args[i].IsPreallocated) { 10102 Flags.setPreallocated(); 10103 // Set the byval flag for CCAssignFn callbacks that don't know about 10104 // preallocated. This way we can know how many bytes we should've 10105 // allocated and how many bytes a callee cleanup function will pop. If 10106 // we port preallocated to more targets, we'll have to add custom 10107 // preallocated handling in the various CC lowering callbacks. 10108 Flags.setByVal(); 10109 } 10110 if (Args[i].IsInAlloca) { 10111 Flags.setInAlloca(); 10112 // Set the byval flag for CCAssignFn callbacks that don't know about 10113 // inalloca. This way we can know how many bytes we should've allocated 10114 // and how many bytes a callee cleanup function will pop. If we port 10115 // inalloca to more targets, we'll have to add custom inalloca handling 10116 // in the various CC lowering callbacks. 10117 Flags.setByVal(); 10118 } 10119 Align MemAlign; 10120 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 10121 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType); 10122 Flags.setByValSize(FrameSize); 10123 10124 // info is not there but there are cases it cannot get right. 10125 if (auto MA = Args[i].Alignment) 10126 MemAlign = *MA; 10127 else 10128 MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL)); 10129 } else if (auto MA = Args[i].Alignment) { 10130 MemAlign = *MA; 10131 } else { 10132 MemAlign = OriginalAlignment; 10133 } 10134 Flags.setMemAlign(MemAlign); 10135 if (Args[i].IsNest) 10136 Flags.setNest(); 10137 if (NeedsRegBlock) 10138 Flags.setInConsecutiveRegs(); 10139 10140 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10141 CLI.CallConv, VT); 10142 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10143 CLI.CallConv, VT); 10144 SmallVector<SDValue, 4> Parts(NumParts); 10145 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 10146 10147 if (Args[i].IsSExt) 10148 ExtendKind = ISD::SIGN_EXTEND; 10149 else if (Args[i].IsZExt) 10150 ExtendKind = ISD::ZERO_EXTEND; 10151 10152 // Conservatively only handle 'returned' on non-vectors that can be lowered, 10153 // for now. 10154 if (Args[i].IsReturned && !Op.getValueType().isVector() && 10155 CanLowerReturn) { 10156 assert((CLI.RetTy == Args[i].Ty || 10157 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 10158 CLI.RetTy->getPointerAddressSpace() == 10159 Args[i].Ty->getPointerAddressSpace())) && 10160 RetTys.size() == NumValues && "unexpected use of 'returned'"); 10161 // Before passing 'returned' to the target lowering code, ensure that 10162 // either the register MVT and the actual EVT are the same size or that 10163 // the return value and argument are extended in the same way; in these 10164 // cases it's safe to pass the argument register value unchanged as the 10165 // return register value (although it's at the target's option whether 10166 // to do so) 10167 // TODO: allow code generation to take advantage of partially preserved 10168 // registers rather than clobbering the entire register when the 10169 // parameter extension method is not compatible with the return 10170 // extension method 10171 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 10172 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 10173 CLI.RetZExt == Args[i].IsZExt)) 10174 Flags.setReturned(); 10175 } 10176 10177 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 10178 CLI.CallConv, ExtendKind); 10179 10180 for (unsigned j = 0; j != NumParts; ++j) { 10181 // if it isn't first piece, alignment must be 1 10182 // For scalable vectors the scalable part is currently handled 10183 // by individual targets, so we just use the known minimum size here. 10184 ISD::OutputArg MyFlags( 10185 Flags, Parts[j].getValueType().getSimpleVT(), VT, 10186 i < CLI.NumFixedArgs, i, 10187 j * Parts[j].getValueType().getStoreSize().getKnownMinValue()); 10188 if (NumParts > 1 && j == 0) 10189 MyFlags.Flags.setSplit(); 10190 else if (j != 0) { 10191 MyFlags.Flags.setOrigAlign(Align(1)); 10192 if (j == NumParts - 1) 10193 MyFlags.Flags.setSplitEnd(); 10194 } 10195 10196 CLI.Outs.push_back(MyFlags); 10197 CLI.OutVals.push_back(Parts[j]); 10198 } 10199 10200 if (NeedsRegBlock && Value == NumValues - 1) 10201 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 10202 } 10203 } 10204 10205 SmallVector<SDValue, 4> InVals; 10206 CLI.Chain = LowerCall(CLI, InVals); 10207 10208 // Update CLI.InVals to use outside of this function. 10209 CLI.InVals = InVals; 10210 10211 // Verify that the target's LowerCall behaved as expected. 10212 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 10213 "LowerCall didn't return a valid chain!"); 10214 assert((!CLI.IsTailCall || InVals.empty()) && 10215 "LowerCall emitted a return value for a tail call!"); 10216 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 10217 "LowerCall didn't emit the correct number of values!"); 10218 10219 // For a tail call, the return value is merely live-out and there aren't 10220 // any nodes in the DAG representing it. Return a special value to 10221 // indicate that a tail call has been emitted and no more Instructions 10222 // should be processed in the current block. 10223 if (CLI.IsTailCall) { 10224 CLI.DAG.setRoot(CLI.Chain); 10225 return std::make_pair(SDValue(), SDValue()); 10226 } 10227 10228 #ifndef NDEBUG 10229 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 10230 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 10231 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 10232 "LowerCall emitted a value with the wrong type!"); 10233 } 10234 #endif 10235 10236 SmallVector<SDValue, 4> ReturnValues; 10237 if (!CanLowerReturn) { 10238 // The instruction result is the result of loading from the 10239 // hidden sret parameter. 10240 SmallVector<EVT, 1> PVTs; 10241 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 10242 10243 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 10244 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 10245 EVT PtrVT = PVTs[0]; 10246 10247 unsigned NumValues = RetTys.size(); 10248 ReturnValues.resize(NumValues); 10249 SmallVector<SDValue, 4> Chains(NumValues); 10250 10251 // An aggregate return value cannot wrap around the address space, so 10252 // offsets to its parts don't wrap either. 10253 SDNodeFlags Flags; 10254 Flags.setNoUnsignedWrap(true); 10255 10256 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10257 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 10258 for (unsigned i = 0; i < NumValues; ++i) { 10259 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 10260 CLI.DAG.getConstant(Offsets[i], CLI.DL, 10261 PtrVT), Flags); 10262 SDValue L = CLI.DAG.getLoad( 10263 RetTys[i], CLI.DL, CLI.Chain, Add, 10264 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 10265 DemoteStackIdx, Offsets[i]), 10266 HiddenSRetAlign); 10267 ReturnValues[i] = L; 10268 Chains[i] = L.getValue(1); 10269 } 10270 10271 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 10272 } else { 10273 // Collect the legal value parts into potentially illegal values 10274 // that correspond to the original function's return values. 10275 std::optional<ISD::NodeType> AssertOp; 10276 if (CLI.RetSExt) 10277 AssertOp = ISD::AssertSext; 10278 else if (CLI.RetZExt) 10279 AssertOp = ISD::AssertZext; 10280 unsigned CurReg = 0; 10281 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 10282 EVT VT = RetTys[I]; 10283 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10284 CLI.CallConv, VT); 10285 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10286 CLI.CallConv, VT); 10287 10288 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 10289 NumRegs, RegisterVT, VT, nullptr, 10290 CLI.CallConv, AssertOp)); 10291 CurReg += NumRegs; 10292 } 10293 10294 // For a function returning void, there is no return value. We can't create 10295 // such a node, so we just return a null return value in that case. In 10296 // that case, nothing will actually look at the value. 10297 if (ReturnValues.empty()) 10298 return std::make_pair(SDValue(), CLI.Chain); 10299 } 10300 10301 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 10302 CLI.DAG.getVTList(RetTys), ReturnValues); 10303 return std::make_pair(Res, CLI.Chain); 10304 } 10305 10306 /// Places new result values for the node in Results (their number 10307 /// and types must exactly match those of the original return values of 10308 /// the node), or leaves Results empty, which indicates that the node is not 10309 /// to be custom lowered after all. 10310 void TargetLowering::LowerOperationWrapper(SDNode *N, 10311 SmallVectorImpl<SDValue> &Results, 10312 SelectionDAG &DAG) const { 10313 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 10314 10315 if (!Res.getNode()) 10316 return; 10317 10318 // If the original node has one result, take the return value from 10319 // LowerOperation as is. It might not be result number 0. 10320 if (N->getNumValues() == 1) { 10321 Results.push_back(Res); 10322 return; 10323 } 10324 10325 // If the original node has multiple results, then the return node should 10326 // have the same number of results. 10327 assert((N->getNumValues() == Res->getNumValues()) && 10328 "Lowering returned the wrong number of results!"); 10329 10330 // Places new result values base on N result number. 10331 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 10332 Results.push_back(Res.getValue(I)); 10333 } 10334 10335 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10336 llvm_unreachable("LowerOperation not implemented for this target!"); 10337 } 10338 10339 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, 10340 unsigned Reg, 10341 ISD::NodeType ExtendType) { 10342 SDValue Op = getNonRegisterValue(V); 10343 assert((Op.getOpcode() != ISD::CopyFromReg || 10344 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 10345 "Copy from a reg to the same reg!"); 10346 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 10347 10348 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10349 // If this is an InlineAsm we have to match the registers required, not the 10350 // notional registers required by the type. 10351 10352 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 10353 std::nullopt); // This is not an ABI copy. 10354 SDValue Chain = DAG.getEntryNode(); 10355 10356 if (ExtendType == ISD::ANY_EXTEND) { 10357 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V); 10358 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end()) 10359 ExtendType = PreferredExtendIt->second; 10360 } 10361 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 10362 PendingExports.push_back(Chain); 10363 } 10364 10365 #include "llvm/CodeGen/SelectionDAGISel.h" 10366 10367 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 10368 /// entry block, return true. This includes arguments used by switches, since 10369 /// the switch may expand into multiple basic blocks. 10370 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 10371 // With FastISel active, we may be splitting blocks, so force creation 10372 // of virtual registers for all non-dead arguments. 10373 if (FastISel) 10374 return A->use_empty(); 10375 10376 const BasicBlock &Entry = A->getParent()->front(); 10377 for (const User *U : A->users()) 10378 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 10379 return false; // Use not in entry block. 10380 10381 return true; 10382 } 10383 10384 using ArgCopyElisionMapTy = 10385 DenseMap<const Argument *, 10386 std::pair<const AllocaInst *, const StoreInst *>>; 10387 10388 /// Scan the entry block of the function in FuncInfo for arguments that look 10389 /// like copies into a local alloca. Record any copied arguments in 10390 /// ArgCopyElisionCandidates. 10391 static void 10392 findArgumentCopyElisionCandidates(const DataLayout &DL, 10393 FunctionLoweringInfo *FuncInfo, 10394 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 10395 // Record the state of every static alloca used in the entry block. Argument 10396 // allocas are all used in the entry block, so we need approximately as many 10397 // entries as we have arguments. 10398 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 10399 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 10400 unsigned NumArgs = FuncInfo->Fn->arg_size(); 10401 StaticAllocas.reserve(NumArgs * 2); 10402 10403 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 10404 if (!V) 10405 return nullptr; 10406 V = V->stripPointerCasts(); 10407 const auto *AI = dyn_cast<AllocaInst>(V); 10408 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 10409 return nullptr; 10410 auto Iter = StaticAllocas.insert({AI, Unknown}); 10411 return &Iter.first->second; 10412 }; 10413 10414 // Look for stores of arguments to static allocas. Look through bitcasts and 10415 // GEPs to handle type coercions, as long as the alloca is fully initialized 10416 // by the store. Any non-store use of an alloca escapes it and any subsequent 10417 // unanalyzed store might write it. 10418 // FIXME: Handle structs initialized with multiple stores. 10419 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 10420 // Look for stores, and handle non-store uses conservatively. 10421 const auto *SI = dyn_cast<StoreInst>(&I); 10422 if (!SI) { 10423 // We will look through cast uses, so ignore them completely. 10424 if (I.isCast()) 10425 continue; 10426 // Ignore debug info and pseudo op intrinsics, they don't escape or store 10427 // to allocas. 10428 if (I.isDebugOrPseudoInst()) 10429 continue; 10430 // This is an unknown instruction. Assume it escapes or writes to all 10431 // static alloca operands. 10432 for (const Use &U : I.operands()) { 10433 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 10434 *Info = StaticAllocaInfo::Clobbered; 10435 } 10436 continue; 10437 } 10438 10439 // If the stored value is a static alloca, mark it as escaped. 10440 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 10441 *Info = StaticAllocaInfo::Clobbered; 10442 10443 // Check if the destination is a static alloca. 10444 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 10445 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 10446 if (!Info) 10447 continue; 10448 const AllocaInst *AI = cast<AllocaInst>(Dst); 10449 10450 // Skip allocas that have been initialized or clobbered. 10451 if (*Info != StaticAllocaInfo::Unknown) 10452 continue; 10453 10454 // Check if the stored value is an argument, and that this store fully 10455 // initializes the alloca. 10456 // If the argument type has padding bits we can't directly forward a pointer 10457 // as the upper bits may contain garbage. 10458 // Don't elide copies from the same argument twice. 10459 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 10460 const auto *Arg = dyn_cast<Argument>(Val); 10461 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 10462 Arg->getType()->isEmptyTy() || 10463 DL.getTypeStoreSize(Arg->getType()) != 10464 DL.getTypeAllocSize(AI->getAllocatedType()) || 10465 !DL.typeSizeEqualsStoreSize(Arg->getType()) || 10466 ArgCopyElisionCandidates.count(Arg)) { 10467 *Info = StaticAllocaInfo::Clobbered; 10468 continue; 10469 } 10470 10471 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 10472 << '\n'); 10473 10474 // Mark this alloca and store for argument copy elision. 10475 *Info = StaticAllocaInfo::Elidable; 10476 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 10477 10478 // Stop scanning if we've seen all arguments. This will happen early in -O0 10479 // builds, which is useful, because -O0 builds have large entry blocks and 10480 // many allocas. 10481 if (ArgCopyElisionCandidates.size() == NumArgs) 10482 break; 10483 } 10484 } 10485 10486 /// Try to elide argument copies from memory into a local alloca. Succeeds if 10487 /// ArgVal is a load from a suitable fixed stack object. 10488 static void tryToElideArgumentCopy( 10489 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 10490 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 10491 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 10492 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 10493 SDValue ArgVal, bool &ArgHasUses) { 10494 // Check if this is a load from a fixed stack object. 10495 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 10496 if (!LNode) 10497 return; 10498 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 10499 if (!FINode) 10500 return; 10501 10502 // Check that the fixed stack object is the right size and alignment. 10503 // Look at the alignment that the user wrote on the alloca instead of looking 10504 // at the stack object. 10505 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 10506 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 10507 const AllocaInst *AI = ArgCopyIter->second.first; 10508 int FixedIndex = FINode->getIndex(); 10509 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 10510 int OldIndex = AllocaIndex; 10511 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 10512 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 10513 LLVM_DEBUG( 10514 dbgs() << " argument copy elision failed due to bad fixed stack " 10515 "object size\n"); 10516 return; 10517 } 10518 Align RequiredAlignment = AI->getAlign(); 10519 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 10520 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 10521 "greater than stack argument alignment (" 10522 << DebugStr(RequiredAlignment) << " vs " 10523 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 10524 return; 10525 } 10526 10527 // Perform the elision. Delete the old stack object and replace its only use 10528 // in the variable info map. Mark the stack object as mutable. 10529 LLVM_DEBUG({ 10530 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 10531 << " Replacing frame index " << OldIndex << " with " << FixedIndex 10532 << '\n'; 10533 }); 10534 MFI.RemoveStackObject(OldIndex); 10535 MFI.setIsImmutableObjectIndex(FixedIndex, false); 10536 AllocaIndex = FixedIndex; 10537 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 10538 Chains.push_back(ArgVal.getValue(1)); 10539 10540 // Avoid emitting code for the store implementing the copy. 10541 const StoreInst *SI = ArgCopyIter->second.second; 10542 ElidedArgCopyInstrs.insert(SI); 10543 10544 // Check for uses of the argument again so that we can avoid exporting ArgVal 10545 // if it is't used by anything other than the store. 10546 for (const Value *U : Arg.users()) { 10547 if (U != SI) { 10548 ArgHasUses = true; 10549 break; 10550 } 10551 } 10552 } 10553 10554 void SelectionDAGISel::LowerArguments(const Function &F) { 10555 SelectionDAG &DAG = SDB->DAG; 10556 SDLoc dl = SDB->getCurSDLoc(); 10557 const DataLayout &DL = DAG.getDataLayout(); 10558 SmallVector<ISD::InputArg, 16> Ins; 10559 10560 // In Naked functions we aren't going to save any registers. 10561 if (F.hasFnAttribute(Attribute::Naked)) 10562 return; 10563 10564 if (!FuncInfo->CanLowerReturn) { 10565 // Put in an sret pointer parameter before all the other parameters. 10566 SmallVector<EVT, 1> ValueVTs; 10567 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10568 F.getReturnType()->getPointerTo( 10569 DAG.getDataLayout().getAllocaAddrSpace()), 10570 ValueVTs); 10571 10572 // NOTE: Assuming that a pointer will never break down to more than one VT 10573 // or one register. 10574 ISD::ArgFlagsTy Flags; 10575 Flags.setSRet(); 10576 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 10577 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 10578 ISD::InputArg::NoArgIndex, 0); 10579 Ins.push_back(RetArg); 10580 } 10581 10582 // Look for stores of arguments to static allocas. Mark such arguments with a 10583 // flag to ask the target to give us the memory location of that argument if 10584 // available. 10585 ArgCopyElisionMapTy ArgCopyElisionCandidates; 10586 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 10587 ArgCopyElisionCandidates); 10588 10589 // Set up the incoming argument description vector. 10590 for (const Argument &Arg : F.args()) { 10591 unsigned ArgNo = Arg.getArgNo(); 10592 SmallVector<EVT, 4> ValueVTs; 10593 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10594 bool isArgValueUsed = !Arg.use_empty(); 10595 unsigned PartBase = 0; 10596 Type *FinalType = Arg.getType(); 10597 if (Arg.hasAttribute(Attribute::ByVal)) 10598 FinalType = Arg.getParamByValType(); 10599 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 10600 FinalType, F.getCallingConv(), F.isVarArg(), DL); 10601 for (unsigned Value = 0, NumValues = ValueVTs.size(); 10602 Value != NumValues; ++Value) { 10603 EVT VT = ValueVTs[Value]; 10604 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 10605 ISD::ArgFlagsTy Flags; 10606 10607 10608 if (Arg.getType()->isPointerTy()) { 10609 Flags.setPointer(); 10610 Flags.setPointerAddrSpace( 10611 cast<PointerType>(Arg.getType())->getAddressSpace()); 10612 } 10613 if (Arg.hasAttribute(Attribute::ZExt)) 10614 Flags.setZExt(); 10615 if (Arg.hasAttribute(Attribute::SExt)) 10616 Flags.setSExt(); 10617 if (Arg.hasAttribute(Attribute::InReg)) { 10618 // If we are using vectorcall calling convention, a structure that is 10619 // passed InReg - is surely an HVA 10620 if (F.getCallingConv() == CallingConv::X86_VectorCall && 10621 isa<StructType>(Arg.getType())) { 10622 // The first value of a structure is marked 10623 if (0 == Value) 10624 Flags.setHvaStart(); 10625 Flags.setHva(); 10626 } 10627 // Set InReg Flag 10628 Flags.setInReg(); 10629 } 10630 if (Arg.hasAttribute(Attribute::StructRet)) 10631 Flags.setSRet(); 10632 if (Arg.hasAttribute(Attribute::SwiftSelf)) 10633 Flags.setSwiftSelf(); 10634 if (Arg.hasAttribute(Attribute::SwiftAsync)) 10635 Flags.setSwiftAsync(); 10636 if (Arg.hasAttribute(Attribute::SwiftError)) 10637 Flags.setSwiftError(); 10638 if (Arg.hasAttribute(Attribute::ByVal)) 10639 Flags.setByVal(); 10640 if (Arg.hasAttribute(Attribute::ByRef)) 10641 Flags.setByRef(); 10642 if (Arg.hasAttribute(Attribute::InAlloca)) { 10643 Flags.setInAlloca(); 10644 // Set the byval flag for CCAssignFn callbacks that don't know about 10645 // inalloca. This way we can know how many bytes we should've allocated 10646 // and how many bytes a callee cleanup function will pop. If we port 10647 // inalloca to more targets, we'll have to add custom inalloca handling 10648 // in the various CC lowering callbacks. 10649 Flags.setByVal(); 10650 } 10651 if (Arg.hasAttribute(Attribute::Preallocated)) { 10652 Flags.setPreallocated(); 10653 // Set the byval flag for CCAssignFn callbacks that don't know about 10654 // preallocated. This way we can know how many bytes we should've 10655 // allocated and how many bytes a callee cleanup function will pop. If 10656 // we port preallocated to more targets, we'll have to add custom 10657 // preallocated handling in the various CC lowering callbacks. 10658 Flags.setByVal(); 10659 } 10660 10661 // Certain targets (such as MIPS), may have a different ABI alignment 10662 // for a type depending on the context. Give the target a chance to 10663 // specify the alignment it wants. 10664 const Align OriginalAlignment( 10665 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 10666 Flags.setOrigAlign(OriginalAlignment); 10667 10668 Align MemAlign; 10669 Type *ArgMemTy = nullptr; 10670 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 10671 Flags.isByRef()) { 10672 if (!ArgMemTy) 10673 ArgMemTy = Arg.getPointeeInMemoryValueType(); 10674 10675 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 10676 10677 // For in-memory arguments, size and alignment should be passed from FE. 10678 // BE will guess if this info is not there but there are cases it cannot 10679 // get right. 10680 if (auto ParamAlign = Arg.getParamStackAlign()) 10681 MemAlign = *ParamAlign; 10682 else if ((ParamAlign = Arg.getParamAlign())) 10683 MemAlign = *ParamAlign; 10684 else 10685 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 10686 if (Flags.isByRef()) 10687 Flags.setByRefSize(MemSize); 10688 else 10689 Flags.setByValSize(MemSize); 10690 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 10691 MemAlign = *ParamAlign; 10692 } else { 10693 MemAlign = OriginalAlignment; 10694 } 10695 Flags.setMemAlign(MemAlign); 10696 10697 if (Arg.hasAttribute(Attribute::Nest)) 10698 Flags.setNest(); 10699 if (NeedsRegBlock) 10700 Flags.setInConsecutiveRegs(); 10701 if (ArgCopyElisionCandidates.count(&Arg)) 10702 Flags.setCopyElisionCandidate(); 10703 if (Arg.hasAttribute(Attribute::Returned)) 10704 Flags.setReturned(); 10705 10706 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 10707 *CurDAG->getContext(), F.getCallingConv(), VT); 10708 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 10709 *CurDAG->getContext(), F.getCallingConv(), VT); 10710 for (unsigned i = 0; i != NumRegs; ++i) { 10711 // For scalable vectors, use the minimum size; individual targets 10712 // are responsible for handling scalable vector arguments and 10713 // return values. 10714 ISD::InputArg MyFlags( 10715 Flags, RegisterVT, VT, isArgValueUsed, ArgNo, 10716 PartBase + i * RegisterVT.getStoreSize().getKnownMinValue()); 10717 if (NumRegs > 1 && i == 0) 10718 MyFlags.Flags.setSplit(); 10719 // if it isn't first piece, alignment must be 1 10720 else if (i > 0) { 10721 MyFlags.Flags.setOrigAlign(Align(1)); 10722 if (i == NumRegs - 1) 10723 MyFlags.Flags.setSplitEnd(); 10724 } 10725 Ins.push_back(MyFlags); 10726 } 10727 if (NeedsRegBlock && Value == NumValues - 1) 10728 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 10729 PartBase += VT.getStoreSize().getKnownMinValue(); 10730 } 10731 } 10732 10733 // Call the target to set up the argument values. 10734 SmallVector<SDValue, 8> InVals; 10735 SDValue NewRoot = TLI->LowerFormalArguments( 10736 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 10737 10738 // Verify that the target's LowerFormalArguments behaved as expected. 10739 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 10740 "LowerFormalArguments didn't return a valid chain!"); 10741 assert(InVals.size() == Ins.size() && 10742 "LowerFormalArguments didn't emit the correct number of values!"); 10743 LLVM_DEBUG({ 10744 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 10745 assert(InVals[i].getNode() && 10746 "LowerFormalArguments emitted a null value!"); 10747 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 10748 "LowerFormalArguments emitted a value with the wrong type!"); 10749 } 10750 }); 10751 10752 // Update the DAG with the new chain value resulting from argument lowering. 10753 DAG.setRoot(NewRoot); 10754 10755 // Set up the argument values. 10756 unsigned i = 0; 10757 if (!FuncInfo->CanLowerReturn) { 10758 // Create a virtual register for the sret pointer, and put in a copy 10759 // from the sret argument into it. 10760 SmallVector<EVT, 1> ValueVTs; 10761 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10762 F.getReturnType()->getPointerTo( 10763 DAG.getDataLayout().getAllocaAddrSpace()), 10764 ValueVTs); 10765 MVT VT = ValueVTs[0].getSimpleVT(); 10766 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 10767 std::optional<ISD::NodeType> AssertOp; 10768 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 10769 nullptr, F.getCallingConv(), AssertOp); 10770 10771 MachineFunction& MF = SDB->DAG.getMachineFunction(); 10772 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 10773 Register SRetReg = 10774 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 10775 FuncInfo->DemoteRegister = SRetReg; 10776 NewRoot = 10777 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 10778 DAG.setRoot(NewRoot); 10779 10780 // i indexes lowered arguments. Bump it past the hidden sret argument. 10781 ++i; 10782 } 10783 10784 SmallVector<SDValue, 4> Chains; 10785 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 10786 for (const Argument &Arg : F.args()) { 10787 SmallVector<SDValue, 4> ArgValues; 10788 SmallVector<EVT, 4> ValueVTs; 10789 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10790 unsigned NumValues = ValueVTs.size(); 10791 if (NumValues == 0) 10792 continue; 10793 10794 bool ArgHasUses = !Arg.use_empty(); 10795 10796 // Elide the copying store if the target loaded this argument from a 10797 // suitable fixed stack object. 10798 if (Ins[i].Flags.isCopyElisionCandidate()) { 10799 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 10800 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 10801 InVals[i], ArgHasUses); 10802 } 10803 10804 // If this argument is unused then remember its value. It is used to generate 10805 // debugging information. 10806 bool isSwiftErrorArg = 10807 TLI->supportSwiftError() && 10808 Arg.hasAttribute(Attribute::SwiftError); 10809 if (!ArgHasUses && !isSwiftErrorArg) { 10810 SDB->setUnusedArgValue(&Arg, InVals[i]); 10811 10812 // Also remember any frame index for use in FastISel. 10813 if (FrameIndexSDNode *FI = 10814 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 10815 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10816 } 10817 10818 for (unsigned Val = 0; Val != NumValues; ++Val) { 10819 EVT VT = ValueVTs[Val]; 10820 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 10821 F.getCallingConv(), VT); 10822 unsigned NumParts = TLI->getNumRegistersForCallingConv( 10823 *CurDAG->getContext(), F.getCallingConv(), VT); 10824 10825 // Even an apparent 'unused' swifterror argument needs to be returned. So 10826 // we do generate a copy for it that can be used on return from the 10827 // function. 10828 if (ArgHasUses || isSwiftErrorArg) { 10829 std::optional<ISD::NodeType> AssertOp; 10830 if (Arg.hasAttribute(Attribute::SExt)) 10831 AssertOp = ISD::AssertSext; 10832 else if (Arg.hasAttribute(Attribute::ZExt)) 10833 AssertOp = ISD::AssertZext; 10834 10835 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 10836 PartVT, VT, nullptr, 10837 F.getCallingConv(), AssertOp)); 10838 } 10839 10840 i += NumParts; 10841 } 10842 10843 // We don't need to do anything else for unused arguments. 10844 if (ArgValues.empty()) 10845 continue; 10846 10847 // Note down frame index. 10848 if (FrameIndexSDNode *FI = 10849 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 10850 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10851 10852 SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues), 10853 SDB->getCurSDLoc()); 10854 10855 SDB->setValue(&Arg, Res); 10856 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 10857 // We want to associate the argument with the frame index, among 10858 // involved operands, that correspond to the lowest address. The 10859 // getCopyFromParts function, called earlier, is swapping the order of 10860 // the operands to BUILD_PAIR depending on endianness. The result of 10861 // that swapping is that the least significant bits of the argument will 10862 // be in the first operand of the BUILD_PAIR node, and the most 10863 // significant bits will be in the second operand. 10864 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 10865 if (LoadSDNode *LNode = 10866 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 10867 if (FrameIndexSDNode *FI = 10868 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 10869 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10870 } 10871 10872 // Analyses past this point are naive and don't expect an assertion. 10873 if (Res.getOpcode() == ISD::AssertZext) 10874 Res = Res.getOperand(0); 10875 10876 // Update the SwiftErrorVRegDefMap. 10877 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 10878 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10879 if (Register::isVirtualRegister(Reg)) 10880 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 10881 Reg); 10882 } 10883 10884 // If this argument is live outside of the entry block, insert a copy from 10885 // wherever we got it to the vreg that other BB's will reference it as. 10886 if (Res.getOpcode() == ISD::CopyFromReg) { 10887 // If we can, though, try to skip creating an unnecessary vreg. 10888 // FIXME: This isn't very clean... it would be nice to make this more 10889 // general. 10890 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10891 if (Register::isVirtualRegister(Reg)) { 10892 FuncInfo->ValueMap[&Arg] = Reg; 10893 continue; 10894 } 10895 } 10896 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 10897 FuncInfo->InitializeRegForValue(&Arg); 10898 SDB->CopyToExportRegsIfNeeded(&Arg); 10899 } 10900 } 10901 10902 if (!Chains.empty()) { 10903 Chains.push_back(NewRoot); 10904 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 10905 } 10906 10907 DAG.setRoot(NewRoot); 10908 10909 assert(i == InVals.size() && "Argument register count mismatch!"); 10910 10911 // If any argument copy elisions occurred and we have debug info, update the 10912 // stale frame indices used in the dbg.declare variable info table. 10913 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 10914 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 10915 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 10916 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 10917 if (I != ArgCopyElisionFrameIndexMap.end()) 10918 VI.Slot = I->second; 10919 } 10920 } 10921 10922 // Finally, if the target has anything special to do, allow it to do so. 10923 emitFunctionEntryCode(); 10924 } 10925 10926 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 10927 /// ensure constants are generated when needed. Remember the virtual registers 10928 /// that need to be added to the Machine PHI nodes as input. We cannot just 10929 /// directly add them, because expansion might result in multiple MBB's for one 10930 /// BB. As such, the start of the BB might correspond to a different MBB than 10931 /// the end. 10932 void 10933 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 10934 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10935 10936 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 10937 10938 // Check PHI nodes in successors that expect a value to be available from this 10939 // block. 10940 for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) { 10941 if (!isa<PHINode>(SuccBB->begin())) continue; 10942 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 10943 10944 // If this terminator has multiple identical successors (common for 10945 // switches), only handle each succ once. 10946 if (!SuccsHandled.insert(SuccMBB).second) 10947 continue; 10948 10949 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 10950 10951 // At this point we know that there is a 1-1 correspondence between LLVM PHI 10952 // nodes and Machine PHI nodes, but the incoming operands have not been 10953 // emitted yet. 10954 for (const PHINode &PN : SuccBB->phis()) { 10955 // Ignore dead phi's. 10956 if (PN.use_empty()) 10957 continue; 10958 10959 // Skip empty types 10960 if (PN.getType()->isEmptyTy()) 10961 continue; 10962 10963 unsigned Reg; 10964 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 10965 10966 if (const auto *C = dyn_cast<Constant>(PHIOp)) { 10967 unsigned &RegOut = ConstantsOut[C]; 10968 if (RegOut == 0) { 10969 RegOut = FuncInfo.CreateRegs(C); 10970 // We need to zero/sign extend ConstantInt phi operands to match 10971 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo. 10972 ISD::NodeType ExtendType = ISD::ANY_EXTEND; 10973 if (auto *CI = dyn_cast<ConstantInt>(C)) 10974 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND 10975 : ISD::ZERO_EXTEND; 10976 CopyValueToVirtualRegister(C, RegOut, ExtendType); 10977 } 10978 Reg = RegOut; 10979 } else { 10980 DenseMap<const Value *, Register>::iterator I = 10981 FuncInfo.ValueMap.find(PHIOp); 10982 if (I != FuncInfo.ValueMap.end()) 10983 Reg = I->second; 10984 else { 10985 assert(isa<AllocaInst>(PHIOp) && 10986 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 10987 "Didn't codegen value into a register!??"); 10988 Reg = FuncInfo.CreateRegs(PHIOp); 10989 CopyValueToVirtualRegister(PHIOp, Reg); 10990 } 10991 } 10992 10993 // Remember that this register needs to added to the machine PHI node as 10994 // the input for this MBB. 10995 SmallVector<EVT, 4> ValueVTs; 10996 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 10997 for (EVT VT : ValueVTs) { 10998 const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 10999 for (unsigned i = 0; i != NumRegisters; ++i) 11000 FuncInfo.PHINodesToUpdate.push_back( 11001 std::make_pair(&*MBBI++, Reg + i)); 11002 Reg += NumRegisters; 11003 } 11004 } 11005 } 11006 11007 ConstantsOut.clear(); 11008 } 11009 11010 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 11011 MachineFunction::iterator I(MBB); 11012 if (++I == FuncInfo.MF->end()) 11013 return nullptr; 11014 return &*I; 11015 } 11016 11017 /// During lowering new call nodes can be created (such as memset, etc.). 11018 /// Those will become new roots of the current DAG, but complications arise 11019 /// when they are tail calls. In such cases, the call lowering will update 11020 /// the root, but the builder still needs to know that a tail call has been 11021 /// lowered in order to avoid generating an additional return. 11022 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 11023 // If the node is null, we do have a tail call. 11024 if (MaybeTC.getNode() != nullptr) 11025 DAG.setRoot(MaybeTC); 11026 else 11027 HasTailCall = true; 11028 } 11029 11030 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 11031 MachineBasicBlock *SwitchMBB, 11032 MachineBasicBlock *DefaultMBB) { 11033 MachineFunction *CurMF = FuncInfo.MF; 11034 MachineBasicBlock *NextMBB = nullptr; 11035 MachineFunction::iterator BBI(W.MBB); 11036 if (++BBI != FuncInfo.MF->end()) 11037 NextMBB = &*BBI; 11038 11039 unsigned Size = W.LastCluster - W.FirstCluster + 1; 11040 11041 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11042 11043 if (Size == 2 && W.MBB == SwitchMBB) { 11044 // If any two of the cases has the same destination, and if one value 11045 // is the same as the other, but has one bit unset that the other has set, 11046 // use bit manipulation to do two compares at once. For example: 11047 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 11048 // TODO: This could be extended to merge any 2 cases in switches with 3 11049 // cases. 11050 // TODO: Handle cases where W.CaseBB != SwitchBB. 11051 CaseCluster &Small = *W.FirstCluster; 11052 CaseCluster &Big = *W.LastCluster; 11053 11054 if (Small.Low == Small.High && Big.Low == Big.High && 11055 Small.MBB == Big.MBB) { 11056 const APInt &SmallValue = Small.Low->getValue(); 11057 const APInt &BigValue = Big.Low->getValue(); 11058 11059 // Check that there is only one bit different. 11060 APInt CommonBit = BigValue ^ SmallValue; 11061 if (CommonBit.isPowerOf2()) { 11062 SDValue CondLHS = getValue(Cond); 11063 EVT VT = CondLHS.getValueType(); 11064 SDLoc DL = getCurSDLoc(); 11065 11066 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 11067 DAG.getConstant(CommonBit, DL, VT)); 11068 SDValue Cond = DAG.getSetCC( 11069 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 11070 ISD::SETEQ); 11071 11072 // Update successor info. 11073 // Both Small and Big will jump to Small.BB, so we sum up the 11074 // probabilities. 11075 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 11076 if (BPI) 11077 addSuccessorWithProb( 11078 SwitchMBB, DefaultMBB, 11079 // The default destination is the first successor in IR. 11080 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 11081 else 11082 addSuccessorWithProb(SwitchMBB, DefaultMBB); 11083 11084 // Insert the true branch. 11085 SDValue BrCond = 11086 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 11087 DAG.getBasicBlock(Small.MBB)); 11088 // Insert the false branch. 11089 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 11090 DAG.getBasicBlock(DefaultMBB)); 11091 11092 DAG.setRoot(BrCond); 11093 return; 11094 } 11095 } 11096 } 11097 11098 if (TM.getOptLevel() != CodeGenOpt::None) { 11099 // Here, we order cases by probability so the most likely case will be 11100 // checked first. However, two clusters can have the same probability in 11101 // which case their relative ordering is non-deterministic. So we use Low 11102 // as a tie-breaker as clusters are guaranteed to never overlap. 11103 llvm::sort(W.FirstCluster, W.LastCluster + 1, 11104 [](const CaseCluster &a, const CaseCluster &b) { 11105 return a.Prob != b.Prob ? 11106 a.Prob > b.Prob : 11107 a.Low->getValue().slt(b.Low->getValue()); 11108 }); 11109 11110 // Rearrange the case blocks so that the last one falls through if possible 11111 // without changing the order of probabilities. 11112 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 11113 --I; 11114 if (I->Prob > W.LastCluster->Prob) 11115 break; 11116 if (I->Kind == CC_Range && I->MBB == NextMBB) { 11117 std::swap(*I, *W.LastCluster); 11118 break; 11119 } 11120 } 11121 } 11122 11123 // Compute total probability. 11124 BranchProbability DefaultProb = W.DefaultProb; 11125 BranchProbability UnhandledProbs = DefaultProb; 11126 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 11127 UnhandledProbs += I->Prob; 11128 11129 MachineBasicBlock *CurMBB = W.MBB; 11130 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 11131 bool FallthroughUnreachable = false; 11132 MachineBasicBlock *Fallthrough; 11133 if (I == W.LastCluster) { 11134 // For the last cluster, fall through to the default destination. 11135 Fallthrough = DefaultMBB; 11136 FallthroughUnreachable = isa<UnreachableInst>( 11137 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 11138 } else { 11139 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 11140 CurMF->insert(BBI, Fallthrough); 11141 // Put Cond in a virtual register to make it available from the new blocks. 11142 ExportFromCurrentBlock(Cond); 11143 } 11144 UnhandledProbs -= I->Prob; 11145 11146 switch (I->Kind) { 11147 case CC_JumpTable: { 11148 // FIXME: Optimize away range check based on pivot comparisons. 11149 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 11150 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 11151 11152 // The jump block hasn't been inserted yet; insert it here. 11153 MachineBasicBlock *JumpMBB = JT->MBB; 11154 CurMF->insert(BBI, JumpMBB); 11155 11156 auto JumpProb = I->Prob; 11157 auto FallthroughProb = UnhandledProbs; 11158 11159 // If the default statement is a target of the jump table, we evenly 11160 // distribute the default probability to successors of CurMBB. Also 11161 // update the probability on the edge from JumpMBB to Fallthrough. 11162 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 11163 SE = JumpMBB->succ_end(); 11164 SI != SE; ++SI) { 11165 if (*SI == DefaultMBB) { 11166 JumpProb += DefaultProb / 2; 11167 FallthroughProb -= DefaultProb / 2; 11168 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 11169 JumpMBB->normalizeSuccProbs(); 11170 break; 11171 } 11172 } 11173 11174 if (FallthroughUnreachable) 11175 JTH->FallthroughUnreachable = true; 11176 11177 if (!JTH->FallthroughUnreachable) 11178 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 11179 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 11180 CurMBB->normalizeSuccProbs(); 11181 11182 // The jump table header will be inserted in our current block, do the 11183 // range check, and fall through to our fallthrough block. 11184 JTH->HeaderBB = CurMBB; 11185 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 11186 11187 // If we're in the right place, emit the jump table header right now. 11188 if (CurMBB == SwitchMBB) { 11189 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 11190 JTH->Emitted = true; 11191 } 11192 break; 11193 } 11194 case CC_BitTests: { 11195 // FIXME: Optimize away range check based on pivot comparisons. 11196 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 11197 11198 // The bit test blocks haven't been inserted yet; insert them here. 11199 for (BitTestCase &BTC : BTB->Cases) 11200 CurMF->insert(BBI, BTC.ThisBB); 11201 11202 // Fill in fields of the BitTestBlock. 11203 BTB->Parent = CurMBB; 11204 BTB->Default = Fallthrough; 11205 11206 BTB->DefaultProb = UnhandledProbs; 11207 // If the cases in bit test don't form a contiguous range, we evenly 11208 // distribute the probability on the edge to Fallthrough to two 11209 // successors of CurMBB. 11210 if (!BTB->ContiguousRange) { 11211 BTB->Prob += DefaultProb / 2; 11212 BTB->DefaultProb -= DefaultProb / 2; 11213 } 11214 11215 if (FallthroughUnreachable) 11216 BTB->FallthroughUnreachable = true; 11217 11218 // If we're in the right place, emit the bit test header right now. 11219 if (CurMBB == SwitchMBB) { 11220 visitBitTestHeader(*BTB, SwitchMBB); 11221 BTB->Emitted = true; 11222 } 11223 break; 11224 } 11225 case CC_Range: { 11226 const Value *RHS, *LHS, *MHS; 11227 ISD::CondCode CC; 11228 if (I->Low == I->High) { 11229 // Check Cond == I->Low. 11230 CC = ISD::SETEQ; 11231 LHS = Cond; 11232 RHS=I->Low; 11233 MHS = nullptr; 11234 } else { 11235 // Check I->Low <= Cond <= I->High. 11236 CC = ISD::SETLE; 11237 LHS = I->Low; 11238 MHS = Cond; 11239 RHS = I->High; 11240 } 11241 11242 // If Fallthrough is unreachable, fold away the comparison. 11243 if (FallthroughUnreachable) 11244 CC = ISD::SETTRUE; 11245 11246 // The false probability is the sum of all unhandled cases. 11247 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 11248 getCurSDLoc(), I->Prob, UnhandledProbs); 11249 11250 if (CurMBB == SwitchMBB) 11251 visitSwitchCase(CB, SwitchMBB); 11252 else 11253 SL->SwitchCases.push_back(CB); 11254 11255 break; 11256 } 11257 } 11258 CurMBB = Fallthrough; 11259 } 11260 } 11261 11262 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 11263 CaseClusterIt First, 11264 CaseClusterIt Last) { 11265 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 11266 if (X.Prob != CC.Prob) 11267 return X.Prob > CC.Prob; 11268 11269 // Ties are broken by comparing the case value. 11270 return X.Low->getValue().slt(CC.Low->getValue()); 11271 }); 11272 } 11273 11274 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 11275 const SwitchWorkListItem &W, 11276 Value *Cond, 11277 MachineBasicBlock *SwitchMBB) { 11278 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 11279 "Clusters not sorted?"); 11280 11281 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 11282 11283 // Balance the tree based on branch probabilities to create a near-optimal (in 11284 // terms of search time given key frequency) binary search tree. See e.g. Kurt 11285 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 11286 CaseClusterIt LastLeft = W.FirstCluster; 11287 CaseClusterIt FirstRight = W.LastCluster; 11288 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 11289 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 11290 11291 // Move LastLeft and FirstRight towards each other from opposite directions to 11292 // find a partitioning of the clusters which balances the probability on both 11293 // sides. If LeftProb and RightProb are equal, alternate which side is 11294 // taken to ensure 0-probability nodes are distributed evenly. 11295 unsigned I = 0; 11296 while (LastLeft + 1 < FirstRight) { 11297 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 11298 LeftProb += (++LastLeft)->Prob; 11299 else 11300 RightProb += (--FirstRight)->Prob; 11301 I++; 11302 } 11303 11304 while (true) { 11305 // Our binary search tree differs from a typical BST in that ours can have up 11306 // to three values in each leaf. The pivot selection above doesn't take that 11307 // into account, which means the tree might require more nodes and be less 11308 // efficient. We compensate for this here. 11309 11310 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 11311 unsigned NumRight = W.LastCluster - FirstRight + 1; 11312 11313 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 11314 // If one side has less than 3 clusters, and the other has more than 3, 11315 // consider taking a cluster from the other side. 11316 11317 if (NumLeft < NumRight) { 11318 // Consider moving the first cluster on the right to the left side. 11319 CaseCluster &CC = *FirstRight; 11320 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11321 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11322 if (LeftSideRank <= RightSideRank) { 11323 // Moving the cluster to the left does not demote it. 11324 ++LastLeft; 11325 ++FirstRight; 11326 continue; 11327 } 11328 } else { 11329 assert(NumRight < NumLeft); 11330 // Consider moving the last element on the left to the right side. 11331 CaseCluster &CC = *LastLeft; 11332 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11333 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11334 if (RightSideRank <= LeftSideRank) { 11335 // Moving the cluster to the right does not demot it. 11336 --LastLeft; 11337 --FirstRight; 11338 continue; 11339 } 11340 } 11341 } 11342 break; 11343 } 11344 11345 assert(LastLeft + 1 == FirstRight); 11346 assert(LastLeft >= W.FirstCluster); 11347 assert(FirstRight <= W.LastCluster); 11348 11349 // Use the first element on the right as pivot since we will make less-than 11350 // comparisons against it. 11351 CaseClusterIt PivotCluster = FirstRight; 11352 assert(PivotCluster > W.FirstCluster); 11353 assert(PivotCluster <= W.LastCluster); 11354 11355 CaseClusterIt FirstLeft = W.FirstCluster; 11356 CaseClusterIt LastRight = W.LastCluster; 11357 11358 const ConstantInt *Pivot = PivotCluster->Low; 11359 11360 // New blocks will be inserted immediately after the current one. 11361 MachineFunction::iterator BBI(W.MBB); 11362 ++BBI; 11363 11364 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 11365 // we can branch to its destination directly if it's squeezed exactly in 11366 // between the known lower bound and Pivot - 1. 11367 MachineBasicBlock *LeftMBB; 11368 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 11369 FirstLeft->Low == W.GE && 11370 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 11371 LeftMBB = FirstLeft->MBB; 11372 } else { 11373 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11374 FuncInfo.MF->insert(BBI, LeftMBB); 11375 WorkList.push_back( 11376 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 11377 // Put Cond in a virtual register to make it available from the new blocks. 11378 ExportFromCurrentBlock(Cond); 11379 } 11380 11381 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 11382 // single cluster, RHS.Low == Pivot, and we can branch to its destination 11383 // directly if RHS.High equals the current upper bound. 11384 MachineBasicBlock *RightMBB; 11385 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 11386 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 11387 RightMBB = FirstRight->MBB; 11388 } else { 11389 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11390 FuncInfo.MF->insert(BBI, RightMBB); 11391 WorkList.push_back( 11392 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 11393 // Put Cond in a virtual register to make it available from the new blocks. 11394 ExportFromCurrentBlock(Cond); 11395 } 11396 11397 // Create the CaseBlock record that will be used to lower the branch. 11398 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 11399 getCurSDLoc(), LeftProb, RightProb); 11400 11401 if (W.MBB == SwitchMBB) 11402 visitSwitchCase(CB, SwitchMBB); 11403 else 11404 SL->SwitchCases.push_back(CB); 11405 } 11406 11407 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 11408 // from the swith statement. 11409 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 11410 BranchProbability PeeledCaseProb) { 11411 if (PeeledCaseProb == BranchProbability::getOne()) 11412 return BranchProbability::getZero(); 11413 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 11414 11415 uint32_t Numerator = CaseProb.getNumerator(); 11416 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 11417 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 11418 } 11419 11420 // Try to peel the top probability case if it exceeds the threshold. 11421 // Return current MachineBasicBlock for the switch statement if the peeling 11422 // does not occur. 11423 // If the peeling is performed, return the newly created MachineBasicBlock 11424 // for the peeled switch statement. Also update Clusters to remove the peeled 11425 // case. PeeledCaseProb is the BranchProbability for the peeled case. 11426 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 11427 const SwitchInst &SI, CaseClusterVector &Clusters, 11428 BranchProbability &PeeledCaseProb) { 11429 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11430 // Don't perform if there is only one cluster or optimizing for size. 11431 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 11432 TM.getOptLevel() == CodeGenOpt::None || 11433 SwitchMBB->getParent()->getFunction().hasMinSize()) 11434 return SwitchMBB; 11435 11436 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 11437 unsigned PeeledCaseIndex = 0; 11438 bool SwitchPeeled = false; 11439 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 11440 CaseCluster &CC = Clusters[Index]; 11441 if (CC.Prob < TopCaseProb) 11442 continue; 11443 TopCaseProb = CC.Prob; 11444 PeeledCaseIndex = Index; 11445 SwitchPeeled = true; 11446 } 11447 if (!SwitchPeeled) 11448 return SwitchMBB; 11449 11450 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 11451 << TopCaseProb << "\n"); 11452 11453 // Record the MBB for the peeled switch statement. 11454 MachineFunction::iterator BBI(SwitchMBB); 11455 ++BBI; 11456 MachineBasicBlock *PeeledSwitchMBB = 11457 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 11458 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 11459 11460 ExportFromCurrentBlock(SI.getCondition()); 11461 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 11462 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 11463 nullptr, nullptr, TopCaseProb.getCompl()}; 11464 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 11465 11466 Clusters.erase(PeeledCaseIt); 11467 for (CaseCluster &CC : Clusters) { 11468 LLVM_DEBUG( 11469 dbgs() << "Scale the probablity for one cluster, before scaling: " 11470 << CC.Prob << "\n"); 11471 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 11472 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 11473 } 11474 PeeledCaseProb = TopCaseProb; 11475 return PeeledSwitchMBB; 11476 } 11477 11478 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 11479 // Extract cases from the switch. 11480 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11481 CaseClusterVector Clusters; 11482 Clusters.reserve(SI.getNumCases()); 11483 for (auto I : SI.cases()) { 11484 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 11485 const ConstantInt *CaseVal = I.getCaseValue(); 11486 BranchProbability Prob = 11487 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 11488 : BranchProbability(1, SI.getNumCases() + 1); 11489 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 11490 } 11491 11492 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 11493 11494 // Cluster adjacent cases with the same destination. We do this at all 11495 // optimization levels because it's cheap to do and will make codegen faster 11496 // if there are many clusters. 11497 sortAndRangeify(Clusters); 11498 11499 // The branch probablity of the peeled case. 11500 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 11501 MachineBasicBlock *PeeledSwitchMBB = 11502 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 11503 11504 // If there is only the default destination, jump there directly. 11505 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11506 if (Clusters.empty()) { 11507 assert(PeeledSwitchMBB == SwitchMBB); 11508 SwitchMBB->addSuccessor(DefaultMBB); 11509 if (DefaultMBB != NextBlock(SwitchMBB)) { 11510 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 11511 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 11512 } 11513 return; 11514 } 11515 11516 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 11517 SL->findBitTestClusters(Clusters, &SI); 11518 11519 LLVM_DEBUG({ 11520 dbgs() << "Case clusters: "; 11521 for (const CaseCluster &C : Clusters) { 11522 if (C.Kind == CC_JumpTable) 11523 dbgs() << "JT:"; 11524 if (C.Kind == CC_BitTests) 11525 dbgs() << "BT:"; 11526 11527 C.Low->getValue().print(dbgs(), true); 11528 if (C.Low != C.High) { 11529 dbgs() << '-'; 11530 C.High->getValue().print(dbgs(), true); 11531 } 11532 dbgs() << ' '; 11533 } 11534 dbgs() << '\n'; 11535 }); 11536 11537 assert(!Clusters.empty()); 11538 SwitchWorkList WorkList; 11539 CaseClusterIt First = Clusters.begin(); 11540 CaseClusterIt Last = Clusters.end() - 1; 11541 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 11542 // Scale the branchprobability for DefaultMBB if the peel occurs and 11543 // DefaultMBB is not replaced. 11544 if (PeeledCaseProb != BranchProbability::getZero() && 11545 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 11546 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 11547 WorkList.push_back( 11548 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 11549 11550 while (!WorkList.empty()) { 11551 SwitchWorkListItem W = WorkList.pop_back_val(); 11552 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 11553 11554 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 11555 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 11556 // For optimized builds, lower large range as a balanced binary tree. 11557 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 11558 continue; 11559 } 11560 11561 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 11562 } 11563 } 11564 11565 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 11566 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11567 auto DL = getCurSDLoc(); 11568 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11569 setValue(&I, DAG.getStepVector(DL, ResultVT)); 11570 } 11571 11572 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 11573 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11574 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11575 11576 SDLoc DL = getCurSDLoc(); 11577 SDValue V = getValue(I.getOperand(0)); 11578 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 11579 11580 if (VT.isScalableVector()) { 11581 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 11582 return; 11583 } 11584 11585 // Use VECTOR_SHUFFLE for the fixed-length vector 11586 // to maintain existing behavior. 11587 SmallVector<int, 8> Mask; 11588 unsigned NumElts = VT.getVectorMinNumElements(); 11589 for (unsigned i = 0; i != NumElts; ++i) 11590 Mask.push_back(NumElts - 1 - i); 11591 11592 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 11593 } 11594 11595 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) { 11596 auto DL = getCurSDLoc(); 11597 SDValue InVec = getValue(I.getOperand(0)); 11598 EVT OutVT = 11599 InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 11600 11601 unsigned OutNumElts = OutVT.getVectorMinNumElements(); 11602 11603 // ISD Node needs the input vectors split into two equal parts 11604 SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 11605 DAG.getVectorIdxConstant(0, DL)); 11606 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 11607 DAG.getVectorIdxConstant(OutNumElts, DL)); 11608 11609 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 11610 // legalisation and combines. 11611 if (OutVT.isFixedLengthVector()) { 11612 SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 11613 createStrideMask(0, 2, OutNumElts)); 11614 SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 11615 createStrideMask(1, 2, OutNumElts)); 11616 SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc()); 11617 setValue(&I, Res); 11618 return; 11619 } 11620 11621 SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL, 11622 DAG.getVTList(OutVT, OutVT), Lo, Hi); 11623 setValue(&I, Res); 11624 } 11625 11626 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) { 11627 auto DL = getCurSDLoc(); 11628 EVT InVT = getValue(I.getOperand(0)).getValueType(); 11629 SDValue InVec0 = getValue(I.getOperand(0)); 11630 SDValue InVec1 = getValue(I.getOperand(1)); 11631 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11632 EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11633 11634 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 11635 // legalisation and combines. 11636 if (OutVT.isFixedLengthVector()) { 11637 unsigned NumElts = InVT.getVectorMinNumElements(); 11638 SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1); 11639 setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT), 11640 createInterleaveMask(NumElts, 2))); 11641 return; 11642 } 11643 11644 SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, 11645 DAG.getVTList(InVT, InVT), InVec0, InVec1); 11646 Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0), 11647 Res.getValue(1)); 11648 setValue(&I, Res); 11649 } 11650 11651 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 11652 SmallVector<EVT, 4> ValueVTs; 11653 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 11654 ValueVTs); 11655 unsigned NumValues = ValueVTs.size(); 11656 if (NumValues == 0) return; 11657 11658 SmallVector<SDValue, 4> Values(NumValues); 11659 SDValue Op = getValue(I.getOperand(0)); 11660 11661 for (unsigned i = 0; i != NumValues; ++i) 11662 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 11663 SDValue(Op.getNode(), Op.getResNo() + i)); 11664 11665 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 11666 DAG.getVTList(ValueVTs), Values)); 11667 } 11668 11669 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 11670 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11671 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11672 11673 SDLoc DL = getCurSDLoc(); 11674 SDValue V1 = getValue(I.getOperand(0)); 11675 SDValue V2 = getValue(I.getOperand(1)); 11676 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 11677 11678 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 11679 if (VT.isScalableVector()) { 11680 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 11681 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 11682 DAG.getConstant(Imm, DL, IdxVT))); 11683 return; 11684 } 11685 11686 unsigned NumElts = VT.getVectorNumElements(); 11687 11688 uint64_t Idx = (NumElts + Imm) % NumElts; 11689 11690 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 11691 SmallVector<int, 8> Mask; 11692 for (unsigned i = 0; i < NumElts; ++i) 11693 Mask.push_back(Idx + i); 11694 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 11695 } 11696 11697 // Consider the following MIR after SelectionDAG, which produces output in 11698 // phyregs in the first case or virtregs in the second case. 11699 // 11700 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx 11701 // %5:gr32 = COPY $ebx 11702 // %6:gr32 = COPY $edx 11703 // %1:gr32 = COPY %6:gr32 11704 // %0:gr32 = COPY %5:gr32 11705 // 11706 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32 11707 // %1:gr32 = COPY %6:gr32 11708 // %0:gr32 = COPY %5:gr32 11709 // 11710 // Given %0, we'd like to return $ebx in the first case and %5 in the second. 11711 // Given %1, we'd like to return $edx in the first case and %6 in the second. 11712 // 11713 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap 11714 // to a single virtreg (such as %0). The remaining outputs monotonically 11715 // increase in virtreg number from there. If a callbr has no outputs, then it 11716 // should not have a corresponding callbr landingpad; in fact, the callbr 11717 // landingpad would not even be able to refer to such a callbr. 11718 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) { 11719 MachineInstr *MI = MRI.def_begin(Reg)->getParent(); 11720 // There is definitely at least one copy. 11721 assert(MI->getOpcode() == TargetOpcode::COPY && 11722 "start of copy chain MUST be COPY"); 11723 Reg = MI->getOperand(1).getReg(); 11724 MI = MRI.def_begin(Reg)->getParent(); 11725 // There may be an optional second copy. 11726 if (MI->getOpcode() == TargetOpcode::COPY) { 11727 assert(Reg.isVirtual() && "expected COPY of virtual register"); 11728 Reg = MI->getOperand(1).getReg(); 11729 assert(Reg.isPhysical() && "expected COPY of physical register"); 11730 MI = MRI.def_begin(Reg)->getParent(); 11731 } 11732 // The start of the chain must be an INLINEASM_BR. 11733 assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR && 11734 "end of copy chain MUST be INLINEASM_BR"); 11735 return Reg; 11736 } 11737 11738 // We must do this walk rather than the simpler 11739 // setValue(&I, getCopyFromRegs(CBR, CBR->getType())); 11740 // otherwise we will end up with copies of virtregs only valid along direct 11741 // edges. 11742 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) { 11743 SmallVector<EVT, 8> ResultVTs; 11744 SmallVector<SDValue, 8> ResultValues; 11745 const auto *CBR = 11746 cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator()); 11747 11748 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11749 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 11750 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11751 11752 unsigned InitialDef = FuncInfo.ValueMap[CBR]; 11753 SDValue Chain = DAG.getRoot(); 11754 11755 // Re-parse the asm constraints string. 11756 TargetLowering::AsmOperandInfoVector TargetConstraints = 11757 TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR); 11758 for (auto &T : TargetConstraints) { 11759 SDISelAsmOperandInfo OpInfo(T); 11760 if (OpInfo.Type != InlineAsm::isOutput) 11761 continue; 11762 11763 // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the 11764 // individual constraint. 11765 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 11766 11767 switch (OpInfo.ConstraintType) { 11768 case TargetLowering::C_Register: 11769 case TargetLowering::C_RegisterClass: { 11770 // Fill in OpInfo.AssignedRegs.Regs. 11771 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo); 11772 11773 // getRegistersForValue may produce 1 to many registers based on whether 11774 // the OpInfo.ConstraintVT is legal on the target or not. 11775 for (size_t i = 0, e = OpInfo.AssignedRegs.Regs.size(); i != e; ++i) { 11776 Register OriginalDef = FollowCopyChain(MRI, InitialDef++); 11777 if (Register::isPhysicalRegister(OriginalDef)) 11778 FuncInfo.MBB->addLiveIn(OriginalDef); 11779 // Update the assigned registers to use the original defs. 11780 OpInfo.AssignedRegs.Regs[i] = OriginalDef; 11781 } 11782 11783 SDValue V = OpInfo.AssignedRegs.getCopyFromRegs( 11784 DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR); 11785 ResultValues.push_back(V); 11786 ResultVTs.push_back(OpInfo.ConstraintVT); 11787 break; 11788 } 11789 case TargetLowering::C_Other: { 11790 SDValue Flag; 11791 SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 11792 OpInfo, DAG); 11793 ++InitialDef; 11794 ResultValues.push_back(V); 11795 ResultVTs.push_back(OpInfo.ConstraintVT); 11796 break; 11797 } 11798 default: 11799 break; 11800 } 11801 } 11802 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 11803 DAG.getVTList(ResultVTs), ResultValues); 11804 setValue(&I, V); 11805 } 11806