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 // Get the exponent as a positive value. 5463 if (Val < 0) 5464 Val = -Val; 5465 // We use the simple binary decomposition method to generate the multiply 5466 // sequence. There are more optimal ways to do this (for example, 5467 // powi(x,15) generates one more multiply than it should), but this has 5468 // the benefit of being both really simple and much better than a libcall. 5469 SDValue Res; // Logically starts equal to 1.0 5470 SDValue CurSquare = LHS; 5471 // TODO: Intrinsics should have fast-math-flags that propagate to these 5472 // nodes. 5473 while (Val) { 5474 if (Val & 1) { 5475 if (Res.getNode()) 5476 Res = 5477 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare); 5478 else 5479 Res = CurSquare; // 1.0*CurSquare. 5480 } 5481 5482 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5483 CurSquare, CurSquare); 5484 Val >>= 1; 5485 } 5486 5487 // If the original was negative, invert the result, producing 1/(x*x*x). 5488 if (RHSC->getSExtValue() < 0) 5489 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5490 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5491 return Res; 5492 } 5493 } 5494 5495 // Otherwise, expand to a libcall. 5496 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5497 } 5498 5499 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5500 SDValue LHS, SDValue RHS, SDValue Scale, 5501 SelectionDAG &DAG, const TargetLowering &TLI) { 5502 EVT VT = LHS.getValueType(); 5503 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5504 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5505 LLVMContext &Ctx = *DAG.getContext(); 5506 5507 // If the type is legal but the operation isn't, this node might survive all 5508 // the way to operation legalization. If we end up there and we do not have 5509 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5510 // node. 5511 5512 // Coax the legalizer into expanding the node during type legalization instead 5513 // by bumping the size by one bit. This will force it to Promote, enabling the 5514 // early expansion and avoiding the need to expand later. 5515 5516 // We don't have to do this if Scale is 0; that can always be expanded, unless 5517 // it's a saturating signed operation. Those can experience true integer 5518 // division overflow, a case which we must avoid. 5519 5520 // FIXME: We wouldn't have to do this (or any of the early 5521 // expansion/promotion) if it was possible to expand a libcall of an 5522 // illegal type during operation legalization. But it's not, so things 5523 // get a bit hacky. 5524 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5525 if ((ScaleInt > 0 || (Saturating && Signed)) && 5526 (TLI.isTypeLegal(VT) || 5527 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5528 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5529 Opcode, VT, ScaleInt); 5530 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5531 EVT PromVT; 5532 if (VT.isScalarInteger()) 5533 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5534 else if (VT.isVector()) { 5535 PromVT = VT.getVectorElementType(); 5536 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5537 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5538 } else 5539 llvm_unreachable("Wrong VT for DIVFIX?"); 5540 if (Signed) { 5541 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5542 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5543 } else { 5544 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5545 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5546 } 5547 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5548 // For saturating operations, we need to shift up the LHS to get the 5549 // proper saturation width, and then shift down again afterwards. 5550 if (Saturating) 5551 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5552 DAG.getConstant(1, DL, ShiftTy)); 5553 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5554 if (Saturating) 5555 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5556 DAG.getConstant(1, DL, ShiftTy)); 5557 return DAG.getZExtOrTrunc(Res, DL, VT); 5558 } 5559 } 5560 5561 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5562 } 5563 5564 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5565 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5566 static void 5567 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5568 const SDValue &N) { 5569 switch (N.getOpcode()) { 5570 case ISD::CopyFromReg: { 5571 SDValue Op = N.getOperand(1); 5572 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5573 Op.getValueType().getSizeInBits()); 5574 return; 5575 } 5576 case ISD::BITCAST: 5577 case ISD::AssertZext: 5578 case ISD::AssertSext: 5579 case ISD::TRUNCATE: 5580 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5581 return; 5582 case ISD::BUILD_PAIR: 5583 case ISD::BUILD_VECTOR: 5584 case ISD::CONCAT_VECTORS: 5585 for (SDValue Op : N->op_values()) 5586 getUnderlyingArgRegs(Regs, Op); 5587 return; 5588 default: 5589 return; 5590 } 5591 } 5592 5593 /// If the DbgValueInst is a dbg_value of a function argument, create the 5594 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5595 /// instruction selection, they will be inserted to the entry BB. 5596 /// We don't currently support this for variadic dbg_values, as they shouldn't 5597 /// appear for function arguments or in the prologue. 5598 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5599 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5600 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) { 5601 const Argument *Arg = dyn_cast<Argument>(V); 5602 if (!Arg) 5603 return false; 5604 5605 MachineFunction &MF = DAG.getMachineFunction(); 5606 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5607 5608 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind 5609 // we've been asked to pursue. 5610 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr, 5611 bool Indirect) { 5612 if (Reg.isVirtual() && MF.useDebugInstrRef()) { 5613 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF 5614 // pointing at the VReg, which will be patched up later. 5615 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF); 5616 SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg( 5617 /* Reg */ Reg, /* isDef */ false, /* isImp */ false, 5618 /* isKill */ false, /* isDead */ false, 5619 /* isUndef */ false, /* isEarlyClobber */ false, 5620 /* SubReg */ 0, /* isDebug */ true)}); 5621 5622 auto *NewDIExpr = FragExpr; 5623 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into 5624 // the DIExpression. 5625 if (Indirect) 5626 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore); 5627 SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0}); 5628 NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops); 5629 return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr); 5630 } else { 5631 // Create a completely standard DBG_VALUE. 5632 auto &Inst = TII->get(TargetOpcode::DBG_VALUE); 5633 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr); 5634 } 5635 }; 5636 5637 if (Kind == FuncArgumentDbgValueKind::Value) { 5638 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5639 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5640 // the entry block. 5641 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5642 if (!IsInEntryBlock) 5643 return false; 5644 5645 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5646 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5647 // variable that also is a param. 5648 // 5649 // Although, if we are at the top of the entry block already, we can still 5650 // emit using ArgDbgValue. This might catch some situations when the 5651 // dbg.value refers to an argument that isn't used in the entry block, so 5652 // any CopyToReg node would be optimized out and the only way to express 5653 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5654 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5655 // we should only emit as ArgDbgValue if the Variable is an argument to the 5656 // current function, and the dbg.value intrinsic is found in the entry 5657 // block. 5658 bool VariableIsFunctionInputArg = Variable->isParameter() && 5659 !DL->getInlinedAt(); 5660 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5661 if (!IsInPrologue && !VariableIsFunctionInputArg) 5662 return false; 5663 5664 // Here we assume that a function argument on IR level only can be used to 5665 // describe one input parameter on source level. If we for example have 5666 // source code like this 5667 // 5668 // struct A { long x, y; }; 5669 // void foo(struct A a, long b) { 5670 // ... 5671 // b = a.x; 5672 // ... 5673 // } 5674 // 5675 // and IR like this 5676 // 5677 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5678 // entry: 5679 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5680 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5681 // call void @llvm.dbg.value(metadata i32 %b, "b", 5682 // ... 5683 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5684 // ... 5685 // 5686 // then the last dbg.value is describing a parameter "b" using a value that 5687 // is an argument. But since we already has used %a1 to describe a parameter 5688 // we should not handle that last dbg.value here (that would result in an 5689 // incorrect hoisting of the DBG_VALUE to the function entry). 5690 // Notice that we allow one dbg.value per IR level argument, to accommodate 5691 // for the situation with fragments above. 5692 if (VariableIsFunctionInputArg) { 5693 unsigned ArgNo = Arg->getArgNo(); 5694 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5695 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5696 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5697 return false; 5698 FuncInfo.DescribedArgs.set(ArgNo); 5699 } 5700 } 5701 5702 bool IsIndirect = false; 5703 std::optional<MachineOperand> Op; 5704 // Some arguments' frame index is recorded during argument lowering. 5705 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5706 if (FI != std::numeric_limits<int>::max()) 5707 Op = MachineOperand::CreateFI(FI); 5708 5709 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 5710 if (!Op && N.getNode()) { 5711 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5712 Register Reg; 5713 if (ArgRegsAndSizes.size() == 1) 5714 Reg = ArgRegsAndSizes.front().first; 5715 5716 if (Reg && Reg.isVirtual()) { 5717 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5718 Register PR = RegInfo.getLiveInPhysReg(Reg); 5719 if (PR) 5720 Reg = PR; 5721 } 5722 if (Reg) { 5723 Op = MachineOperand::CreateReg(Reg, false); 5724 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5725 } 5726 } 5727 5728 if (!Op && N.getNode()) { 5729 // Check if frame index is available. 5730 SDValue LCandidate = peekThroughBitcasts(N); 5731 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5732 if (FrameIndexSDNode *FINode = 5733 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5734 Op = MachineOperand::CreateFI(FINode->getIndex()); 5735 } 5736 5737 if (!Op) { 5738 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5739 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 5740 SplitRegs) { 5741 unsigned Offset = 0; 5742 for (const auto &RegAndSize : SplitRegs) { 5743 // If the expression is already a fragment, the current register 5744 // offset+size might extend beyond the fragment. In this case, only 5745 // the register bits that are inside the fragment are relevant. 5746 int RegFragmentSizeInBits = RegAndSize.second; 5747 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5748 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5749 // The register is entirely outside the expression fragment, 5750 // so is irrelevant for debug info. 5751 if (Offset >= ExprFragmentSizeInBits) 5752 break; 5753 // The register is partially outside the expression fragment, only 5754 // the low bits within the fragment are relevant for debug info. 5755 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5756 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5757 } 5758 } 5759 5760 auto FragmentExpr = DIExpression::createFragmentExpression( 5761 Expr, Offset, RegFragmentSizeInBits); 5762 Offset += RegAndSize.second; 5763 // If a valid fragment expression cannot be created, the variable's 5764 // correct value cannot be determined and so it is set as Undef. 5765 if (!FragmentExpr) { 5766 SDDbgValue *SDV = DAG.getConstantDbgValue( 5767 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5768 DAG.AddDbgValue(SDV, false); 5769 continue; 5770 } 5771 MachineInstr *NewMI = 5772 MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, 5773 Kind != FuncArgumentDbgValueKind::Value); 5774 FuncInfo.ArgDbgValues.push_back(NewMI); 5775 } 5776 }; 5777 5778 // Check if ValueMap has reg number. 5779 DenseMap<const Value *, Register>::const_iterator 5780 VMI = FuncInfo.ValueMap.find(V); 5781 if (VMI != FuncInfo.ValueMap.end()) { 5782 const auto &TLI = DAG.getTargetLoweringInfo(); 5783 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5784 V->getType(), std::nullopt); 5785 if (RFV.occupiesMultipleRegs()) { 5786 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5787 return true; 5788 } 5789 5790 Op = MachineOperand::CreateReg(VMI->second, false); 5791 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5792 } else if (ArgRegsAndSizes.size() > 1) { 5793 // This was split due to the calling convention, and no virtual register 5794 // mapping exists for the value. 5795 splitMultiRegDbgValue(ArgRegsAndSizes); 5796 return true; 5797 } 5798 } 5799 5800 if (!Op) 5801 return false; 5802 5803 assert(Variable->isValidLocationForIntrinsic(DL) && 5804 "Expected inlined-at fields to agree"); 5805 MachineInstr *NewMI = nullptr; 5806 5807 if (Op->isReg()) 5808 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect); 5809 else 5810 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op, 5811 Variable, Expr); 5812 5813 // Otherwise, use ArgDbgValues. 5814 FuncInfo.ArgDbgValues.push_back(NewMI); 5815 return true; 5816 } 5817 5818 /// Return the appropriate SDDbgValue based on N. 5819 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5820 DILocalVariable *Variable, 5821 DIExpression *Expr, 5822 const DebugLoc &dl, 5823 unsigned DbgSDNodeOrder) { 5824 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5825 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5826 // stack slot locations. 5827 // 5828 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5829 // debug values here after optimization: 5830 // 5831 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5832 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5833 // 5834 // Both describe the direct values of their associated variables. 5835 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5836 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5837 } 5838 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5839 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5840 } 5841 5842 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5843 switch (Intrinsic) { 5844 case Intrinsic::smul_fix: 5845 return ISD::SMULFIX; 5846 case Intrinsic::umul_fix: 5847 return ISD::UMULFIX; 5848 case Intrinsic::smul_fix_sat: 5849 return ISD::SMULFIXSAT; 5850 case Intrinsic::umul_fix_sat: 5851 return ISD::UMULFIXSAT; 5852 case Intrinsic::sdiv_fix: 5853 return ISD::SDIVFIX; 5854 case Intrinsic::udiv_fix: 5855 return ISD::UDIVFIX; 5856 case Intrinsic::sdiv_fix_sat: 5857 return ISD::SDIVFIXSAT; 5858 case Intrinsic::udiv_fix_sat: 5859 return ISD::UDIVFIXSAT; 5860 default: 5861 llvm_unreachable("Unhandled fixed point intrinsic"); 5862 } 5863 } 5864 5865 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5866 const char *FunctionName) { 5867 assert(FunctionName && "FunctionName must not be nullptr"); 5868 SDValue Callee = DAG.getExternalSymbol( 5869 FunctionName, 5870 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5871 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 5872 } 5873 5874 /// Given a @llvm.call.preallocated.setup, return the corresponding 5875 /// preallocated call. 5876 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5877 assert(cast<CallBase>(PreallocatedSetup) 5878 ->getCalledFunction() 5879 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5880 "expected call_preallocated_setup Value"); 5881 for (const auto *U : PreallocatedSetup->users()) { 5882 auto *UseCall = cast<CallBase>(U); 5883 const Function *Fn = UseCall->getCalledFunction(); 5884 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5885 return UseCall; 5886 } 5887 } 5888 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5889 } 5890 5891 /// Lower the call to the specified intrinsic function. 5892 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5893 unsigned Intrinsic) { 5894 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5895 SDLoc sdl = getCurSDLoc(); 5896 DebugLoc dl = getCurDebugLoc(); 5897 SDValue Res; 5898 5899 SDNodeFlags Flags; 5900 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 5901 Flags.copyFMF(*FPOp); 5902 5903 switch (Intrinsic) { 5904 default: 5905 // By default, turn this into a target intrinsic node. 5906 visitTargetIntrinsic(I, Intrinsic); 5907 return; 5908 case Intrinsic::vscale: { 5909 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5910 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1))); 5911 return; 5912 } 5913 case Intrinsic::vastart: visitVAStart(I); return; 5914 case Intrinsic::vaend: visitVAEnd(I); return; 5915 case Intrinsic::vacopy: visitVACopy(I); return; 5916 case Intrinsic::returnaddress: 5917 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5918 TLI.getValueType(DAG.getDataLayout(), I.getType()), 5919 getValue(I.getArgOperand(0)))); 5920 return; 5921 case Intrinsic::addressofreturnaddress: 5922 setValue(&I, 5923 DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5924 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 5925 return; 5926 case Intrinsic::sponentry: 5927 setValue(&I, 5928 DAG.getNode(ISD::SPONENTRY, sdl, 5929 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 5930 return; 5931 case Intrinsic::frameaddress: 5932 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5933 TLI.getFrameIndexTy(DAG.getDataLayout()), 5934 getValue(I.getArgOperand(0)))); 5935 return; 5936 case Intrinsic::read_volatile_register: 5937 case Intrinsic::read_register: { 5938 Value *Reg = I.getArgOperand(0); 5939 SDValue Chain = getRoot(); 5940 SDValue RegName = 5941 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5942 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5943 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5944 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5945 setValue(&I, Res); 5946 DAG.setRoot(Res.getValue(1)); 5947 return; 5948 } 5949 case Intrinsic::write_register: { 5950 Value *Reg = I.getArgOperand(0); 5951 Value *RegValue = I.getArgOperand(1); 5952 SDValue Chain = getRoot(); 5953 SDValue RegName = 5954 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5955 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5956 RegName, getValue(RegValue))); 5957 return; 5958 } 5959 case Intrinsic::memcpy: { 5960 const auto &MCI = cast<MemCpyInst>(I); 5961 SDValue Op1 = getValue(I.getArgOperand(0)); 5962 SDValue Op2 = getValue(I.getArgOperand(1)); 5963 SDValue Op3 = getValue(I.getArgOperand(2)); 5964 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5965 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5966 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5967 Align Alignment = std::min(DstAlign, SrcAlign); 5968 bool isVol = MCI.isVolatile(); 5969 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5970 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5971 // node. 5972 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5973 SDValue MC = DAG.getMemcpy( 5974 Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5975 /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)), 5976 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 5977 updateDAGForMaybeTailCall(MC); 5978 return; 5979 } 5980 case Intrinsic::memcpy_inline: { 5981 const auto &MCI = cast<MemCpyInlineInst>(I); 5982 SDValue Dst = getValue(I.getArgOperand(0)); 5983 SDValue Src = getValue(I.getArgOperand(1)); 5984 SDValue Size = getValue(I.getArgOperand(2)); 5985 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 5986 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 5987 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5988 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5989 Align Alignment = std::min(DstAlign, SrcAlign); 5990 bool isVol = MCI.isVolatile(); 5991 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5992 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5993 // node. 5994 SDValue MC = DAG.getMemcpy( 5995 getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 5996 /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)), 5997 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 5998 updateDAGForMaybeTailCall(MC); 5999 return; 6000 } 6001 case Intrinsic::memset: { 6002 const auto &MSI = cast<MemSetInst>(I); 6003 SDValue Op1 = getValue(I.getArgOperand(0)); 6004 SDValue Op2 = getValue(I.getArgOperand(1)); 6005 SDValue Op3 = getValue(I.getArgOperand(2)); 6006 // @llvm.memset defines 0 and 1 to both mean no alignment. 6007 Align Alignment = MSI.getDestAlign().valueOrOne(); 6008 bool isVol = MSI.isVolatile(); 6009 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6010 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6011 SDValue MS = DAG.getMemset( 6012 Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false, 6013 isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata()); 6014 updateDAGForMaybeTailCall(MS); 6015 return; 6016 } 6017 case Intrinsic::memset_inline: { 6018 const auto &MSII = cast<MemSetInlineInst>(I); 6019 SDValue Dst = getValue(I.getArgOperand(0)); 6020 SDValue Value = getValue(I.getArgOperand(1)); 6021 SDValue Size = getValue(I.getArgOperand(2)); 6022 assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size"); 6023 // @llvm.memset defines 0 and 1 to both mean no alignment. 6024 Align DstAlign = MSII.getDestAlign().valueOrOne(); 6025 bool isVol = MSII.isVolatile(); 6026 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6027 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6028 SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol, 6029 /* AlwaysInline */ true, isTC, 6030 MachinePointerInfo(I.getArgOperand(0)), 6031 I.getAAMetadata()); 6032 updateDAGForMaybeTailCall(MC); 6033 return; 6034 } 6035 case Intrinsic::memmove: { 6036 const auto &MMI = cast<MemMoveInst>(I); 6037 SDValue Op1 = getValue(I.getArgOperand(0)); 6038 SDValue Op2 = getValue(I.getArgOperand(1)); 6039 SDValue Op3 = getValue(I.getArgOperand(2)); 6040 // @llvm.memmove defines 0 and 1 to both mean no alignment. 6041 Align DstAlign = MMI.getDestAlign().valueOrOne(); 6042 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 6043 Align Alignment = std::min(DstAlign, SrcAlign); 6044 bool isVol = MMI.isVolatile(); 6045 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6046 // FIXME: Support passing different dest/src alignments to the memmove DAG 6047 // node. 6048 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6049 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6050 isTC, MachinePointerInfo(I.getArgOperand(0)), 6051 MachinePointerInfo(I.getArgOperand(1)), 6052 I.getAAMetadata(), AA); 6053 updateDAGForMaybeTailCall(MM); 6054 return; 6055 } 6056 case Intrinsic::memcpy_element_unordered_atomic: { 6057 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 6058 SDValue Dst = getValue(MI.getRawDest()); 6059 SDValue Src = getValue(MI.getRawSource()); 6060 SDValue Length = getValue(MI.getLength()); 6061 6062 Type *LengthTy = MI.getLength()->getType(); 6063 unsigned ElemSz = MI.getElementSizeInBytes(); 6064 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6065 SDValue MC = 6066 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6067 isTC, MachinePointerInfo(MI.getRawDest()), 6068 MachinePointerInfo(MI.getRawSource())); 6069 updateDAGForMaybeTailCall(MC); 6070 return; 6071 } 6072 case Intrinsic::memmove_element_unordered_atomic: { 6073 auto &MI = cast<AtomicMemMoveInst>(I); 6074 SDValue Dst = getValue(MI.getRawDest()); 6075 SDValue Src = getValue(MI.getRawSource()); 6076 SDValue Length = getValue(MI.getLength()); 6077 6078 Type *LengthTy = MI.getLength()->getType(); 6079 unsigned ElemSz = MI.getElementSizeInBytes(); 6080 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6081 SDValue MC = 6082 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6083 isTC, MachinePointerInfo(MI.getRawDest()), 6084 MachinePointerInfo(MI.getRawSource())); 6085 updateDAGForMaybeTailCall(MC); 6086 return; 6087 } 6088 case Intrinsic::memset_element_unordered_atomic: { 6089 auto &MI = cast<AtomicMemSetInst>(I); 6090 SDValue Dst = getValue(MI.getRawDest()); 6091 SDValue Val = getValue(MI.getValue()); 6092 SDValue Length = getValue(MI.getLength()); 6093 6094 Type *LengthTy = MI.getLength()->getType(); 6095 unsigned ElemSz = MI.getElementSizeInBytes(); 6096 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6097 SDValue MC = 6098 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz, 6099 isTC, MachinePointerInfo(MI.getRawDest())); 6100 updateDAGForMaybeTailCall(MC); 6101 return; 6102 } 6103 case Intrinsic::call_preallocated_setup: { 6104 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 6105 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6106 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 6107 getRoot(), SrcValue); 6108 setValue(&I, Res); 6109 DAG.setRoot(Res); 6110 return; 6111 } 6112 case Intrinsic::call_preallocated_arg: { 6113 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 6114 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6115 SDValue Ops[3]; 6116 Ops[0] = getRoot(); 6117 Ops[1] = SrcValue; 6118 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 6119 MVT::i32); // arg index 6120 SDValue Res = DAG.getNode( 6121 ISD::PREALLOCATED_ARG, sdl, 6122 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 6123 setValue(&I, Res); 6124 DAG.setRoot(Res.getValue(1)); 6125 return; 6126 } 6127 case Intrinsic::dbg_declare: { 6128 // Debug intrinsics are handled separately in assignment tracking mode. 6129 if (AssignmentTrackingEnabled) 6130 return; 6131 // Assume dbg.declare can not currently use DIArgList, i.e. 6132 // it is non-variadic. 6133 const auto &DI = cast<DbgVariableIntrinsic>(I); 6134 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 6135 DILocalVariable *Variable = DI.getVariable(); 6136 DIExpression *Expression = DI.getExpression(); 6137 dropDanglingDebugInfo(Variable, Expression); 6138 assert(Variable && "Missing variable"); 6139 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 6140 << "\n"); 6141 // Check if address has undef value. 6142 const Value *Address = DI.getVariableLocationOp(0); 6143 if (!Address || isa<UndefValue>(Address) || 6144 (Address->use_empty() && !isa<Argument>(Address))) { 6145 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6146 << " (bad/undef/unused-arg address)\n"); 6147 return; 6148 } 6149 6150 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 6151 6152 // Check if this variable can be described by a frame index, typically 6153 // either as a static alloca or a byval parameter. 6154 int FI = std::numeric_limits<int>::max(); 6155 if (const auto *AI = 6156 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 6157 if (AI->isStaticAlloca()) { 6158 auto I = FuncInfo.StaticAllocaMap.find(AI); 6159 if (I != FuncInfo.StaticAllocaMap.end()) 6160 FI = I->second; 6161 } 6162 } else if (const auto *Arg = dyn_cast<Argument>( 6163 Address->stripInBoundsConstantOffsets())) { 6164 FI = FuncInfo.getArgumentFrameIndex(Arg); 6165 } 6166 6167 // llvm.dbg.declare is handled as a frame index in the MachineFunction 6168 // variable table. 6169 if (FI != std::numeric_limits<int>::max()) { 6170 LLVM_DEBUG(dbgs() << "Skipping " << DI 6171 << " (variable info stashed in MF side table)\n"); 6172 return; 6173 } 6174 6175 SDValue &N = NodeMap[Address]; 6176 if (!N.getNode() && isa<Argument>(Address)) 6177 // Check unused arguments map. 6178 N = UnusedArgNodeMap[Address]; 6179 SDDbgValue *SDV; 6180 if (N.getNode()) { 6181 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 6182 Address = BCI->getOperand(0); 6183 // Parameters are handled specially. 6184 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 6185 if (isParameter && FINode) { 6186 // Byval parameter. We have a frame index at this point. 6187 SDV = 6188 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 6189 /*IsIndirect*/ true, dl, SDNodeOrder); 6190 } else if (isa<Argument>(Address)) { 6191 // Address is an argument, so try to emit its dbg value using 6192 // virtual register info from the FuncInfo.ValueMap. 6193 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 6194 FuncArgumentDbgValueKind::Declare, N); 6195 return; 6196 } else { 6197 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 6198 true, dl, SDNodeOrder); 6199 } 6200 DAG.AddDbgValue(SDV, isParameter); 6201 } else { 6202 // If Address is an argument then try to emit its dbg value using 6203 // virtual register info from the FuncInfo.ValueMap. 6204 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 6205 FuncArgumentDbgValueKind::Declare, N)) { 6206 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6207 << " (could not emit func-arg dbg_value)\n"); 6208 } 6209 } 6210 return; 6211 } 6212 case Intrinsic::dbg_label: { 6213 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6214 DILabel *Label = DI.getLabel(); 6215 assert(Label && "Missing label"); 6216 6217 SDDbgLabel *SDV; 6218 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6219 DAG.AddDbgLabel(SDV); 6220 return; 6221 } 6222 case Intrinsic::dbg_assign: { 6223 // Debug intrinsics are handled seperately in assignment tracking mode. 6224 if (AssignmentTrackingEnabled) 6225 return; 6226 // If assignment tracking hasn't been enabled then fall through and treat 6227 // the dbg.assign as a dbg.value. 6228 [[fallthrough]]; 6229 } 6230 case Intrinsic::dbg_value: { 6231 // Debug intrinsics are handled seperately in assignment tracking mode. 6232 if (AssignmentTrackingEnabled) 6233 return; 6234 const DbgValueInst &DI = cast<DbgValueInst>(I); 6235 assert(DI.getVariable() && "Missing variable"); 6236 6237 DILocalVariable *Variable = DI.getVariable(); 6238 DIExpression *Expression = DI.getExpression(); 6239 dropDanglingDebugInfo(Variable, Expression); 6240 6241 if (DI.isKillLocation()) { 6242 handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder); 6243 return; 6244 } 6245 6246 SmallVector<Value *, 4> Values(DI.getValues()); 6247 if (Values.empty()) 6248 return; 6249 6250 bool IsVariadic = DI.hasArgList(); 6251 if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(), 6252 SDNodeOrder, IsVariadic)) 6253 addDanglingDebugInfo(&DI, SDNodeOrder); 6254 return; 6255 } 6256 6257 case Intrinsic::eh_typeid_for: { 6258 // Find the type id for the given typeinfo. 6259 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6260 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6261 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6262 setValue(&I, Res); 6263 return; 6264 } 6265 6266 case Intrinsic::eh_return_i32: 6267 case Intrinsic::eh_return_i64: 6268 DAG.getMachineFunction().setCallsEHReturn(true); 6269 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6270 MVT::Other, 6271 getControlRoot(), 6272 getValue(I.getArgOperand(0)), 6273 getValue(I.getArgOperand(1)))); 6274 return; 6275 case Intrinsic::eh_unwind_init: 6276 DAG.getMachineFunction().setCallsUnwindInit(true); 6277 return; 6278 case Intrinsic::eh_dwarf_cfa: 6279 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6280 TLI.getPointerTy(DAG.getDataLayout()), 6281 getValue(I.getArgOperand(0)))); 6282 return; 6283 case Intrinsic::eh_sjlj_callsite: { 6284 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6285 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0)); 6286 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6287 6288 MMI.setCurrentCallSite(CI->getZExtValue()); 6289 return; 6290 } 6291 case Intrinsic::eh_sjlj_functioncontext: { 6292 // Get and store the index of the function context. 6293 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6294 AllocaInst *FnCtx = 6295 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6296 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6297 MFI.setFunctionContextIndex(FI); 6298 return; 6299 } 6300 case Intrinsic::eh_sjlj_setjmp: { 6301 SDValue Ops[2]; 6302 Ops[0] = getRoot(); 6303 Ops[1] = getValue(I.getArgOperand(0)); 6304 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6305 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6306 setValue(&I, Op.getValue(0)); 6307 DAG.setRoot(Op.getValue(1)); 6308 return; 6309 } 6310 case Intrinsic::eh_sjlj_longjmp: 6311 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6312 getRoot(), getValue(I.getArgOperand(0)))); 6313 return; 6314 case Intrinsic::eh_sjlj_setup_dispatch: 6315 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6316 getRoot())); 6317 return; 6318 case Intrinsic::masked_gather: 6319 visitMaskedGather(I); 6320 return; 6321 case Intrinsic::masked_load: 6322 visitMaskedLoad(I); 6323 return; 6324 case Intrinsic::masked_scatter: 6325 visitMaskedScatter(I); 6326 return; 6327 case Intrinsic::masked_store: 6328 visitMaskedStore(I); 6329 return; 6330 case Intrinsic::masked_expandload: 6331 visitMaskedLoad(I, true /* IsExpanding */); 6332 return; 6333 case Intrinsic::masked_compressstore: 6334 visitMaskedStore(I, true /* IsCompressing */); 6335 return; 6336 case Intrinsic::powi: 6337 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6338 getValue(I.getArgOperand(1)), DAG)); 6339 return; 6340 case Intrinsic::log: 6341 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6342 return; 6343 case Intrinsic::log2: 6344 setValue(&I, 6345 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6346 return; 6347 case Intrinsic::log10: 6348 setValue(&I, 6349 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6350 return; 6351 case Intrinsic::exp: 6352 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6353 return; 6354 case Intrinsic::exp2: 6355 setValue(&I, 6356 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6357 return; 6358 case Intrinsic::pow: 6359 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6360 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6361 return; 6362 case Intrinsic::sqrt: 6363 case Intrinsic::fabs: 6364 case Intrinsic::sin: 6365 case Intrinsic::cos: 6366 case Intrinsic::floor: 6367 case Intrinsic::ceil: 6368 case Intrinsic::trunc: 6369 case Intrinsic::rint: 6370 case Intrinsic::nearbyint: 6371 case Intrinsic::round: 6372 case Intrinsic::roundeven: 6373 case Intrinsic::canonicalize: { 6374 unsigned Opcode; 6375 switch (Intrinsic) { 6376 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6377 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6378 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6379 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6380 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6381 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6382 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6383 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6384 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6385 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6386 case Intrinsic::round: Opcode = ISD::FROUND; break; 6387 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6388 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6389 } 6390 6391 setValue(&I, DAG.getNode(Opcode, sdl, 6392 getValue(I.getArgOperand(0)).getValueType(), 6393 getValue(I.getArgOperand(0)), Flags)); 6394 return; 6395 } 6396 case Intrinsic::lround: 6397 case Intrinsic::llround: 6398 case Intrinsic::lrint: 6399 case Intrinsic::llrint: { 6400 unsigned Opcode; 6401 switch (Intrinsic) { 6402 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6403 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6404 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6405 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6406 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6407 } 6408 6409 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6410 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6411 getValue(I.getArgOperand(0)))); 6412 return; 6413 } 6414 case Intrinsic::minnum: 6415 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6416 getValue(I.getArgOperand(0)).getValueType(), 6417 getValue(I.getArgOperand(0)), 6418 getValue(I.getArgOperand(1)), Flags)); 6419 return; 6420 case Intrinsic::maxnum: 6421 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6422 getValue(I.getArgOperand(0)).getValueType(), 6423 getValue(I.getArgOperand(0)), 6424 getValue(I.getArgOperand(1)), Flags)); 6425 return; 6426 case Intrinsic::minimum: 6427 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6428 getValue(I.getArgOperand(0)).getValueType(), 6429 getValue(I.getArgOperand(0)), 6430 getValue(I.getArgOperand(1)), Flags)); 6431 return; 6432 case Intrinsic::maximum: 6433 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6434 getValue(I.getArgOperand(0)).getValueType(), 6435 getValue(I.getArgOperand(0)), 6436 getValue(I.getArgOperand(1)), Flags)); 6437 return; 6438 case Intrinsic::copysign: 6439 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6440 getValue(I.getArgOperand(0)).getValueType(), 6441 getValue(I.getArgOperand(0)), 6442 getValue(I.getArgOperand(1)), Flags)); 6443 return; 6444 case Intrinsic::arithmetic_fence: { 6445 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl, 6446 getValue(I.getArgOperand(0)).getValueType(), 6447 getValue(I.getArgOperand(0)), Flags)); 6448 return; 6449 } 6450 case Intrinsic::fma: 6451 setValue(&I, DAG.getNode( 6452 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6453 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6454 getValue(I.getArgOperand(2)), Flags)); 6455 return; 6456 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6457 case Intrinsic::INTRINSIC: 6458 #include "llvm/IR/ConstrainedOps.def" 6459 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6460 return; 6461 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6462 #include "llvm/IR/VPIntrinsics.def" 6463 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6464 return; 6465 case Intrinsic::fptrunc_round: { 6466 // Get the last argument, the metadata and convert it to an integer in the 6467 // call 6468 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata(); 6469 std::optional<RoundingMode> RoundMode = 6470 convertStrToRoundingMode(cast<MDString>(MD)->getString()); 6471 6472 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6473 6474 // Propagate fast-math-flags from IR to node(s). 6475 SDNodeFlags Flags; 6476 Flags.copyFMF(*cast<FPMathOperator>(&I)); 6477 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 6478 6479 SDValue Result; 6480 Result = DAG.getNode( 6481 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)), 6482 DAG.getTargetConstant((int)*RoundMode, sdl, 6483 TLI.getPointerTy(DAG.getDataLayout()))); 6484 setValue(&I, Result); 6485 6486 return; 6487 } 6488 case Intrinsic::fmuladd: { 6489 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6490 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6491 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6492 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6493 getValue(I.getArgOperand(0)).getValueType(), 6494 getValue(I.getArgOperand(0)), 6495 getValue(I.getArgOperand(1)), 6496 getValue(I.getArgOperand(2)), Flags)); 6497 } else { 6498 // TODO: Intrinsic calls should have fast-math-flags. 6499 SDValue Mul = DAG.getNode( 6500 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6501 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6502 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6503 getValue(I.getArgOperand(0)).getValueType(), 6504 Mul, getValue(I.getArgOperand(2)), Flags); 6505 setValue(&I, Add); 6506 } 6507 return; 6508 } 6509 case Intrinsic::convert_to_fp16: 6510 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6511 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6512 getValue(I.getArgOperand(0)), 6513 DAG.getTargetConstant(0, sdl, 6514 MVT::i32)))); 6515 return; 6516 case Intrinsic::convert_from_fp16: 6517 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6518 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6519 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6520 getValue(I.getArgOperand(0))))); 6521 return; 6522 case Intrinsic::fptosi_sat: { 6523 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6524 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 6525 getValue(I.getArgOperand(0)), 6526 DAG.getValueType(VT.getScalarType()))); 6527 return; 6528 } 6529 case Intrinsic::fptoui_sat: { 6530 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6531 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 6532 getValue(I.getArgOperand(0)), 6533 DAG.getValueType(VT.getScalarType()))); 6534 return; 6535 } 6536 case Intrinsic::set_rounding: 6537 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6538 {getRoot(), getValue(I.getArgOperand(0))}); 6539 setValue(&I, Res); 6540 DAG.setRoot(Res.getValue(0)); 6541 return; 6542 case Intrinsic::is_fpclass: { 6543 const DataLayout DLayout = DAG.getDataLayout(); 6544 EVT DestVT = TLI.getValueType(DLayout, I.getType()); 6545 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType()); 6546 FPClassTest Test = static_cast<FPClassTest>( 6547 cast<ConstantInt>(I.getArgOperand(1))->getZExtValue()); 6548 MachineFunction &MF = DAG.getMachineFunction(); 6549 const Function &F = MF.getFunction(); 6550 SDValue Op = getValue(I.getArgOperand(0)); 6551 SDNodeFlags Flags; 6552 Flags.setNoFPExcept( 6553 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP)); 6554 // If ISD::IS_FPCLASS should be expanded, do it right now, because the 6555 // expansion can use illegal types. Making expansion early allows 6556 // legalizing these types prior to selection. 6557 if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) { 6558 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG); 6559 setValue(&I, Result); 6560 return; 6561 } 6562 6563 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32); 6564 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags); 6565 setValue(&I, V); 6566 return; 6567 } 6568 case Intrinsic::pcmarker: { 6569 SDValue Tmp = getValue(I.getArgOperand(0)); 6570 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6571 return; 6572 } 6573 case Intrinsic::readcyclecounter: { 6574 SDValue Op = getRoot(); 6575 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6576 DAG.getVTList(MVT::i64, MVT::Other), Op); 6577 setValue(&I, Res); 6578 DAG.setRoot(Res.getValue(1)); 6579 return; 6580 } 6581 case Intrinsic::bitreverse: 6582 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6583 getValue(I.getArgOperand(0)).getValueType(), 6584 getValue(I.getArgOperand(0)))); 6585 return; 6586 case Intrinsic::bswap: 6587 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6588 getValue(I.getArgOperand(0)).getValueType(), 6589 getValue(I.getArgOperand(0)))); 6590 return; 6591 case Intrinsic::cttz: { 6592 SDValue Arg = getValue(I.getArgOperand(0)); 6593 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6594 EVT Ty = Arg.getValueType(); 6595 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6596 sdl, Ty, Arg)); 6597 return; 6598 } 6599 case Intrinsic::ctlz: { 6600 SDValue Arg = getValue(I.getArgOperand(0)); 6601 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6602 EVT Ty = Arg.getValueType(); 6603 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6604 sdl, Ty, Arg)); 6605 return; 6606 } 6607 case Intrinsic::ctpop: { 6608 SDValue Arg = getValue(I.getArgOperand(0)); 6609 EVT Ty = Arg.getValueType(); 6610 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6611 return; 6612 } 6613 case Intrinsic::fshl: 6614 case Intrinsic::fshr: { 6615 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6616 SDValue X = getValue(I.getArgOperand(0)); 6617 SDValue Y = getValue(I.getArgOperand(1)); 6618 SDValue Z = getValue(I.getArgOperand(2)); 6619 EVT VT = X.getValueType(); 6620 6621 if (X == Y) { 6622 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6623 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6624 } else { 6625 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6626 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6627 } 6628 return; 6629 } 6630 case Intrinsic::sadd_sat: { 6631 SDValue Op1 = getValue(I.getArgOperand(0)); 6632 SDValue Op2 = getValue(I.getArgOperand(1)); 6633 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6634 return; 6635 } 6636 case Intrinsic::uadd_sat: { 6637 SDValue Op1 = getValue(I.getArgOperand(0)); 6638 SDValue Op2 = getValue(I.getArgOperand(1)); 6639 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6640 return; 6641 } 6642 case Intrinsic::ssub_sat: { 6643 SDValue Op1 = getValue(I.getArgOperand(0)); 6644 SDValue Op2 = getValue(I.getArgOperand(1)); 6645 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6646 return; 6647 } 6648 case Intrinsic::usub_sat: { 6649 SDValue Op1 = getValue(I.getArgOperand(0)); 6650 SDValue Op2 = getValue(I.getArgOperand(1)); 6651 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6652 return; 6653 } 6654 case Intrinsic::sshl_sat: { 6655 SDValue Op1 = getValue(I.getArgOperand(0)); 6656 SDValue Op2 = getValue(I.getArgOperand(1)); 6657 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6658 return; 6659 } 6660 case Intrinsic::ushl_sat: { 6661 SDValue Op1 = getValue(I.getArgOperand(0)); 6662 SDValue Op2 = getValue(I.getArgOperand(1)); 6663 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6664 return; 6665 } 6666 case Intrinsic::smul_fix: 6667 case Intrinsic::umul_fix: 6668 case Intrinsic::smul_fix_sat: 6669 case Intrinsic::umul_fix_sat: { 6670 SDValue Op1 = getValue(I.getArgOperand(0)); 6671 SDValue Op2 = getValue(I.getArgOperand(1)); 6672 SDValue Op3 = getValue(I.getArgOperand(2)); 6673 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6674 Op1.getValueType(), Op1, Op2, Op3)); 6675 return; 6676 } 6677 case Intrinsic::sdiv_fix: 6678 case Intrinsic::udiv_fix: 6679 case Intrinsic::sdiv_fix_sat: 6680 case Intrinsic::udiv_fix_sat: { 6681 SDValue Op1 = getValue(I.getArgOperand(0)); 6682 SDValue Op2 = getValue(I.getArgOperand(1)); 6683 SDValue Op3 = getValue(I.getArgOperand(2)); 6684 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6685 Op1, Op2, Op3, DAG, TLI)); 6686 return; 6687 } 6688 case Intrinsic::smax: { 6689 SDValue Op1 = getValue(I.getArgOperand(0)); 6690 SDValue Op2 = getValue(I.getArgOperand(1)); 6691 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6692 return; 6693 } 6694 case Intrinsic::smin: { 6695 SDValue Op1 = getValue(I.getArgOperand(0)); 6696 SDValue Op2 = getValue(I.getArgOperand(1)); 6697 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6698 return; 6699 } 6700 case Intrinsic::umax: { 6701 SDValue Op1 = getValue(I.getArgOperand(0)); 6702 SDValue Op2 = getValue(I.getArgOperand(1)); 6703 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6704 return; 6705 } 6706 case Intrinsic::umin: { 6707 SDValue Op1 = getValue(I.getArgOperand(0)); 6708 SDValue Op2 = getValue(I.getArgOperand(1)); 6709 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6710 return; 6711 } 6712 case Intrinsic::abs: { 6713 // TODO: Preserve "int min is poison" arg in SDAG? 6714 SDValue Op1 = getValue(I.getArgOperand(0)); 6715 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6716 return; 6717 } 6718 case Intrinsic::stacksave: { 6719 SDValue Op = getRoot(); 6720 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6721 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6722 setValue(&I, Res); 6723 DAG.setRoot(Res.getValue(1)); 6724 return; 6725 } 6726 case Intrinsic::stackrestore: 6727 Res = getValue(I.getArgOperand(0)); 6728 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6729 return; 6730 case Intrinsic::get_dynamic_area_offset: { 6731 SDValue Op = getRoot(); 6732 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6733 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6734 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6735 // target. 6736 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 6737 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6738 " intrinsic!"); 6739 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6740 Op); 6741 DAG.setRoot(Op); 6742 setValue(&I, Res); 6743 return; 6744 } 6745 case Intrinsic::stackguard: { 6746 MachineFunction &MF = DAG.getMachineFunction(); 6747 const Module &M = *MF.getFunction().getParent(); 6748 SDValue Chain = getRoot(); 6749 if (TLI.useLoadStackGuardNode()) { 6750 Res = getLoadStackGuard(DAG, sdl, Chain); 6751 } else { 6752 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6753 const Value *Global = TLI.getSDagStackGuard(M); 6754 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType()); 6755 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6756 MachinePointerInfo(Global, 0), Align, 6757 MachineMemOperand::MOVolatile); 6758 } 6759 if (TLI.useStackGuardXorFP()) 6760 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6761 DAG.setRoot(Chain); 6762 setValue(&I, Res); 6763 return; 6764 } 6765 case Intrinsic::stackprotector: { 6766 // Emit code into the DAG to store the stack guard onto the stack. 6767 MachineFunction &MF = DAG.getMachineFunction(); 6768 MachineFrameInfo &MFI = MF.getFrameInfo(); 6769 SDValue Src, Chain = getRoot(); 6770 6771 if (TLI.useLoadStackGuardNode()) 6772 Src = getLoadStackGuard(DAG, sdl, Chain); 6773 else 6774 Src = getValue(I.getArgOperand(0)); // The guard's value. 6775 6776 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6777 6778 int FI = FuncInfo.StaticAllocaMap[Slot]; 6779 MFI.setStackProtectorIndex(FI); 6780 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6781 6782 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6783 6784 // Store the stack protector onto the stack. 6785 Res = DAG.getStore( 6786 Chain, sdl, Src, FIN, 6787 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 6788 MaybeAlign(), MachineMemOperand::MOVolatile); 6789 setValue(&I, Res); 6790 DAG.setRoot(Res); 6791 return; 6792 } 6793 case Intrinsic::objectsize: 6794 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6795 6796 case Intrinsic::is_constant: 6797 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6798 6799 case Intrinsic::annotation: 6800 case Intrinsic::ptr_annotation: 6801 case Intrinsic::launder_invariant_group: 6802 case Intrinsic::strip_invariant_group: 6803 // Drop the intrinsic, but forward the value 6804 setValue(&I, getValue(I.getOperand(0))); 6805 return; 6806 6807 case Intrinsic::assume: 6808 case Intrinsic::experimental_noalias_scope_decl: 6809 case Intrinsic::var_annotation: 6810 case Intrinsic::sideeffect: 6811 // Discard annotate attributes, noalias scope declarations, assumptions, and 6812 // artificial side-effects. 6813 return; 6814 6815 case Intrinsic::codeview_annotation: { 6816 // Emit a label associated with this metadata. 6817 MachineFunction &MF = DAG.getMachineFunction(); 6818 MCSymbol *Label = 6819 MF.getMMI().getContext().createTempSymbol("annotation", true); 6820 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6821 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6822 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6823 DAG.setRoot(Res); 6824 return; 6825 } 6826 6827 case Intrinsic::init_trampoline: { 6828 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6829 6830 SDValue Ops[6]; 6831 Ops[0] = getRoot(); 6832 Ops[1] = getValue(I.getArgOperand(0)); 6833 Ops[2] = getValue(I.getArgOperand(1)); 6834 Ops[3] = getValue(I.getArgOperand(2)); 6835 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6836 Ops[5] = DAG.getSrcValue(F); 6837 6838 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6839 6840 DAG.setRoot(Res); 6841 return; 6842 } 6843 case Intrinsic::adjust_trampoline: 6844 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6845 TLI.getPointerTy(DAG.getDataLayout()), 6846 getValue(I.getArgOperand(0)))); 6847 return; 6848 case Intrinsic::gcroot: { 6849 assert(DAG.getMachineFunction().getFunction().hasGC() && 6850 "only valid in functions with gc specified, enforced by Verifier"); 6851 assert(GFI && "implied by previous"); 6852 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6853 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6854 6855 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6856 GFI->addStackRoot(FI->getIndex(), TypeMap); 6857 return; 6858 } 6859 case Intrinsic::gcread: 6860 case Intrinsic::gcwrite: 6861 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6862 case Intrinsic::get_rounding: 6863 Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot()); 6864 setValue(&I, Res); 6865 DAG.setRoot(Res.getValue(1)); 6866 return; 6867 6868 case Intrinsic::expect: 6869 // Just replace __builtin_expect(exp, c) with EXP. 6870 setValue(&I, getValue(I.getArgOperand(0))); 6871 return; 6872 6873 case Intrinsic::ubsantrap: 6874 case Intrinsic::debugtrap: 6875 case Intrinsic::trap: { 6876 StringRef TrapFuncName = 6877 I.getAttributes().getFnAttr("trap-func-name").getValueAsString(); 6878 if (TrapFuncName.empty()) { 6879 switch (Intrinsic) { 6880 case Intrinsic::trap: 6881 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 6882 break; 6883 case Intrinsic::debugtrap: 6884 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 6885 break; 6886 case Intrinsic::ubsantrap: 6887 DAG.setRoot(DAG.getNode( 6888 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 6889 DAG.getTargetConstant( 6890 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 6891 MVT::i32))); 6892 break; 6893 default: llvm_unreachable("unknown trap intrinsic"); 6894 } 6895 return; 6896 } 6897 TargetLowering::ArgListTy Args; 6898 if (Intrinsic == Intrinsic::ubsantrap) { 6899 Args.push_back(TargetLoweringBase::ArgListEntry()); 6900 Args[0].Val = I.getArgOperand(0); 6901 Args[0].Node = getValue(Args[0].Val); 6902 Args[0].Ty = Args[0].Val->getType(); 6903 } 6904 6905 TargetLowering::CallLoweringInfo CLI(DAG); 6906 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6907 CallingConv::C, I.getType(), 6908 DAG.getExternalSymbol(TrapFuncName.data(), 6909 TLI.getPointerTy(DAG.getDataLayout())), 6910 std::move(Args)); 6911 6912 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6913 DAG.setRoot(Result.second); 6914 return; 6915 } 6916 6917 case Intrinsic::uadd_with_overflow: 6918 case Intrinsic::sadd_with_overflow: 6919 case Intrinsic::usub_with_overflow: 6920 case Intrinsic::ssub_with_overflow: 6921 case Intrinsic::umul_with_overflow: 6922 case Intrinsic::smul_with_overflow: { 6923 ISD::NodeType Op; 6924 switch (Intrinsic) { 6925 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6926 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6927 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6928 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6929 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6930 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6931 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6932 } 6933 SDValue Op1 = getValue(I.getArgOperand(0)); 6934 SDValue Op2 = getValue(I.getArgOperand(1)); 6935 6936 EVT ResultVT = Op1.getValueType(); 6937 EVT OverflowVT = MVT::i1; 6938 if (ResultVT.isVector()) 6939 OverflowVT = EVT::getVectorVT( 6940 *Context, OverflowVT, ResultVT.getVectorElementCount()); 6941 6942 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6943 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6944 return; 6945 } 6946 case Intrinsic::prefetch: { 6947 SDValue Ops[5]; 6948 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6949 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6950 Ops[0] = DAG.getRoot(); 6951 Ops[1] = getValue(I.getArgOperand(0)); 6952 Ops[2] = getValue(I.getArgOperand(1)); 6953 Ops[3] = getValue(I.getArgOperand(2)); 6954 Ops[4] = getValue(I.getArgOperand(3)); 6955 SDValue Result = DAG.getMemIntrinsicNode( 6956 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 6957 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 6958 /* align */ std::nullopt, Flags); 6959 6960 // Chain the prefetch in parallell with any pending loads, to stay out of 6961 // the way of later optimizations. 6962 PendingLoads.push_back(Result); 6963 Result = getRoot(); 6964 DAG.setRoot(Result); 6965 return; 6966 } 6967 case Intrinsic::lifetime_start: 6968 case Intrinsic::lifetime_end: { 6969 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6970 // Stack coloring is not enabled in O0, discard region information. 6971 if (TM.getOptLevel() == CodeGenOpt::None) 6972 return; 6973 6974 const int64_t ObjectSize = 6975 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6976 Value *const ObjectPtr = I.getArgOperand(1); 6977 SmallVector<const Value *, 4> Allocas; 6978 getUnderlyingObjects(ObjectPtr, Allocas); 6979 6980 for (const Value *Alloca : Allocas) { 6981 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 6982 6983 // Could not find an Alloca. 6984 if (!LifetimeObject) 6985 continue; 6986 6987 // First check that the Alloca is static, otherwise it won't have a 6988 // valid frame index. 6989 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6990 if (SI == FuncInfo.StaticAllocaMap.end()) 6991 return; 6992 6993 const int FrameIndex = SI->second; 6994 int64_t Offset; 6995 if (GetPointerBaseWithConstantOffset( 6996 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6997 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6998 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6999 Offset); 7000 DAG.setRoot(Res); 7001 } 7002 return; 7003 } 7004 case Intrinsic::pseudoprobe: { 7005 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 7006 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 7007 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 7008 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 7009 DAG.setRoot(Res); 7010 return; 7011 } 7012 case Intrinsic::invariant_start: 7013 // Discard region information. 7014 setValue(&I, 7015 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType()))); 7016 return; 7017 case Intrinsic::invariant_end: 7018 // Discard region information. 7019 return; 7020 case Intrinsic::clear_cache: 7021 /// FunctionName may be null. 7022 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 7023 lowerCallToExternalSymbol(I, FunctionName); 7024 return; 7025 case Intrinsic::donothing: 7026 case Intrinsic::seh_try_begin: 7027 case Intrinsic::seh_scope_begin: 7028 case Intrinsic::seh_try_end: 7029 case Intrinsic::seh_scope_end: 7030 // ignore 7031 return; 7032 case Intrinsic::experimental_stackmap: 7033 visitStackmap(I); 7034 return; 7035 case Intrinsic::experimental_patchpoint_void: 7036 case Intrinsic::experimental_patchpoint_i64: 7037 visitPatchpoint(I); 7038 return; 7039 case Intrinsic::experimental_gc_statepoint: 7040 LowerStatepoint(cast<GCStatepointInst>(I)); 7041 return; 7042 case Intrinsic::experimental_gc_result: 7043 visitGCResult(cast<GCResultInst>(I)); 7044 return; 7045 case Intrinsic::experimental_gc_relocate: 7046 visitGCRelocate(cast<GCRelocateInst>(I)); 7047 return; 7048 case Intrinsic::instrprof_cover: 7049 llvm_unreachable("instrprof failed to lower a cover"); 7050 case Intrinsic::instrprof_increment: 7051 llvm_unreachable("instrprof failed to lower an increment"); 7052 case Intrinsic::instrprof_timestamp: 7053 llvm_unreachable("instrprof failed to lower a timestamp"); 7054 case Intrinsic::instrprof_value_profile: 7055 llvm_unreachable("instrprof failed to lower a value profiling call"); 7056 case Intrinsic::localescape: { 7057 MachineFunction &MF = DAG.getMachineFunction(); 7058 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 7059 7060 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 7061 // is the same on all targets. 7062 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) { 7063 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 7064 if (isa<ConstantPointerNull>(Arg)) 7065 continue; // Skip null pointers. They represent a hole in index space. 7066 AllocaInst *Slot = cast<AllocaInst>(Arg); 7067 assert(FuncInfo.StaticAllocaMap.count(Slot) && 7068 "can only escape static allocas"); 7069 int FI = FuncInfo.StaticAllocaMap[Slot]; 7070 MCSymbol *FrameAllocSym = 7071 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7072 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 7073 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 7074 TII->get(TargetOpcode::LOCAL_ESCAPE)) 7075 .addSym(FrameAllocSym) 7076 .addFrameIndex(FI); 7077 } 7078 7079 return; 7080 } 7081 7082 case Intrinsic::localrecover: { 7083 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 7084 MachineFunction &MF = DAG.getMachineFunction(); 7085 7086 // Get the symbol that defines the frame offset. 7087 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 7088 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 7089 unsigned IdxVal = 7090 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 7091 MCSymbol *FrameAllocSym = 7092 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7093 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 7094 7095 Value *FP = I.getArgOperand(1); 7096 SDValue FPVal = getValue(FP); 7097 EVT PtrVT = FPVal.getValueType(); 7098 7099 // Create a MCSymbol for the label to avoid any target lowering 7100 // that would make this PC relative. 7101 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 7102 SDValue OffsetVal = 7103 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 7104 7105 // Add the offset to the FP. 7106 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 7107 setValue(&I, Add); 7108 7109 return; 7110 } 7111 7112 case Intrinsic::eh_exceptionpointer: 7113 case Intrinsic::eh_exceptioncode: { 7114 // Get the exception pointer vreg, copy from it, and resize it to fit. 7115 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 7116 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 7117 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 7118 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 7119 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT); 7120 if (Intrinsic == Intrinsic::eh_exceptioncode) 7121 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32); 7122 setValue(&I, N); 7123 return; 7124 } 7125 case Intrinsic::xray_customevent: { 7126 // Here we want to make sure that the intrinsic behaves as if it has a 7127 // specific calling convention, and only for x86_64. 7128 // FIXME: Support other platforms later. 7129 const auto &Triple = DAG.getTarget().getTargetTriple(); 7130 if (Triple.getArch() != Triple::x86_64) 7131 return; 7132 7133 SmallVector<SDValue, 8> Ops; 7134 7135 // We want to say that we always want the arguments in registers. 7136 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 7137 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 7138 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7139 SDValue Chain = getRoot(); 7140 Ops.push_back(LogEntryVal); 7141 Ops.push_back(StrSizeVal); 7142 Ops.push_back(Chain); 7143 7144 // We need to enforce the calling convention for the callsite, so that 7145 // argument ordering is enforced correctly, and that register allocation can 7146 // see that some registers may be assumed clobbered and have to preserve 7147 // them across calls to the intrinsic. 7148 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 7149 sdl, NodeTys, Ops); 7150 SDValue patchableNode = SDValue(MN, 0); 7151 DAG.setRoot(patchableNode); 7152 setValue(&I, patchableNode); 7153 return; 7154 } 7155 case Intrinsic::xray_typedevent: { 7156 // Here we want to make sure that the intrinsic behaves as if it has a 7157 // specific calling convention, and only for x86_64. 7158 // FIXME: Support other platforms later. 7159 const auto &Triple = DAG.getTarget().getTargetTriple(); 7160 if (Triple.getArch() != Triple::x86_64) 7161 return; 7162 7163 SmallVector<SDValue, 8> Ops; 7164 7165 // We want to say that we always want the arguments in registers. 7166 // It's unclear to me how manipulating the selection DAG here forces callers 7167 // to provide arguments in registers instead of on the stack. 7168 SDValue LogTypeId = getValue(I.getArgOperand(0)); 7169 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 7170 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 7171 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7172 SDValue Chain = getRoot(); 7173 Ops.push_back(LogTypeId); 7174 Ops.push_back(LogEntryVal); 7175 Ops.push_back(StrSizeVal); 7176 Ops.push_back(Chain); 7177 7178 // We need to enforce the calling convention for the callsite, so that 7179 // argument ordering is enforced correctly, and that register allocation can 7180 // see that some registers may be assumed clobbered and have to preserve 7181 // them across calls to the intrinsic. 7182 MachineSDNode *MN = DAG.getMachineNode( 7183 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops); 7184 SDValue patchableNode = SDValue(MN, 0); 7185 DAG.setRoot(patchableNode); 7186 setValue(&I, patchableNode); 7187 return; 7188 } 7189 case Intrinsic::experimental_deoptimize: 7190 LowerDeoptimizeCall(&I); 7191 return; 7192 case Intrinsic::experimental_stepvector: 7193 visitStepVector(I); 7194 return; 7195 case Intrinsic::vector_reduce_fadd: 7196 case Intrinsic::vector_reduce_fmul: 7197 case Intrinsic::vector_reduce_add: 7198 case Intrinsic::vector_reduce_mul: 7199 case Intrinsic::vector_reduce_and: 7200 case Intrinsic::vector_reduce_or: 7201 case Intrinsic::vector_reduce_xor: 7202 case Intrinsic::vector_reduce_smax: 7203 case Intrinsic::vector_reduce_smin: 7204 case Intrinsic::vector_reduce_umax: 7205 case Intrinsic::vector_reduce_umin: 7206 case Intrinsic::vector_reduce_fmax: 7207 case Intrinsic::vector_reduce_fmin: 7208 visitVectorReduce(I, Intrinsic); 7209 return; 7210 7211 case Intrinsic::icall_branch_funnel: { 7212 SmallVector<SDValue, 16> Ops; 7213 Ops.push_back(getValue(I.getArgOperand(0))); 7214 7215 int64_t Offset; 7216 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7217 I.getArgOperand(1), Offset, DAG.getDataLayout())); 7218 if (!Base) 7219 report_fatal_error( 7220 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7221 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0)); 7222 7223 struct BranchFunnelTarget { 7224 int64_t Offset; 7225 SDValue Target; 7226 }; 7227 SmallVector<BranchFunnelTarget, 8> Targets; 7228 7229 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) { 7230 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7231 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7232 if (ElemBase != Base) 7233 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7234 "to the same GlobalValue"); 7235 7236 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7237 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7238 if (!GA) 7239 report_fatal_error( 7240 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7241 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7242 GA->getGlobal(), sdl, Val.getValueType(), 7243 GA->getOffset())}); 7244 } 7245 llvm::sort(Targets, 7246 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7247 return T1.Offset < T2.Offset; 7248 }); 7249 7250 for (auto &T : Targets) { 7251 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32)); 7252 Ops.push_back(T.Target); 7253 } 7254 7255 Ops.push_back(DAG.getRoot()); // Chain 7256 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl, 7257 MVT::Other, Ops), 7258 0); 7259 DAG.setRoot(N); 7260 setValue(&I, N); 7261 HasTailCall = true; 7262 return; 7263 } 7264 7265 case Intrinsic::wasm_landingpad_index: 7266 // Information this intrinsic contained has been transferred to 7267 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7268 // delete it now. 7269 return; 7270 7271 case Intrinsic::aarch64_settag: 7272 case Intrinsic::aarch64_settag_zero: { 7273 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7274 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7275 SDValue Val = TSI.EmitTargetCodeForSetTag( 7276 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)), 7277 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7278 ZeroMemory); 7279 DAG.setRoot(Val); 7280 setValue(&I, Val); 7281 return; 7282 } 7283 case Intrinsic::ptrmask: { 7284 SDValue Ptr = getValue(I.getOperand(0)); 7285 SDValue Const = getValue(I.getOperand(1)); 7286 7287 EVT PtrVT = Ptr.getValueType(); 7288 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, 7289 DAG.getZExtOrTrunc(Const, sdl, PtrVT))); 7290 return; 7291 } 7292 case Intrinsic::threadlocal_address: { 7293 setValue(&I, getValue(I.getOperand(0))); 7294 return; 7295 } 7296 case Intrinsic::get_active_lane_mask: { 7297 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7298 SDValue Index = getValue(I.getOperand(0)); 7299 EVT ElementVT = Index.getValueType(); 7300 7301 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) { 7302 visitTargetIntrinsic(I, Intrinsic); 7303 return; 7304 } 7305 7306 SDValue TripCount = getValue(I.getOperand(1)); 7307 auto VecTy = CCVT.changeVectorElementType(ElementVT); 7308 7309 SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index); 7310 SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount); 7311 SDValue VectorStep = DAG.getStepVector(sdl, VecTy); 7312 SDValue VectorInduction = DAG.getNode( 7313 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep); 7314 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction, 7315 VectorTripCount, ISD::CondCode::SETULT); 7316 setValue(&I, SetCC); 7317 return; 7318 } 7319 case Intrinsic::vector_insert: { 7320 SDValue Vec = getValue(I.getOperand(0)); 7321 SDValue SubVec = getValue(I.getOperand(1)); 7322 SDValue Index = getValue(I.getOperand(2)); 7323 7324 // The intrinsic's index type is i64, but the SDNode requires an index type 7325 // suitable for the target. Convert the index as required. 7326 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7327 if (Index.getValueType() != VectorIdxTy) 7328 Index = DAG.getVectorIdxConstant( 7329 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7330 7331 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7332 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec, 7333 Index)); 7334 return; 7335 } 7336 case Intrinsic::vector_extract: { 7337 SDValue Vec = getValue(I.getOperand(0)); 7338 SDValue Index = getValue(I.getOperand(1)); 7339 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7340 7341 // The intrinsic's index type is i64, but the SDNode requires an index type 7342 // suitable for the target. Convert the index as required. 7343 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7344 if (Index.getValueType() != VectorIdxTy) 7345 Index = DAG.getVectorIdxConstant( 7346 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7347 7348 setValue(&I, 7349 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index)); 7350 return; 7351 } 7352 case Intrinsic::experimental_vector_reverse: 7353 visitVectorReverse(I); 7354 return; 7355 case Intrinsic::experimental_vector_splice: 7356 visitVectorSplice(I); 7357 return; 7358 case Intrinsic::callbr_landingpad: 7359 visitCallBrLandingPad(I); 7360 return; 7361 case Intrinsic::experimental_vector_interleave2: 7362 visitVectorInterleave(I); 7363 return; 7364 case Intrinsic::experimental_vector_deinterleave2: 7365 visitVectorDeinterleave(I); 7366 return; 7367 } 7368 } 7369 7370 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7371 const ConstrainedFPIntrinsic &FPI) { 7372 SDLoc sdl = getCurSDLoc(); 7373 7374 // We do not need to serialize constrained FP intrinsics against 7375 // each other or against (nonvolatile) loads, so they can be 7376 // chained like loads. 7377 SDValue Chain = DAG.getRoot(); 7378 SmallVector<SDValue, 4> Opers; 7379 Opers.push_back(Chain); 7380 if (FPI.isUnaryOp()) { 7381 Opers.push_back(getValue(FPI.getArgOperand(0))); 7382 } else if (FPI.isTernaryOp()) { 7383 Opers.push_back(getValue(FPI.getArgOperand(0))); 7384 Opers.push_back(getValue(FPI.getArgOperand(1))); 7385 Opers.push_back(getValue(FPI.getArgOperand(2))); 7386 } else { 7387 Opers.push_back(getValue(FPI.getArgOperand(0))); 7388 Opers.push_back(getValue(FPI.getArgOperand(1))); 7389 } 7390 7391 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7392 assert(Result.getNode()->getNumValues() == 2); 7393 7394 // Push node to the appropriate list so that future instructions can be 7395 // chained up correctly. 7396 SDValue OutChain = Result.getValue(1); 7397 switch (EB) { 7398 case fp::ExceptionBehavior::ebIgnore: 7399 // The only reason why ebIgnore nodes still need to be chained is that 7400 // they might depend on the current rounding mode, and therefore must 7401 // not be moved across instruction that may change that mode. 7402 [[fallthrough]]; 7403 case fp::ExceptionBehavior::ebMayTrap: 7404 // These must not be moved across calls or instructions that may change 7405 // floating-point exception masks. 7406 PendingConstrainedFP.push_back(OutChain); 7407 break; 7408 case fp::ExceptionBehavior::ebStrict: 7409 // These must not be moved across calls or instructions that may change 7410 // floating-point exception masks or read floating-point exception flags. 7411 // In addition, they cannot be optimized out even if unused. 7412 PendingConstrainedFPStrict.push_back(OutChain); 7413 break; 7414 } 7415 }; 7416 7417 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7418 EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType()); 7419 SDVTList VTs = DAG.getVTList(VT, MVT::Other); 7420 fp::ExceptionBehavior EB = *FPI.getExceptionBehavior(); 7421 7422 SDNodeFlags Flags; 7423 if (EB == fp::ExceptionBehavior::ebIgnore) 7424 Flags.setNoFPExcept(true); 7425 7426 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7427 Flags.copyFMF(*FPOp); 7428 7429 unsigned Opcode; 7430 switch (FPI.getIntrinsicID()) { 7431 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7432 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7433 case Intrinsic::INTRINSIC: \ 7434 Opcode = ISD::STRICT_##DAGN; \ 7435 break; 7436 #include "llvm/IR/ConstrainedOps.def" 7437 case Intrinsic::experimental_constrained_fmuladd: { 7438 Opcode = ISD::STRICT_FMA; 7439 // Break fmuladd into fmul and fadd. 7440 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7441 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 7442 Opers.pop_back(); 7443 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7444 pushOutChain(Mul, EB); 7445 Opcode = ISD::STRICT_FADD; 7446 Opers.clear(); 7447 Opers.push_back(Mul.getValue(1)); 7448 Opers.push_back(Mul.getValue(0)); 7449 Opers.push_back(getValue(FPI.getArgOperand(2))); 7450 } 7451 break; 7452 } 7453 } 7454 7455 // A few strict DAG nodes carry additional operands that are not 7456 // set up by the default code above. 7457 switch (Opcode) { 7458 default: break; 7459 case ISD::STRICT_FP_ROUND: 7460 Opers.push_back( 7461 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7462 break; 7463 case ISD::STRICT_FSETCC: 7464 case ISD::STRICT_FSETCCS: { 7465 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7466 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 7467 if (TM.Options.NoNaNsFPMath) 7468 Condition = getFCmpCodeWithoutNaN(Condition); 7469 Opers.push_back(DAG.getCondCode(Condition)); 7470 break; 7471 } 7472 } 7473 7474 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7475 pushOutChain(Result, EB); 7476 7477 SDValue FPResult = Result.getValue(0); 7478 setValue(&FPI, FPResult); 7479 } 7480 7481 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 7482 std::optional<unsigned> ResOPC; 7483 switch (VPIntrin.getIntrinsicID()) { 7484 case Intrinsic::vp_ctlz: { 7485 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 7486 ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ; 7487 break; 7488 } 7489 case Intrinsic::vp_cttz: { 7490 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 7491 ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ; 7492 break; 7493 } 7494 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \ 7495 case Intrinsic::VPID: \ 7496 ResOPC = ISD::VPSD; \ 7497 break; 7498 #include "llvm/IR/VPIntrinsics.def" 7499 } 7500 7501 if (!ResOPC) 7502 llvm_unreachable( 7503 "Inconsistency: no SDNode available for this VPIntrinsic!"); 7504 7505 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD || 7506 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) { 7507 if (VPIntrin.getFastMathFlags().allowReassoc()) 7508 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD 7509 : ISD::VP_REDUCE_FMUL; 7510 } 7511 7512 return *ResOPC; 7513 } 7514 7515 void SelectionDAGBuilder::visitVPLoad( 7516 const VPIntrinsic &VPIntrin, EVT VT, 7517 const SmallVectorImpl<SDValue> &OpValues) { 7518 SDLoc DL = getCurSDLoc(); 7519 Value *PtrOperand = VPIntrin.getArgOperand(0); 7520 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7521 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7522 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7523 SDValue LD; 7524 // Do not serialize variable-length loads of constant memory with 7525 // anything. 7526 if (!Alignment) 7527 Alignment = DAG.getEVTAlign(VT); 7528 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7529 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7530 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7531 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7532 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7533 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7534 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2], 7535 MMO, false /*IsExpanding */); 7536 if (AddToChain) 7537 PendingLoads.push_back(LD.getValue(1)); 7538 setValue(&VPIntrin, LD); 7539 } 7540 7541 void SelectionDAGBuilder::visitVPGather( 7542 const VPIntrinsic &VPIntrin, EVT VT, 7543 const SmallVectorImpl<SDValue> &OpValues) { 7544 SDLoc DL = getCurSDLoc(); 7545 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7546 Value *PtrOperand = VPIntrin.getArgOperand(0); 7547 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7548 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7549 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7550 SDValue LD; 7551 if (!Alignment) 7552 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7553 unsigned AS = 7554 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7555 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7556 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 7557 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7558 SDValue Base, Index, Scale; 7559 ISD::MemIndexType IndexType; 7560 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7561 this, VPIntrin.getParent(), 7562 VT.getScalarStoreSize()); 7563 if (!UniformBase) { 7564 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7565 Index = getValue(PtrOperand); 7566 IndexType = ISD::SIGNED_SCALED; 7567 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7568 } 7569 EVT IdxVT = Index.getValueType(); 7570 EVT EltTy = IdxVT.getVectorElementType(); 7571 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7572 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7573 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7574 } 7575 LD = DAG.getGatherVP( 7576 DAG.getVTList(VT, MVT::Other), VT, DL, 7577 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO, 7578 IndexType); 7579 PendingLoads.push_back(LD.getValue(1)); 7580 setValue(&VPIntrin, LD); 7581 } 7582 7583 void SelectionDAGBuilder::visitVPStore( 7584 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 7585 SDLoc DL = getCurSDLoc(); 7586 Value *PtrOperand = VPIntrin.getArgOperand(1); 7587 EVT VT = OpValues[0].getValueType(); 7588 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7589 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7590 SDValue ST; 7591 if (!Alignment) 7592 Alignment = DAG.getEVTAlign(VT); 7593 SDValue Ptr = OpValues[1]; 7594 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 7595 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7596 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7597 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7598 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset, 7599 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED, 7600 /* IsTruncating */ false, /*IsCompressing*/ false); 7601 DAG.setRoot(ST); 7602 setValue(&VPIntrin, ST); 7603 } 7604 7605 void SelectionDAGBuilder::visitVPScatter( 7606 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 7607 SDLoc DL = getCurSDLoc(); 7608 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7609 Value *PtrOperand = VPIntrin.getArgOperand(1); 7610 EVT VT = OpValues[0].getValueType(); 7611 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7612 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7613 SDValue ST; 7614 if (!Alignment) 7615 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7616 unsigned AS = 7617 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7618 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7619 MachinePointerInfo(AS), MachineMemOperand::MOStore, 7620 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7621 SDValue Base, Index, Scale; 7622 ISD::MemIndexType IndexType; 7623 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7624 this, VPIntrin.getParent(), 7625 VT.getScalarStoreSize()); 7626 if (!UniformBase) { 7627 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7628 Index = getValue(PtrOperand); 7629 IndexType = ISD::SIGNED_SCALED; 7630 Scale = 7631 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7632 } 7633 EVT IdxVT = Index.getValueType(); 7634 EVT EltTy = IdxVT.getVectorElementType(); 7635 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7636 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7637 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7638 } 7639 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL, 7640 {getMemoryRoot(), OpValues[0], Base, Index, Scale, 7641 OpValues[2], OpValues[3]}, 7642 MMO, IndexType); 7643 DAG.setRoot(ST); 7644 setValue(&VPIntrin, ST); 7645 } 7646 7647 void SelectionDAGBuilder::visitVPStridedLoad( 7648 const VPIntrinsic &VPIntrin, EVT VT, 7649 const SmallVectorImpl<SDValue> &OpValues) { 7650 SDLoc DL = getCurSDLoc(); 7651 Value *PtrOperand = VPIntrin.getArgOperand(0); 7652 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7653 if (!Alignment) 7654 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7655 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7656 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7657 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7658 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7659 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7660 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7661 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7662 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7663 7664 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], 7665 OpValues[2], OpValues[3], MMO, 7666 false /*IsExpanding*/); 7667 7668 if (AddToChain) 7669 PendingLoads.push_back(LD.getValue(1)); 7670 setValue(&VPIntrin, LD); 7671 } 7672 7673 void SelectionDAGBuilder::visitVPStridedStore( 7674 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 7675 SDLoc DL = getCurSDLoc(); 7676 Value *PtrOperand = VPIntrin.getArgOperand(1); 7677 EVT VT = OpValues[0].getValueType(); 7678 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7679 if (!Alignment) 7680 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7681 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7682 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7683 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7684 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7685 7686 SDValue ST = DAG.getStridedStoreVP( 7687 getMemoryRoot(), DL, OpValues[0], OpValues[1], 7688 DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3], 7689 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false, 7690 /*IsCompressing*/ false); 7691 7692 DAG.setRoot(ST); 7693 setValue(&VPIntrin, ST); 7694 } 7695 7696 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) { 7697 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7698 SDLoc DL = getCurSDLoc(); 7699 7700 ISD::CondCode Condition; 7701 CmpInst::Predicate CondCode = VPIntrin.getPredicate(); 7702 bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy(); 7703 if (IsFP) { 7704 // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan) 7705 // flags, but calls that don't return floating-point types can't be 7706 // FPMathOperators, like vp.fcmp. This affects constrained fcmp too. 7707 Condition = getFCmpCondCode(CondCode); 7708 if (TM.Options.NoNaNsFPMath) 7709 Condition = getFCmpCodeWithoutNaN(Condition); 7710 } else { 7711 Condition = getICmpCondCode(CondCode); 7712 } 7713 7714 SDValue Op1 = getValue(VPIntrin.getOperand(0)); 7715 SDValue Op2 = getValue(VPIntrin.getOperand(1)); 7716 // #2 is the condition code 7717 SDValue MaskOp = getValue(VPIntrin.getOperand(3)); 7718 SDValue EVL = getValue(VPIntrin.getOperand(4)); 7719 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7720 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7721 "Unexpected target EVL type"); 7722 EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL); 7723 7724 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7725 VPIntrin.getType()); 7726 setValue(&VPIntrin, 7727 DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL)); 7728 } 7729 7730 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 7731 const VPIntrinsic &VPIntrin) { 7732 SDLoc DL = getCurSDLoc(); 7733 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 7734 7735 auto IID = VPIntrin.getIntrinsicID(); 7736 7737 if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin)) 7738 return visitVPCmp(*CmpI); 7739 7740 SmallVector<EVT, 4> ValueVTs; 7741 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7742 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 7743 SDVTList VTs = DAG.getVTList(ValueVTs); 7744 7745 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID); 7746 7747 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7748 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7749 "Unexpected target EVL type"); 7750 7751 // Request operands. 7752 SmallVector<SDValue, 7> OpValues; 7753 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) { 7754 auto Op = getValue(VPIntrin.getArgOperand(I)); 7755 if (I == EVLParamPos) 7756 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op); 7757 OpValues.push_back(Op); 7758 } 7759 7760 switch (Opcode) { 7761 default: { 7762 SDNodeFlags SDFlags; 7763 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 7764 SDFlags.copyFMF(*FPMO); 7765 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags); 7766 setValue(&VPIntrin, Result); 7767 break; 7768 } 7769 case ISD::VP_LOAD: 7770 visitVPLoad(VPIntrin, ValueVTs[0], OpValues); 7771 break; 7772 case ISD::VP_GATHER: 7773 visitVPGather(VPIntrin, ValueVTs[0], OpValues); 7774 break; 7775 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: 7776 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues); 7777 break; 7778 case ISD::VP_STORE: 7779 visitVPStore(VPIntrin, OpValues); 7780 break; 7781 case ISD::VP_SCATTER: 7782 visitVPScatter(VPIntrin, OpValues); 7783 break; 7784 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: 7785 visitVPStridedStore(VPIntrin, OpValues); 7786 break; 7787 case ISD::VP_FMULADD: { 7788 assert(OpValues.size() == 5 && "Unexpected number of operands"); 7789 SDNodeFlags SDFlags; 7790 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 7791 SDFlags.copyFMF(*FPMO); 7792 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 7793 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) { 7794 setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags)); 7795 } else { 7796 SDValue Mul = DAG.getNode( 7797 ISD::VP_FMUL, DL, VTs, 7798 {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags); 7799 SDValue Add = 7800 DAG.getNode(ISD::VP_FADD, DL, VTs, 7801 {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags); 7802 setValue(&VPIntrin, Add); 7803 } 7804 break; 7805 } 7806 case ISD::VP_INTTOPTR: { 7807 SDValue N = OpValues[0]; 7808 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType()); 7809 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType()); 7810 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 7811 OpValues[2]); 7812 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 7813 OpValues[2]); 7814 setValue(&VPIntrin, N); 7815 break; 7816 } 7817 case ISD::VP_PTRTOINT: { 7818 SDValue N = OpValues[0]; 7819 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7820 VPIntrin.getType()); 7821 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), 7822 VPIntrin.getOperand(0)->getType()); 7823 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 7824 OpValues[2]); 7825 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 7826 OpValues[2]); 7827 setValue(&VPIntrin, N); 7828 break; 7829 } 7830 case ISD::VP_ABS: 7831 case ISD::VP_CTLZ: 7832 case ISD::VP_CTLZ_ZERO_UNDEF: 7833 case ISD::VP_CTTZ: 7834 case ISD::VP_CTTZ_ZERO_UNDEF: { 7835 SDValue Result = 7836 DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]}); 7837 setValue(&VPIntrin, Result); 7838 break; 7839 } 7840 } 7841 } 7842 7843 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 7844 const BasicBlock *EHPadBB, 7845 MCSymbol *&BeginLabel) { 7846 MachineFunction &MF = DAG.getMachineFunction(); 7847 MachineModuleInfo &MMI = MF.getMMI(); 7848 7849 // Insert a label before the invoke call to mark the try range. This can be 7850 // used to detect deletion of the invoke via the MachineModuleInfo. 7851 BeginLabel = MMI.getContext().createTempSymbol(); 7852 7853 // For SjLj, keep track of which landing pads go with which invokes 7854 // so as to maintain the ordering of pads in the LSDA. 7855 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7856 if (CallSiteIndex) { 7857 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7858 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7859 7860 // Now that the call site is handled, stop tracking it. 7861 MMI.setCurrentCallSite(0); 7862 } 7863 7864 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 7865 } 7866 7867 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 7868 const BasicBlock *EHPadBB, 7869 MCSymbol *BeginLabel) { 7870 assert(BeginLabel && "BeginLabel should've been set"); 7871 7872 MachineFunction &MF = DAG.getMachineFunction(); 7873 MachineModuleInfo &MMI = MF.getMMI(); 7874 7875 // Insert a label at the end of the invoke call to mark the try range. This 7876 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7877 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7878 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 7879 7880 // Inform MachineModuleInfo of range. 7881 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7882 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7883 // actually use outlined funclets and their LSDA info style. 7884 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7885 assert(II && "II should've been set"); 7886 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 7887 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 7888 } else if (!isScopedEHPersonality(Pers)) { 7889 assert(EHPadBB); 7890 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7891 } 7892 7893 return Chain; 7894 } 7895 7896 std::pair<SDValue, SDValue> 7897 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7898 const BasicBlock *EHPadBB) { 7899 MCSymbol *BeginLabel = nullptr; 7900 7901 if (EHPadBB) { 7902 // Both PendingLoads and PendingExports must be flushed here; 7903 // this call might not return. 7904 (void)getRoot(); 7905 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 7906 CLI.setChain(getRoot()); 7907 } 7908 7909 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7910 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7911 7912 assert((CLI.IsTailCall || Result.second.getNode()) && 7913 "Non-null chain expected with non-tail call!"); 7914 assert((Result.second.getNode() || !Result.first.getNode()) && 7915 "Null value expected with tail call!"); 7916 7917 if (!Result.second.getNode()) { 7918 // As a special case, a null chain means that a tail call has been emitted 7919 // and the DAG root is already updated. 7920 HasTailCall = true; 7921 7922 // Since there's no actual continuation from this block, nothing can be 7923 // relying on us setting vregs for them. 7924 PendingExports.clear(); 7925 } else { 7926 DAG.setRoot(Result.second); 7927 } 7928 7929 if (EHPadBB) { 7930 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 7931 BeginLabel)); 7932 } 7933 7934 return Result; 7935 } 7936 7937 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 7938 bool isTailCall, 7939 bool isMustTailCall, 7940 const BasicBlock *EHPadBB) { 7941 auto &DL = DAG.getDataLayout(); 7942 FunctionType *FTy = CB.getFunctionType(); 7943 Type *RetTy = CB.getType(); 7944 7945 TargetLowering::ArgListTy Args; 7946 Args.reserve(CB.arg_size()); 7947 7948 const Value *SwiftErrorVal = nullptr; 7949 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7950 7951 if (isTailCall) { 7952 // Avoid emitting tail calls in functions with the disable-tail-calls 7953 // attribute. 7954 auto *Caller = CB.getParent()->getParent(); 7955 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7956 "true" && !isMustTailCall) 7957 isTailCall = false; 7958 7959 // We can't tail call inside a function with a swifterror argument. Lowering 7960 // does not support this yet. It would have to move into the swifterror 7961 // register before the call. 7962 if (TLI.supportSwiftError() && 7963 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7964 isTailCall = false; 7965 } 7966 7967 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 7968 TargetLowering::ArgListEntry Entry; 7969 const Value *V = *I; 7970 7971 // Skip empty types 7972 if (V->getType()->isEmptyTy()) 7973 continue; 7974 7975 SDValue ArgNode = getValue(V); 7976 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7977 7978 Entry.setAttributes(&CB, I - CB.arg_begin()); 7979 7980 // Use swifterror virtual register as input to the call. 7981 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7982 SwiftErrorVal = V; 7983 // We find the virtual register for the actual swifterror argument. 7984 // Instead of using the Value, we use the virtual register instead. 7985 Entry.Node = 7986 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 7987 EVT(TLI.getPointerTy(DL))); 7988 } 7989 7990 Args.push_back(Entry); 7991 7992 // If we have an explicit sret argument that is an Instruction, (i.e., it 7993 // might point to function-local memory), we can't meaningfully tail-call. 7994 if (Entry.IsSRet && isa<Instruction>(V)) 7995 isTailCall = false; 7996 } 7997 7998 // If call site has a cfguardtarget operand bundle, create and add an 7999 // additional ArgListEntry. 8000 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 8001 TargetLowering::ArgListEntry Entry; 8002 Value *V = Bundle->Inputs[0]; 8003 SDValue ArgNode = getValue(V); 8004 Entry.Node = ArgNode; 8005 Entry.Ty = V->getType(); 8006 Entry.IsCFGuardTarget = true; 8007 Args.push_back(Entry); 8008 } 8009 8010 // Check if target-independent constraints permit a tail call here. 8011 // Target-dependent constraints are checked within TLI->LowerCallTo. 8012 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 8013 isTailCall = false; 8014 8015 // Disable tail calls if there is an swifterror argument. Targets have not 8016 // been updated to support tail calls. 8017 if (TLI.supportSwiftError() && SwiftErrorVal) 8018 isTailCall = false; 8019 8020 ConstantInt *CFIType = nullptr; 8021 if (CB.isIndirectCall()) { 8022 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) { 8023 if (!TLI.supportKCFIBundles()) 8024 report_fatal_error( 8025 "Target doesn't support calls with kcfi operand bundles."); 8026 CFIType = cast<ConstantInt>(Bundle->Inputs[0]); 8027 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type"); 8028 } 8029 } 8030 8031 TargetLowering::CallLoweringInfo CLI(DAG); 8032 CLI.setDebugLoc(getCurSDLoc()) 8033 .setChain(getRoot()) 8034 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 8035 .setTailCall(isTailCall) 8036 .setConvergent(CB.isConvergent()) 8037 .setIsPreallocated( 8038 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0) 8039 .setCFIType(CFIType); 8040 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8041 8042 if (Result.first.getNode()) { 8043 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 8044 setValue(&CB, Result.first); 8045 } 8046 8047 // The last element of CLI.InVals has the SDValue for swifterror return. 8048 // Here we copy it to a virtual register and update SwiftErrorMap for 8049 // book-keeping. 8050 if (SwiftErrorVal && TLI.supportSwiftError()) { 8051 // Get the last element of InVals. 8052 SDValue Src = CLI.InVals.back(); 8053 Register VReg = 8054 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 8055 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 8056 DAG.setRoot(CopyNode); 8057 } 8058 } 8059 8060 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 8061 SelectionDAGBuilder &Builder) { 8062 // Check to see if this load can be trivially constant folded, e.g. if the 8063 // input is from a string literal. 8064 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 8065 // Cast pointer to the type we really want to load. 8066 Type *LoadTy = 8067 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 8068 if (LoadVT.isVector()) 8069 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 8070 8071 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 8072 PointerType::getUnqual(LoadTy)); 8073 8074 if (const Constant *LoadCst = 8075 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput), 8076 LoadTy, Builder.DAG.getDataLayout())) 8077 return Builder.getValue(LoadCst); 8078 } 8079 8080 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 8081 // still constant memory, the input chain can be the entry node. 8082 SDValue Root; 8083 bool ConstantMemory = false; 8084 8085 // Do not serialize (non-volatile) loads of constant memory with anything. 8086 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 8087 Root = Builder.DAG.getEntryNode(); 8088 ConstantMemory = true; 8089 } else { 8090 // Do not serialize non-volatile loads against each other. 8091 Root = Builder.DAG.getRoot(); 8092 } 8093 8094 SDValue Ptr = Builder.getValue(PtrVal); 8095 SDValue LoadVal = 8096 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 8097 MachinePointerInfo(PtrVal), Align(1)); 8098 8099 if (!ConstantMemory) 8100 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 8101 return LoadVal; 8102 } 8103 8104 /// Record the value for an instruction that produces an integer result, 8105 /// converting the type where necessary. 8106 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 8107 SDValue Value, 8108 bool IsSigned) { 8109 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8110 I.getType(), true); 8111 if (IsSigned) 8112 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 8113 else 8114 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 8115 setValue(&I, Value); 8116 } 8117 8118 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 8119 /// true and lower it. Otherwise return false, and it will be lowered like a 8120 /// normal call. 8121 /// The caller already checked that \p I calls the appropriate LibFunc with a 8122 /// correct prototype. 8123 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 8124 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 8125 const Value *Size = I.getArgOperand(2); 8126 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size)); 8127 if (CSize && CSize->getZExtValue() == 0) { 8128 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8129 I.getType(), true); 8130 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 8131 return true; 8132 } 8133 8134 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8135 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 8136 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 8137 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 8138 if (Res.first.getNode()) { 8139 processIntegerCallValue(I, Res.first, true); 8140 PendingLoads.push_back(Res.second); 8141 return true; 8142 } 8143 8144 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 8145 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 8146 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 8147 return false; 8148 8149 // If the target has a fast compare for the given size, it will return a 8150 // preferred load type for that size. Require that the load VT is legal and 8151 // that the target supports unaligned loads of that type. Otherwise, return 8152 // INVALID. 8153 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 8154 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8155 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 8156 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 8157 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 8158 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 8159 // TODO: Check alignment of src and dest ptrs. 8160 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 8161 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 8162 if (!TLI.isTypeLegal(LVT) || 8163 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 8164 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 8165 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 8166 } 8167 8168 return LVT; 8169 }; 8170 8171 // This turns into unaligned loads. We only do this if the target natively 8172 // supports the MVT we'll be loading or if it is small enough (<= 4) that 8173 // we'll only produce a small number of byte loads. 8174 MVT LoadVT; 8175 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 8176 switch (NumBitsToCompare) { 8177 default: 8178 return false; 8179 case 16: 8180 LoadVT = MVT::i16; 8181 break; 8182 case 32: 8183 LoadVT = MVT::i32; 8184 break; 8185 case 64: 8186 case 128: 8187 case 256: 8188 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 8189 break; 8190 } 8191 8192 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 8193 return false; 8194 8195 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 8196 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 8197 8198 // Bitcast to a wide integer type if the loads are vectors. 8199 if (LoadVT.isVector()) { 8200 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 8201 LoadL = DAG.getBitcast(CmpVT, LoadL); 8202 LoadR = DAG.getBitcast(CmpVT, LoadR); 8203 } 8204 8205 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 8206 processIntegerCallValue(I, Cmp, false); 8207 return true; 8208 } 8209 8210 /// See if we can lower a memchr call into an optimized form. If so, return 8211 /// true and lower it. Otherwise return false, and it will be lowered like a 8212 /// normal call. 8213 /// The caller already checked that \p I calls the appropriate LibFunc with a 8214 /// correct prototype. 8215 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 8216 const Value *Src = I.getArgOperand(0); 8217 const Value *Char = I.getArgOperand(1); 8218 const Value *Length = I.getArgOperand(2); 8219 8220 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8221 std::pair<SDValue, SDValue> Res = 8222 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 8223 getValue(Src), getValue(Char), getValue(Length), 8224 MachinePointerInfo(Src)); 8225 if (Res.first.getNode()) { 8226 setValue(&I, Res.first); 8227 PendingLoads.push_back(Res.second); 8228 return true; 8229 } 8230 8231 return false; 8232 } 8233 8234 /// See if we can lower a mempcpy call into an optimized form. If so, return 8235 /// true and lower it. Otherwise return false, and it will be lowered like a 8236 /// normal call. 8237 /// The caller already checked that \p I calls the appropriate LibFunc with a 8238 /// correct prototype. 8239 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 8240 SDValue Dst = getValue(I.getArgOperand(0)); 8241 SDValue Src = getValue(I.getArgOperand(1)); 8242 SDValue Size = getValue(I.getArgOperand(2)); 8243 8244 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 8245 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 8246 // DAG::getMemcpy needs Alignment to be defined. 8247 Align Alignment = std::min(DstAlign, SrcAlign); 8248 8249 bool isVol = false; 8250 SDLoc sdl = getCurSDLoc(); 8251 8252 // In the mempcpy context we need to pass in a false value for isTailCall 8253 // because the return pointer needs to be adjusted by the size of 8254 // the copied memory. 8255 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 8256 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false, 8257 /*isTailCall=*/false, 8258 MachinePointerInfo(I.getArgOperand(0)), 8259 MachinePointerInfo(I.getArgOperand(1)), 8260 I.getAAMetadata()); 8261 assert(MC.getNode() != nullptr && 8262 "** memcpy should not be lowered as TailCall in mempcpy context **"); 8263 DAG.setRoot(MC); 8264 8265 // Check if Size needs to be truncated or extended. 8266 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 8267 8268 // Adjust return pointer to point just past the last dst byte. 8269 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 8270 Dst, Size); 8271 setValue(&I, DstPlusSize); 8272 return true; 8273 } 8274 8275 /// See if we can lower a strcpy call into an optimized form. If so, return 8276 /// true and lower it, otherwise return false and it will be lowered like a 8277 /// normal call. 8278 /// The caller already checked that \p I calls the appropriate LibFunc with a 8279 /// correct prototype. 8280 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 8281 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8282 8283 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8284 std::pair<SDValue, SDValue> Res = 8285 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 8286 getValue(Arg0), getValue(Arg1), 8287 MachinePointerInfo(Arg0), 8288 MachinePointerInfo(Arg1), isStpcpy); 8289 if (Res.first.getNode()) { 8290 setValue(&I, Res.first); 8291 DAG.setRoot(Res.second); 8292 return true; 8293 } 8294 8295 return false; 8296 } 8297 8298 /// See if we can lower a strcmp call into an optimized form. If so, return 8299 /// true and lower it, otherwise return false and it will be lowered like a 8300 /// normal call. 8301 /// The caller already checked that \p I calls the appropriate LibFunc with a 8302 /// correct prototype. 8303 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 8304 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8305 8306 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8307 std::pair<SDValue, SDValue> Res = 8308 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 8309 getValue(Arg0), getValue(Arg1), 8310 MachinePointerInfo(Arg0), 8311 MachinePointerInfo(Arg1)); 8312 if (Res.first.getNode()) { 8313 processIntegerCallValue(I, Res.first, true); 8314 PendingLoads.push_back(Res.second); 8315 return true; 8316 } 8317 8318 return false; 8319 } 8320 8321 /// See if we can lower a strlen call into an optimized form. If so, return 8322 /// true and lower it, otherwise return false and it will be lowered like a 8323 /// normal call. 8324 /// The caller already checked that \p I calls the appropriate LibFunc with a 8325 /// correct prototype. 8326 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 8327 const Value *Arg0 = I.getArgOperand(0); 8328 8329 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8330 std::pair<SDValue, SDValue> Res = 8331 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 8332 getValue(Arg0), MachinePointerInfo(Arg0)); 8333 if (Res.first.getNode()) { 8334 processIntegerCallValue(I, Res.first, false); 8335 PendingLoads.push_back(Res.second); 8336 return true; 8337 } 8338 8339 return false; 8340 } 8341 8342 /// See if we can lower a strnlen call into an optimized form. If so, return 8343 /// true and lower it, otherwise return false and it will be lowered like a 8344 /// normal call. 8345 /// The caller already checked that \p I calls the appropriate LibFunc with a 8346 /// correct prototype. 8347 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 8348 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8349 8350 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8351 std::pair<SDValue, SDValue> Res = 8352 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 8353 getValue(Arg0), getValue(Arg1), 8354 MachinePointerInfo(Arg0)); 8355 if (Res.first.getNode()) { 8356 processIntegerCallValue(I, Res.first, false); 8357 PendingLoads.push_back(Res.second); 8358 return true; 8359 } 8360 8361 return false; 8362 } 8363 8364 /// See if we can lower a unary floating-point operation into an SDNode with 8365 /// the specified Opcode. If so, return true and lower it, otherwise return 8366 /// false and it will be lowered like a normal call. 8367 /// The caller already checked that \p I calls the appropriate LibFunc with a 8368 /// correct prototype. 8369 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 8370 unsigned Opcode) { 8371 // We already checked this call's prototype; verify it doesn't modify errno. 8372 if (!I.onlyReadsMemory()) 8373 return false; 8374 8375 SDNodeFlags Flags; 8376 Flags.copyFMF(cast<FPMathOperator>(I)); 8377 8378 SDValue Tmp = getValue(I.getArgOperand(0)); 8379 setValue(&I, 8380 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 8381 return true; 8382 } 8383 8384 /// See if we can lower a binary floating-point operation into an SDNode with 8385 /// the specified Opcode. If so, return true and lower it. Otherwise return 8386 /// false, and it will be lowered like a normal call. 8387 /// The caller already checked that \p I calls the appropriate LibFunc with a 8388 /// correct prototype. 8389 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 8390 unsigned Opcode) { 8391 // We already checked this call's prototype; verify it doesn't modify errno. 8392 if (!I.onlyReadsMemory()) 8393 return false; 8394 8395 SDNodeFlags Flags; 8396 Flags.copyFMF(cast<FPMathOperator>(I)); 8397 8398 SDValue Tmp0 = getValue(I.getArgOperand(0)); 8399 SDValue Tmp1 = getValue(I.getArgOperand(1)); 8400 EVT VT = Tmp0.getValueType(); 8401 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 8402 return true; 8403 } 8404 8405 void SelectionDAGBuilder::visitCall(const CallInst &I) { 8406 // Handle inline assembly differently. 8407 if (I.isInlineAsm()) { 8408 visitInlineAsm(I); 8409 return; 8410 } 8411 8412 diagnoseDontCall(I); 8413 8414 if (Function *F = I.getCalledFunction()) { 8415 if (F->isDeclaration()) { 8416 // Is this an LLVM intrinsic or a target-specific intrinsic? 8417 unsigned IID = F->getIntrinsicID(); 8418 if (!IID) 8419 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 8420 IID = II->getIntrinsicID(F); 8421 8422 if (IID) { 8423 visitIntrinsicCall(I, IID); 8424 return; 8425 } 8426 } 8427 8428 // Check for well-known libc/libm calls. If the function is internal, it 8429 // can't be a library call. Don't do the check if marked as nobuiltin for 8430 // some reason or the call site requires strict floating point semantics. 8431 LibFunc Func; 8432 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 8433 F->hasName() && LibInfo->getLibFunc(*F, Func) && 8434 LibInfo->hasOptimizedCodeGen(Func)) { 8435 switch (Func) { 8436 default: break; 8437 case LibFunc_bcmp: 8438 if (visitMemCmpBCmpCall(I)) 8439 return; 8440 break; 8441 case LibFunc_copysign: 8442 case LibFunc_copysignf: 8443 case LibFunc_copysignl: 8444 // We already checked this call's prototype; verify it doesn't modify 8445 // errno. 8446 if (I.onlyReadsMemory()) { 8447 SDValue LHS = getValue(I.getArgOperand(0)); 8448 SDValue RHS = getValue(I.getArgOperand(1)); 8449 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 8450 LHS.getValueType(), LHS, RHS)); 8451 return; 8452 } 8453 break; 8454 case LibFunc_fabs: 8455 case LibFunc_fabsf: 8456 case LibFunc_fabsl: 8457 if (visitUnaryFloatCall(I, ISD::FABS)) 8458 return; 8459 break; 8460 case LibFunc_fmin: 8461 case LibFunc_fminf: 8462 case LibFunc_fminl: 8463 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 8464 return; 8465 break; 8466 case LibFunc_fmax: 8467 case LibFunc_fmaxf: 8468 case LibFunc_fmaxl: 8469 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 8470 return; 8471 break; 8472 case LibFunc_sin: 8473 case LibFunc_sinf: 8474 case LibFunc_sinl: 8475 if (visitUnaryFloatCall(I, ISD::FSIN)) 8476 return; 8477 break; 8478 case LibFunc_cos: 8479 case LibFunc_cosf: 8480 case LibFunc_cosl: 8481 if (visitUnaryFloatCall(I, ISD::FCOS)) 8482 return; 8483 break; 8484 case LibFunc_sqrt: 8485 case LibFunc_sqrtf: 8486 case LibFunc_sqrtl: 8487 case LibFunc_sqrt_finite: 8488 case LibFunc_sqrtf_finite: 8489 case LibFunc_sqrtl_finite: 8490 if (visitUnaryFloatCall(I, ISD::FSQRT)) 8491 return; 8492 break; 8493 case LibFunc_floor: 8494 case LibFunc_floorf: 8495 case LibFunc_floorl: 8496 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 8497 return; 8498 break; 8499 case LibFunc_nearbyint: 8500 case LibFunc_nearbyintf: 8501 case LibFunc_nearbyintl: 8502 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 8503 return; 8504 break; 8505 case LibFunc_ceil: 8506 case LibFunc_ceilf: 8507 case LibFunc_ceill: 8508 if (visitUnaryFloatCall(I, ISD::FCEIL)) 8509 return; 8510 break; 8511 case LibFunc_rint: 8512 case LibFunc_rintf: 8513 case LibFunc_rintl: 8514 if (visitUnaryFloatCall(I, ISD::FRINT)) 8515 return; 8516 break; 8517 case LibFunc_round: 8518 case LibFunc_roundf: 8519 case LibFunc_roundl: 8520 if (visitUnaryFloatCall(I, ISD::FROUND)) 8521 return; 8522 break; 8523 case LibFunc_trunc: 8524 case LibFunc_truncf: 8525 case LibFunc_truncl: 8526 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 8527 return; 8528 break; 8529 case LibFunc_log2: 8530 case LibFunc_log2f: 8531 case LibFunc_log2l: 8532 if (visitUnaryFloatCall(I, ISD::FLOG2)) 8533 return; 8534 break; 8535 case LibFunc_exp2: 8536 case LibFunc_exp2f: 8537 case LibFunc_exp2l: 8538 if (visitUnaryFloatCall(I, ISD::FEXP2)) 8539 return; 8540 break; 8541 case LibFunc_memcmp: 8542 if (visitMemCmpBCmpCall(I)) 8543 return; 8544 break; 8545 case LibFunc_mempcpy: 8546 if (visitMemPCpyCall(I)) 8547 return; 8548 break; 8549 case LibFunc_memchr: 8550 if (visitMemChrCall(I)) 8551 return; 8552 break; 8553 case LibFunc_strcpy: 8554 if (visitStrCpyCall(I, false)) 8555 return; 8556 break; 8557 case LibFunc_stpcpy: 8558 if (visitStrCpyCall(I, true)) 8559 return; 8560 break; 8561 case LibFunc_strcmp: 8562 if (visitStrCmpCall(I)) 8563 return; 8564 break; 8565 case LibFunc_strlen: 8566 if (visitStrLenCall(I)) 8567 return; 8568 break; 8569 case LibFunc_strnlen: 8570 if (visitStrNLenCall(I)) 8571 return; 8572 break; 8573 } 8574 } 8575 } 8576 8577 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 8578 // have to do anything here to lower funclet bundles. 8579 // CFGuardTarget bundles are lowered in LowerCallTo. 8580 assert(!I.hasOperandBundlesOtherThan( 8581 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 8582 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 8583 LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) && 8584 "Cannot lower calls with arbitrary operand bundles!"); 8585 8586 SDValue Callee = getValue(I.getCalledOperand()); 8587 8588 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 8589 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 8590 else 8591 // Check if we can potentially perform a tail call. More detailed checking 8592 // is be done within LowerCallTo, after more information about the call is 8593 // known. 8594 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 8595 } 8596 8597 namespace { 8598 8599 /// AsmOperandInfo - This contains information for each constraint that we are 8600 /// lowering. 8601 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 8602 public: 8603 /// CallOperand - If this is the result output operand or a clobber 8604 /// this is null, otherwise it is the incoming operand to the CallInst. 8605 /// This gets modified as the asm is processed. 8606 SDValue CallOperand; 8607 8608 /// AssignedRegs - If this is a register or register class operand, this 8609 /// contains the set of register corresponding to the operand. 8610 RegsForValue AssignedRegs; 8611 8612 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 8613 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 8614 } 8615 8616 /// Whether or not this operand accesses memory 8617 bool hasMemory(const TargetLowering &TLI) const { 8618 // Indirect operand accesses access memory. 8619 if (isIndirect) 8620 return true; 8621 8622 for (const auto &Code : Codes) 8623 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 8624 return true; 8625 8626 return false; 8627 } 8628 }; 8629 8630 8631 } // end anonymous namespace 8632 8633 /// Make sure that the output operand \p OpInfo and its corresponding input 8634 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 8635 /// out). 8636 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 8637 SDISelAsmOperandInfo &MatchingOpInfo, 8638 SelectionDAG &DAG) { 8639 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 8640 return; 8641 8642 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 8643 const auto &TLI = DAG.getTargetLoweringInfo(); 8644 8645 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 8646 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 8647 OpInfo.ConstraintVT); 8648 std::pair<unsigned, const TargetRegisterClass *> InputRC = 8649 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 8650 MatchingOpInfo.ConstraintVT); 8651 if ((OpInfo.ConstraintVT.isInteger() != 8652 MatchingOpInfo.ConstraintVT.isInteger()) || 8653 (MatchRC.second != InputRC.second)) { 8654 // FIXME: error out in a more elegant fashion 8655 report_fatal_error("Unsupported asm: input constraint" 8656 " with a matching output constraint of" 8657 " incompatible type!"); 8658 } 8659 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 8660 } 8661 8662 /// Get a direct memory input to behave well as an indirect operand. 8663 /// This may introduce stores, hence the need for a \p Chain. 8664 /// \return The (possibly updated) chain. 8665 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 8666 SDISelAsmOperandInfo &OpInfo, 8667 SelectionDAG &DAG) { 8668 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8669 8670 // If we don't have an indirect input, put it in the constpool if we can, 8671 // otherwise spill it to a stack slot. 8672 // TODO: This isn't quite right. We need to handle these according to 8673 // the addressing mode that the constraint wants. Also, this may take 8674 // an additional register for the computation and we don't want that 8675 // either. 8676 8677 // If the operand is a float, integer, or vector constant, spill to a 8678 // constant pool entry to get its address. 8679 const Value *OpVal = OpInfo.CallOperandVal; 8680 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 8681 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 8682 OpInfo.CallOperand = DAG.getConstantPool( 8683 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 8684 return Chain; 8685 } 8686 8687 // Otherwise, create a stack slot and emit a store to it before the asm. 8688 Type *Ty = OpVal->getType(); 8689 auto &DL = DAG.getDataLayout(); 8690 uint64_t TySize = DL.getTypeAllocSize(Ty); 8691 MachineFunction &MF = DAG.getMachineFunction(); 8692 int SSFI = MF.getFrameInfo().CreateStackObject( 8693 TySize, DL.getPrefTypeAlign(Ty), false); 8694 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 8695 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 8696 MachinePointerInfo::getFixedStack(MF, SSFI), 8697 TLI.getMemValueType(DL, Ty)); 8698 OpInfo.CallOperand = StackSlot; 8699 8700 return Chain; 8701 } 8702 8703 /// GetRegistersForValue - Assign registers (virtual or physical) for the 8704 /// specified operand. We prefer to assign virtual registers, to allow the 8705 /// register allocator to handle the assignment process. However, if the asm 8706 /// uses features that we can't model on machineinstrs, we have SDISel do the 8707 /// allocation. This produces generally horrible, but correct, code. 8708 /// 8709 /// OpInfo describes the operand 8710 /// RefOpInfo describes the matching operand if any, the operand otherwise 8711 static std::optional<unsigned> 8712 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 8713 SDISelAsmOperandInfo &OpInfo, 8714 SDISelAsmOperandInfo &RefOpInfo) { 8715 LLVMContext &Context = *DAG.getContext(); 8716 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8717 8718 MachineFunction &MF = DAG.getMachineFunction(); 8719 SmallVector<unsigned, 4> Regs; 8720 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8721 8722 // No work to do for memory/address operands. 8723 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8724 OpInfo.ConstraintType == TargetLowering::C_Address) 8725 return std::nullopt; 8726 8727 // If this is a constraint for a single physreg, or a constraint for a 8728 // register class, find it. 8729 unsigned AssignedReg; 8730 const TargetRegisterClass *RC; 8731 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 8732 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 8733 // RC is unset only on failure. Return immediately. 8734 if (!RC) 8735 return std::nullopt; 8736 8737 // Get the actual register value type. This is important, because the user 8738 // may have asked for (e.g.) the AX register in i32 type. We need to 8739 // remember that AX is actually i16 to get the right extension. 8740 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 8741 8742 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) { 8743 // If this is an FP operand in an integer register (or visa versa), or more 8744 // generally if the operand value disagrees with the register class we plan 8745 // to stick it in, fix the operand type. 8746 // 8747 // If this is an input value, the bitcast to the new type is done now. 8748 // Bitcast for output value is done at the end of visitInlineAsm(). 8749 if ((OpInfo.Type == InlineAsm::isOutput || 8750 OpInfo.Type == InlineAsm::isInput) && 8751 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 8752 // Try to convert to the first EVT that the reg class contains. If the 8753 // types are identical size, use a bitcast to convert (e.g. two differing 8754 // vector types). Note: output bitcast is done at the end of 8755 // visitInlineAsm(). 8756 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 8757 // Exclude indirect inputs while they are unsupported because the code 8758 // to perform the load is missing and thus OpInfo.CallOperand still 8759 // refers to the input address rather than the pointed-to value. 8760 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 8761 OpInfo.CallOperand = 8762 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 8763 OpInfo.ConstraintVT = RegVT; 8764 // If the operand is an FP value and we want it in integer registers, 8765 // use the corresponding integer type. This turns an f64 value into 8766 // i64, which can be passed with two i32 values on a 32-bit machine. 8767 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 8768 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 8769 if (OpInfo.Type == InlineAsm::isInput) 8770 OpInfo.CallOperand = 8771 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 8772 OpInfo.ConstraintVT = VT; 8773 } 8774 } 8775 } 8776 8777 // No need to allocate a matching input constraint since the constraint it's 8778 // matching to has already been allocated. 8779 if (OpInfo.isMatchingInputConstraint()) 8780 return std::nullopt; 8781 8782 EVT ValueVT = OpInfo.ConstraintVT; 8783 if (OpInfo.ConstraintVT == MVT::Other) 8784 ValueVT = RegVT; 8785 8786 // Initialize NumRegs. 8787 unsigned NumRegs = 1; 8788 if (OpInfo.ConstraintVT != MVT::Other) 8789 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT); 8790 8791 // If this is a constraint for a specific physical register, like {r17}, 8792 // assign it now. 8793 8794 // If this associated to a specific register, initialize iterator to correct 8795 // place. If virtual, make sure we have enough registers 8796 8797 // Initialize iterator if necessary 8798 TargetRegisterClass::iterator I = RC->begin(); 8799 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8800 8801 // Do not check for single registers. 8802 if (AssignedReg) { 8803 I = std::find(I, RC->end(), AssignedReg); 8804 if (I == RC->end()) { 8805 // RC does not contain the selected register, which indicates a 8806 // mismatch between the register and the required type/bitwidth. 8807 return {AssignedReg}; 8808 } 8809 } 8810 8811 for (; NumRegs; --NumRegs, ++I) { 8812 assert(I != RC->end() && "Ran out of registers to allocate!"); 8813 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8814 Regs.push_back(R); 8815 } 8816 8817 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8818 return std::nullopt; 8819 } 8820 8821 static unsigned 8822 findMatchingInlineAsmOperand(unsigned OperandNo, 8823 const std::vector<SDValue> &AsmNodeOperands) { 8824 // Scan until we find the definition we already emitted of this operand. 8825 unsigned CurOp = InlineAsm::Op_FirstOperand; 8826 for (; OperandNo; --OperandNo) { 8827 // Advance to the next operand. 8828 unsigned OpFlag = 8829 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8830 assert((InlineAsm::isRegDefKind(OpFlag) || 8831 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8832 InlineAsm::isMemKind(OpFlag)) && 8833 "Skipped past definitions?"); 8834 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8835 } 8836 return CurOp; 8837 } 8838 8839 namespace { 8840 8841 class ExtraFlags { 8842 unsigned Flags = 0; 8843 8844 public: 8845 explicit ExtraFlags(const CallBase &Call) { 8846 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8847 if (IA->hasSideEffects()) 8848 Flags |= InlineAsm::Extra_HasSideEffects; 8849 if (IA->isAlignStack()) 8850 Flags |= InlineAsm::Extra_IsAlignStack; 8851 if (Call.isConvergent()) 8852 Flags |= InlineAsm::Extra_IsConvergent; 8853 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8854 } 8855 8856 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8857 // Ideally, we would only check against memory constraints. However, the 8858 // meaning of an Other constraint can be target-specific and we can't easily 8859 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8860 // for Other constraints as well. 8861 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8862 OpInfo.ConstraintType == TargetLowering::C_Other) { 8863 if (OpInfo.Type == InlineAsm::isInput) 8864 Flags |= InlineAsm::Extra_MayLoad; 8865 else if (OpInfo.Type == InlineAsm::isOutput) 8866 Flags |= InlineAsm::Extra_MayStore; 8867 else if (OpInfo.Type == InlineAsm::isClobber) 8868 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8869 } 8870 } 8871 8872 unsigned get() const { return Flags; } 8873 }; 8874 8875 } // end anonymous namespace 8876 8877 static bool isFunction(SDValue Op) { 8878 if (Op && Op.getOpcode() == ISD::GlobalAddress) { 8879 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 8880 auto Fn = dyn_cast_or_null<Function>(GA->getGlobal()); 8881 8882 // In normal "call dllimport func" instruction (non-inlineasm) it force 8883 // indirect access by specifing call opcode. And usually specially print 8884 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can 8885 // not do in this way now. (In fact, this is similar with "Data Access" 8886 // action). So here we ignore dllimport function. 8887 if (Fn && !Fn->hasDLLImportStorageClass()) 8888 return true; 8889 } 8890 } 8891 return false; 8892 } 8893 8894 /// visitInlineAsm - Handle a call to an InlineAsm object. 8895 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 8896 const BasicBlock *EHPadBB) { 8897 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8898 8899 /// ConstraintOperands - Information about all of the constraints. 8900 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 8901 8902 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8903 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8904 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 8905 8906 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8907 // AsmDialect, MayLoad, MayStore). 8908 bool HasSideEffect = IA->hasSideEffects(); 8909 ExtraFlags ExtraInfo(Call); 8910 8911 for (auto &T : TargetConstraints) { 8912 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8913 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8914 8915 if (OpInfo.CallOperandVal) 8916 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8917 8918 if (!HasSideEffect) 8919 HasSideEffect = OpInfo.hasMemory(TLI); 8920 8921 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8922 // FIXME: Could we compute this on OpInfo rather than T? 8923 8924 // Compute the constraint code and ConstraintType to use. 8925 TLI.ComputeConstraintToUse(T, SDValue()); 8926 8927 if (T.ConstraintType == TargetLowering::C_Immediate && 8928 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8929 // We've delayed emitting a diagnostic like the "n" constraint because 8930 // inlining could cause an integer showing up. 8931 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 8932 "' expects an integer constant " 8933 "expression"); 8934 8935 ExtraInfo.update(T); 8936 } 8937 8938 // We won't need to flush pending loads if this asm doesn't touch 8939 // memory and is nonvolatile. 8940 SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8941 8942 bool EmitEHLabels = isa<InvokeInst>(Call); 8943 if (EmitEHLabels) { 8944 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 8945 } 8946 bool IsCallBr = isa<CallBrInst>(Call); 8947 8948 if (IsCallBr || EmitEHLabels) { 8949 // If this is a callbr or invoke we need to flush pending exports since 8950 // inlineasm_br and invoke are terminators. 8951 // We need to do this before nodes are glued to the inlineasm_br node. 8952 Chain = getControlRoot(); 8953 } 8954 8955 MCSymbol *BeginLabel = nullptr; 8956 if (EmitEHLabels) { 8957 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 8958 } 8959 8960 int OpNo = -1; 8961 SmallVector<StringRef> AsmStrs; 8962 IA->collectAsmStrs(AsmStrs); 8963 8964 // Second pass over the constraints: compute which constraint option to use. 8965 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8966 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput) 8967 OpNo++; 8968 8969 // If this is an output operand with a matching input operand, look up the 8970 // matching input. If their types mismatch, e.g. one is an integer, the 8971 // other is floating point, or their sizes are different, flag it as an 8972 // error. 8973 if (OpInfo.hasMatchingInput()) { 8974 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8975 patchMatchingInput(OpInfo, Input, DAG); 8976 } 8977 8978 // Compute the constraint code and ConstraintType to use. 8979 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8980 8981 if ((OpInfo.ConstraintType == TargetLowering::C_Memory && 8982 OpInfo.Type == InlineAsm::isClobber) || 8983 OpInfo.ConstraintType == TargetLowering::C_Address) 8984 continue; 8985 8986 // In Linux PIC model, there are 4 cases about value/label addressing: 8987 // 8988 // 1: Function call or Label jmp inside the module. 8989 // 2: Data access (such as global variable, static variable) inside module. 8990 // 3: Function call or Label jmp outside the module. 8991 // 4: Data access (such as global variable) outside the module. 8992 // 8993 // Due to current llvm inline asm architecture designed to not "recognize" 8994 // the asm code, there are quite troubles for us to treat mem addressing 8995 // differently for same value/adress used in different instuctions. 8996 // For example, in pic model, call a func may in plt way or direclty 8997 // pc-related, but lea/mov a function adress may use got. 8998 // 8999 // Here we try to "recognize" function call for the case 1 and case 3 in 9000 // inline asm. And try to adjust the constraint for them. 9001 // 9002 // TODO: Due to current inline asm didn't encourage to jmp to the outsider 9003 // label, so here we don't handle jmp function label now, but we need to 9004 // enhance it (especilly in PIC model) if we meet meaningful requirements. 9005 if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) && 9006 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) && 9007 TM.getCodeModel() != CodeModel::Large) { 9008 OpInfo.isIndirect = false; 9009 OpInfo.ConstraintType = TargetLowering::C_Address; 9010 } 9011 9012 // If this is a memory input, and if the operand is not indirect, do what we 9013 // need to provide an address for the memory input. 9014 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 9015 !OpInfo.isIndirect) { 9016 assert((OpInfo.isMultipleAlternative || 9017 (OpInfo.Type == InlineAsm::isInput)) && 9018 "Can only indirectify direct input operands!"); 9019 9020 // Memory operands really want the address of the value. 9021 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 9022 9023 // There is no longer a Value* corresponding to this operand. 9024 OpInfo.CallOperandVal = nullptr; 9025 9026 // It is now an indirect operand. 9027 OpInfo.isIndirect = true; 9028 } 9029 9030 } 9031 9032 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 9033 std::vector<SDValue> AsmNodeOperands; 9034 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 9035 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 9036 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 9037 9038 // If we have a !srcloc metadata node associated with it, we want to attach 9039 // this to the ultimately generated inline asm machineinstr. To do this, we 9040 // pass in the third operand as this (potentially null) inline asm MDNode. 9041 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 9042 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 9043 9044 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 9045 // bits as operand 3. 9046 AsmNodeOperands.push_back(DAG.getTargetConstant( 9047 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9048 9049 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 9050 // this, assign virtual and physical registers for inputs and otput. 9051 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9052 // Assign Registers. 9053 SDISelAsmOperandInfo &RefOpInfo = 9054 OpInfo.isMatchingInputConstraint() 9055 ? ConstraintOperands[OpInfo.getMatchedOperand()] 9056 : OpInfo; 9057 const auto RegError = 9058 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 9059 if (RegError) { 9060 const MachineFunction &MF = DAG.getMachineFunction(); 9061 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9062 const char *RegName = TRI.getName(*RegError); 9063 emitInlineAsmError(Call, "register '" + Twine(RegName) + 9064 "' allocated for constraint '" + 9065 Twine(OpInfo.ConstraintCode) + 9066 "' does not match required type"); 9067 return; 9068 } 9069 9070 auto DetectWriteToReservedRegister = [&]() { 9071 const MachineFunction &MF = DAG.getMachineFunction(); 9072 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9073 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 9074 if (Register::isPhysicalRegister(Reg) && 9075 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 9076 const char *RegName = TRI.getName(Reg); 9077 emitInlineAsmError(Call, "write to reserved register '" + 9078 Twine(RegName) + "'"); 9079 return true; 9080 } 9081 } 9082 return false; 9083 }; 9084 assert((OpInfo.ConstraintType != TargetLowering::C_Address || 9085 (OpInfo.Type == InlineAsm::isInput && 9086 !OpInfo.isMatchingInputConstraint())) && 9087 "Only address as input operand is allowed."); 9088 9089 switch (OpInfo.Type) { 9090 case InlineAsm::isOutput: 9091 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9092 unsigned ConstraintID = 9093 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9094 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9095 "Failed to convert memory constraint code to constraint id."); 9096 9097 // Add information to the INLINEASM node to know about this output. 9098 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9099 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 9100 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 9101 MVT::i32)); 9102 AsmNodeOperands.push_back(OpInfo.CallOperand); 9103 } else { 9104 // Otherwise, this outputs to a register (directly for C_Register / 9105 // C_RegisterClass, and a target-defined fashion for 9106 // C_Immediate/C_Other). Find a register that we can use. 9107 if (OpInfo.AssignedRegs.Regs.empty()) { 9108 emitInlineAsmError( 9109 Call, "couldn't allocate output register for constraint '" + 9110 Twine(OpInfo.ConstraintCode) + "'"); 9111 return; 9112 } 9113 9114 if (DetectWriteToReservedRegister()) 9115 return; 9116 9117 // Add information to the INLINEASM node to know that this register is 9118 // set. 9119 OpInfo.AssignedRegs.AddInlineAsmOperands( 9120 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 9121 : InlineAsm::Kind_RegDef, 9122 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 9123 } 9124 break; 9125 9126 case InlineAsm::isInput: 9127 case InlineAsm::isLabel: { 9128 SDValue InOperandVal = OpInfo.CallOperand; 9129 9130 if (OpInfo.isMatchingInputConstraint()) { 9131 // If this is required to match an output register we have already set, 9132 // just use its register. 9133 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 9134 AsmNodeOperands); 9135 unsigned OpFlag = 9136 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 9137 if (InlineAsm::isRegDefKind(OpFlag) || 9138 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 9139 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 9140 if (OpInfo.isIndirect) { 9141 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 9142 emitInlineAsmError(Call, "inline asm not supported yet: " 9143 "don't know how to handle tied " 9144 "indirect register inputs"); 9145 return; 9146 } 9147 9148 SmallVector<unsigned, 4> Regs; 9149 MachineFunction &MF = DAG.getMachineFunction(); 9150 MachineRegisterInfo &MRI = MF.getRegInfo(); 9151 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9152 auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]); 9153 Register TiedReg = R->getReg(); 9154 MVT RegVT = R->getSimpleValueType(0); 9155 const TargetRegisterClass *RC = 9156 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg) 9157 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT) 9158 : TRI.getMinimalPhysRegClass(TiedReg); 9159 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 9160 for (unsigned i = 0; i != NumRegs; ++i) 9161 Regs.push_back(MRI.createVirtualRegister(RC)); 9162 9163 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 9164 9165 SDLoc dl = getCurSDLoc(); 9166 // Use the produced MatchedRegs object to 9167 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call); 9168 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 9169 true, OpInfo.getMatchedOperand(), dl, 9170 DAG, AsmNodeOperands); 9171 break; 9172 } 9173 9174 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 9175 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 9176 "Unexpected number of operands"); 9177 // Add information to the INLINEASM node to know about this input. 9178 // See InlineAsm.h isUseOperandTiedToDef. 9179 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 9180 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 9181 OpInfo.getMatchedOperand()); 9182 AsmNodeOperands.push_back(DAG.getTargetConstant( 9183 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9184 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 9185 break; 9186 } 9187 9188 // Treat indirect 'X' constraint as memory. 9189 if (OpInfo.ConstraintType == TargetLowering::C_Other && 9190 OpInfo.isIndirect) 9191 OpInfo.ConstraintType = TargetLowering::C_Memory; 9192 9193 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 9194 OpInfo.ConstraintType == TargetLowering::C_Other) { 9195 std::vector<SDValue> Ops; 9196 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 9197 Ops, DAG); 9198 if (Ops.empty()) { 9199 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 9200 if (isa<ConstantSDNode>(InOperandVal)) { 9201 emitInlineAsmError(Call, "value out of range for constraint '" + 9202 Twine(OpInfo.ConstraintCode) + "'"); 9203 return; 9204 } 9205 9206 emitInlineAsmError(Call, 9207 "invalid operand for inline asm constraint '" + 9208 Twine(OpInfo.ConstraintCode) + "'"); 9209 return; 9210 } 9211 9212 // Add information to the INLINEASM node to know about this input. 9213 unsigned ResOpType = 9214 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 9215 AsmNodeOperands.push_back(DAG.getTargetConstant( 9216 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9217 llvm::append_range(AsmNodeOperands, Ops); 9218 break; 9219 } 9220 9221 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9222 assert((OpInfo.isIndirect || 9223 OpInfo.ConstraintType != TargetLowering::C_Memory) && 9224 "Operand must be indirect to be a mem!"); 9225 assert(InOperandVal.getValueType() == 9226 TLI.getPointerTy(DAG.getDataLayout()) && 9227 "Memory operands expect pointer values"); 9228 9229 unsigned ConstraintID = 9230 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9231 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9232 "Failed to convert memory constraint code to constraint id."); 9233 9234 // Add information to the INLINEASM node to know about this input. 9235 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9236 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 9237 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 9238 getCurSDLoc(), 9239 MVT::i32)); 9240 AsmNodeOperands.push_back(InOperandVal); 9241 break; 9242 } 9243 9244 if (OpInfo.ConstraintType == TargetLowering::C_Address) { 9245 assert(InOperandVal.getValueType() == 9246 TLI.getPointerTy(DAG.getDataLayout()) && 9247 "Address operands expect pointer values"); 9248 9249 unsigned ConstraintID = 9250 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9251 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9252 "Failed to convert memory constraint code to constraint id."); 9253 9254 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9255 9256 SDValue AsmOp = InOperandVal; 9257 if (isFunction(InOperandVal)) { 9258 auto *GA = cast<GlobalAddressSDNode>(InOperandVal); 9259 ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Func, 1); 9260 AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(), 9261 InOperandVal.getValueType(), 9262 GA->getOffset()); 9263 } 9264 9265 // Add information to the INLINEASM node to know about this input. 9266 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 9267 9268 AsmNodeOperands.push_back( 9269 DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32)); 9270 9271 AsmNodeOperands.push_back(AsmOp); 9272 break; 9273 } 9274 9275 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 9276 OpInfo.ConstraintType == TargetLowering::C_Register) && 9277 "Unknown constraint type!"); 9278 9279 // TODO: Support this. 9280 if (OpInfo.isIndirect) { 9281 emitInlineAsmError( 9282 Call, "Don't know how to handle indirect register inputs yet " 9283 "for constraint '" + 9284 Twine(OpInfo.ConstraintCode) + "'"); 9285 return; 9286 } 9287 9288 // Copy the input into the appropriate registers. 9289 if (OpInfo.AssignedRegs.Regs.empty()) { 9290 emitInlineAsmError(Call, 9291 "couldn't allocate input reg for constraint '" + 9292 Twine(OpInfo.ConstraintCode) + "'"); 9293 return; 9294 } 9295 9296 if (DetectWriteToReservedRegister()) 9297 return; 9298 9299 SDLoc dl = getCurSDLoc(); 9300 9301 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, 9302 &Call); 9303 9304 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 9305 dl, DAG, AsmNodeOperands); 9306 break; 9307 } 9308 case InlineAsm::isClobber: 9309 // Add the clobbered value to the operand list, so that the register 9310 // allocator is aware that the physreg got clobbered. 9311 if (!OpInfo.AssignedRegs.Regs.empty()) 9312 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 9313 false, 0, getCurSDLoc(), DAG, 9314 AsmNodeOperands); 9315 break; 9316 } 9317 } 9318 9319 // Finish up input operands. Set the input chain and add the flag last. 9320 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 9321 if (Glue.getNode()) AsmNodeOperands.push_back(Glue); 9322 9323 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 9324 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 9325 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 9326 Glue = Chain.getValue(1); 9327 9328 // Do additional work to generate outputs. 9329 9330 SmallVector<EVT, 1> ResultVTs; 9331 SmallVector<SDValue, 1> ResultValues; 9332 SmallVector<SDValue, 8> OutChains; 9333 9334 llvm::Type *CallResultType = Call.getType(); 9335 ArrayRef<Type *> ResultTypes; 9336 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 9337 ResultTypes = StructResult->elements(); 9338 else if (!CallResultType->isVoidTy()) 9339 ResultTypes = ArrayRef(CallResultType); 9340 9341 auto CurResultType = ResultTypes.begin(); 9342 auto handleRegAssign = [&](SDValue V) { 9343 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 9344 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 9345 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 9346 ++CurResultType; 9347 // If the type of the inline asm call site return value is different but has 9348 // same size as the type of the asm output bitcast it. One example of this 9349 // is for vectors with different width / number of elements. This can 9350 // happen for register classes that can contain multiple different value 9351 // types. The preg or vreg allocated may not have the same VT as was 9352 // expected. 9353 // 9354 // This can also happen for a return value that disagrees with the register 9355 // class it is put in, eg. a double in a general-purpose register on a 9356 // 32-bit machine. 9357 if (ResultVT != V.getValueType() && 9358 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 9359 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 9360 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 9361 V.getValueType().isInteger()) { 9362 // If a result value was tied to an input value, the computed result 9363 // may have a wider width than the expected result. Extract the 9364 // relevant portion. 9365 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 9366 } 9367 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 9368 ResultVTs.push_back(ResultVT); 9369 ResultValues.push_back(V); 9370 }; 9371 9372 // Deal with output operands. 9373 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9374 if (OpInfo.Type == InlineAsm::isOutput) { 9375 SDValue Val; 9376 // Skip trivial output operands. 9377 if (OpInfo.AssignedRegs.Regs.empty()) 9378 continue; 9379 9380 switch (OpInfo.ConstraintType) { 9381 case TargetLowering::C_Register: 9382 case TargetLowering::C_RegisterClass: 9383 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 9384 Chain, &Glue, &Call); 9385 break; 9386 case TargetLowering::C_Immediate: 9387 case TargetLowering::C_Other: 9388 Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(), 9389 OpInfo, DAG); 9390 break; 9391 case TargetLowering::C_Memory: 9392 break; // Already handled. 9393 case TargetLowering::C_Address: 9394 break; // Silence warning. 9395 case TargetLowering::C_Unknown: 9396 assert(false && "Unexpected unknown constraint"); 9397 } 9398 9399 // Indirect output manifest as stores. Record output chains. 9400 if (OpInfo.isIndirect) { 9401 const Value *Ptr = OpInfo.CallOperandVal; 9402 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 9403 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 9404 MachinePointerInfo(Ptr)); 9405 OutChains.push_back(Store); 9406 } else { 9407 // generate CopyFromRegs to associated registers. 9408 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 9409 if (Val.getOpcode() == ISD::MERGE_VALUES) { 9410 for (const SDValue &V : Val->op_values()) 9411 handleRegAssign(V); 9412 } else 9413 handleRegAssign(Val); 9414 } 9415 } 9416 } 9417 9418 // Set results. 9419 if (!ResultValues.empty()) { 9420 assert(CurResultType == ResultTypes.end() && 9421 "Mismatch in number of ResultTypes"); 9422 assert(ResultValues.size() == ResultTypes.size() && 9423 "Mismatch in number of output operands in asm result"); 9424 9425 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 9426 DAG.getVTList(ResultVTs), ResultValues); 9427 setValue(&Call, V); 9428 } 9429 9430 // Collect store chains. 9431 if (!OutChains.empty()) 9432 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 9433 9434 if (EmitEHLabels) { 9435 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 9436 } 9437 9438 // Only Update Root if inline assembly has a memory effect. 9439 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 9440 EmitEHLabels) 9441 DAG.setRoot(Chain); 9442 } 9443 9444 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 9445 const Twine &Message) { 9446 LLVMContext &Ctx = *DAG.getContext(); 9447 Ctx.emitError(&Call, Message); 9448 9449 // Make sure we leave the DAG in a valid state 9450 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9451 SmallVector<EVT, 1> ValueVTs; 9452 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 9453 9454 if (ValueVTs.empty()) 9455 return; 9456 9457 SmallVector<SDValue, 1> Ops; 9458 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 9459 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 9460 9461 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 9462 } 9463 9464 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 9465 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 9466 MVT::Other, getRoot(), 9467 getValue(I.getArgOperand(0)), 9468 DAG.getSrcValue(I.getArgOperand(0)))); 9469 } 9470 9471 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 9472 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9473 const DataLayout &DL = DAG.getDataLayout(); 9474 SDValue V = DAG.getVAArg( 9475 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 9476 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 9477 DL.getABITypeAlign(I.getType()).value()); 9478 DAG.setRoot(V.getValue(1)); 9479 9480 if (I.getType()->isPointerTy()) 9481 V = DAG.getPtrExtOrTrunc( 9482 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 9483 setValue(&I, V); 9484 } 9485 9486 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 9487 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 9488 MVT::Other, getRoot(), 9489 getValue(I.getArgOperand(0)), 9490 DAG.getSrcValue(I.getArgOperand(0)))); 9491 } 9492 9493 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 9494 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 9495 MVT::Other, getRoot(), 9496 getValue(I.getArgOperand(0)), 9497 getValue(I.getArgOperand(1)), 9498 DAG.getSrcValue(I.getArgOperand(0)), 9499 DAG.getSrcValue(I.getArgOperand(1)))); 9500 } 9501 9502 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 9503 const Instruction &I, 9504 SDValue Op) { 9505 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 9506 if (!Range) 9507 return Op; 9508 9509 ConstantRange CR = getConstantRangeFromMetadata(*Range); 9510 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 9511 return Op; 9512 9513 APInt Lo = CR.getUnsignedMin(); 9514 if (!Lo.isMinValue()) 9515 return Op; 9516 9517 APInt Hi = CR.getUnsignedMax(); 9518 unsigned Bits = std::max(Hi.getActiveBits(), 9519 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 9520 9521 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9522 9523 SDLoc SL = getCurSDLoc(); 9524 9525 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 9526 DAG.getValueType(SmallVT)); 9527 unsigned NumVals = Op.getNode()->getNumValues(); 9528 if (NumVals == 1) 9529 return ZExt; 9530 9531 SmallVector<SDValue, 4> Ops; 9532 9533 Ops.push_back(ZExt); 9534 for (unsigned I = 1; I != NumVals; ++I) 9535 Ops.push_back(Op.getValue(I)); 9536 9537 return DAG.getMergeValues(Ops, SL); 9538 } 9539 9540 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 9541 /// the call being lowered. 9542 /// 9543 /// This is a helper for lowering intrinsics that follow a target calling 9544 /// convention or require stack pointer adjustment. Only a subset of the 9545 /// intrinsic's operands need to participate in the calling convention. 9546 void SelectionDAGBuilder::populateCallLoweringInfo( 9547 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 9548 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 9549 bool IsPatchPoint) { 9550 TargetLowering::ArgListTy Args; 9551 Args.reserve(NumArgs); 9552 9553 // Populate the argument list. 9554 // Attributes for args start at offset 1, after the return attribute. 9555 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 9556 ArgI != ArgE; ++ArgI) { 9557 const Value *V = Call->getOperand(ArgI); 9558 9559 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 9560 9561 TargetLowering::ArgListEntry Entry; 9562 Entry.Node = getValue(V); 9563 Entry.Ty = V->getType(); 9564 Entry.setAttributes(Call, ArgI); 9565 Args.push_back(Entry); 9566 } 9567 9568 CLI.setDebugLoc(getCurSDLoc()) 9569 .setChain(getRoot()) 9570 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 9571 .setDiscardResult(Call->use_empty()) 9572 .setIsPatchPoint(IsPatchPoint) 9573 .setIsPreallocated( 9574 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 9575 } 9576 9577 /// Add a stack map intrinsic call's live variable operands to a stackmap 9578 /// or patchpoint target node's operand list. 9579 /// 9580 /// Constants are converted to TargetConstants purely as an optimization to 9581 /// avoid constant materialization and register allocation. 9582 /// 9583 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 9584 /// generate addess computation nodes, and so FinalizeISel can convert the 9585 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 9586 /// address materialization and register allocation, but may also be required 9587 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 9588 /// alloca in the entry block, then the runtime may assume that the alloca's 9589 /// StackMap location can be read immediately after compilation and that the 9590 /// location is valid at any point during execution (this is similar to the 9591 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 9592 /// only available in a register, then the runtime would need to trap when 9593 /// execution reaches the StackMap in order to read the alloca's location. 9594 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 9595 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 9596 SelectionDAGBuilder &Builder) { 9597 SelectionDAG &DAG = Builder.DAG; 9598 for (unsigned I = StartIdx; I < Call.arg_size(); I++) { 9599 SDValue Op = Builder.getValue(Call.getArgOperand(I)); 9600 9601 // Things on the stack are pointer-typed, meaning that they are already 9602 // legal and can be emitted directly to target nodes. 9603 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) { 9604 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType())); 9605 } else { 9606 // Otherwise emit a target independent node to be legalised. 9607 Ops.push_back(Builder.getValue(Call.getArgOperand(I))); 9608 } 9609 } 9610 } 9611 9612 /// Lower llvm.experimental.stackmap. 9613 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 9614 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>, 9615 // [live variables...]) 9616 9617 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 9618 9619 SDValue Chain, InGlue, Callee; 9620 SmallVector<SDValue, 32> Ops; 9621 9622 SDLoc DL = getCurSDLoc(); 9623 Callee = getValue(CI.getCalledOperand()); 9624 9625 // The stackmap intrinsic only records the live variables (the arguments 9626 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 9627 // intrinsic, this won't be lowered to a function call. This means we don't 9628 // have to worry about calling conventions and target specific lowering code. 9629 // Instead we perform the call lowering right here. 9630 // 9631 // chain, flag = CALLSEQ_START(chain, 0, 0) 9632 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 9633 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 9634 // 9635 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 9636 InGlue = Chain.getValue(1); 9637 9638 // Add the STACKMAP operands, starting with DAG house-keeping. 9639 Ops.push_back(Chain); 9640 Ops.push_back(InGlue); 9641 9642 // Add the <id>, <numShadowBytes> operands. 9643 // 9644 // These do not require legalisation, and can be emitted directly to target 9645 // constant nodes. 9646 SDValue ID = getValue(CI.getArgOperand(0)); 9647 assert(ID.getValueType() == MVT::i64); 9648 SDValue IDConst = DAG.getTargetConstant( 9649 cast<ConstantSDNode>(ID)->getZExtValue(), DL, ID.getValueType()); 9650 Ops.push_back(IDConst); 9651 9652 SDValue Shad = getValue(CI.getArgOperand(1)); 9653 assert(Shad.getValueType() == MVT::i32); 9654 SDValue ShadConst = DAG.getTargetConstant( 9655 cast<ConstantSDNode>(Shad)->getZExtValue(), DL, Shad.getValueType()); 9656 Ops.push_back(ShadConst); 9657 9658 // Add the live variables. 9659 addStackMapLiveVars(CI, 2, DL, Ops, *this); 9660 9661 // Create the STACKMAP node. 9662 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9663 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops); 9664 InGlue = Chain.getValue(1); 9665 9666 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL); 9667 9668 // Stackmaps don't generate values, so nothing goes into the NodeMap. 9669 9670 // Set the root to the target-lowered call chain. 9671 DAG.setRoot(Chain); 9672 9673 // Inform the Frame Information that we have a stackmap in this function. 9674 FuncInfo.MF->getFrameInfo().setHasStackMap(); 9675 } 9676 9677 /// Lower llvm.experimental.patchpoint directly to its target opcode. 9678 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 9679 const BasicBlock *EHPadBB) { 9680 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 9681 // i32 <numBytes>, 9682 // i8* <target>, 9683 // i32 <numArgs>, 9684 // [Args...], 9685 // [live variables...]) 9686 9687 CallingConv::ID CC = CB.getCallingConv(); 9688 bool IsAnyRegCC = CC == CallingConv::AnyReg; 9689 bool HasDef = !CB.getType()->isVoidTy(); 9690 SDLoc dl = getCurSDLoc(); 9691 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 9692 9693 // Handle immediate and symbolic callees. 9694 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 9695 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 9696 /*isTarget=*/true); 9697 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 9698 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 9699 SDLoc(SymbolicCallee), 9700 SymbolicCallee->getValueType(0)); 9701 9702 // Get the real number of arguments participating in the call <numArgs> 9703 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 9704 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 9705 9706 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 9707 // Intrinsics include all meta-operands up to but not including CC. 9708 unsigned NumMetaOpers = PatchPointOpers::CCPos; 9709 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 9710 "Not enough arguments provided to the patchpoint intrinsic"); 9711 9712 // For AnyRegCC the arguments are lowered later on manually. 9713 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 9714 Type *ReturnTy = 9715 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 9716 9717 TargetLowering::CallLoweringInfo CLI(DAG); 9718 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 9719 ReturnTy, true); 9720 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 9721 9722 SDNode *CallEnd = Result.second.getNode(); 9723 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 9724 CallEnd = CallEnd->getOperand(0).getNode(); 9725 9726 /// Get a call instruction from the call sequence chain. 9727 /// Tail calls are not allowed. 9728 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 9729 "Expected a callseq node."); 9730 SDNode *Call = CallEnd->getOperand(0).getNode(); 9731 bool HasGlue = Call->getGluedNode(); 9732 9733 // Replace the target specific call node with the patchable intrinsic. 9734 SmallVector<SDValue, 8> Ops; 9735 9736 // Push the chain. 9737 Ops.push_back(*(Call->op_begin())); 9738 9739 // Optionally, push the glue (if any). 9740 if (HasGlue) 9741 Ops.push_back(*(Call->op_end() - 1)); 9742 9743 // Push the register mask info. 9744 if (HasGlue) 9745 Ops.push_back(*(Call->op_end() - 2)); 9746 else 9747 Ops.push_back(*(Call->op_end() - 1)); 9748 9749 // Add the <id> and <numBytes> constants. 9750 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 9751 Ops.push_back(DAG.getTargetConstant( 9752 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 9753 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 9754 Ops.push_back(DAG.getTargetConstant( 9755 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 9756 MVT::i32)); 9757 9758 // Add the callee. 9759 Ops.push_back(Callee); 9760 9761 // Adjust <numArgs> to account for any arguments that have been passed on the 9762 // stack instead. 9763 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 9764 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 9765 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 9766 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 9767 9768 // Add the calling convention 9769 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 9770 9771 // Add the arguments we omitted previously. The register allocator should 9772 // place these in any free register. 9773 if (IsAnyRegCC) 9774 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 9775 Ops.push_back(getValue(CB.getArgOperand(i))); 9776 9777 // Push the arguments from the call instruction. 9778 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 9779 Ops.append(Call->op_begin() + 2, e); 9780 9781 // Push live variables for the stack map. 9782 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 9783 9784 SDVTList NodeTys; 9785 if (IsAnyRegCC && HasDef) { 9786 // Create the return types based on the intrinsic definition 9787 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9788 SmallVector<EVT, 3> ValueVTs; 9789 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 9790 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 9791 9792 // There is always a chain and a glue type at the end 9793 ValueVTs.push_back(MVT::Other); 9794 ValueVTs.push_back(MVT::Glue); 9795 NodeTys = DAG.getVTList(ValueVTs); 9796 } else 9797 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9798 9799 // Replace the target specific call node with a PATCHPOINT node. 9800 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops); 9801 9802 // Update the NodeMap. 9803 if (HasDef) { 9804 if (IsAnyRegCC) 9805 setValue(&CB, SDValue(PPV.getNode(), 0)); 9806 else 9807 setValue(&CB, Result.first); 9808 } 9809 9810 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 9811 // call sequence. Furthermore the location of the chain and glue can change 9812 // when the AnyReg calling convention is used and the intrinsic returns a 9813 // value. 9814 if (IsAnyRegCC && HasDef) { 9815 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 9816 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)}; 9817 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 9818 } else 9819 DAG.ReplaceAllUsesWith(Call, PPV.getNode()); 9820 DAG.DeleteNode(Call); 9821 9822 // Inform the Frame Information that we have a patchpoint in this function. 9823 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 9824 } 9825 9826 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 9827 unsigned Intrinsic) { 9828 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9829 SDValue Op1 = getValue(I.getArgOperand(0)); 9830 SDValue Op2; 9831 if (I.arg_size() > 1) 9832 Op2 = getValue(I.getArgOperand(1)); 9833 SDLoc dl = getCurSDLoc(); 9834 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 9835 SDValue Res; 9836 SDNodeFlags SDFlags; 9837 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 9838 SDFlags.copyFMF(*FPMO); 9839 9840 switch (Intrinsic) { 9841 case Intrinsic::vector_reduce_fadd: 9842 if (SDFlags.hasAllowReassociation()) 9843 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 9844 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 9845 SDFlags); 9846 else 9847 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 9848 break; 9849 case Intrinsic::vector_reduce_fmul: 9850 if (SDFlags.hasAllowReassociation()) 9851 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 9852 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 9853 SDFlags); 9854 else 9855 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 9856 break; 9857 case Intrinsic::vector_reduce_add: 9858 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 9859 break; 9860 case Intrinsic::vector_reduce_mul: 9861 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 9862 break; 9863 case Intrinsic::vector_reduce_and: 9864 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 9865 break; 9866 case Intrinsic::vector_reduce_or: 9867 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 9868 break; 9869 case Intrinsic::vector_reduce_xor: 9870 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 9871 break; 9872 case Intrinsic::vector_reduce_smax: 9873 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 9874 break; 9875 case Intrinsic::vector_reduce_smin: 9876 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 9877 break; 9878 case Intrinsic::vector_reduce_umax: 9879 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 9880 break; 9881 case Intrinsic::vector_reduce_umin: 9882 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 9883 break; 9884 case Intrinsic::vector_reduce_fmax: 9885 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 9886 break; 9887 case Intrinsic::vector_reduce_fmin: 9888 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 9889 break; 9890 default: 9891 llvm_unreachable("Unhandled vector reduce intrinsic"); 9892 } 9893 setValue(&I, Res); 9894 } 9895 9896 /// Returns an AttributeList representing the attributes applied to the return 9897 /// value of the given call. 9898 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9899 SmallVector<Attribute::AttrKind, 2> Attrs; 9900 if (CLI.RetSExt) 9901 Attrs.push_back(Attribute::SExt); 9902 if (CLI.RetZExt) 9903 Attrs.push_back(Attribute::ZExt); 9904 if (CLI.IsInReg) 9905 Attrs.push_back(Attribute::InReg); 9906 9907 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9908 Attrs); 9909 } 9910 9911 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9912 /// implementation, which just calls LowerCall. 9913 /// FIXME: When all targets are 9914 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9915 std::pair<SDValue, SDValue> 9916 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9917 // Handle the incoming return values from the call. 9918 CLI.Ins.clear(); 9919 Type *OrigRetTy = CLI.RetTy; 9920 SmallVector<EVT, 4> RetTys; 9921 SmallVector<uint64_t, 4> Offsets; 9922 auto &DL = CLI.DAG.getDataLayout(); 9923 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 9924 9925 if (CLI.IsPostTypeLegalization) { 9926 // If we are lowering a libcall after legalization, split the return type. 9927 SmallVector<EVT, 4> OldRetTys; 9928 SmallVector<uint64_t, 4> OldOffsets; 9929 RetTys.swap(OldRetTys); 9930 Offsets.swap(OldOffsets); 9931 9932 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9933 EVT RetVT = OldRetTys[i]; 9934 uint64_t Offset = OldOffsets[i]; 9935 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9936 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9937 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9938 RetTys.append(NumRegs, RegisterVT); 9939 for (unsigned j = 0; j != NumRegs; ++j) 9940 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9941 } 9942 } 9943 9944 SmallVector<ISD::OutputArg, 4> Outs; 9945 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9946 9947 bool CanLowerReturn = 9948 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9949 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9950 9951 SDValue DemoteStackSlot; 9952 int DemoteStackIdx = -100; 9953 if (!CanLowerReturn) { 9954 // FIXME: equivalent assert? 9955 // assert(!CS.hasInAllocaArgument() && 9956 // "sret demotion is incompatible with inalloca"); 9957 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9958 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 9959 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9960 DemoteStackIdx = 9961 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 9962 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9963 DL.getAllocaAddrSpace()); 9964 9965 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9966 ArgListEntry Entry; 9967 Entry.Node = DemoteStackSlot; 9968 Entry.Ty = StackSlotPtrType; 9969 Entry.IsSExt = false; 9970 Entry.IsZExt = false; 9971 Entry.IsInReg = false; 9972 Entry.IsSRet = true; 9973 Entry.IsNest = false; 9974 Entry.IsByVal = false; 9975 Entry.IsByRef = false; 9976 Entry.IsReturned = false; 9977 Entry.IsSwiftSelf = false; 9978 Entry.IsSwiftAsync = false; 9979 Entry.IsSwiftError = false; 9980 Entry.IsCFGuardTarget = false; 9981 Entry.Alignment = Alignment; 9982 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9983 CLI.NumFixedArgs += 1; 9984 CLI.getArgs()[0].IndirectType = CLI.RetTy; 9985 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9986 9987 // sret demotion isn't compatible with tail-calls, since the sret argument 9988 // points into the callers stack frame. 9989 CLI.IsTailCall = false; 9990 } else { 9991 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9992 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL); 9993 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9994 ISD::ArgFlagsTy Flags; 9995 if (NeedsRegBlock) { 9996 Flags.setInConsecutiveRegs(); 9997 if (I == RetTys.size() - 1) 9998 Flags.setInConsecutiveRegsLast(); 9999 } 10000 EVT VT = RetTys[I]; 10001 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10002 CLI.CallConv, VT); 10003 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10004 CLI.CallConv, VT); 10005 for (unsigned i = 0; i != NumRegs; ++i) { 10006 ISD::InputArg MyFlags; 10007 MyFlags.Flags = Flags; 10008 MyFlags.VT = RegisterVT; 10009 MyFlags.ArgVT = VT; 10010 MyFlags.Used = CLI.IsReturnValueUsed; 10011 if (CLI.RetTy->isPointerTy()) { 10012 MyFlags.Flags.setPointer(); 10013 MyFlags.Flags.setPointerAddrSpace( 10014 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 10015 } 10016 if (CLI.RetSExt) 10017 MyFlags.Flags.setSExt(); 10018 if (CLI.RetZExt) 10019 MyFlags.Flags.setZExt(); 10020 if (CLI.IsInReg) 10021 MyFlags.Flags.setInReg(); 10022 CLI.Ins.push_back(MyFlags); 10023 } 10024 } 10025 } 10026 10027 // We push in swifterror return as the last element of CLI.Ins. 10028 ArgListTy &Args = CLI.getArgs(); 10029 if (supportSwiftError()) { 10030 for (const ArgListEntry &Arg : Args) { 10031 if (Arg.IsSwiftError) { 10032 ISD::InputArg MyFlags; 10033 MyFlags.VT = getPointerTy(DL); 10034 MyFlags.ArgVT = EVT(getPointerTy(DL)); 10035 MyFlags.Flags.setSwiftError(); 10036 CLI.Ins.push_back(MyFlags); 10037 } 10038 } 10039 } 10040 10041 // Handle all of the outgoing arguments. 10042 CLI.Outs.clear(); 10043 CLI.OutVals.clear(); 10044 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 10045 SmallVector<EVT, 4> ValueVTs; 10046 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 10047 // FIXME: Split arguments if CLI.IsPostTypeLegalization 10048 Type *FinalType = Args[i].Ty; 10049 if (Args[i].IsByVal) 10050 FinalType = Args[i].IndirectType; 10051 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10052 FinalType, CLI.CallConv, CLI.IsVarArg, DL); 10053 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 10054 ++Value) { 10055 EVT VT = ValueVTs[Value]; 10056 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 10057 SDValue Op = SDValue(Args[i].Node.getNode(), 10058 Args[i].Node.getResNo() + Value); 10059 ISD::ArgFlagsTy Flags; 10060 10061 // Certain targets (such as MIPS), may have a different ABI alignment 10062 // for a type depending on the context. Give the target a chance to 10063 // specify the alignment it wants. 10064 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 10065 Flags.setOrigAlign(OriginalAlignment); 10066 10067 if (Args[i].Ty->isPointerTy()) { 10068 Flags.setPointer(); 10069 Flags.setPointerAddrSpace( 10070 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 10071 } 10072 if (Args[i].IsZExt) 10073 Flags.setZExt(); 10074 if (Args[i].IsSExt) 10075 Flags.setSExt(); 10076 if (Args[i].IsInReg) { 10077 // If we are using vectorcall calling convention, a structure that is 10078 // passed InReg - is surely an HVA 10079 if (CLI.CallConv == CallingConv::X86_VectorCall && 10080 isa<StructType>(FinalType)) { 10081 // The first value of a structure is marked 10082 if (0 == Value) 10083 Flags.setHvaStart(); 10084 Flags.setHva(); 10085 } 10086 // Set InReg Flag 10087 Flags.setInReg(); 10088 } 10089 if (Args[i].IsSRet) 10090 Flags.setSRet(); 10091 if (Args[i].IsSwiftSelf) 10092 Flags.setSwiftSelf(); 10093 if (Args[i].IsSwiftAsync) 10094 Flags.setSwiftAsync(); 10095 if (Args[i].IsSwiftError) 10096 Flags.setSwiftError(); 10097 if (Args[i].IsCFGuardTarget) 10098 Flags.setCFGuardTarget(); 10099 if (Args[i].IsByVal) 10100 Flags.setByVal(); 10101 if (Args[i].IsByRef) 10102 Flags.setByRef(); 10103 if (Args[i].IsPreallocated) { 10104 Flags.setPreallocated(); 10105 // Set the byval flag for CCAssignFn callbacks that don't know about 10106 // preallocated. This way we can know how many bytes we should've 10107 // allocated and how many bytes a callee cleanup function will pop. If 10108 // we port preallocated to more targets, we'll have to add custom 10109 // preallocated handling in the various CC lowering callbacks. 10110 Flags.setByVal(); 10111 } 10112 if (Args[i].IsInAlloca) { 10113 Flags.setInAlloca(); 10114 // Set the byval flag for CCAssignFn callbacks that don't know about 10115 // inalloca. This way we can know how many bytes we should've allocated 10116 // and how many bytes a callee cleanup function will pop. If we port 10117 // inalloca to more targets, we'll have to add custom inalloca handling 10118 // in the various CC lowering callbacks. 10119 Flags.setByVal(); 10120 } 10121 Align MemAlign; 10122 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 10123 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType); 10124 Flags.setByValSize(FrameSize); 10125 10126 // info is not there but there are cases it cannot get right. 10127 if (auto MA = Args[i].Alignment) 10128 MemAlign = *MA; 10129 else 10130 MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL)); 10131 } else if (auto MA = Args[i].Alignment) { 10132 MemAlign = *MA; 10133 } else { 10134 MemAlign = OriginalAlignment; 10135 } 10136 Flags.setMemAlign(MemAlign); 10137 if (Args[i].IsNest) 10138 Flags.setNest(); 10139 if (NeedsRegBlock) 10140 Flags.setInConsecutiveRegs(); 10141 10142 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10143 CLI.CallConv, VT); 10144 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10145 CLI.CallConv, VT); 10146 SmallVector<SDValue, 4> Parts(NumParts); 10147 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 10148 10149 if (Args[i].IsSExt) 10150 ExtendKind = ISD::SIGN_EXTEND; 10151 else if (Args[i].IsZExt) 10152 ExtendKind = ISD::ZERO_EXTEND; 10153 10154 // Conservatively only handle 'returned' on non-vectors that can be lowered, 10155 // for now. 10156 if (Args[i].IsReturned && !Op.getValueType().isVector() && 10157 CanLowerReturn) { 10158 assert((CLI.RetTy == Args[i].Ty || 10159 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 10160 CLI.RetTy->getPointerAddressSpace() == 10161 Args[i].Ty->getPointerAddressSpace())) && 10162 RetTys.size() == NumValues && "unexpected use of 'returned'"); 10163 // Before passing 'returned' to the target lowering code, ensure that 10164 // either the register MVT and the actual EVT are the same size or that 10165 // the return value and argument are extended in the same way; in these 10166 // cases it's safe to pass the argument register value unchanged as the 10167 // return register value (although it's at the target's option whether 10168 // to do so) 10169 // TODO: allow code generation to take advantage of partially preserved 10170 // registers rather than clobbering the entire register when the 10171 // parameter extension method is not compatible with the return 10172 // extension method 10173 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 10174 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 10175 CLI.RetZExt == Args[i].IsZExt)) 10176 Flags.setReturned(); 10177 } 10178 10179 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 10180 CLI.CallConv, ExtendKind); 10181 10182 for (unsigned j = 0; j != NumParts; ++j) { 10183 // if it isn't first piece, alignment must be 1 10184 // For scalable vectors the scalable part is currently handled 10185 // by individual targets, so we just use the known minimum size here. 10186 ISD::OutputArg MyFlags( 10187 Flags, Parts[j].getValueType().getSimpleVT(), VT, 10188 i < CLI.NumFixedArgs, i, 10189 j * Parts[j].getValueType().getStoreSize().getKnownMinValue()); 10190 if (NumParts > 1 && j == 0) 10191 MyFlags.Flags.setSplit(); 10192 else if (j != 0) { 10193 MyFlags.Flags.setOrigAlign(Align(1)); 10194 if (j == NumParts - 1) 10195 MyFlags.Flags.setSplitEnd(); 10196 } 10197 10198 CLI.Outs.push_back(MyFlags); 10199 CLI.OutVals.push_back(Parts[j]); 10200 } 10201 10202 if (NeedsRegBlock && Value == NumValues - 1) 10203 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 10204 } 10205 } 10206 10207 SmallVector<SDValue, 4> InVals; 10208 CLI.Chain = LowerCall(CLI, InVals); 10209 10210 // Update CLI.InVals to use outside of this function. 10211 CLI.InVals = InVals; 10212 10213 // Verify that the target's LowerCall behaved as expected. 10214 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 10215 "LowerCall didn't return a valid chain!"); 10216 assert((!CLI.IsTailCall || InVals.empty()) && 10217 "LowerCall emitted a return value for a tail call!"); 10218 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 10219 "LowerCall didn't emit the correct number of values!"); 10220 10221 // For a tail call, the return value is merely live-out and there aren't 10222 // any nodes in the DAG representing it. Return a special value to 10223 // indicate that a tail call has been emitted and no more Instructions 10224 // should be processed in the current block. 10225 if (CLI.IsTailCall) { 10226 CLI.DAG.setRoot(CLI.Chain); 10227 return std::make_pair(SDValue(), SDValue()); 10228 } 10229 10230 #ifndef NDEBUG 10231 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 10232 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 10233 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 10234 "LowerCall emitted a value with the wrong type!"); 10235 } 10236 #endif 10237 10238 SmallVector<SDValue, 4> ReturnValues; 10239 if (!CanLowerReturn) { 10240 // The instruction result is the result of loading from the 10241 // hidden sret parameter. 10242 SmallVector<EVT, 1> PVTs; 10243 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 10244 10245 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 10246 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 10247 EVT PtrVT = PVTs[0]; 10248 10249 unsigned NumValues = RetTys.size(); 10250 ReturnValues.resize(NumValues); 10251 SmallVector<SDValue, 4> Chains(NumValues); 10252 10253 // An aggregate return value cannot wrap around the address space, so 10254 // offsets to its parts don't wrap either. 10255 SDNodeFlags Flags; 10256 Flags.setNoUnsignedWrap(true); 10257 10258 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10259 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 10260 for (unsigned i = 0; i < NumValues; ++i) { 10261 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 10262 CLI.DAG.getConstant(Offsets[i], CLI.DL, 10263 PtrVT), Flags); 10264 SDValue L = CLI.DAG.getLoad( 10265 RetTys[i], CLI.DL, CLI.Chain, Add, 10266 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 10267 DemoteStackIdx, Offsets[i]), 10268 HiddenSRetAlign); 10269 ReturnValues[i] = L; 10270 Chains[i] = L.getValue(1); 10271 } 10272 10273 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 10274 } else { 10275 // Collect the legal value parts into potentially illegal values 10276 // that correspond to the original function's return values. 10277 std::optional<ISD::NodeType> AssertOp; 10278 if (CLI.RetSExt) 10279 AssertOp = ISD::AssertSext; 10280 else if (CLI.RetZExt) 10281 AssertOp = ISD::AssertZext; 10282 unsigned CurReg = 0; 10283 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 10284 EVT VT = RetTys[I]; 10285 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10286 CLI.CallConv, VT); 10287 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10288 CLI.CallConv, VT); 10289 10290 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 10291 NumRegs, RegisterVT, VT, nullptr, 10292 CLI.CallConv, AssertOp)); 10293 CurReg += NumRegs; 10294 } 10295 10296 // For a function returning void, there is no return value. We can't create 10297 // such a node, so we just return a null return value in that case. In 10298 // that case, nothing will actually look at the value. 10299 if (ReturnValues.empty()) 10300 return std::make_pair(SDValue(), CLI.Chain); 10301 } 10302 10303 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 10304 CLI.DAG.getVTList(RetTys), ReturnValues); 10305 return std::make_pair(Res, CLI.Chain); 10306 } 10307 10308 /// Places new result values for the node in Results (their number 10309 /// and types must exactly match those of the original return values of 10310 /// the node), or leaves Results empty, which indicates that the node is not 10311 /// to be custom lowered after all. 10312 void TargetLowering::LowerOperationWrapper(SDNode *N, 10313 SmallVectorImpl<SDValue> &Results, 10314 SelectionDAG &DAG) const { 10315 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 10316 10317 if (!Res.getNode()) 10318 return; 10319 10320 // If the original node has one result, take the return value from 10321 // LowerOperation as is. It might not be result number 0. 10322 if (N->getNumValues() == 1) { 10323 Results.push_back(Res); 10324 return; 10325 } 10326 10327 // If the original node has multiple results, then the return node should 10328 // have the same number of results. 10329 assert((N->getNumValues() == Res->getNumValues()) && 10330 "Lowering returned the wrong number of results!"); 10331 10332 // Places new result values base on N result number. 10333 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 10334 Results.push_back(Res.getValue(I)); 10335 } 10336 10337 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10338 llvm_unreachable("LowerOperation not implemented for this target!"); 10339 } 10340 10341 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, 10342 unsigned Reg, 10343 ISD::NodeType ExtendType) { 10344 SDValue Op = getNonRegisterValue(V); 10345 assert((Op.getOpcode() != ISD::CopyFromReg || 10346 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 10347 "Copy from a reg to the same reg!"); 10348 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 10349 10350 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10351 // If this is an InlineAsm we have to match the registers required, not the 10352 // notional registers required by the type. 10353 10354 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 10355 std::nullopt); // This is not an ABI copy. 10356 SDValue Chain = DAG.getEntryNode(); 10357 10358 if (ExtendType == ISD::ANY_EXTEND) { 10359 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V); 10360 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end()) 10361 ExtendType = PreferredExtendIt->second; 10362 } 10363 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 10364 PendingExports.push_back(Chain); 10365 } 10366 10367 #include "llvm/CodeGen/SelectionDAGISel.h" 10368 10369 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 10370 /// entry block, return true. This includes arguments used by switches, since 10371 /// the switch may expand into multiple basic blocks. 10372 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 10373 // With FastISel active, we may be splitting blocks, so force creation 10374 // of virtual registers for all non-dead arguments. 10375 if (FastISel) 10376 return A->use_empty(); 10377 10378 const BasicBlock &Entry = A->getParent()->front(); 10379 for (const User *U : A->users()) 10380 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 10381 return false; // Use not in entry block. 10382 10383 return true; 10384 } 10385 10386 using ArgCopyElisionMapTy = 10387 DenseMap<const Argument *, 10388 std::pair<const AllocaInst *, const StoreInst *>>; 10389 10390 /// Scan the entry block of the function in FuncInfo for arguments that look 10391 /// like copies into a local alloca. Record any copied arguments in 10392 /// ArgCopyElisionCandidates. 10393 static void 10394 findArgumentCopyElisionCandidates(const DataLayout &DL, 10395 FunctionLoweringInfo *FuncInfo, 10396 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 10397 // Record the state of every static alloca used in the entry block. Argument 10398 // allocas are all used in the entry block, so we need approximately as many 10399 // entries as we have arguments. 10400 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 10401 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 10402 unsigned NumArgs = FuncInfo->Fn->arg_size(); 10403 StaticAllocas.reserve(NumArgs * 2); 10404 10405 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 10406 if (!V) 10407 return nullptr; 10408 V = V->stripPointerCasts(); 10409 const auto *AI = dyn_cast<AllocaInst>(V); 10410 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 10411 return nullptr; 10412 auto Iter = StaticAllocas.insert({AI, Unknown}); 10413 return &Iter.first->second; 10414 }; 10415 10416 // Look for stores of arguments to static allocas. Look through bitcasts and 10417 // GEPs to handle type coercions, as long as the alloca is fully initialized 10418 // by the store. Any non-store use of an alloca escapes it and any subsequent 10419 // unanalyzed store might write it. 10420 // FIXME: Handle structs initialized with multiple stores. 10421 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 10422 // Look for stores, and handle non-store uses conservatively. 10423 const auto *SI = dyn_cast<StoreInst>(&I); 10424 if (!SI) { 10425 // We will look through cast uses, so ignore them completely. 10426 if (I.isCast()) 10427 continue; 10428 // Ignore debug info and pseudo op intrinsics, they don't escape or store 10429 // to allocas. 10430 if (I.isDebugOrPseudoInst()) 10431 continue; 10432 // This is an unknown instruction. Assume it escapes or writes to all 10433 // static alloca operands. 10434 for (const Use &U : I.operands()) { 10435 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 10436 *Info = StaticAllocaInfo::Clobbered; 10437 } 10438 continue; 10439 } 10440 10441 // If the stored value is a static alloca, mark it as escaped. 10442 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 10443 *Info = StaticAllocaInfo::Clobbered; 10444 10445 // Check if the destination is a static alloca. 10446 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 10447 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 10448 if (!Info) 10449 continue; 10450 const AllocaInst *AI = cast<AllocaInst>(Dst); 10451 10452 // Skip allocas that have been initialized or clobbered. 10453 if (*Info != StaticAllocaInfo::Unknown) 10454 continue; 10455 10456 // Check if the stored value is an argument, and that this store fully 10457 // initializes the alloca. 10458 // If the argument type has padding bits we can't directly forward a pointer 10459 // as the upper bits may contain garbage. 10460 // Don't elide copies from the same argument twice. 10461 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 10462 const auto *Arg = dyn_cast<Argument>(Val); 10463 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 10464 Arg->getType()->isEmptyTy() || 10465 DL.getTypeStoreSize(Arg->getType()) != 10466 DL.getTypeAllocSize(AI->getAllocatedType()) || 10467 !DL.typeSizeEqualsStoreSize(Arg->getType()) || 10468 ArgCopyElisionCandidates.count(Arg)) { 10469 *Info = StaticAllocaInfo::Clobbered; 10470 continue; 10471 } 10472 10473 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 10474 << '\n'); 10475 10476 // Mark this alloca and store for argument copy elision. 10477 *Info = StaticAllocaInfo::Elidable; 10478 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 10479 10480 // Stop scanning if we've seen all arguments. This will happen early in -O0 10481 // builds, which is useful, because -O0 builds have large entry blocks and 10482 // many allocas. 10483 if (ArgCopyElisionCandidates.size() == NumArgs) 10484 break; 10485 } 10486 } 10487 10488 /// Try to elide argument copies from memory into a local alloca. Succeeds if 10489 /// ArgVal is a load from a suitable fixed stack object. 10490 static void tryToElideArgumentCopy( 10491 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 10492 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 10493 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 10494 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 10495 SDValue ArgVal, bool &ArgHasUses) { 10496 // Check if this is a load from a fixed stack object. 10497 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 10498 if (!LNode) 10499 return; 10500 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 10501 if (!FINode) 10502 return; 10503 10504 // Check that the fixed stack object is the right size and alignment. 10505 // Look at the alignment that the user wrote on the alloca instead of looking 10506 // at the stack object. 10507 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 10508 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 10509 const AllocaInst *AI = ArgCopyIter->second.first; 10510 int FixedIndex = FINode->getIndex(); 10511 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 10512 int OldIndex = AllocaIndex; 10513 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 10514 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 10515 LLVM_DEBUG( 10516 dbgs() << " argument copy elision failed due to bad fixed stack " 10517 "object size\n"); 10518 return; 10519 } 10520 Align RequiredAlignment = AI->getAlign(); 10521 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 10522 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 10523 "greater than stack argument alignment (" 10524 << DebugStr(RequiredAlignment) << " vs " 10525 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 10526 return; 10527 } 10528 10529 // Perform the elision. Delete the old stack object and replace its only use 10530 // in the variable info map. Mark the stack object as mutable. 10531 LLVM_DEBUG({ 10532 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 10533 << " Replacing frame index " << OldIndex << " with " << FixedIndex 10534 << '\n'; 10535 }); 10536 MFI.RemoveStackObject(OldIndex); 10537 MFI.setIsImmutableObjectIndex(FixedIndex, false); 10538 AllocaIndex = FixedIndex; 10539 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 10540 Chains.push_back(ArgVal.getValue(1)); 10541 10542 // Avoid emitting code for the store implementing the copy. 10543 const StoreInst *SI = ArgCopyIter->second.second; 10544 ElidedArgCopyInstrs.insert(SI); 10545 10546 // Check for uses of the argument again so that we can avoid exporting ArgVal 10547 // if it is't used by anything other than the store. 10548 for (const Value *U : Arg.users()) { 10549 if (U != SI) { 10550 ArgHasUses = true; 10551 break; 10552 } 10553 } 10554 } 10555 10556 void SelectionDAGISel::LowerArguments(const Function &F) { 10557 SelectionDAG &DAG = SDB->DAG; 10558 SDLoc dl = SDB->getCurSDLoc(); 10559 const DataLayout &DL = DAG.getDataLayout(); 10560 SmallVector<ISD::InputArg, 16> Ins; 10561 10562 // In Naked functions we aren't going to save any registers. 10563 if (F.hasFnAttribute(Attribute::Naked)) 10564 return; 10565 10566 if (!FuncInfo->CanLowerReturn) { 10567 // Put in an sret pointer parameter before all the other parameters. 10568 SmallVector<EVT, 1> ValueVTs; 10569 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10570 F.getReturnType()->getPointerTo( 10571 DAG.getDataLayout().getAllocaAddrSpace()), 10572 ValueVTs); 10573 10574 // NOTE: Assuming that a pointer will never break down to more than one VT 10575 // or one register. 10576 ISD::ArgFlagsTy Flags; 10577 Flags.setSRet(); 10578 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 10579 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 10580 ISD::InputArg::NoArgIndex, 0); 10581 Ins.push_back(RetArg); 10582 } 10583 10584 // Look for stores of arguments to static allocas. Mark such arguments with a 10585 // flag to ask the target to give us the memory location of that argument if 10586 // available. 10587 ArgCopyElisionMapTy ArgCopyElisionCandidates; 10588 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 10589 ArgCopyElisionCandidates); 10590 10591 // Set up the incoming argument description vector. 10592 for (const Argument &Arg : F.args()) { 10593 unsigned ArgNo = Arg.getArgNo(); 10594 SmallVector<EVT, 4> ValueVTs; 10595 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10596 bool isArgValueUsed = !Arg.use_empty(); 10597 unsigned PartBase = 0; 10598 Type *FinalType = Arg.getType(); 10599 if (Arg.hasAttribute(Attribute::ByVal)) 10600 FinalType = Arg.getParamByValType(); 10601 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 10602 FinalType, F.getCallingConv(), F.isVarArg(), DL); 10603 for (unsigned Value = 0, NumValues = ValueVTs.size(); 10604 Value != NumValues; ++Value) { 10605 EVT VT = ValueVTs[Value]; 10606 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 10607 ISD::ArgFlagsTy Flags; 10608 10609 10610 if (Arg.getType()->isPointerTy()) { 10611 Flags.setPointer(); 10612 Flags.setPointerAddrSpace( 10613 cast<PointerType>(Arg.getType())->getAddressSpace()); 10614 } 10615 if (Arg.hasAttribute(Attribute::ZExt)) 10616 Flags.setZExt(); 10617 if (Arg.hasAttribute(Attribute::SExt)) 10618 Flags.setSExt(); 10619 if (Arg.hasAttribute(Attribute::InReg)) { 10620 // If we are using vectorcall calling convention, a structure that is 10621 // passed InReg - is surely an HVA 10622 if (F.getCallingConv() == CallingConv::X86_VectorCall && 10623 isa<StructType>(Arg.getType())) { 10624 // The first value of a structure is marked 10625 if (0 == Value) 10626 Flags.setHvaStart(); 10627 Flags.setHva(); 10628 } 10629 // Set InReg Flag 10630 Flags.setInReg(); 10631 } 10632 if (Arg.hasAttribute(Attribute::StructRet)) 10633 Flags.setSRet(); 10634 if (Arg.hasAttribute(Attribute::SwiftSelf)) 10635 Flags.setSwiftSelf(); 10636 if (Arg.hasAttribute(Attribute::SwiftAsync)) 10637 Flags.setSwiftAsync(); 10638 if (Arg.hasAttribute(Attribute::SwiftError)) 10639 Flags.setSwiftError(); 10640 if (Arg.hasAttribute(Attribute::ByVal)) 10641 Flags.setByVal(); 10642 if (Arg.hasAttribute(Attribute::ByRef)) 10643 Flags.setByRef(); 10644 if (Arg.hasAttribute(Attribute::InAlloca)) { 10645 Flags.setInAlloca(); 10646 // Set the byval flag for CCAssignFn callbacks that don't know about 10647 // inalloca. This way we can know how many bytes we should've allocated 10648 // and how many bytes a callee cleanup function will pop. If we port 10649 // inalloca to more targets, we'll have to add custom inalloca handling 10650 // in the various CC lowering callbacks. 10651 Flags.setByVal(); 10652 } 10653 if (Arg.hasAttribute(Attribute::Preallocated)) { 10654 Flags.setPreallocated(); 10655 // Set the byval flag for CCAssignFn callbacks that don't know about 10656 // preallocated. This way we can know how many bytes we should've 10657 // allocated and how many bytes a callee cleanup function will pop. If 10658 // we port preallocated to more targets, we'll have to add custom 10659 // preallocated handling in the various CC lowering callbacks. 10660 Flags.setByVal(); 10661 } 10662 10663 // Certain targets (such as MIPS), may have a different ABI alignment 10664 // for a type depending on the context. Give the target a chance to 10665 // specify the alignment it wants. 10666 const Align OriginalAlignment( 10667 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 10668 Flags.setOrigAlign(OriginalAlignment); 10669 10670 Align MemAlign; 10671 Type *ArgMemTy = nullptr; 10672 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 10673 Flags.isByRef()) { 10674 if (!ArgMemTy) 10675 ArgMemTy = Arg.getPointeeInMemoryValueType(); 10676 10677 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 10678 10679 // For in-memory arguments, size and alignment should be passed from FE. 10680 // BE will guess if this info is not there but there are cases it cannot 10681 // get right. 10682 if (auto ParamAlign = Arg.getParamStackAlign()) 10683 MemAlign = *ParamAlign; 10684 else if ((ParamAlign = Arg.getParamAlign())) 10685 MemAlign = *ParamAlign; 10686 else 10687 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 10688 if (Flags.isByRef()) 10689 Flags.setByRefSize(MemSize); 10690 else 10691 Flags.setByValSize(MemSize); 10692 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 10693 MemAlign = *ParamAlign; 10694 } else { 10695 MemAlign = OriginalAlignment; 10696 } 10697 Flags.setMemAlign(MemAlign); 10698 10699 if (Arg.hasAttribute(Attribute::Nest)) 10700 Flags.setNest(); 10701 if (NeedsRegBlock) 10702 Flags.setInConsecutiveRegs(); 10703 if (ArgCopyElisionCandidates.count(&Arg)) 10704 Flags.setCopyElisionCandidate(); 10705 if (Arg.hasAttribute(Attribute::Returned)) 10706 Flags.setReturned(); 10707 10708 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 10709 *CurDAG->getContext(), F.getCallingConv(), VT); 10710 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 10711 *CurDAG->getContext(), F.getCallingConv(), VT); 10712 for (unsigned i = 0; i != NumRegs; ++i) { 10713 // For scalable vectors, use the minimum size; individual targets 10714 // are responsible for handling scalable vector arguments and 10715 // return values. 10716 ISD::InputArg MyFlags( 10717 Flags, RegisterVT, VT, isArgValueUsed, ArgNo, 10718 PartBase + i * RegisterVT.getStoreSize().getKnownMinValue()); 10719 if (NumRegs > 1 && i == 0) 10720 MyFlags.Flags.setSplit(); 10721 // if it isn't first piece, alignment must be 1 10722 else if (i > 0) { 10723 MyFlags.Flags.setOrigAlign(Align(1)); 10724 if (i == NumRegs - 1) 10725 MyFlags.Flags.setSplitEnd(); 10726 } 10727 Ins.push_back(MyFlags); 10728 } 10729 if (NeedsRegBlock && Value == NumValues - 1) 10730 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 10731 PartBase += VT.getStoreSize().getKnownMinValue(); 10732 } 10733 } 10734 10735 // Call the target to set up the argument values. 10736 SmallVector<SDValue, 8> InVals; 10737 SDValue NewRoot = TLI->LowerFormalArguments( 10738 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 10739 10740 // Verify that the target's LowerFormalArguments behaved as expected. 10741 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 10742 "LowerFormalArguments didn't return a valid chain!"); 10743 assert(InVals.size() == Ins.size() && 10744 "LowerFormalArguments didn't emit the correct number of values!"); 10745 LLVM_DEBUG({ 10746 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 10747 assert(InVals[i].getNode() && 10748 "LowerFormalArguments emitted a null value!"); 10749 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 10750 "LowerFormalArguments emitted a value with the wrong type!"); 10751 } 10752 }); 10753 10754 // Update the DAG with the new chain value resulting from argument lowering. 10755 DAG.setRoot(NewRoot); 10756 10757 // Set up the argument values. 10758 unsigned i = 0; 10759 if (!FuncInfo->CanLowerReturn) { 10760 // Create a virtual register for the sret pointer, and put in a copy 10761 // from the sret argument into it. 10762 SmallVector<EVT, 1> ValueVTs; 10763 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10764 F.getReturnType()->getPointerTo( 10765 DAG.getDataLayout().getAllocaAddrSpace()), 10766 ValueVTs); 10767 MVT VT = ValueVTs[0].getSimpleVT(); 10768 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 10769 std::optional<ISD::NodeType> AssertOp; 10770 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 10771 nullptr, F.getCallingConv(), AssertOp); 10772 10773 MachineFunction& MF = SDB->DAG.getMachineFunction(); 10774 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 10775 Register SRetReg = 10776 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 10777 FuncInfo->DemoteRegister = SRetReg; 10778 NewRoot = 10779 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 10780 DAG.setRoot(NewRoot); 10781 10782 // i indexes lowered arguments. Bump it past the hidden sret argument. 10783 ++i; 10784 } 10785 10786 SmallVector<SDValue, 4> Chains; 10787 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 10788 for (const Argument &Arg : F.args()) { 10789 SmallVector<SDValue, 4> ArgValues; 10790 SmallVector<EVT, 4> ValueVTs; 10791 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10792 unsigned NumValues = ValueVTs.size(); 10793 if (NumValues == 0) 10794 continue; 10795 10796 bool ArgHasUses = !Arg.use_empty(); 10797 10798 // Elide the copying store if the target loaded this argument from a 10799 // suitable fixed stack object. 10800 if (Ins[i].Flags.isCopyElisionCandidate()) { 10801 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 10802 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 10803 InVals[i], ArgHasUses); 10804 } 10805 10806 // If this argument is unused then remember its value. It is used to generate 10807 // debugging information. 10808 bool isSwiftErrorArg = 10809 TLI->supportSwiftError() && 10810 Arg.hasAttribute(Attribute::SwiftError); 10811 if (!ArgHasUses && !isSwiftErrorArg) { 10812 SDB->setUnusedArgValue(&Arg, InVals[i]); 10813 10814 // Also remember any frame index for use in FastISel. 10815 if (FrameIndexSDNode *FI = 10816 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 10817 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10818 } 10819 10820 for (unsigned Val = 0; Val != NumValues; ++Val) { 10821 EVT VT = ValueVTs[Val]; 10822 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 10823 F.getCallingConv(), VT); 10824 unsigned NumParts = TLI->getNumRegistersForCallingConv( 10825 *CurDAG->getContext(), F.getCallingConv(), VT); 10826 10827 // Even an apparent 'unused' swifterror argument needs to be returned. So 10828 // we do generate a copy for it that can be used on return from the 10829 // function. 10830 if (ArgHasUses || isSwiftErrorArg) { 10831 std::optional<ISD::NodeType> AssertOp; 10832 if (Arg.hasAttribute(Attribute::SExt)) 10833 AssertOp = ISD::AssertSext; 10834 else if (Arg.hasAttribute(Attribute::ZExt)) 10835 AssertOp = ISD::AssertZext; 10836 10837 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 10838 PartVT, VT, nullptr, 10839 F.getCallingConv(), AssertOp)); 10840 } 10841 10842 i += NumParts; 10843 } 10844 10845 // We don't need to do anything else for unused arguments. 10846 if (ArgValues.empty()) 10847 continue; 10848 10849 // Note down frame index. 10850 if (FrameIndexSDNode *FI = 10851 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 10852 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10853 10854 SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues), 10855 SDB->getCurSDLoc()); 10856 10857 SDB->setValue(&Arg, Res); 10858 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 10859 // We want to associate the argument with the frame index, among 10860 // involved operands, that correspond to the lowest address. The 10861 // getCopyFromParts function, called earlier, is swapping the order of 10862 // the operands to BUILD_PAIR depending on endianness. The result of 10863 // that swapping is that the least significant bits of the argument will 10864 // be in the first operand of the BUILD_PAIR node, and the most 10865 // significant bits will be in the second operand. 10866 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 10867 if (LoadSDNode *LNode = 10868 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 10869 if (FrameIndexSDNode *FI = 10870 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 10871 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10872 } 10873 10874 // Analyses past this point are naive and don't expect an assertion. 10875 if (Res.getOpcode() == ISD::AssertZext) 10876 Res = Res.getOperand(0); 10877 10878 // Update the SwiftErrorVRegDefMap. 10879 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 10880 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10881 if (Register::isVirtualRegister(Reg)) 10882 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 10883 Reg); 10884 } 10885 10886 // If this argument is live outside of the entry block, insert a copy from 10887 // wherever we got it to the vreg that other BB's will reference it as. 10888 if (Res.getOpcode() == ISD::CopyFromReg) { 10889 // If we can, though, try to skip creating an unnecessary vreg. 10890 // FIXME: This isn't very clean... it would be nice to make this more 10891 // general. 10892 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10893 if (Register::isVirtualRegister(Reg)) { 10894 FuncInfo->ValueMap[&Arg] = Reg; 10895 continue; 10896 } 10897 } 10898 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 10899 FuncInfo->InitializeRegForValue(&Arg); 10900 SDB->CopyToExportRegsIfNeeded(&Arg); 10901 } 10902 } 10903 10904 if (!Chains.empty()) { 10905 Chains.push_back(NewRoot); 10906 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 10907 } 10908 10909 DAG.setRoot(NewRoot); 10910 10911 assert(i == InVals.size() && "Argument register count mismatch!"); 10912 10913 // If any argument copy elisions occurred and we have debug info, update the 10914 // stale frame indices used in the dbg.declare variable info table. 10915 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 10916 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 10917 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 10918 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 10919 if (I != ArgCopyElisionFrameIndexMap.end()) 10920 VI.Slot = I->second; 10921 } 10922 } 10923 10924 // Finally, if the target has anything special to do, allow it to do so. 10925 emitFunctionEntryCode(); 10926 } 10927 10928 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 10929 /// ensure constants are generated when needed. Remember the virtual registers 10930 /// that need to be added to the Machine PHI nodes as input. We cannot just 10931 /// directly add them, because expansion might result in multiple MBB's for one 10932 /// BB. As such, the start of the BB might correspond to a different MBB than 10933 /// the end. 10934 void 10935 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 10936 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10937 10938 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 10939 10940 // Check PHI nodes in successors that expect a value to be available from this 10941 // block. 10942 for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) { 10943 if (!isa<PHINode>(SuccBB->begin())) continue; 10944 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 10945 10946 // If this terminator has multiple identical successors (common for 10947 // switches), only handle each succ once. 10948 if (!SuccsHandled.insert(SuccMBB).second) 10949 continue; 10950 10951 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 10952 10953 // At this point we know that there is a 1-1 correspondence between LLVM PHI 10954 // nodes and Machine PHI nodes, but the incoming operands have not been 10955 // emitted yet. 10956 for (const PHINode &PN : SuccBB->phis()) { 10957 // Ignore dead phi's. 10958 if (PN.use_empty()) 10959 continue; 10960 10961 // Skip empty types 10962 if (PN.getType()->isEmptyTy()) 10963 continue; 10964 10965 unsigned Reg; 10966 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 10967 10968 if (const auto *C = dyn_cast<Constant>(PHIOp)) { 10969 unsigned &RegOut = ConstantsOut[C]; 10970 if (RegOut == 0) { 10971 RegOut = FuncInfo.CreateRegs(C); 10972 // We need to zero/sign extend ConstantInt phi operands to match 10973 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo. 10974 ISD::NodeType ExtendType = ISD::ANY_EXTEND; 10975 if (auto *CI = dyn_cast<ConstantInt>(C)) 10976 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND 10977 : ISD::ZERO_EXTEND; 10978 CopyValueToVirtualRegister(C, RegOut, ExtendType); 10979 } 10980 Reg = RegOut; 10981 } else { 10982 DenseMap<const Value *, Register>::iterator I = 10983 FuncInfo.ValueMap.find(PHIOp); 10984 if (I != FuncInfo.ValueMap.end()) 10985 Reg = I->second; 10986 else { 10987 assert(isa<AllocaInst>(PHIOp) && 10988 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 10989 "Didn't codegen value into a register!??"); 10990 Reg = FuncInfo.CreateRegs(PHIOp); 10991 CopyValueToVirtualRegister(PHIOp, Reg); 10992 } 10993 } 10994 10995 // Remember that this register needs to added to the machine PHI node as 10996 // the input for this MBB. 10997 SmallVector<EVT, 4> ValueVTs; 10998 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 10999 for (EVT VT : ValueVTs) { 11000 const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 11001 for (unsigned i = 0; i != NumRegisters; ++i) 11002 FuncInfo.PHINodesToUpdate.push_back( 11003 std::make_pair(&*MBBI++, Reg + i)); 11004 Reg += NumRegisters; 11005 } 11006 } 11007 } 11008 11009 ConstantsOut.clear(); 11010 } 11011 11012 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 11013 MachineFunction::iterator I(MBB); 11014 if (++I == FuncInfo.MF->end()) 11015 return nullptr; 11016 return &*I; 11017 } 11018 11019 /// During lowering new call nodes can be created (such as memset, etc.). 11020 /// Those will become new roots of the current DAG, but complications arise 11021 /// when they are tail calls. In such cases, the call lowering will update 11022 /// the root, but the builder still needs to know that a tail call has been 11023 /// lowered in order to avoid generating an additional return. 11024 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 11025 // If the node is null, we do have a tail call. 11026 if (MaybeTC.getNode() != nullptr) 11027 DAG.setRoot(MaybeTC); 11028 else 11029 HasTailCall = true; 11030 } 11031 11032 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 11033 MachineBasicBlock *SwitchMBB, 11034 MachineBasicBlock *DefaultMBB) { 11035 MachineFunction *CurMF = FuncInfo.MF; 11036 MachineBasicBlock *NextMBB = nullptr; 11037 MachineFunction::iterator BBI(W.MBB); 11038 if (++BBI != FuncInfo.MF->end()) 11039 NextMBB = &*BBI; 11040 11041 unsigned Size = W.LastCluster - W.FirstCluster + 1; 11042 11043 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11044 11045 if (Size == 2 && W.MBB == SwitchMBB) { 11046 // If any two of the cases has the same destination, and if one value 11047 // is the same as the other, but has one bit unset that the other has set, 11048 // use bit manipulation to do two compares at once. For example: 11049 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 11050 // TODO: This could be extended to merge any 2 cases in switches with 3 11051 // cases. 11052 // TODO: Handle cases where W.CaseBB != SwitchBB. 11053 CaseCluster &Small = *W.FirstCluster; 11054 CaseCluster &Big = *W.LastCluster; 11055 11056 if (Small.Low == Small.High && Big.Low == Big.High && 11057 Small.MBB == Big.MBB) { 11058 const APInt &SmallValue = Small.Low->getValue(); 11059 const APInt &BigValue = Big.Low->getValue(); 11060 11061 // Check that there is only one bit different. 11062 APInt CommonBit = BigValue ^ SmallValue; 11063 if (CommonBit.isPowerOf2()) { 11064 SDValue CondLHS = getValue(Cond); 11065 EVT VT = CondLHS.getValueType(); 11066 SDLoc DL = getCurSDLoc(); 11067 11068 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 11069 DAG.getConstant(CommonBit, DL, VT)); 11070 SDValue Cond = DAG.getSetCC( 11071 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 11072 ISD::SETEQ); 11073 11074 // Update successor info. 11075 // Both Small and Big will jump to Small.BB, so we sum up the 11076 // probabilities. 11077 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 11078 if (BPI) 11079 addSuccessorWithProb( 11080 SwitchMBB, DefaultMBB, 11081 // The default destination is the first successor in IR. 11082 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 11083 else 11084 addSuccessorWithProb(SwitchMBB, DefaultMBB); 11085 11086 // Insert the true branch. 11087 SDValue BrCond = 11088 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 11089 DAG.getBasicBlock(Small.MBB)); 11090 // Insert the false branch. 11091 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 11092 DAG.getBasicBlock(DefaultMBB)); 11093 11094 DAG.setRoot(BrCond); 11095 return; 11096 } 11097 } 11098 } 11099 11100 if (TM.getOptLevel() != CodeGenOpt::None) { 11101 // Here, we order cases by probability so the most likely case will be 11102 // checked first. However, two clusters can have the same probability in 11103 // which case their relative ordering is non-deterministic. So we use Low 11104 // as a tie-breaker as clusters are guaranteed to never overlap. 11105 llvm::sort(W.FirstCluster, W.LastCluster + 1, 11106 [](const CaseCluster &a, const CaseCluster &b) { 11107 return a.Prob != b.Prob ? 11108 a.Prob > b.Prob : 11109 a.Low->getValue().slt(b.Low->getValue()); 11110 }); 11111 11112 // Rearrange the case blocks so that the last one falls through if possible 11113 // without changing the order of probabilities. 11114 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 11115 --I; 11116 if (I->Prob > W.LastCluster->Prob) 11117 break; 11118 if (I->Kind == CC_Range && I->MBB == NextMBB) { 11119 std::swap(*I, *W.LastCluster); 11120 break; 11121 } 11122 } 11123 } 11124 11125 // Compute total probability. 11126 BranchProbability DefaultProb = W.DefaultProb; 11127 BranchProbability UnhandledProbs = DefaultProb; 11128 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 11129 UnhandledProbs += I->Prob; 11130 11131 MachineBasicBlock *CurMBB = W.MBB; 11132 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 11133 bool FallthroughUnreachable = false; 11134 MachineBasicBlock *Fallthrough; 11135 if (I == W.LastCluster) { 11136 // For the last cluster, fall through to the default destination. 11137 Fallthrough = DefaultMBB; 11138 FallthroughUnreachable = isa<UnreachableInst>( 11139 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 11140 } else { 11141 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 11142 CurMF->insert(BBI, Fallthrough); 11143 // Put Cond in a virtual register to make it available from the new blocks. 11144 ExportFromCurrentBlock(Cond); 11145 } 11146 UnhandledProbs -= I->Prob; 11147 11148 switch (I->Kind) { 11149 case CC_JumpTable: { 11150 // FIXME: Optimize away range check based on pivot comparisons. 11151 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 11152 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 11153 11154 // The jump block hasn't been inserted yet; insert it here. 11155 MachineBasicBlock *JumpMBB = JT->MBB; 11156 CurMF->insert(BBI, JumpMBB); 11157 11158 auto JumpProb = I->Prob; 11159 auto FallthroughProb = UnhandledProbs; 11160 11161 // If the default statement is a target of the jump table, we evenly 11162 // distribute the default probability to successors of CurMBB. Also 11163 // update the probability on the edge from JumpMBB to Fallthrough. 11164 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 11165 SE = JumpMBB->succ_end(); 11166 SI != SE; ++SI) { 11167 if (*SI == DefaultMBB) { 11168 JumpProb += DefaultProb / 2; 11169 FallthroughProb -= DefaultProb / 2; 11170 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 11171 JumpMBB->normalizeSuccProbs(); 11172 break; 11173 } 11174 } 11175 11176 if (FallthroughUnreachable) 11177 JTH->FallthroughUnreachable = true; 11178 11179 if (!JTH->FallthroughUnreachable) 11180 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 11181 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 11182 CurMBB->normalizeSuccProbs(); 11183 11184 // The jump table header will be inserted in our current block, do the 11185 // range check, and fall through to our fallthrough block. 11186 JTH->HeaderBB = CurMBB; 11187 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 11188 11189 // If we're in the right place, emit the jump table header right now. 11190 if (CurMBB == SwitchMBB) { 11191 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 11192 JTH->Emitted = true; 11193 } 11194 break; 11195 } 11196 case CC_BitTests: { 11197 // FIXME: Optimize away range check based on pivot comparisons. 11198 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 11199 11200 // The bit test blocks haven't been inserted yet; insert them here. 11201 for (BitTestCase &BTC : BTB->Cases) 11202 CurMF->insert(BBI, BTC.ThisBB); 11203 11204 // Fill in fields of the BitTestBlock. 11205 BTB->Parent = CurMBB; 11206 BTB->Default = Fallthrough; 11207 11208 BTB->DefaultProb = UnhandledProbs; 11209 // If the cases in bit test don't form a contiguous range, we evenly 11210 // distribute the probability on the edge to Fallthrough to two 11211 // successors of CurMBB. 11212 if (!BTB->ContiguousRange) { 11213 BTB->Prob += DefaultProb / 2; 11214 BTB->DefaultProb -= DefaultProb / 2; 11215 } 11216 11217 if (FallthroughUnreachable) 11218 BTB->FallthroughUnreachable = true; 11219 11220 // If we're in the right place, emit the bit test header right now. 11221 if (CurMBB == SwitchMBB) { 11222 visitBitTestHeader(*BTB, SwitchMBB); 11223 BTB->Emitted = true; 11224 } 11225 break; 11226 } 11227 case CC_Range: { 11228 const Value *RHS, *LHS, *MHS; 11229 ISD::CondCode CC; 11230 if (I->Low == I->High) { 11231 // Check Cond == I->Low. 11232 CC = ISD::SETEQ; 11233 LHS = Cond; 11234 RHS=I->Low; 11235 MHS = nullptr; 11236 } else { 11237 // Check I->Low <= Cond <= I->High. 11238 CC = ISD::SETLE; 11239 LHS = I->Low; 11240 MHS = Cond; 11241 RHS = I->High; 11242 } 11243 11244 // If Fallthrough is unreachable, fold away the comparison. 11245 if (FallthroughUnreachable) 11246 CC = ISD::SETTRUE; 11247 11248 // The false probability is the sum of all unhandled cases. 11249 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 11250 getCurSDLoc(), I->Prob, UnhandledProbs); 11251 11252 if (CurMBB == SwitchMBB) 11253 visitSwitchCase(CB, SwitchMBB); 11254 else 11255 SL->SwitchCases.push_back(CB); 11256 11257 break; 11258 } 11259 } 11260 CurMBB = Fallthrough; 11261 } 11262 } 11263 11264 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 11265 CaseClusterIt First, 11266 CaseClusterIt Last) { 11267 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 11268 if (X.Prob != CC.Prob) 11269 return X.Prob > CC.Prob; 11270 11271 // Ties are broken by comparing the case value. 11272 return X.Low->getValue().slt(CC.Low->getValue()); 11273 }); 11274 } 11275 11276 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 11277 const SwitchWorkListItem &W, 11278 Value *Cond, 11279 MachineBasicBlock *SwitchMBB) { 11280 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 11281 "Clusters not sorted?"); 11282 11283 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 11284 11285 // Balance the tree based on branch probabilities to create a near-optimal (in 11286 // terms of search time given key frequency) binary search tree. See e.g. Kurt 11287 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 11288 CaseClusterIt LastLeft = W.FirstCluster; 11289 CaseClusterIt FirstRight = W.LastCluster; 11290 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 11291 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 11292 11293 // Move LastLeft and FirstRight towards each other from opposite directions to 11294 // find a partitioning of the clusters which balances the probability on both 11295 // sides. If LeftProb and RightProb are equal, alternate which side is 11296 // taken to ensure 0-probability nodes are distributed evenly. 11297 unsigned I = 0; 11298 while (LastLeft + 1 < FirstRight) { 11299 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 11300 LeftProb += (++LastLeft)->Prob; 11301 else 11302 RightProb += (--FirstRight)->Prob; 11303 I++; 11304 } 11305 11306 while (true) { 11307 // Our binary search tree differs from a typical BST in that ours can have up 11308 // to three values in each leaf. The pivot selection above doesn't take that 11309 // into account, which means the tree might require more nodes and be less 11310 // efficient. We compensate for this here. 11311 11312 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 11313 unsigned NumRight = W.LastCluster - FirstRight + 1; 11314 11315 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 11316 // If one side has less than 3 clusters, and the other has more than 3, 11317 // consider taking a cluster from the other side. 11318 11319 if (NumLeft < NumRight) { 11320 // Consider moving the first cluster on the right to the left side. 11321 CaseCluster &CC = *FirstRight; 11322 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11323 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11324 if (LeftSideRank <= RightSideRank) { 11325 // Moving the cluster to the left does not demote it. 11326 ++LastLeft; 11327 ++FirstRight; 11328 continue; 11329 } 11330 } else { 11331 assert(NumRight < NumLeft); 11332 // Consider moving the last element on the left to the right side. 11333 CaseCluster &CC = *LastLeft; 11334 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11335 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11336 if (RightSideRank <= LeftSideRank) { 11337 // Moving the cluster to the right does not demot it. 11338 --LastLeft; 11339 --FirstRight; 11340 continue; 11341 } 11342 } 11343 } 11344 break; 11345 } 11346 11347 assert(LastLeft + 1 == FirstRight); 11348 assert(LastLeft >= W.FirstCluster); 11349 assert(FirstRight <= W.LastCluster); 11350 11351 // Use the first element on the right as pivot since we will make less-than 11352 // comparisons against it. 11353 CaseClusterIt PivotCluster = FirstRight; 11354 assert(PivotCluster > W.FirstCluster); 11355 assert(PivotCluster <= W.LastCluster); 11356 11357 CaseClusterIt FirstLeft = W.FirstCluster; 11358 CaseClusterIt LastRight = W.LastCluster; 11359 11360 const ConstantInt *Pivot = PivotCluster->Low; 11361 11362 // New blocks will be inserted immediately after the current one. 11363 MachineFunction::iterator BBI(W.MBB); 11364 ++BBI; 11365 11366 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 11367 // we can branch to its destination directly if it's squeezed exactly in 11368 // between the known lower bound and Pivot - 1. 11369 MachineBasicBlock *LeftMBB; 11370 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 11371 FirstLeft->Low == W.GE && 11372 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 11373 LeftMBB = FirstLeft->MBB; 11374 } else { 11375 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11376 FuncInfo.MF->insert(BBI, LeftMBB); 11377 WorkList.push_back( 11378 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 11379 // Put Cond in a virtual register to make it available from the new blocks. 11380 ExportFromCurrentBlock(Cond); 11381 } 11382 11383 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 11384 // single cluster, RHS.Low == Pivot, and we can branch to its destination 11385 // directly if RHS.High equals the current upper bound. 11386 MachineBasicBlock *RightMBB; 11387 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 11388 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 11389 RightMBB = FirstRight->MBB; 11390 } else { 11391 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11392 FuncInfo.MF->insert(BBI, RightMBB); 11393 WorkList.push_back( 11394 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 11395 // Put Cond in a virtual register to make it available from the new blocks. 11396 ExportFromCurrentBlock(Cond); 11397 } 11398 11399 // Create the CaseBlock record that will be used to lower the branch. 11400 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 11401 getCurSDLoc(), LeftProb, RightProb); 11402 11403 if (W.MBB == SwitchMBB) 11404 visitSwitchCase(CB, SwitchMBB); 11405 else 11406 SL->SwitchCases.push_back(CB); 11407 } 11408 11409 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 11410 // from the swith statement. 11411 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 11412 BranchProbability PeeledCaseProb) { 11413 if (PeeledCaseProb == BranchProbability::getOne()) 11414 return BranchProbability::getZero(); 11415 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 11416 11417 uint32_t Numerator = CaseProb.getNumerator(); 11418 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 11419 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 11420 } 11421 11422 // Try to peel the top probability case if it exceeds the threshold. 11423 // Return current MachineBasicBlock for the switch statement if the peeling 11424 // does not occur. 11425 // If the peeling is performed, return the newly created MachineBasicBlock 11426 // for the peeled switch statement. Also update Clusters to remove the peeled 11427 // case. PeeledCaseProb is the BranchProbability for the peeled case. 11428 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 11429 const SwitchInst &SI, CaseClusterVector &Clusters, 11430 BranchProbability &PeeledCaseProb) { 11431 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11432 // Don't perform if there is only one cluster or optimizing for size. 11433 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 11434 TM.getOptLevel() == CodeGenOpt::None || 11435 SwitchMBB->getParent()->getFunction().hasMinSize()) 11436 return SwitchMBB; 11437 11438 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 11439 unsigned PeeledCaseIndex = 0; 11440 bool SwitchPeeled = false; 11441 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 11442 CaseCluster &CC = Clusters[Index]; 11443 if (CC.Prob < TopCaseProb) 11444 continue; 11445 TopCaseProb = CC.Prob; 11446 PeeledCaseIndex = Index; 11447 SwitchPeeled = true; 11448 } 11449 if (!SwitchPeeled) 11450 return SwitchMBB; 11451 11452 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 11453 << TopCaseProb << "\n"); 11454 11455 // Record the MBB for the peeled switch statement. 11456 MachineFunction::iterator BBI(SwitchMBB); 11457 ++BBI; 11458 MachineBasicBlock *PeeledSwitchMBB = 11459 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 11460 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 11461 11462 ExportFromCurrentBlock(SI.getCondition()); 11463 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 11464 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 11465 nullptr, nullptr, TopCaseProb.getCompl()}; 11466 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 11467 11468 Clusters.erase(PeeledCaseIt); 11469 for (CaseCluster &CC : Clusters) { 11470 LLVM_DEBUG( 11471 dbgs() << "Scale the probablity for one cluster, before scaling: " 11472 << CC.Prob << "\n"); 11473 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 11474 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 11475 } 11476 PeeledCaseProb = TopCaseProb; 11477 return PeeledSwitchMBB; 11478 } 11479 11480 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 11481 // Extract cases from the switch. 11482 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11483 CaseClusterVector Clusters; 11484 Clusters.reserve(SI.getNumCases()); 11485 for (auto I : SI.cases()) { 11486 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 11487 const ConstantInt *CaseVal = I.getCaseValue(); 11488 BranchProbability Prob = 11489 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 11490 : BranchProbability(1, SI.getNumCases() + 1); 11491 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 11492 } 11493 11494 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 11495 11496 // Cluster adjacent cases with the same destination. We do this at all 11497 // optimization levels because it's cheap to do and will make codegen faster 11498 // if there are many clusters. 11499 sortAndRangeify(Clusters); 11500 11501 // The branch probablity of the peeled case. 11502 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 11503 MachineBasicBlock *PeeledSwitchMBB = 11504 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 11505 11506 // If there is only the default destination, jump there directly. 11507 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11508 if (Clusters.empty()) { 11509 assert(PeeledSwitchMBB == SwitchMBB); 11510 SwitchMBB->addSuccessor(DefaultMBB); 11511 if (DefaultMBB != NextBlock(SwitchMBB)) { 11512 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 11513 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 11514 } 11515 return; 11516 } 11517 11518 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 11519 SL->findBitTestClusters(Clusters, &SI); 11520 11521 LLVM_DEBUG({ 11522 dbgs() << "Case clusters: "; 11523 for (const CaseCluster &C : Clusters) { 11524 if (C.Kind == CC_JumpTable) 11525 dbgs() << "JT:"; 11526 if (C.Kind == CC_BitTests) 11527 dbgs() << "BT:"; 11528 11529 C.Low->getValue().print(dbgs(), true); 11530 if (C.Low != C.High) { 11531 dbgs() << '-'; 11532 C.High->getValue().print(dbgs(), true); 11533 } 11534 dbgs() << ' '; 11535 } 11536 dbgs() << '\n'; 11537 }); 11538 11539 assert(!Clusters.empty()); 11540 SwitchWorkList WorkList; 11541 CaseClusterIt First = Clusters.begin(); 11542 CaseClusterIt Last = Clusters.end() - 1; 11543 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 11544 // Scale the branchprobability for DefaultMBB if the peel occurs and 11545 // DefaultMBB is not replaced. 11546 if (PeeledCaseProb != BranchProbability::getZero() && 11547 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 11548 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 11549 WorkList.push_back( 11550 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 11551 11552 while (!WorkList.empty()) { 11553 SwitchWorkListItem W = WorkList.pop_back_val(); 11554 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 11555 11556 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 11557 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 11558 // For optimized builds, lower large range as a balanced binary tree. 11559 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 11560 continue; 11561 } 11562 11563 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 11564 } 11565 } 11566 11567 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 11568 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11569 auto DL = getCurSDLoc(); 11570 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11571 setValue(&I, DAG.getStepVector(DL, ResultVT)); 11572 } 11573 11574 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 11575 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11576 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11577 11578 SDLoc DL = getCurSDLoc(); 11579 SDValue V = getValue(I.getOperand(0)); 11580 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 11581 11582 if (VT.isScalableVector()) { 11583 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 11584 return; 11585 } 11586 11587 // Use VECTOR_SHUFFLE for the fixed-length vector 11588 // to maintain existing behavior. 11589 SmallVector<int, 8> Mask; 11590 unsigned NumElts = VT.getVectorMinNumElements(); 11591 for (unsigned i = 0; i != NumElts; ++i) 11592 Mask.push_back(NumElts - 1 - i); 11593 11594 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 11595 } 11596 11597 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) { 11598 auto DL = getCurSDLoc(); 11599 SDValue InVec = getValue(I.getOperand(0)); 11600 EVT OutVT = 11601 InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 11602 11603 unsigned OutNumElts = OutVT.getVectorMinNumElements(); 11604 11605 // ISD Node needs the input vectors split into two equal parts 11606 SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 11607 DAG.getVectorIdxConstant(0, DL)); 11608 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 11609 DAG.getVectorIdxConstant(OutNumElts, DL)); 11610 11611 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 11612 // legalisation and combines. 11613 if (OutVT.isFixedLengthVector()) { 11614 SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 11615 createStrideMask(0, 2, OutNumElts)); 11616 SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 11617 createStrideMask(1, 2, OutNumElts)); 11618 SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc()); 11619 setValue(&I, Res); 11620 return; 11621 } 11622 11623 SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL, 11624 DAG.getVTList(OutVT, OutVT), Lo, Hi); 11625 setValue(&I, Res); 11626 } 11627 11628 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) { 11629 auto DL = getCurSDLoc(); 11630 EVT InVT = getValue(I.getOperand(0)).getValueType(); 11631 SDValue InVec0 = getValue(I.getOperand(0)); 11632 SDValue InVec1 = getValue(I.getOperand(1)); 11633 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11634 EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11635 11636 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 11637 // legalisation and combines. 11638 if (OutVT.isFixedLengthVector()) { 11639 unsigned NumElts = InVT.getVectorMinNumElements(); 11640 SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1); 11641 setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT), 11642 createInterleaveMask(NumElts, 2))); 11643 return; 11644 } 11645 11646 SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, 11647 DAG.getVTList(InVT, InVT), InVec0, InVec1); 11648 Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0), 11649 Res.getValue(1)); 11650 setValue(&I, Res); 11651 } 11652 11653 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 11654 SmallVector<EVT, 4> ValueVTs; 11655 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 11656 ValueVTs); 11657 unsigned NumValues = ValueVTs.size(); 11658 if (NumValues == 0) return; 11659 11660 SmallVector<SDValue, 4> Values(NumValues); 11661 SDValue Op = getValue(I.getOperand(0)); 11662 11663 for (unsigned i = 0; i != NumValues; ++i) 11664 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 11665 SDValue(Op.getNode(), Op.getResNo() + i)); 11666 11667 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 11668 DAG.getVTList(ValueVTs), Values)); 11669 } 11670 11671 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 11672 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11673 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11674 11675 SDLoc DL = getCurSDLoc(); 11676 SDValue V1 = getValue(I.getOperand(0)); 11677 SDValue V2 = getValue(I.getOperand(1)); 11678 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 11679 11680 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 11681 if (VT.isScalableVector()) { 11682 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 11683 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 11684 DAG.getConstant(Imm, DL, IdxVT))); 11685 return; 11686 } 11687 11688 unsigned NumElts = VT.getVectorNumElements(); 11689 11690 uint64_t Idx = (NumElts + Imm) % NumElts; 11691 11692 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 11693 SmallVector<int, 8> Mask; 11694 for (unsigned i = 0; i < NumElts; ++i) 11695 Mask.push_back(Idx + i); 11696 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 11697 } 11698 11699 // Consider the following MIR after SelectionDAG, which produces output in 11700 // phyregs in the first case or virtregs in the second case. 11701 // 11702 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx 11703 // %5:gr32 = COPY $ebx 11704 // %6:gr32 = COPY $edx 11705 // %1:gr32 = COPY %6:gr32 11706 // %0:gr32 = COPY %5:gr32 11707 // 11708 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32 11709 // %1:gr32 = COPY %6:gr32 11710 // %0:gr32 = COPY %5:gr32 11711 // 11712 // Given %0, we'd like to return $ebx in the first case and %5 in the second. 11713 // Given %1, we'd like to return $edx in the first case and %6 in the second. 11714 // 11715 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap 11716 // to a single virtreg (such as %0). The remaining outputs monotonically 11717 // increase in virtreg number from there. If a callbr has no outputs, then it 11718 // should not have a corresponding callbr landingpad; in fact, the callbr 11719 // landingpad would not even be able to refer to such a callbr. 11720 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) { 11721 MachineInstr *MI = MRI.def_begin(Reg)->getParent(); 11722 // There is definitely at least one copy. 11723 assert(MI->getOpcode() == TargetOpcode::COPY && 11724 "start of copy chain MUST be COPY"); 11725 Reg = MI->getOperand(1).getReg(); 11726 MI = MRI.def_begin(Reg)->getParent(); 11727 // There may be an optional second copy. 11728 if (MI->getOpcode() == TargetOpcode::COPY) { 11729 assert(Reg.isVirtual() && "expected COPY of virtual register"); 11730 Reg = MI->getOperand(1).getReg(); 11731 assert(Reg.isPhysical() && "expected COPY of physical register"); 11732 MI = MRI.def_begin(Reg)->getParent(); 11733 } 11734 // The start of the chain must be an INLINEASM_BR. 11735 assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR && 11736 "end of copy chain MUST be INLINEASM_BR"); 11737 return Reg; 11738 } 11739 11740 // We must do this walk rather than the simpler 11741 // setValue(&I, getCopyFromRegs(CBR, CBR->getType())); 11742 // otherwise we will end up with copies of virtregs only valid along direct 11743 // edges. 11744 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) { 11745 SmallVector<EVT, 8> ResultVTs; 11746 SmallVector<SDValue, 8> ResultValues; 11747 const auto *CBR = 11748 cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator()); 11749 11750 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11751 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 11752 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11753 11754 unsigned InitialDef = FuncInfo.ValueMap[CBR]; 11755 SDValue Chain = DAG.getRoot(); 11756 11757 // Re-parse the asm constraints string. 11758 TargetLowering::AsmOperandInfoVector TargetConstraints = 11759 TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR); 11760 for (auto &T : TargetConstraints) { 11761 SDISelAsmOperandInfo OpInfo(T); 11762 if (OpInfo.Type != InlineAsm::isOutput) 11763 continue; 11764 11765 // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the 11766 // individual constraint. 11767 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 11768 11769 switch (OpInfo.ConstraintType) { 11770 case TargetLowering::C_Register: 11771 case TargetLowering::C_RegisterClass: { 11772 // Fill in OpInfo.AssignedRegs.Regs. 11773 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo); 11774 11775 // getRegistersForValue may produce 1 to many registers based on whether 11776 // the OpInfo.ConstraintVT is legal on the target or not. 11777 for (size_t i = 0, e = OpInfo.AssignedRegs.Regs.size(); i != e; ++i) { 11778 Register OriginalDef = FollowCopyChain(MRI, InitialDef++); 11779 if (Register::isPhysicalRegister(OriginalDef)) 11780 FuncInfo.MBB->addLiveIn(OriginalDef); 11781 // Update the assigned registers to use the original defs. 11782 OpInfo.AssignedRegs.Regs[i] = OriginalDef; 11783 } 11784 11785 SDValue V = OpInfo.AssignedRegs.getCopyFromRegs( 11786 DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR); 11787 ResultValues.push_back(V); 11788 ResultVTs.push_back(OpInfo.ConstraintVT); 11789 break; 11790 } 11791 case TargetLowering::C_Other: { 11792 SDValue Flag; 11793 SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 11794 OpInfo, DAG); 11795 ++InitialDef; 11796 ResultValues.push_back(V); 11797 ResultVTs.push_back(OpInfo.ConstraintVT); 11798 break; 11799 } 11800 default: 11801 break; 11802 } 11803 } 11804 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 11805 DAG.getVTList(ResultVTs), ResultValues); 11806 setValue(&I, V); 11807 } 11808