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/None.h" 19 #include "llvm/ADT/Optional.h" 20 #include "llvm/ADT/STLExtras.h" 21 #include "llvm/ADT/SmallPtrSet.h" 22 #include "llvm/ADT/SmallSet.h" 23 #include "llvm/ADT/StringRef.h" 24 #include "llvm/ADT/Triple.h" 25 #include "llvm/ADT/Twine.h" 26 #include "llvm/Analysis/AliasAnalysis.h" 27 #include "llvm/Analysis/BranchProbabilityInfo.h" 28 #include "llvm/Analysis/ConstantFolding.h" 29 #include "llvm/Analysis/EHPersonalities.h" 30 #include "llvm/Analysis/Loads.h" 31 #include "llvm/Analysis/MemoryLocation.h" 32 #include "llvm/Analysis/TargetLibraryInfo.h" 33 #include "llvm/Analysis/ValueTracking.h" 34 #include "llvm/CodeGen/Analysis.h" 35 #include "llvm/CodeGen/CodeGenCommonISel.h" 36 #include "llvm/CodeGen/FunctionLoweringInfo.h" 37 #include "llvm/CodeGen/GCMetadata.h" 38 #include "llvm/CodeGen/MachineBasicBlock.h" 39 #include "llvm/CodeGen/MachineFrameInfo.h" 40 #include "llvm/CodeGen/MachineFunction.h" 41 #include "llvm/CodeGen/MachineInstrBuilder.h" 42 #include "llvm/CodeGen/MachineInstrBundleIterator.h" 43 #include "llvm/CodeGen/MachineMemOperand.h" 44 #include "llvm/CodeGen/MachineModuleInfo.h" 45 #include "llvm/CodeGen/MachineOperand.h" 46 #include "llvm/CodeGen/MachineRegisterInfo.h" 47 #include "llvm/CodeGen/RuntimeLibcalls.h" 48 #include "llvm/CodeGen/SelectionDAG.h" 49 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 50 #include "llvm/CodeGen/StackMaps.h" 51 #include "llvm/CodeGen/SwiftErrorValueTracking.h" 52 #include "llvm/CodeGen/TargetFrameLowering.h" 53 #include "llvm/CodeGen/TargetInstrInfo.h" 54 #include "llvm/CodeGen/TargetOpcodes.h" 55 #include "llvm/CodeGen/TargetRegisterInfo.h" 56 #include "llvm/CodeGen/TargetSubtargetInfo.h" 57 #include "llvm/CodeGen/WinEHFuncInfo.h" 58 #include "llvm/IR/Argument.h" 59 #include "llvm/IR/Attributes.h" 60 #include "llvm/IR/BasicBlock.h" 61 #include "llvm/IR/CFG.h" 62 #include "llvm/IR/CallingConv.h" 63 #include "llvm/IR/Constant.h" 64 #include "llvm/IR/ConstantRange.h" 65 #include "llvm/IR/Constants.h" 66 #include "llvm/IR/DataLayout.h" 67 #include "llvm/IR/DebugInfoMetadata.h" 68 #include "llvm/IR/DerivedTypes.h" 69 #include "llvm/IR/DiagnosticInfo.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/Transforms/Utils/Local.h" 100 #include <cstddef> 101 #include <iterator> 102 #include <limits> 103 #include <tuple> 104 105 using namespace llvm; 106 using namespace PatternMatch; 107 using namespace SwitchCG; 108 109 #define DEBUG_TYPE "isel" 110 111 /// LimitFloatPrecision - Generate low-precision inline sequences for 112 /// some float libcalls (6, 8 or 12 bits). 113 static unsigned LimitFloatPrecision; 114 115 static cl::opt<bool> 116 InsertAssertAlign("insert-assert-align", cl::init(true), 117 cl::desc("Insert the experimental `assertalign` node."), 118 cl::ReallyHidden); 119 120 static cl::opt<unsigned, true> 121 LimitFPPrecision("limit-float-precision", 122 cl::desc("Generate low-precision inline sequences " 123 "for some float libcalls"), 124 cl::location(LimitFloatPrecision), cl::Hidden, 125 cl::init(0)); 126 127 static cl::opt<unsigned> SwitchPeelThreshold( 128 "switch-peel-threshold", cl::Hidden, cl::init(66), 129 cl::desc("Set the case probability threshold for peeling the case from a " 130 "switch statement. A value greater than 100 will void this " 131 "optimization")); 132 133 // Limit the width of DAG chains. This is important in general to prevent 134 // DAG-based analysis from blowing up. For example, alias analysis and 135 // load clustering may not complete in reasonable time. It is difficult to 136 // recognize and avoid this situation within each individual analysis, and 137 // future analyses are likely to have the same behavior. Limiting DAG width is 138 // the safe approach and will be especially important with global DAGs. 139 // 140 // MaxParallelChains default is arbitrarily high to avoid affecting 141 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 142 // sequence over this should have been converted to llvm.memcpy by the 143 // frontend. It is easy to induce this behavior with .ll code such as: 144 // %buffer = alloca [4096 x i8] 145 // %data = load [4096 x i8]* %argPtr 146 // store [4096 x i8] %data, [4096 x i8]* %buffer 147 static const unsigned MaxParallelChains = 64; 148 149 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 150 const SDValue *Parts, unsigned NumParts, 151 MVT PartVT, EVT ValueVT, const Value *V, 152 Optional<CallingConv::ID> CC); 153 154 /// getCopyFromParts - Create a value that contains the specified legal parts 155 /// combined into the value they represent. If the parts combine to a type 156 /// larger than ValueVT then AssertOp can be used to specify whether the extra 157 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 158 /// (ISD::AssertSext). 159 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 160 const SDValue *Parts, unsigned NumParts, 161 MVT PartVT, EVT ValueVT, const Value *V, 162 Optional<CallingConv::ID> CC = None, 163 Optional<ISD::NodeType> AssertOp = None) { 164 // Let the target assemble the parts if it wants to 165 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 166 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts, 167 PartVT, ValueVT, CC)) 168 return Val; 169 170 if (ValueVT.isVector()) 171 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 172 CC); 173 174 assert(NumParts > 0 && "No parts to assemble!"); 175 SDValue Val = Parts[0]; 176 177 if (NumParts > 1) { 178 // Assemble the value from multiple parts. 179 if (ValueVT.isInteger()) { 180 unsigned PartBits = PartVT.getSizeInBits(); 181 unsigned ValueBits = ValueVT.getSizeInBits(); 182 183 // Assemble the power of 2 part. 184 unsigned RoundParts = 185 (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts; 186 unsigned RoundBits = PartBits * RoundParts; 187 EVT RoundVT = RoundBits == ValueBits ? 188 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 189 SDValue Lo, Hi; 190 191 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 192 193 if (RoundParts > 2) { 194 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 195 PartVT, HalfVT, V); 196 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 197 RoundParts / 2, PartVT, HalfVT, V); 198 } else { 199 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 200 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 201 } 202 203 if (DAG.getDataLayout().isBigEndian()) 204 std::swap(Lo, Hi); 205 206 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 207 208 if (RoundParts < NumParts) { 209 // Assemble the trailing non-power-of-2 part. 210 unsigned OddParts = NumParts - RoundParts; 211 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 212 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 213 OddVT, V, CC); 214 215 // Combine the round and odd parts. 216 Lo = Val; 217 if (DAG.getDataLayout().isBigEndian()) 218 std::swap(Lo, Hi); 219 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 220 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 221 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 222 DAG.getConstant(Lo.getValueSizeInBits(), DL, 223 TLI.getShiftAmountTy( 224 TotalVT, DAG.getDataLayout()))); 225 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 226 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 227 } 228 } else if (PartVT.isFloatingPoint()) { 229 // FP split into multiple FP parts (for ppcf128) 230 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 231 "Unexpected split"); 232 SDValue Lo, Hi; 233 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 234 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 235 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 236 std::swap(Lo, Hi); 237 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 238 } else { 239 // FP split into integer parts (soft fp) 240 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 241 !PartVT.isVector() && "Unexpected split"); 242 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 243 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 244 } 245 } 246 247 // There is now one part, held in Val. Correct it to match ValueVT. 248 // PartEVT is the type of the register class that holds the value. 249 // ValueVT is the type of the inline asm operation. 250 EVT PartEVT = Val.getValueType(); 251 252 if (PartEVT == ValueVT) 253 return Val; 254 255 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 256 ValueVT.bitsLT(PartEVT)) { 257 // For an FP value in an integer part, we need to truncate to the right 258 // width first. 259 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 260 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 261 } 262 263 // Handle types that have the same size. 264 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 265 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 266 267 // Handle types with different sizes. 268 if (PartEVT.isInteger() && ValueVT.isInteger()) { 269 if (ValueVT.bitsLT(PartEVT)) { 270 // For a truncate, see if we have any information to 271 // indicate whether the truncated bits will always be 272 // zero or sign-extension. 273 if (AssertOp) 274 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 275 DAG.getValueType(ValueVT)); 276 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 277 } 278 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 279 } 280 281 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 282 // FP_ROUND's are always exact here. 283 if (ValueVT.bitsLT(Val.getValueType())) 284 return DAG.getNode( 285 ISD::FP_ROUND, DL, ValueVT, Val, 286 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 287 288 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 289 } 290 291 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 292 // then truncating. 293 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 294 ValueVT.bitsLT(PartEVT)) { 295 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 296 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 297 } 298 299 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 300 } 301 302 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 303 const Twine &ErrMsg) { 304 const Instruction *I = dyn_cast_or_null<Instruction>(V); 305 if (!V) 306 return Ctx.emitError(ErrMsg); 307 308 const char *AsmError = ", possible invalid constraint for vector type"; 309 if (const CallInst *CI = dyn_cast<CallInst>(I)) 310 if (CI->isInlineAsm()) 311 return Ctx.emitError(I, ErrMsg + AsmError); 312 313 return Ctx.emitError(I, ErrMsg); 314 } 315 316 /// getCopyFromPartsVector - Create a value that contains the specified legal 317 /// parts combined into the value they represent. If the parts combine to a 318 /// type larger than ValueVT then AssertOp can be used to specify whether the 319 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 320 /// ValueVT (ISD::AssertSext). 321 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 322 const SDValue *Parts, unsigned NumParts, 323 MVT PartVT, EVT ValueVT, const Value *V, 324 Optional<CallingConv::ID> CallConv) { 325 assert(ValueVT.isVector() && "Not a vector value"); 326 assert(NumParts > 0 && "No parts to assemble!"); 327 const bool IsABIRegCopy = CallConv.has_value(); 328 329 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 330 SDValue Val = Parts[0]; 331 332 // Handle a multi-element vector. 333 if (NumParts > 1) { 334 EVT IntermediateVT; 335 MVT RegisterVT; 336 unsigned NumIntermediates; 337 unsigned NumRegs; 338 339 if (IsABIRegCopy) { 340 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 341 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, 342 NumIntermediates, RegisterVT); 343 } else { 344 NumRegs = 345 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 346 NumIntermediates, RegisterVT); 347 } 348 349 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 350 NumParts = NumRegs; // Silence a compiler warning. 351 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 352 assert(RegisterVT.getSizeInBits() == 353 Parts[0].getSimpleValueType().getSizeInBits() && 354 "Part type sizes don't match!"); 355 356 // Assemble the parts into intermediate operands. 357 SmallVector<SDValue, 8> Ops(NumIntermediates); 358 if (NumIntermediates == NumParts) { 359 // If the register was not expanded, truncate or copy the value, 360 // as appropriate. 361 for (unsigned i = 0; i != NumParts; ++i) 362 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 363 PartVT, IntermediateVT, V, CallConv); 364 } else if (NumParts > 0) { 365 // If the intermediate type was expanded, build the intermediate 366 // operands from the parts. 367 assert(NumParts % NumIntermediates == 0 && 368 "Must expand into a divisible number of parts!"); 369 unsigned Factor = NumParts / NumIntermediates; 370 for (unsigned i = 0; i != NumIntermediates; ++i) 371 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 372 PartVT, IntermediateVT, V, CallConv); 373 } 374 375 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 376 // intermediate operands. 377 EVT BuiltVectorTy = 378 IntermediateVT.isVector() 379 ? EVT::getVectorVT( 380 *DAG.getContext(), IntermediateVT.getScalarType(), 381 IntermediateVT.getVectorElementCount() * NumParts) 382 : EVT::getVectorVT(*DAG.getContext(), 383 IntermediateVT.getScalarType(), 384 NumIntermediates); 385 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 386 : ISD::BUILD_VECTOR, 387 DL, BuiltVectorTy, Ops); 388 } 389 390 // There is now one part, held in Val. Correct it to match ValueVT. 391 EVT PartEVT = Val.getValueType(); 392 393 if (PartEVT == ValueVT) 394 return Val; 395 396 if (PartEVT.isVector()) { 397 // Vector/Vector bitcast. 398 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 399 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 400 401 // If the element type of the source/dest vectors are the same, but the 402 // parts vector has more elements than the value vector, then we have a 403 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 404 // 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 } 419 420 // Promoted vector extract 421 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 422 } 423 424 // Trivial bitcast if the types are the same size and the destination 425 // vector type is legal. 426 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 427 TLI.isTypeLegal(ValueVT)) 428 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 429 430 if (ValueVT.getVectorNumElements() != 1) { 431 // Certain ABIs require that vectors are passed as integers. For vectors 432 // are the same size, this is an obvious bitcast. 433 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 434 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 435 } else if (ValueVT.bitsLT(PartEVT)) { 436 const uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 437 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 438 // Drop the extra bits. 439 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 440 return DAG.getBitcast(ValueVT, Val); 441 } 442 443 diagnosePossiblyInvalidConstraint( 444 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 445 return DAG.getUNDEF(ValueVT); 446 } 447 448 // Handle cases such as i8 -> <1 x i1> 449 EVT ValueSVT = ValueVT.getVectorElementType(); 450 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 451 unsigned ValueSize = ValueSVT.getSizeInBits(); 452 if (ValueSize == PartEVT.getSizeInBits()) { 453 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 454 } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) { 455 // It's possible a scalar floating point type gets softened to integer and 456 // then promoted to a larger integer. If PartEVT is the larger integer 457 // we need to truncate it and then bitcast to the FP type. 458 assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types"); 459 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 460 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 461 Val = DAG.getBitcast(ValueSVT, Val); 462 } else { 463 Val = ValueVT.isFloatingPoint() 464 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 465 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 466 } 467 } 468 469 return DAG.getBuildVector(ValueVT, DL, Val); 470 } 471 472 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 473 SDValue Val, SDValue *Parts, unsigned NumParts, 474 MVT PartVT, const Value *V, 475 Optional<CallingConv::ID> CallConv); 476 477 /// getCopyToParts - Create a series of nodes that contain the specified value 478 /// split into legal parts. If the parts contain more bits than Val, then, for 479 /// integers, ExtendKind can be used to specify how to generate the extra bits. 480 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 481 SDValue *Parts, unsigned NumParts, MVT PartVT, 482 const Value *V, 483 Optional<CallingConv::ID> CallConv = None, 484 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 485 // Let the target split the parts if it wants to 486 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 487 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 488 CallConv)) 489 return; 490 EVT ValueVT = Val.getValueType(); 491 492 // Handle the vector case separately. 493 if (ValueVT.isVector()) 494 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 495 CallConv); 496 497 unsigned PartBits = PartVT.getSizeInBits(); 498 unsigned OrigNumParts = NumParts; 499 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 500 "Copying to an illegal type!"); 501 502 if (NumParts == 0) 503 return; 504 505 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 506 EVT PartEVT = PartVT; 507 if (PartEVT == ValueVT) { 508 assert(NumParts == 1 && "No-op copy with multiple parts!"); 509 Parts[0] = Val; 510 return; 511 } 512 513 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 514 // If the parts cover more bits than the value has, promote the value. 515 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 516 assert(NumParts == 1 && "Do not know what to promote to!"); 517 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 518 } else { 519 if (ValueVT.isFloatingPoint()) { 520 // FP values need to be bitcast, then extended if they are being put 521 // into a larger container. 522 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 523 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 524 } 525 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 526 ValueVT.isInteger() && 527 "Unknown mismatch!"); 528 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 529 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 530 if (PartVT == MVT::x86mmx) 531 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 532 } 533 } else if (PartBits == ValueVT.getSizeInBits()) { 534 // Different types of the same size. 535 assert(NumParts == 1 && PartEVT != ValueVT); 536 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 537 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 538 // If the parts cover less bits than value has, truncate the value. 539 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 540 ValueVT.isInteger() && 541 "Unknown mismatch!"); 542 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 543 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 544 if (PartVT == MVT::x86mmx) 545 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 546 } 547 548 // The value may have changed - recompute ValueVT. 549 ValueVT = Val.getValueType(); 550 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 551 "Failed to tile the value with PartVT!"); 552 553 if (NumParts == 1) { 554 if (PartEVT != ValueVT) { 555 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 556 "scalar-to-vector conversion failed"); 557 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 558 } 559 560 Parts[0] = Val; 561 return; 562 } 563 564 // Expand the value into multiple parts. 565 if (NumParts & (NumParts - 1)) { 566 // The number of parts is not a power of 2. Split off and copy the tail. 567 assert(PartVT.isInteger() && ValueVT.isInteger() && 568 "Do not know what to expand to!"); 569 unsigned RoundParts = 1 << Log2_32(NumParts); 570 unsigned RoundBits = RoundParts * PartBits; 571 unsigned OddParts = NumParts - RoundParts; 572 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 573 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL)); 574 575 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 576 CallConv); 577 578 if (DAG.getDataLayout().isBigEndian()) 579 // The odd parts were reversed by getCopyToParts - unreverse them. 580 std::reverse(Parts + RoundParts, Parts + NumParts); 581 582 NumParts = RoundParts; 583 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 584 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 585 } 586 587 // The number of parts is a power of 2. Repeatedly bisect the value using 588 // EXTRACT_ELEMENT. 589 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 590 EVT::getIntegerVT(*DAG.getContext(), 591 ValueVT.getSizeInBits()), 592 Val); 593 594 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 595 for (unsigned i = 0; i < NumParts; i += StepSize) { 596 unsigned ThisBits = StepSize * PartBits / 2; 597 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 598 SDValue &Part0 = Parts[i]; 599 SDValue &Part1 = Parts[i+StepSize/2]; 600 601 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 602 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 603 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 604 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 605 606 if (ThisBits == PartBits && ThisVT != PartVT) { 607 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 608 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 609 } 610 } 611 } 612 613 if (DAG.getDataLayout().isBigEndian()) 614 std::reverse(Parts, Parts + OrigNumParts); 615 } 616 617 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val, 618 const SDLoc &DL, EVT PartVT) { 619 if (!PartVT.isVector()) 620 return SDValue(); 621 622 EVT ValueVT = Val.getValueType(); 623 ElementCount PartNumElts = PartVT.getVectorElementCount(); 624 ElementCount ValueNumElts = ValueVT.getVectorElementCount(); 625 626 // We only support widening vectors with equivalent element types and 627 // fixed/scalable properties. If a target needs to widen a fixed-length type 628 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below. 629 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) || 630 PartNumElts.isScalable() != ValueNumElts.isScalable() || 631 PartVT.getVectorElementType() != ValueVT.getVectorElementType()) 632 return SDValue(); 633 634 // Widening a scalable vector to another scalable vector is done by inserting 635 // the vector into a larger undef one. 636 if (PartNumElts.isScalable()) 637 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 638 Val, DAG.getVectorIdxConstant(0, DL)); 639 640 EVT ElementVT = PartVT.getVectorElementType(); 641 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 642 // undef elements. 643 SmallVector<SDValue, 16> Ops; 644 DAG.ExtractVectorElements(Val, Ops); 645 SDValue EltUndef = DAG.getUNDEF(ElementVT); 646 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef); 647 648 // FIXME: Use CONCAT for 2x -> 4x. 649 return DAG.getBuildVector(PartVT, DL, Ops); 650 } 651 652 /// getCopyToPartsVector - Create a series of nodes that contain the specified 653 /// value split into legal parts. 654 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 655 SDValue Val, SDValue *Parts, unsigned NumParts, 656 MVT PartVT, const Value *V, 657 Optional<CallingConv::ID> CallConv) { 658 EVT ValueVT = Val.getValueType(); 659 assert(ValueVT.isVector() && "Not a vector"); 660 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 661 const bool IsABIRegCopy = CallConv.has_value(); 662 663 if (NumParts == 1) { 664 EVT PartEVT = PartVT; 665 if (PartEVT == ValueVT) { 666 // Nothing to do. 667 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 668 // Bitconvert vector->vector case. 669 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 670 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 671 Val = Widened; 672 } else if (PartVT.isVector() && 673 PartEVT.getVectorElementType().bitsGE( 674 ValueVT.getVectorElementType()) && 675 PartEVT.getVectorElementCount() == 676 ValueVT.getVectorElementCount()) { 677 678 // Promoted vector extract 679 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 680 } else if (PartEVT.isVector() && 681 PartEVT.getVectorElementType() != 682 ValueVT.getVectorElementType() && 683 TLI.getTypeAction(*DAG.getContext(), ValueVT) == 684 TargetLowering::TypeWidenVector) { 685 // Combination of widening and promotion. 686 EVT WidenVT = 687 EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(), 688 PartVT.getVectorElementCount()); 689 SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT); 690 Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT); 691 } else { 692 // Don't extract an integer from a float vector. This can happen if the 693 // FP type gets softened to integer and then promoted. The promotion 694 // prevents it from being picked up by the earlier bitcast case. 695 if (ValueVT.getVectorElementCount().isScalar() && 696 (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) { 697 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 698 DAG.getVectorIdxConstant(0, DL)); 699 } else { 700 uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 701 assert(PartVT.getFixedSizeInBits() > ValueSize && 702 "lossy conversion of vector to scalar type"); 703 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 704 Val = DAG.getBitcast(IntermediateType, Val); 705 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 706 } 707 } 708 709 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 710 Parts[0] = Val; 711 return; 712 } 713 714 // Handle a multi-element vector. 715 EVT IntermediateVT; 716 MVT RegisterVT; 717 unsigned NumIntermediates; 718 unsigned NumRegs; 719 if (IsABIRegCopy) { 720 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 721 *DAG.getContext(), CallConv.value(), ValueVT, IntermediateVT, 722 NumIntermediates, RegisterVT); 723 } else { 724 NumRegs = 725 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 726 NumIntermediates, RegisterVT); 727 } 728 729 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 730 NumParts = NumRegs; // Silence a compiler warning. 731 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 732 733 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 734 "Mixing scalable and fixed vectors when copying in parts"); 735 736 Optional<ElementCount> DestEltCnt; 737 738 if (IntermediateVT.isVector()) 739 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 740 else 741 DestEltCnt = ElementCount::getFixed(NumIntermediates); 742 743 EVT BuiltVectorTy = EVT::getVectorVT( 744 *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt); 745 746 if (ValueVT == BuiltVectorTy) { 747 // Nothing to do. 748 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) { 749 // Bitconvert vector->vector case. 750 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 751 } else { 752 if (BuiltVectorTy.getVectorElementType().bitsGT( 753 ValueVT.getVectorElementType())) { 754 // Integer promotion. 755 ValueVT = EVT::getVectorVT(*DAG.getContext(), 756 BuiltVectorTy.getVectorElementType(), 757 ValueVT.getVectorElementCount()); 758 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 759 } 760 761 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) { 762 Val = Widened; 763 } 764 } 765 766 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type"); 767 768 // Split the vector into intermediate operands. 769 SmallVector<SDValue, 8> Ops(NumIntermediates); 770 for (unsigned i = 0; i != NumIntermediates; ++i) { 771 if (IntermediateVT.isVector()) { 772 // This does something sensible for scalable vectors - see the 773 // definition of EXTRACT_SUBVECTOR for further details. 774 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 775 Ops[i] = 776 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 777 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 778 } else { 779 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 780 DAG.getVectorIdxConstant(i, DL)); 781 } 782 } 783 784 // Split the intermediate operands into legal parts. 785 if (NumParts == NumIntermediates) { 786 // If the register was not expanded, promote or copy the value, 787 // as appropriate. 788 for (unsigned i = 0; i != NumParts; ++i) 789 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 790 } else if (NumParts > 0) { 791 // If the intermediate type was expanded, split each the value into 792 // legal parts. 793 assert(NumIntermediates != 0 && "division by zero"); 794 assert(NumParts % NumIntermediates == 0 && 795 "Must expand into a divisible number of parts!"); 796 unsigned Factor = NumParts / NumIntermediates; 797 for (unsigned i = 0; i != NumIntermediates; ++i) 798 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 799 CallConv); 800 } 801 } 802 803 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 804 EVT valuevt, Optional<CallingConv::ID> CC) 805 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 806 RegCount(1, regs.size()), CallConv(CC) {} 807 808 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 809 const DataLayout &DL, unsigned Reg, Type *Ty, 810 Optional<CallingConv::ID> CC) { 811 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 812 813 CallConv = CC; 814 815 for (EVT ValueVT : ValueVTs) { 816 unsigned NumRegs = 817 isABIMangled() 818 ? TLI.getNumRegistersForCallingConv(Context, CC.value(), ValueVT) 819 : TLI.getNumRegisters(Context, ValueVT); 820 MVT RegisterVT = 821 isABIMangled() 822 ? TLI.getRegisterTypeForCallingConv(Context, CC.value(), ValueVT) 823 : TLI.getRegisterType(Context, ValueVT); 824 for (unsigned i = 0; i != NumRegs; ++i) 825 Regs.push_back(Reg + i); 826 RegVTs.push_back(RegisterVT); 827 RegCount.push_back(NumRegs); 828 Reg += NumRegs; 829 } 830 } 831 832 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 833 FunctionLoweringInfo &FuncInfo, 834 const SDLoc &dl, SDValue &Chain, 835 SDValue *Flag, const Value *V) const { 836 // A Value with type {} or [0 x %t] needs no registers. 837 if (ValueVTs.empty()) 838 return SDValue(); 839 840 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 841 842 // Assemble the legal parts into the final values. 843 SmallVector<SDValue, 4> Values(ValueVTs.size()); 844 SmallVector<SDValue, 8> Parts; 845 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 846 // Copy the legal parts from the registers. 847 EVT ValueVT = ValueVTs[Value]; 848 unsigned NumRegs = RegCount[Value]; 849 MVT RegisterVT = 850 isABIMangled() ? TLI.getRegisterTypeForCallingConv( 851 *DAG.getContext(), CallConv.value(), RegVTs[Value]) 852 : RegVTs[Value]; 853 854 Parts.resize(NumRegs); 855 for (unsigned i = 0; i != NumRegs; ++i) { 856 SDValue P; 857 if (!Flag) { 858 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 859 } else { 860 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 861 *Flag = P.getValue(2); 862 } 863 864 Chain = P.getValue(1); 865 Parts[i] = P; 866 867 // If the source register was virtual and if we know something about it, 868 // add an assert node. 869 if (!Register::isVirtualRegister(Regs[Part + i]) || 870 !RegisterVT.isInteger()) 871 continue; 872 873 const FunctionLoweringInfo::LiveOutInfo *LOI = 874 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 875 if (!LOI) 876 continue; 877 878 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 879 unsigned NumSignBits = LOI->NumSignBits; 880 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 881 882 if (NumZeroBits == RegSize) { 883 // The current value is a zero. 884 // Explicitly express that as it would be easier for 885 // optimizations to kick in. 886 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 887 continue; 888 } 889 890 // FIXME: We capture more information than the dag can represent. For 891 // now, just use the tightest assertzext/assertsext possible. 892 bool isSExt; 893 EVT FromVT(MVT::Other); 894 if (NumZeroBits) { 895 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 896 isSExt = false; 897 } else if (NumSignBits > 1) { 898 FromVT = 899 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 900 isSExt = true; 901 } else { 902 continue; 903 } 904 // Add an assertion node. 905 assert(FromVT != MVT::Other); 906 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 907 RegisterVT, P, DAG.getValueType(FromVT)); 908 } 909 910 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 911 RegisterVT, ValueVT, V, CallConv); 912 Part += NumRegs; 913 Parts.clear(); 914 } 915 916 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 917 } 918 919 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 920 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 921 const Value *V, 922 ISD::NodeType PreferredExtendType) const { 923 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 924 ISD::NodeType ExtendKind = PreferredExtendType; 925 926 // Get the list of the values's legal parts. 927 unsigned NumRegs = Regs.size(); 928 SmallVector<SDValue, 8> Parts(NumRegs); 929 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 930 unsigned NumParts = RegCount[Value]; 931 932 MVT RegisterVT = 933 isABIMangled() ? TLI.getRegisterTypeForCallingConv( 934 *DAG.getContext(), CallConv.value(), RegVTs[Value]) 935 : RegVTs[Value]; 936 937 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 938 ExtendKind = ISD::ZERO_EXTEND; 939 940 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 941 NumParts, RegisterVT, V, CallConv, ExtendKind); 942 Part += NumParts; 943 } 944 945 // Copy the parts into the registers. 946 SmallVector<SDValue, 8> Chains(NumRegs); 947 for (unsigned i = 0; i != NumRegs; ++i) { 948 SDValue Part; 949 if (!Flag) { 950 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 951 } else { 952 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 953 *Flag = Part.getValue(1); 954 } 955 956 Chains[i] = Part.getValue(0); 957 } 958 959 if (NumRegs == 1 || Flag) 960 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 961 // flagged to it. That is the CopyToReg nodes and the user are considered 962 // a single scheduling unit. If we create a TokenFactor and return it as 963 // chain, then the TokenFactor is both a predecessor (operand) of the 964 // user as well as a successor (the TF operands are flagged to the user). 965 // c1, f1 = CopyToReg 966 // c2, f2 = CopyToReg 967 // c3 = TokenFactor c1, c2 968 // ... 969 // = op c3, ..., f2 970 Chain = Chains[NumRegs-1]; 971 else 972 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 973 } 974 975 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 976 unsigned MatchingIdx, const SDLoc &dl, 977 SelectionDAG &DAG, 978 std::vector<SDValue> &Ops) const { 979 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 980 981 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 982 if (HasMatching) 983 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 984 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 985 // Put the register class of the virtual registers in the flag word. That 986 // way, later passes can recompute register class constraints for inline 987 // assembly as well as normal instructions. 988 // Don't do this for tied operands that can use the regclass information 989 // from the def. 990 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 991 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 992 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 993 } 994 995 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 996 Ops.push_back(Res); 997 998 if (Code == InlineAsm::Kind_Clobber) { 999 // Clobbers should always have a 1:1 mapping with registers, and may 1000 // reference registers that have illegal (e.g. vector) types. Hence, we 1001 // shouldn't try to apply any sort of splitting logic to them. 1002 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 1003 "No 1:1 mapping from clobbers to regs?"); 1004 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 1005 (void)SP; 1006 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 1007 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 1008 assert( 1009 (Regs[I] != SP || 1010 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 1011 "If we clobbered the stack pointer, MFI should know about it."); 1012 } 1013 return; 1014 } 1015 1016 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 1017 MVT RegisterVT = RegVTs[Value]; 1018 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value], 1019 RegisterVT); 1020 for (unsigned i = 0; i != NumRegs; ++i) { 1021 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 1022 unsigned TheReg = Regs[Reg++]; 1023 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 1024 } 1025 } 1026 } 1027 1028 SmallVector<std::pair<unsigned, TypeSize>, 4> 1029 RegsForValue::getRegsAndSizes() const { 1030 SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec; 1031 unsigned I = 0; 1032 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1033 unsigned RegCount = std::get<0>(CountAndVT); 1034 MVT RegisterVT = std::get<1>(CountAndVT); 1035 TypeSize RegisterSize = RegisterVT.getSizeInBits(); 1036 for (unsigned E = I + RegCount; I != E; ++I) 1037 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1038 } 1039 return OutVec; 1040 } 1041 1042 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1043 AssumptionCache *ac, 1044 const TargetLibraryInfo *li) { 1045 AA = aa; 1046 AC = ac; 1047 GFI = gfi; 1048 LibInfo = li; 1049 Context = DAG.getContext(); 1050 LPadToCallSiteMap.clear(); 1051 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1052 } 1053 1054 void SelectionDAGBuilder::clear() { 1055 NodeMap.clear(); 1056 UnusedArgNodeMap.clear(); 1057 PendingLoads.clear(); 1058 PendingExports.clear(); 1059 PendingConstrainedFP.clear(); 1060 PendingConstrainedFPStrict.clear(); 1061 CurInst = nullptr; 1062 HasTailCall = false; 1063 SDNodeOrder = LowestSDNodeOrder; 1064 StatepointLowering.clear(); 1065 } 1066 1067 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1068 DanglingDebugInfoMap.clear(); 1069 } 1070 1071 // Update DAG root to include dependencies on Pending chains. 1072 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1073 SDValue Root = DAG.getRoot(); 1074 1075 if (Pending.empty()) 1076 return Root; 1077 1078 // Add current root to PendingChains, unless we already indirectly 1079 // depend on it. 1080 if (Root.getOpcode() != ISD::EntryToken) { 1081 unsigned i = 0, e = Pending.size(); 1082 for (; i != e; ++i) { 1083 assert(Pending[i].getNode()->getNumOperands() > 1); 1084 if (Pending[i].getNode()->getOperand(0) == Root) 1085 break; // Don't add the root if we already indirectly depend on it. 1086 } 1087 1088 if (i == e) 1089 Pending.push_back(Root); 1090 } 1091 1092 if (Pending.size() == 1) 1093 Root = Pending[0]; 1094 else 1095 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1096 1097 DAG.setRoot(Root); 1098 Pending.clear(); 1099 return Root; 1100 } 1101 1102 SDValue SelectionDAGBuilder::getMemoryRoot() { 1103 return updateRoot(PendingLoads); 1104 } 1105 1106 SDValue SelectionDAGBuilder::getRoot() { 1107 // Chain up all pending constrained intrinsics together with all 1108 // pending loads, by simply appending them to PendingLoads and 1109 // then calling getMemoryRoot(). 1110 PendingLoads.reserve(PendingLoads.size() + 1111 PendingConstrainedFP.size() + 1112 PendingConstrainedFPStrict.size()); 1113 PendingLoads.append(PendingConstrainedFP.begin(), 1114 PendingConstrainedFP.end()); 1115 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1116 PendingConstrainedFPStrict.end()); 1117 PendingConstrainedFP.clear(); 1118 PendingConstrainedFPStrict.clear(); 1119 return getMemoryRoot(); 1120 } 1121 1122 SDValue SelectionDAGBuilder::getControlRoot() { 1123 // We need to emit pending fpexcept.strict constrained intrinsics, 1124 // so append them to the PendingExports list. 1125 PendingExports.append(PendingConstrainedFPStrict.begin(), 1126 PendingConstrainedFPStrict.end()); 1127 PendingConstrainedFPStrict.clear(); 1128 return updateRoot(PendingExports); 1129 } 1130 1131 void SelectionDAGBuilder::visit(const Instruction &I) { 1132 // Set up outgoing PHI node register values before emitting the terminator. 1133 if (I.isTerminator()) { 1134 HandlePHINodesInSuccessorBlocks(I.getParent()); 1135 } 1136 1137 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1138 if (!isa<DbgInfoIntrinsic>(I)) 1139 ++SDNodeOrder; 1140 1141 CurInst = &I; 1142 1143 // Set inserted listener only if required. 1144 bool NodeInserted = false; 1145 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener; 1146 MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections); 1147 if (PCSectionsMD) { 1148 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>( 1149 DAG, [&](SDNode *) { NodeInserted = true; }); 1150 } 1151 1152 visit(I.getOpcode(), I); 1153 1154 if (!I.isTerminator() && !HasTailCall && 1155 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1156 CopyToExportRegsIfNeeded(&I); 1157 1158 // Handle metadata. 1159 if (PCSectionsMD) { 1160 auto It = NodeMap.find(&I); 1161 if (It != NodeMap.end()) { 1162 DAG.addPCSections(It->second.getNode(), PCSectionsMD); 1163 } else if (NodeInserted) { 1164 // This should not happen; if it does, don't let it go unnoticed so we can 1165 // fix it. Relevant visit*() function is probably missing a setValue(). 1166 errs() << "warning: loosing !pcsections metadata [" 1167 << I.getModule()->getName() << "]\n"; 1168 LLVM_DEBUG(I.dump()); 1169 assert(false); 1170 } 1171 } 1172 1173 CurInst = nullptr; 1174 } 1175 1176 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1177 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1178 } 1179 1180 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1181 // Note: this doesn't use InstVisitor, because it has to work with 1182 // ConstantExpr's in addition to instructions. 1183 switch (Opcode) { 1184 default: llvm_unreachable("Unknown instruction type encountered!"); 1185 // Build the switch statement using the Instruction.def file. 1186 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1187 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1188 #include "llvm/IR/Instruction.def" 1189 } 1190 } 1191 1192 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI, 1193 DebugLoc DL, unsigned Order) { 1194 // We treat variadic dbg_values differently at this stage. 1195 if (DI->hasArgList()) { 1196 // For variadic dbg_values we will now insert an undef. 1197 // FIXME: We can potentially recover these! 1198 SmallVector<SDDbgOperand, 2> Locs; 1199 for (const Value *V : DI->getValues()) { 1200 auto Undef = UndefValue::get(V->getType()); 1201 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1202 } 1203 SDDbgValue *SDV = DAG.getDbgValueList( 1204 DI->getVariable(), DI->getExpression(), Locs, {}, 1205 /*IsIndirect=*/false, DL, Order, /*IsVariadic=*/true); 1206 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1207 } else { 1208 // TODO: Dangling debug info will eventually either be resolved or produce 1209 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1210 // between the original dbg.value location and its resolved DBG_VALUE, 1211 // which we should ideally fill with an extra Undef DBG_VALUE. 1212 assert(DI->getNumVariableLocationOps() == 1 && 1213 "DbgValueInst without an ArgList should have a single location " 1214 "operand."); 1215 DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, DL, Order); 1216 } 1217 } 1218 1219 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1220 const DIExpression *Expr) { 1221 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1222 const DbgValueInst *DI = DDI.getDI(); 1223 DIVariable *DanglingVariable = DI->getVariable(); 1224 DIExpression *DanglingExpr = DI->getExpression(); 1225 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1226 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1227 return true; 1228 } 1229 return false; 1230 }; 1231 1232 for (auto &DDIMI : DanglingDebugInfoMap) { 1233 DanglingDebugInfoVector &DDIV = DDIMI.second; 1234 1235 // If debug info is to be dropped, run it through final checks to see 1236 // whether it can be salvaged. 1237 for (auto &DDI : DDIV) 1238 if (isMatchingDbgValue(DDI)) 1239 salvageUnresolvedDbgValue(DDI); 1240 1241 erase_if(DDIV, isMatchingDbgValue); 1242 } 1243 } 1244 1245 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1246 // generate the debug data structures now that we've seen its definition. 1247 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1248 SDValue Val) { 1249 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1250 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1251 return; 1252 1253 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1254 for (auto &DDI : DDIV) { 1255 const DbgValueInst *DI = DDI.getDI(); 1256 assert(!DI->hasArgList() && "Not implemented for variadic dbg_values"); 1257 assert(DI && "Ill-formed DanglingDebugInfo"); 1258 DebugLoc dl = DDI.getdl(); 1259 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1260 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1261 DILocalVariable *Variable = DI->getVariable(); 1262 DIExpression *Expr = DI->getExpression(); 1263 assert(Variable->isValidLocationForIntrinsic(dl) && 1264 "Expected inlined-at fields to agree"); 1265 SDDbgValue *SDV; 1266 if (Val.getNode()) { 1267 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1268 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1269 // we couldn't resolve it directly when examining the DbgValue intrinsic 1270 // in the first place we should not be more successful here). Unless we 1271 // have some test case that prove this to be correct we should avoid 1272 // calling EmitFuncArgumentDbgValue here. 1273 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, 1274 FuncArgumentDbgValueKind::Value, Val)) { 1275 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1276 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1277 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1278 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1279 // inserted after the definition of Val when emitting the instructions 1280 // after ISel. An alternative could be to teach 1281 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1282 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1283 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1284 << ValSDNodeOrder << "\n"); 1285 SDV = getDbgValue(Val, Variable, Expr, dl, 1286 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1287 DAG.AddDbgValue(SDV, false); 1288 } else 1289 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1290 << "in EmitFuncArgumentDbgValue\n"); 1291 } else { 1292 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1293 auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType()); 1294 auto SDV = 1295 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); 1296 DAG.AddDbgValue(SDV, false); 1297 } 1298 } 1299 DDIV.clear(); 1300 } 1301 1302 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1303 // TODO: For the variadic implementation, instead of only checking the fail 1304 // state of `handleDebugValue`, we need know specifically which values were 1305 // invalid, so that we attempt to salvage only those values when processing 1306 // a DIArgList. 1307 assert(!DDI.getDI()->hasArgList() && 1308 "Not implemented for variadic dbg_values"); 1309 Value *V = DDI.getDI()->getValue(0); 1310 DILocalVariable *Var = DDI.getDI()->getVariable(); 1311 DIExpression *Expr = DDI.getDI()->getExpression(); 1312 DebugLoc DL = DDI.getdl(); 1313 DebugLoc InstDL = DDI.getDI()->getDebugLoc(); 1314 unsigned SDOrder = DDI.getSDNodeOrder(); 1315 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1316 // that DW_OP_stack_value is desired. 1317 assert(isa<DbgValueInst>(DDI.getDI())); 1318 bool StackValue = true; 1319 1320 // Can this Value can be encoded without any further work? 1321 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, /*IsVariadic=*/false)) 1322 return; 1323 1324 // Attempt to salvage back through as many instructions as possible. Bail if 1325 // a non-instruction is seen, such as a constant expression or global 1326 // variable. FIXME: Further work could recover those too. 1327 while (isa<Instruction>(V)) { 1328 Instruction &VAsInst = *cast<Instruction>(V); 1329 // Temporary "0", awaiting real implementation. 1330 SmallVector<uint64_t, 16> Ops; 1331 SmallVector<Value *, 4> AdditionalValues; 1332 V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops, 1333 AdditionalValues); 1334 // If we cannot salvage any further, and haven't yet found a suitable debug 1335 // expression, bail out. 1336 if (!V) 1337 break; 1338 1339 // TODO: If AdditionalValues isn't empty, then the salvage can only be 1340 // represented with a DBG_VALUE_LIST, so we give up. When we have support 1341 // here for variadic dbg_values, remove that condition. 1342 if (!AdditionalValues.empty()) 1343 break; 1344 1345 // New value and expr now represent this debuginfo. 1346 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue); 1347 1348 // Some kind of simplification occurred: check whether the operand of the 1349 // salvaged debug expression can be encoded in this DAG. 1350 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, 1351 /*IsVariadic=*/false)) { 1352 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n " 1353 << *DDI.getDI() << "\nBy stripping back to:\n " << *V); 1354 return; 1355 } 1356 } 1357 1358 // This was the final opportunity to salvage this debug information, and it 1359 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1360 // any earlier variable location. 1361 auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType()); 1362 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1363 DAG.AddDbgValue(SDV, false); 1364 1365 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << *DDI.getDI() 1366 << "\n"); 1367 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0) 1368 << "\n"); 1369 } 1370 1371 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1372 DILocalVariable *Var, 1373 DIExpression *Expr, DebugLoc dl, 1374 DebugLoc InstDL, unsigned Order, 1375 bool IsVariadic) { 1376 if (Values.empty()) 1377 return true; 1378 SmallVector<SDDbgOperand> LocationOps; 1379 SmallVector<SDNode *> Dependencies; 1380 for (const Value *V : Values) { 1381 // Constant value. 1382 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1383 isa<ConstantPointerNull>(V)) { 1384 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1385 continue; 1386 } 1387 1388 // Look through IntToPtr constants. 1389 if (auto *CE = dyn_cast<ConstantExpr>(V)) 1390 if (CE->getOpcode() == Instruction::IntToPtr) { 1391 LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0))); 1392 continue; 1393 } 1394 1395 // If the Value is a frame index, we can create a FrameIndex debug value 1396 // without relying on the DAG at all. 1397 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1398 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1399 if (SI != FuncInfo.StaticAllocaMap.end()) { 1400 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1401 continue; 1402 } 1403 } 1404 1405 // Do not use getValue() in here; we don't want to generate code at 1406 // this point if it hasn't been done yet. 1407 SDValue N = NodeMap[V]; 1408 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1409 N = UnusedArgNodeMap[V]; 1410 if (N.getNode()) { 1411 // Only emit func arg dbg value for non-variadic dbg.values for now. 1412 if (!IsVariadic && 1413 EmitFuncArgumentDbgValue(V, Var, Expr, dl, 1414 FuncArgumentDbgValueKind::Value, N)) 1415 return true; 1416 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1417 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1418 // describe stack slot locations. 1419 // 1420 // Consider "int x = 0; int *px = &x;". There are two kinds of 1421 // interesting debug values here after optimization: 1422 // 1423 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1424 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1425 // 1426 // Both describe the direct values of their associated variables. 1427 Dependencies.push_back(N.getNode()); 1428 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1429 continue; 1430 } 1431 LocationOps.emplace_back( 1432 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1433 continue; 1434 } 1435 1436 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1437 // Special rules apply for the first dbg.values of parameter variables in a 1438 // function. Identify them by the fact they reference Argument Values, that 1439 // they're parameters, and they are parameters of the current function. We 1440 // need to let them dangle until they get an SDNode. 1441 bool IsParamOfFunc = 1442 isa<Argument>(V) && Var->isParameter() && !InstDL.getInlinedAt(); 1443 if (IsParamOfFunc) 1444 return false; 1445 1446 // The value is not used in this block yet (or it would have an SDNode). 1447 // We still want the value to appear for the user if possible -- if it has 1448 // an associated VReg, we can refer to that instead. 1449 auto VMI = FuncInfo.ValueMap.find(V); 1450 if (VMI != FuncInfo.ValueMap.end()) { 1451 unsigned Reg = VMI->second; 1452 // If this is a PHI node, it may be split up into several MI PHI nodes 1453 // (in FunctionLoweringInfo::set). 1454 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1455 V->getType(), None); 1456 if (RFV.occupiesMultipleRegs()) { 1457 // FIXME: We could potentially support variadic dbg_values here. 1458 if (IsVariadic) 1459 return false; 1460 unsigned Offset = 0; 1461 unsigned BitsToDescribe = 0; 1462 if (auto VarSize = Var->getSizeInBits()) 1463 BitsToDescribe = *VarSize; 1464 if (auto Fragment = Expr->getFragmentInfo()) 1465 BitsToDescribe = Fragment->SizeInBits; 1466 for (const auto &RegAndSize : RFV.getRegsAndSizes()) { 1467 // Bail out if all bits are described already. 1468 if (Offset >= BitsToDescribe) 1469 break; 1470 // TODO: handle scalable vectors. 1471 unsigned RegisterSize = RegAndSize.second; 1472 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1473 ? BitsToDescribe - Offset 1474 : RegisterSize; 1475 auto FragmentExpr = DIExpression::createFragmentExpression( 1476 Expr, Offset, FragmentSize); 1477 if (!FragmentExpr) 1478 continue; 1479 SDDbgValue *SDV = DAG.getVRegDbgValue( 1480 Var, *FragmentExpr, RegAndSize.first, false, dl, SDNodeOrder); 1481 DAG.AddDbgValue(SDV, false); 1482 Offset += RegisterSize; 1483 } 1484 return true; 1485 } 1486 // We can use simple vreg locations for variadic dbg_values as well. 1487 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1488 continue; 1489 } 1490 // We failed to create a SDDbgOperand for V. 1491 return false; 1492 } 1493 1494 // We have created a SDDbgOperand for each Value in Values. 1495 // Should use Order instead of SDNodeOrder? 1496 assert(!LocationOps.empty()); 1497 SDDbgValue *SDV = 1498 DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1499 /*IsIndirect=*/false, dl, SDNodeOrder, IsVariadic); 1500 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1501 return true; 1502 } 1503 1504 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1505 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1506 for (auto &Pair : DanglingDebugInfoMap) 1507 for (auto &DDI : Pair.second) 1508 salvageUnresolvedDbgValue(DDI); 1509 clearDanglingDebugInfo(); 1510 } 1511 1512 /// getCopyFromRegs - If there was virtual register allocated for the value V 1513 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1514 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1515 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1516 SDValue Result; 1517 1518 if (It != FuncInfo.ValueMap.end()) { 1519 Register InReg = It->second; 1520 1521 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1522 DAG.getDataLayout(), InReg, Ty, 1523 None); // This is not an ABI copy. 1524 SDValue Chain = DAG.getEntryNode(); 1525 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1526 V); 1527 resolveDanglingDebugInfo(V, Result); 1528 } 1529 1530 return Result; 1531 } 1532 1533 /// getValue - Return an SDValue for the given Value. 1534 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1535 // If we already have an SDValue for this value, use it. It's important 1536 // to do this first, so that we don't create a CopyFromReg if we already 1537 // have a regular SDValue. 1538 SDValue &N = NodeMap[V]; 1539 if (N.getNode()) return N; 1540 1541 // If there's a virtual register allocated and initialized for this 1542 // value, use it. 1543 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1544 return copyFromReg; 1545 1546 // Otherwise create a new SDValue and remember it. 1547 SDValue Val = getValueImpl(V); 1548 NodeMap[V] = Val; 1549 resolveDanglingDebugInfo(V, Val); 1550 return Val; 1551 } 1552 1553 /// getNonRegisterValue - Return an SDValue for the given Value, but 1554 /// don't look in FuncInfo.ValueMap for a virtual register. 1555 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1556 // If we already have an SDValue for this value, use it. 1557 SDValue &N = NodeMap[V]; 1558 if (N.getNode()) { 1559 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1560 // Remove the debug location from the node as the node is about to be used 1561 // in a location which may differ from the original debug location. This 1562 // is relevant to Constant and ConstantFP nodes because they can appear 1563 // as constant expressions inside PHI nodes. 1564 N->setDebugLoc(DebugLoc()); 1565 } 1566 return N; 1567 } 1568 1569 // Otherwise create a new SDValue and remember it. 1570 SDValue Val = getValueImpl(V); 1571 NodeMap[V] = Val; 1572 resolveDanglingDebugInfo(V, Val); 1573 return Val; 1574 } 1575 1576 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1577 /// Create an SDValue for the given value. 1578 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1579 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1580 1581 if (const Constant *C = dyn_cast<Constant>(V)) { 1582 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1583 1584 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1585 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1586 1587 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1588 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1589 1590 if (isa<ConstantPointerNull>(C)) { 1591 unsigned AS = V->getType()->getPointerAddressSpace(); 1592 return DAG.getConstant(0, getCurSDLoc(), 1593 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1594 } 1595 1596 if (match(C, m_VScale(DAG.getDataLayout()))) 1597 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1598 1599 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1600 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1601 1602 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1603 return DAG.getUNDEF(VT); 1604 1605 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1606 visit(CE->getOpcode(), *CE); 1607 SDValue N1 = NodeMap[V]; 1608 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1609 return N1; 1610 } 1611 1612 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1613 SmallVector<SDValue, 4> Constants; 1614 for (const Use &U : C->operands()) { 1615 SDNode *Val = getValue(U).getNode(); 1616 // If the operand is an empty aggregate, there are no values. 1617 if (!Val) continue; 1618 // Add each leaf value from the operand to the Constants list 1619 // to form a flattened list of all the values. 1620 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1621 Constants.push_back(SDValue(Val, i)); 1622 } 1623 1624 return DAG.getMergeValues(Constants, getCurSDLoc()); 1625 } 1626 1627 if (const ConstantDataSequential *CDS = 1628 dyn_cast<ConstantDataSequential>(C)) { 1629 SmallVector<SDValue, 4> Ops; 1630 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1631 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1632 // Add each leaf value from the operand to the Constants list 1633 // to form a flattened list of all the values. 1634 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1635 Ops.push_back(SDValue(Val, i)); 1636 } 1637 1638 if (isa<ArrayType>(CDS->getType())) 1639 return DAG.getMergeValues(Ops, getCurSDLoc()); 1640 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1641 } 1642 1643 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1644 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1645 "Unknown struct or array constant!"); 1646 1647 SmallVector<EVT, 4> ValueVTs; 1648 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1649 unsigned NumElts = ValueVTs.size(); 1650 if (NumElts == 0) 1651 return SDValue(); // empty struct 1652 SmallVector<SDValue, 4> Constants(NumElts); 1653 for (unsigned i = 0; i != NumElts; ++i) { 1654 EVT EltVT = ValueVTs[i]; 1655 if (isa<UndefValue>(C)) 1656 Constants[i] = DAG.getUNDEF(EltVT); 1657 else if (EltVT.isFloatingPoint()) 1658 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1659 else 1660 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1661 } 1662 1663 return DAG.getMergeValues(Constants, getCurSDLoc()); 1664 } 1665 1666 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1667 return DAG.getBlockAddress(BA, VT); 1668 1669 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1670 return getValue(Equiv->getGlobalValue()); 1671 1672 if (const auto *NC = dyn_cast<NoCFIValue>(C)) 1673 return getValue(NC->getGlobalValue()); 1674 1675 VectorType *VecTy = cast<VectorType>(V->getType()); 1676 1677 // Now that we know the number and type of the elements, get that number of 1678 // elements into the Ops array based on what kind of constant it is. 1679 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1680 SmallVector<SDValue, 16> Ops; 1681 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1682 for (unsigned i = 0; i != NumElements; ++i) 1683 Ops.push_back(getValue(CV->getOperand(i))); 1684 1685 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1686 } 1687 1688 if (isa<ConstantAggregateZero>(C)) { 1689 EVT EltVT = 1690 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1691 1692 SDValue Op; 1693 if (EltVT.isFloatingPoint()) 1694 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1695 else 1696 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1697 1698 if (isa<ScalableVectorType>(VecTy)) 1699 return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op); 1700 1701 SmallVector<SDValue, 16> Ops; 1702 Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op); 1703 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1704 } 1705 1706 llvm_unreachable("Unknown vector constant"); 1707 } 1708 1709 // If this is a static alloca, generate it as the frameindex instead of 1710 // computation. 1711 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1712 DenseMap<const AllocaInst*, int>::iterator SI = 1713 FuncInfo.StaticAllocaMap.find(AI); 1714 if (SI != FuncInfo.StaticAllocaMap.end()) 1715 return DAG.getFrameIndex(SI->second, 1716 TLI.getFrameIndexTy(DAG.getDataLayout())); 1717 } 1718 1719 // If this is an instruction which fast-isel has deferred, select it now. 1720 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1721 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1722 1723 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1724 Inst->getType(), None); 1725 SDValue Chain = DAG.getEntryNode(); 1726 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1727 } 1728 1729 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) 1730 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1731 1732 if (const auto *BB = dyn_cast<BasicBlock>(V)) 1733 return DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 1734 1735 llvm_unreachable("Can't get register for value!"); 1736 } 1737 1738 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1739 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1740 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1741 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1742 bool IsSEH = isAsynchronousEHPersonality(Pers); 1743 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1744 if (!IsSEH) 1745 CatchPadMBB->setIsEHScopeEntry(); 1746 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1747 if (IsMSVCCXX || IsCoreCLR) 1748 CatchPadMBB->setIsEHFuncletEntry(); 1749 } 1750 1751 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1752 // Update machine-CFG edge. 1753 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1754 FuncInfo.MBB->addSuccessor(TargetMBB); 1755 TargetMBB->setIsEHCatchretTarget(true); 1756 DAG.getMachineFunction().setHasEHCatchret(true); 1757 1758 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1759 bool IsSEH = isAsynchronousEHPersonality(Pers); 1760 if (IsSEH) { 1761 // If this is not a fall-through branch or optimizations are switched off, 1762 // emit the branch. 1763 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1764 TM.getOptLevel() == CodeGenOpt::None) 1765 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1766 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1767 return; 1768 } 1769 1770 // Figure out the funclet membership for the catchret's successor. 1771 // This will be used by the FuncletLayout pass to determine how to order the 1772 // BB's. 1773 // A 'catchret' returns to the outer scope's color. 1774 Value *ParentPad = I.getCatchSwitchParentPad(); 1775 const BasicBlock *SuccessorColor; 1776 if (isa<ConstantTokenNone>(ParentPad)) 1777 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1778 else 1779 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1780 assert(SuccessorColor && "No parent funclet for catchret!"); 1781 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1782 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1783 1784 // Create the terminator node. 1785 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1786 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1787 DAG.getBasicBlock(SuccessorColorMBB)); 1788 DAG.setRoot(Ret); 1789 } 1790 1791 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1792 // Don't emit any special code for the cleanuppad instruction. It just marks 1793 // the start of an EH scope/funclet. 1794 FuncInfo.MBB->setIsEHScopeEntry(); 1795 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1796 if (Pers != EHPersonality::Wasm_CXX) { 1797 FuncInfo.MBB->setIsEHFuncletEntry(); 1798 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1799 } 1800 } 1801 1802 // In wasm EH, even though a catchpad may not catch an exception if a tag does 1803 // not match, it is OK to add only the first unwind destination catchpad to the 1804 // successors, because there will be at least one invoke instruction within the 1805 // catch scope that points to the next unwind destination, if one exists, so 1806 // CFGSort cannot mess up with BB sorting order. 1807 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 1808 // call within them, and catchpads only consisting of 'catch (...)' have a 1809 // '__cxa_end_catch' call within them, both of which generate invokes in case 1810 // the next unwind destination exists, i.e., the next unwind destination is not 1811 // the caller.) 1812 // 1813 // Having at most one EH pad successor is also simpler and helps later 1814 // transformations. 1815 // 1816 // For example, 1817 // current: 1818 // invoke void @foo to ... unwind label %catch.dispatch 1819 // catch.dispatch: 1820 // %0 = catchswitch within ... [label %catch.start] unwind label %next 1821 // catch.start: 1822 // ... 1823 // ... in this BB or some other child BB dominated by this BB there will be an 1824 // invoke that points to 'next' BB as an unwind destination 1825 // 1826 // next: ; We don't need to add this to 'current' BB's successor 1827 // ... 1828 static void findWasmUnwindDestinations( 1829 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1830 BranchProbability Prob, 1831 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1832 &UnwindDests) { 1833 while (EHPadBB) { 1834 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1835 if (isa<CleanupPadInst>(Pad)) { 1836 // Stop on cleanup pads. 1837 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1838 UnwindDests.back().first->setIsEHScopeEntry(); 1839 break; 1840 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1841 // Add the catchpad handlers to the possible destinations. We don't 1842 // continue to the unwind destination of the catchswitch for wasm. 1843 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1844 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1845 UnwindDests.back().first->setIsEHScopeEntry(); 1846 } 1847 break; 1848 } else { 1849 continue; 1850 } 1851 } 1852 } 1853 1854 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1855 /// many places it could ultimately go. In the IR, we have a single unwind 1856 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1857 /// This function skips over imaginary basic blocks that hold catchswitch 1858 /// instructions, and finds all the "real" machine 1859 /// basic block destinations. As those destinations may not be successors of 1860 /// EHPadBB, here we also calculate the edge probability to those destinations. 1861 /// The passed-in Prob is the edge probability to EHPadBB. 1862 static void findUnwindDestinations( 1863 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1864 BranchProbability Prob, 1865 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1866 &UnwindDests) { 1867 EHPersonality Personality = 1868 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1869 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1870 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1871 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1872 bool IsSEH = isAsynchronousEHPersonality(Personality); 1873 1874 if (IsWasmCXX) { 1875 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1876 assert(UnwindDests.size() <= 1 && 1877 "There should be at most one unwind destination for wasm"); 1878 return; 1879 } 1880 1881 while (EHPadBB) { 1882 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1883 BasicBlock *NewEHPadBB = nullptr; 1884 if (isa<LandingPadInst>(Pad)) { 1885 // Stop on landingpads. They are not funclets. 1886 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1887 break; 1888 } else if (isa<CleanupPadInst>(Pad)) { 1889 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1890 // personalities. 1891 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1892 UnwindDests.back().first->setIsEHScopeEntry(); 1893 UnwindDests.back().first->setIsEHFuncletEntry(); 1894 break; 1895 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1896 // Add the catchpad handlers to the possible destinations. 1897 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1898 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1899 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1900 if (IsMSVCCXX || IsCoreCLR) 1901 UnwindDests.back().first->setIsEHFuncletEntry(); 1902 if (!IsSEH) 1903 UnwindDests.back().first->setIsEHScopeEntry(); 1904 } 1905 NewEHPadBB = CatchSwitch->getUnwindDest(); 1906 } else { 1907 continue; 1908 } 1909 1910 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1911 if (BPI && NewEHPadBB) 1912 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1913 EHPadBB = NewEHPadBB; 1914 } 1915 } 1916 1917 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1918 // Update successor info. 1919 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1920 auto UnwindDest = I.getUnwindDest(); 1921 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1922 BranchProbability UnwindDestProb = 1923 (BPI && UnwindDest) 1924 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1925 : BranchProbability::getZero(); 1926 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1927 for (auto &UnwindDest : UnwindDests) { 1928 UnwindDest.first->setIsEHPad(); 1929 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1930 } 1931 FuncInfo.MBB->normalizeSuccProbs(); 1932 1933 // Create the terminator node. 1934 SDValue Ret = 1935 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1936 DAG.setRoot(Ret); 1937 } 1938 1939 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1940 report_fatal_error("visitCatchSwitch not yet implemented!"); 1941 } 1942 1943 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1944 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1945 auto &DL = DAG.getDataLayout(); 1946 SDValue Chain = getControlRoot(); 1947 SmallVector<ISD::OutputArg, 8> Outs; 1948 SmallVector<SDValue, 8> OutVals; 1949 1950 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1951 // lower 1952 // 1953 // %val = call <ty> @llvm.experimental.deoptimize() 1954 // ret <ty> %val 1955 // 1956 // differently. 1957 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1958 LowerDeoptimizingReturn(); 1959 return; 1960 } 1961 1962 if (!FuncInfo.CanLowerReturn) { 1963 unsigned DemoteReg = FuncInfo.DemoteRegister; 1964 const Function *F = I.getParent()->getParent(); 1965 1966 // Emit a store of the return value through the virtual register. 1967 // Leave Outs empty so that LowerReturn won't try to load return 1968 // registers the usual way. 1969 SmallVector<EVT, 1> PtrValueVTs; 1970 ComputeValueVTs(TLI, DL, 1971 F->getReturnType()->getPointerTo( 1972 DAG.getDataLayout().getAllocaAddrSpace()), 1973 PtrValueVTs); 1974 1975 SDValue RetPtr = 1976 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]); 1977 SDValue RetOp = getValue(I.getOperand(0)); 1978 1979 SmallVector<EVT, 4> ValueVTs, MemVTs; 1980 SmallVector<uint64_t, 4> Offsets; 1981 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1982 &Offsets); 1983 unsigned NumValues = ValueVTs.size(); 1984 1985 SmallVector<SDValue, 4> Chains(NumValues); 1986 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 1987 for (unsigned i = 0; i != NumValues; ++i) { 1988 // An aggregate return value cannot wrap around the address space, so 1989 // offsets to its parts don't wrap either. 1990 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 1991 TypeSize::Fixed(Offsets[i])); 1992 1993 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 1994 if (MemVTs[i] != ValueVTs[i]) 1995 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 1996 Chains[i] = DAG.getStore( 1997 Chain, getCurSDLoc(), Val, 1998 // FIXME: better loc info would be nice. 1999 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 2000 commonAlignment(BaseAlign, Offsets[i])); 2001 } 2002 2003 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 2004 MVT::Other, Chains); 2005 } else if (I.getNumOperands() != 0) { 2006 SmallVector<EVT, 4> ValueVTs; 2007 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 2008 unsigned NumValues = ValueVTs.size(); 2009 if (NumValues) { 2010 SDValue RetOp = getValue(I.getOperand(0)); 2011 2012 const Function *F = I.getParent()->getParent(); 2013 2014 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 2015 I.getOperand(0)->getType(), F->getCallingConv(), 2016 /*IsVarArg*/ false, DL); 2017 2018 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 2019 if (F->getAttributes().hasRetAttr(Attribute::SExt)) 2020 ExtendKind = ISD::SIGN_EXTEND; 2021 else if (F->getAttributes().hasRetAttr(Attribute::ZExt)) 2022 ExtendKind = ISD::ZERO_EXTEND; 2023 2024 LLVMContext &Context = F->getContext(); 2025 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg); 2026 2027 for (unsigned j = 0; j != NumValues; ++j) { 2028 EVT VT = ValueVTs[j]; 2029 2030 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 2031 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 2032 2033 CallingConv::ID CC = F->getCallingConv(); 2034 2035 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 2036 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 2037 SmallVector<SDValue, 4> Parts(NumParts); 2038 getCopyToParts(DAG, getCurSDLoc(), 2039 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 2040 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 2041 2042 // 'inreg' on function refers to return value 2043 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2044 if (RetInReg) 2045 Flags.setInReg(); 2046 2047 if (I.getOperand(0)->getType()->isPointerTy()) { 2048 Flags.setPointer(); 2049 Flags.setPointerAddrSpace( 2050 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 2051 } 2052 2053 if (NeedsRegBlock) { 2054 Flags.setInConsecutiveRegs(); 2055 if (j == NumValues - 1) 2056 Flags.setInConsecutiveRegsLast(); 2057 } 2058 2059 // Propagate extension type if any 2060 if (ExtendKind == ISD::SIGN_EXTEND) 2061 Flags.setSExt(); 2062 else if (ExtendKind == ISD::ZERO_EXTEND) 2063 Flags.setZExt(); 2064 2065 for (unsigned i = 0; i < NumParts; ++i) { 2066 Outs.push_back(ISD::OutputArg(Flags, 2067 Parts[i].getValueType().getSimpleVT(), 2068 VT, /*isfixed=*/true, 0, 0)); 2069 OutVals.push_back(Parts[i]); 2070 } 2071 } 2072 } 2073 } 2074 2075 // Push in swifterror virtual register as the last element of Outs. This makes 2076 // sure swifterror virtual register will be returned in the swifterror 2077 // physical register. 2078 const Function *F = I.getParent()->getParent(); 2079 if (TLI.supportSwiftError() && 2080 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2081 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2082 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2083 Flags.setSwiftError(); 2084 Outs.push_back(ISD::OutputArg( 2085 Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)), 2086 /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0)); 2087 // Create SDNode for the swifterror virtual register. 2088 OutVals.push_back( 2089 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2090 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2091 EVT(TLI.getPointerTy(DL)))); 2092 } 2093 2094 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2095 CallingConv::ID CallConv = 2096 DAG.getMachineFunction().getFunction().getCallingConv(); 2097 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2098 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2099 2100 // Verify that the target's LowerReturn behaved as expected. 2101 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2102 "LowerReturn didn't return a valid chain!"); 2103 2104 // Update the DAG with the new chain value resulting from return lowering. 2105 DAG.setRoot(Chain); 2106 } 2107 2108 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2109 /// created for it, emit nodes to copy the value into the virtual 2110 /// registers. 2111 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2112 // Skip empty types 2113 if (V->getType()->isEmptyTy()) 2114 return; 2115 2116 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2117 if (VMI != FuncInfo.ValueMap.end()) { 2118 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 2119 CopyValueToVirtualRegister(V, VMI->second); 2120 } 2121 } 2122 2123 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2124 /// the current basic block, add it to ValueMap now so that we'll get a 2125 /// CopyTo/FromReg. 2126 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2127 // No need to export constants. 2128 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2129 2130 // Already exported? 2131 if (FuncInfo.isExportedInst(V)) return; 2132 2133 unsigned Reg = FuncInfo.InitializeRegForValue(V); 2134 CopyValueToVirtualRegister(V, Reg); 2135 } 2136 2137 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2138 const BasicBlock *FromBB) { 2139 // The operands of the setcc have to be in this block. We don't know 2140 // how to export them from some other block. 2141 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2142 // Can export from current BB. 2143 if (VI->getParent() == FromBB) 2144 return true; 2145 2146 // Is already exported, noop. 2147 return FuncInfo.isExportedInst(V); 2148 } 2149 2150 // If this is an argument, we can export it if the BB is the entry block or 2151 // if it is already exported. 2152 if (isa<Argument>(V)) { 2153 if (FromBB->isEntryBlock()) 2154 return true; 2155 2156 // Otherwise, can only export this if it is already exported. 2157 return FuncInfo.isExportedInst(V); 2158 } 2159 2160 // Otherwise, constants can always be exported. 2161 return true; 2162 } 2163 2164 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2165 BranchProbability 2166 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2167 const MachineBasicBlock *Dst) const { 2168 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2169 const BasicBlock *SrcBB = Src->getBasicBlock(); 2170 const BasicBlock *DstBB = Dst->getBasicBlock(); 2171 if (!BPI) { 2172 // If BPI is not available, set the default probability as 1 / N, where N is 2173 // the number of successors. 2174 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2175 return BranchProbability(1, SuccSize); 2176 } 2177 return BPI->getEdgeProbability(SrcBB, DstBB); 2178 } 2179 2180 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2181 MachineBasicBlock *Dst, 2182 BranchProbability Prob) { 2183 if (!FuncInfo.BPI) 2184 Src->addSuccessorWithoutProb(Dst); 2185 else { 2186 if (Prob.isUnknown()) 2187 Prob = getEdgeProbability(Src, Dst); 2188 Src->addSuccessor(Dst, Prob); 2189 } 2190 } 2191 2192 static bool InBlock(const Value *V, const BasicBlock *BB) { 2193 if (const Instruction *I = dyn_cast<Instruction>(V)) 2194 return I->getParent() == BB; 2195 return true; 2196 } 2197 2198 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2199 /// This function emits a branch and is used at the leaves of an OR or an 2200 /// AND operator tree. 2201 void 2202 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2203 MachineBasicBlock *TBB, 2204 MachineBasicBlock *FBB, 2205 MachineBasicBlock *CurBB, 2206 MachineBasicBlock *SwitchBB, 2207 BranchProbability TProb, 2208 BranchProbability FProb, 2209 bool InvertCond) { 2210 const BasicBlock *BB = CurBB->getBasicBlock(); 2211 2212 // If the leaf of the tree is a comparison, merge the condition into 2213 // the caseblock. 2214 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2215 // The operands of the cmp have to be in this block. We don't know 2216 // how to export them from some other block. If this is the first block 2217 // of the sequence, no exporting is needed. 2218 if (CurBB == SwitchBB || 2219 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2220 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2221 ISD::CondCode Condition; 2222 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2223 ICmpInst::Predicate Pred = 2224 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2225 Condition = getICmpCondCode(Pred); 2226 } else { 2227 const FCmpInst *FC = cast<FCmpInst>(Cond); 2228 FCmpInst::Predicate Pred = 2229 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2230 Condition = getFCmpCondCode(Pred); 2231 if (TM.Options.NoNaNsFPMath) 2232 Condition = getFCmpCodeWithoutNaN(Condition); 2233 } 2234 2235 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2236 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2237 SL->SwitchCases.push_back(CB); 2238 return; 2239 } 2240 } 2241 2242 // Create a CaseBlock record representing this branch. 2243 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2244 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2245 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2246 SL->SwitchCases.push_back(CB); 2247 } 2248 2249 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2250 MachineBasicBlock *TBB, 2251 MachineBasicBlock *FBB, 2252 MachineBasicBlock *CurBB, 2253 MachineBasicBlock *SwitchBB, 2254 Instruction::BinaryOps Opc, 2255 BranchProbability TProb, 2256 BranchProbability FProb, 2257 bool InvertCond) { 2258 // Skip over not part of the tree and remember to invert op and operands at 2259 // next level. 2260 Value *NotCond; 2261 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2262 InBlock(NotCond, CurBB->getBasicBlock())) { 2263 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2264 !InvertCond); 2265 return; 2266 } 2267 2268 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2269 const Value *BOpOp0, *BOpOp1; 2270 // Compute the effective opcode for Cond, taking into account whether it needs 2271 // to be inverted, e.g. 2272 // and (not (or A, B)), C 2273 // gets lowered as 2274 // and (and (not A, not B), C) 2275 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2276 if (BOp) { 2277 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2278 ? Instruction::And 2279 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2280 ? Instruction::Or 2281 : (Instruction::BinaryOps)0); 2282 if (InvertCond) { 2283 if (BOpc == Instruction::And) 2284 BOpc = Instruction::Or; 2285 else if (BOpc == Instruction::Or) 2286 BOpc = Instruction::And; 2287 } 2288 } 2289 2290 // If this node is not part of the or/and tree, emit it as a branch. 2291 // Note that all nodes in the tree should have same opcode. 2292 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2293 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2294 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2295 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2296 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2297 TProb, FProb, InvertCond); 2298 return; 2299 } 2300 2301 // Create TmpBB after CurBB. 2302 MachineFunction::iterator BBI(CurBB); 2303 MachineFunction &MF = DAG.getMachineFunction(); 2304 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2305 CurBB->getParent()->insert(++BBI, TmpBB); 2306 2307 if (Opc == Instruction::Or) { 2308 // Codegen X | Y as: 2309 // BB1: 2310 // jmp_if_X TBB 2311 // jmp TmpBB 2312 // TmpBB: 2313 // jmp_if_Y TBB 2314 // jmp FBB 2315 // 2316 2317 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2318 // The requirement is that 2319 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2320 // = TrueProb for original BB. 2321 // Assuming the original probabilities are A and B, one choice is to set 2322 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2323 // A/(1+B) and 2B/(1+B). This choice assumes that 2324 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2325 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2326 // TmpBB, but the math is more complicated. 2327 2328 auto NewTrueProb = TProb / 2; 2329 auto NewFalseProb = TProb / 2 + FProb; 2330 // Emit the LHS condition. 2331 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2332 NewFalseProb, InvertCond); 2333 2334 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2335 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2336 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2337 // Emit the RHS condition into TmpBB. 2338 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2339 Probs[1], InvertCond); 2340 } else { 2341 assert(Opc == Instruction::And && "Unknown merge op!"); 2342 // Codegen X & Y as: 2343 // BB1: 2344 // jmp_if_X TmpBB 2345 // jmp FBB 2346 // TmpBB: 2347 // jmp_if_Y TBB 2348 // jmp FBB 2349 // 2350 // This requires creation of TmpBB after CurBB. 2351 2352 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2353 // The requirement is that 2354 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2355 // = FalseProb for original BB. 2356 // Assuming the original probabilities are A and B, one choice is to set 2357 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2358 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2359 // TrueProb for BB1 * FalseProb for TmpBB. 2360 2361 auto NewTrueProb = TProb + FProb / 2; 2362 auto NewFalseProb = FProb / 2; 2363 // Emit the LHS condition. 2364 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2365 NewFalseProb, InvertCond); 2366 2367 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2368 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2369 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2370 // Emit the RHS condition into TmpBB. 2371 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2372 Probs[1], InvertCond); 2373 } 2374 } 2375 2376 /// If the set of cases should be emitted as a series of branches, return true. 2377 /// If we should emit this as a bunch of and/or'd together conditions, return 2378 /// false. 2379 bool 2380 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2381 if (Cases.size() != 2) return true; 2382 2383 // If this is two comparisons of the same values or'd or and'd together, they 2384 // will get folded into a single comparison, so don't emit two blocks. 2385 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2386 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2387 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2388 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2389 return false; 2390 } 2391 2392 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2393 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2394 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2395 Cases[0].CC == Cases[1].CC && 2396 isa<Constant>(Cases[0].CmpRHS) && 2397 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2398 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2399 return false; 2400 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2401 return false; 2402 } 2403 2404 return true; 2405 } 2406 2407 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2408 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2409 2410 // Update machine-CFG edges. 2411 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2412 2413 if (I.isUnconditional()) { 2414 // Update machine-CFG edges. 2415 BrMBB->addSuccessor(Succ0MBB); 2416 2417 // If this is not a fall-through branch or optimizations are switched off, 2418 // emit the branch. 2419 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2420 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2421 MVT::Other, getControlRoot(), 2422 DAG.getBasicBlock(Succ0MBB))); 2423 2424 return; 2425 } 2426 2427 // If this condition is one of the special cases we handle, do special stuff 2428 // now. 2429 const Value *CondVal = I.getCondition(); 2430 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2431 2432 // If this is a series of conditions that are or'd or and'd together, emit 2433 // this as a sequence of branches instead of setcc's with and/or operations. 2434 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2435 // unpredictable branches, and vector extracts because those jumps are likely 2436 // expensive for any target), this should improve performance. 2437 // For example, instead of something like: 2438 // cmp A, B 2439 // C = seteq 2440 // cmp D, E 2441 // F = setle 2442 // or C, F 2443 // jnz foo 2444 // Emit: 2445 // cmp A, B 2446 // je foo 2447 // cmp D, E 2448 // jle foo 2449 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2450 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2451 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2452 Value *Vec; 2453 const Value *BOp0, *BOp1; 2454 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2455 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2456 Opcode = Instruction::And; 2457 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2458 Opcode = Instruction::Or; 2459 2460 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2461 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2462 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2463 getEdgeProbability(BrMBB, Succ0MBB), 2464 getEdgeProbability(BrMBB, Succ1MBB), 2465 /*InvertCond=*/false); 2466 // If the compares in later blocks need to use values not currently 2467 // exported from this block, export them now. This block should always 2468 // be the first entry. 2469 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2470 2471 // Allow some cases to be rejected. 2472 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2473 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2474 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2475 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2476 } 2477 2478 // Emit the branch for this block. 2479 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2480 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2481 return; 2482 } 2483 2484 // Okay, we decided not to do this, remove any inserted MBB's and clear 2485 // SwitchCases. 2486 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2487 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2488 2489 SL->SwitchCases.clear(); 2490 } 2491 } 2492 2493 // Create a CaseBlock record representing this branch. 2494 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2495 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2496 2497 // Use visitSwitchCase to actually insert the fast branch sequence for this 2498 // cond branch. 2499 visitSwitchCase(CB, BrMBB); 2500 } 2501 2502 /// visitSwitchCase - Emits the necessary code to represent a single node in 2503 /// the binary search tree resulting from lowering a switch instruction. 2504 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2505 MachineBasicBlock *SwitchBB) { 2506 SDValue Cond; 2507 SDValue CondLHS = getValue(CB.CmpLHS); 2508 SDLoc dl = CB.DL; 2509 2510 if (CB.CC == ISD::SETTRUE) { 2511 // Branch or fall through to TrueBB. 2512 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2513 SwitchBB->normalizeSuccProbs(); 2514 if (CB.TrueBB != NextBlock(SwitchBB)) { 2515 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2516 DAG.getBasicBlock(CB.TrueBB))); 2517 } 2518 return; 2519 } 2520 2521 auto &TLI = DAG.getTargetLoweringInfo(); 2522 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2523 2524 // Build the setcc now. 2525 if (!CB.CmpMHS) { 2526 // Fold "(X == true)" to X and "(X == false)" to !X to 2527 // handle common cases produced by branch lowering. 2528 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2529 CB.CC == ISD::SETEQ) 2530 Cond = CondLHS; 2531 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2532 CB.CC == ISD::SETEQ) { 2533 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2534 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2535 } else { 2536 SDValue CondRHS = getValue(CB.CmpRHS); 2537 2538 // If a pointer's DAG type is larger than its memory type then the DAG 2539 // values are zero-extended. This breaks signed comparisons so truncate 2540 // back to the underlying type before doing the compare. 2541 if (CondLHS.getValueType() != MemVT) { 2542 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2543 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2544 } 2545 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2546 } 2547 } else { 2548 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2549 2550 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2551 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2552 2553 SDValue CmpOp = getValue(CB.CmpMHS); 2554 EVT VT = CmpOp.getValueType(); 2555 2556 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2557 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2558 ISD::SETLE); 2559 } else { 2560 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2561 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2562 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2563 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2564 } 2565 } 2566 2567 // Update successor info 2568 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2569 // TrueBB and FalseBB are always different unless the incoming IR is 2570 // degenerate. This only happens when running llc on weird IR. 2571 if (CB.TrueBB != CB.FalseBB) 2572 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2573 SwitchBB->normalizeSuccProbs(); 2574 2575 // If the lhs block is the next block, invert the condition so that we can 2576 // fall through to the lhs instead of the rhs block. 2577 if (CB.TrueBB == NextBlock(SwitchBB)) { 2578 std::swap(CB.TrueBB, CB.FalseBB); 2579 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2580 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2581 } 2582 2583 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2584 MVT::Other, getControlRoot(), Cond, 2585 DAG.getBasicBlock(CB.TrueBB)); 2586 2587 setValue(CurInst, BrCond); 2588 2589 // Insert the false branch. Do this even if it's a fall through branch, 2590 // this makes it easier to do DAG optimizations which require inverting 2591 // the branch condition. 2592 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2593 DAG.getBasicBlock(CB.FalseBB)); 2594 2595 DAG.setRoot(BrCond); 2596 } 2597 2598 /// visitJumpTable - Emit JumpTable node in the current MBB 2599 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2600 // Emit the code for the jump table 2601 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2602 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2603 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2604 JT.Reg, PTy); 2605 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2606 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2607 MVT::Other, Index.getValue(1), 2608 Table, Index); 2609 DAG.setRoot(BrJumpTable); 2610 } 2611 2612 /// visitJumpTableHeader - This function emits necessary code to produce index 2613 /// in the JumpTable from switch case. 2614 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2615 JumpTableHeader &JTH, 2616 MachineBasicBlock *SwitchBB) { 2617 SDLoc dl = getCurSDLoc(); 2618 2619 // Subtract the lowest switch case value from the value being switched on. 2620 SDValue SwitchOp = getValue(JTH.SValue); 2621 EVT VT = SwitchOp.getValueType(); 2622 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2623 DAG.getConstant(JTH.First, dl, VT)); 2624 2625 // The SDNode we just created, which holds the value being switched on minus 2626 // the smallest case value, needs to be copied to a virtual register so it 2627 // can be used as an index into the jump table in a subsequent basic block. 2628 // This value may be smaller or larger than the target's pointer type, and 2629 // therefore require extension or truncating. 2630 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2631 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2632 2633 unsigned JumpTableReg = 2634 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2635 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2636 JumpTableReg, SwitchOp); 2637 JT.Reg = JumpTableReg; 2638 2639 if (!JTH.FallthroughUnreachable) { 2640 // Emit the range check for the jump table, and branch to the default block 2641 // for the switch statement if the value being switched on exceeds the 2642 // largest case in the switch. 2643 SDValue CMP = DAG.getSetCC( 2644 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2645 Sub.getValueType()), 2646 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2647 2648 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2649 MVT::Other, CopyTo, CMP, 2650 DAG.getBasicBlock(JT.Default)); 2651 2652 // Avoid emitting unnecessary branches to the next block. 2653 if (JT.MBB != NextBlock(SwitchBB)) 2654 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2655 DAG.getBasicBlock(JT.MBB)); 2656 2657 DAG.setRoot(BrCond); 2658 } else { 2659 // Avoid emitting unnecessary branches to the next block. 2660 if (JT.MBB != NextBlock(SwitchBB)) 2661 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2662 DAG.getBasicBlock(JT.MBB))); 2663 else 2664 DAG.setRoot(CopyTo); 2665 } 2666 } 2667 2668 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2669 /// variable if there exists one. 2670 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2671 SDValue &Chain) { 2672 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2673 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2674 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2675 MachineFunction &MF = DAG.getMachineFunction(); 2676 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2677 MachineSDNode *Node = 2678 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2679 if (Global) { 2680 MachinePointerInfo MPInfo(Global); 2681 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2682 MachineMemOperand::MODereferenceable; 2683 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2684 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2685 DAG.setNodeMemRefs(Node, {MemRef}); 2686 } 2687 if (PtrTy != PtrMemTy) 2688 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2689 return SDValue(Node, 0); 2690 } 2691 2692 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2693 /// tail spliced into a stack protector check success bb. 2694 /// 2695 /// For a high level explanation of how this fits into the stack protector 2696 /// generation see the comment on the declaration of class 2697 /// StackProtectorDescriptor. 2698 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2699 MachineBasicBlock *ParentBB) { 2700 2701 // First create the loads to the guard/stack slot for the comparison. 2702 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2703 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2704 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2705 2706 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2707 int FI = MFI.getStackProtectorIndex(); 2708 2709 SDValue Guard; 2710 SDLoc dl = getCurSDLoc(); 2711 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2712 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2713 Align Align = 2714 DAG.getDataLayout().getPrefTypeAlign(Type::getInt8PtrTy(M.getContext())); 2715 2716 // Generate code to load the content of the guard slot. 2717 SDValue GuardVal = DAG.getLoad( 2718 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2719 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2720 MachineMemOperand::MOVolatile); 2721 2722 if (TLI.useStackGuardXorFP()) 2723 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2724 2725 // Retrieve guard check function, nullptr if instrumentation is inlined. 2726 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2727 // The target provides a guard check function to validate the guard value. 2728 // Generate a call to that function with the content of the guard slot as 2729 // argument. 2730 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2731 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2732 2733 TargetLowering::ArgListTy Args; 2734 TargetLowering::ArgListEntry Entry; 2735 Entry.Node = GuardVal; 2736 Entry.Ty = FnTy->getParamType(0); 2737 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg)) 2738 Entry.IsInReg = true; 2739 Args.push_back(Entry); 2740 2741 TargetLowering::CallLoweringInfo CLI(DAG); 2742 CLI.setDebugLoc(getCurSDLoc()) 2743 .setChain(DAG.getEntryNode()) 2744 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2745 getValue(GuardCheckFn), std::move(Args)); 2746 2747 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2748 DAG.setRoot(Result.second); 2749 return; 2750 } 2751 2752 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2753 // Otherwise, emit a volatile load to retrieve the stack guard value. 2754 SDValue Chain = DAG.getEntryNode(); 2755 if (TLI.useLoadStackGuardNode()) { 2756 Guard = getLoadStackGuard(DAG, dl, Chain); 2757 } else { 2758 const Value *IRGuard = TLI.getSDagStackGuard(M); 2759 SDValue GuardPtr = getValue(IRGuard); 2760 2761 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2762 MachinePointerInfo(IRGuard, 0), Align, 2763 MachineMemOperand::MOVolatile); 2764 } 2765 2766 // Perform the comparison via a getsetcc. 2767 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2768 *DAG.getContext(), 2769 Guard.getValueType()), 2770 Guard, GuardVal, ISD::SETNE); 2771 2772 // If the guard/stackslot do not equal, branch to failure MBB. 2773 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2774 MVT::Other, GuardVal.getOperand(0), 2775 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2776 // Otherwise branch to success MBB. 2777 SDValue Br = DAG.getNode(ISD::BR, dl, 2778 MVT::Other, BrCond, 2779 DAG.getBasicBlock(SPD.getSuccessMBB())); 2780 2781 DAG.setRoot(Br); 2782 } 2783 2784 /// Codegen the failure basic block for a stack protector check. 2785 /// 2786 /// A failure stack protector machine basic block consists simply of a call to 2787 /// __stack_chk_fail(). 2788 /// 2789 /// For a high level explanation of how this fits into the stack protector 2790 /// generation see the comment on the declaration of class 2791 /// StackProtectorDescriptor. 2792 void 2793 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2794 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2795 TargetLowering::MakeLibCallOptions CallOptions; 2796 CallOptions.setDiscardResult(true); 2797 SDValue Chain = 2798 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2799 None, CallOptions, getCurSDLoc()).second; 2800 // On PS4/PS5, the "return address" must still be within the calling 2801 // function, even if it's at the very end, so emit an explicit TRAP here. 2802 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2803 if (TM.getTargetTriple().isPS()) 2804 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2805 // WebAssembly needs an unreachable instruction after a non-returning call, 2806 // because the function return type can be different from __stack_chk_fail's 2807 // return type (void). 2808 if (TM.getTargetTriple().isWasm()) 2809 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2810 2811 DAG.setRoot(Chain); 2812 } 2813 2814 /// visitBitTestHeader - This function emits necessary code to produce value 2815 /// suitable for "bit tests" 2816 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2817 MachineBasicBlock *SwitchBB) { 2818 SDLoc dl = getCurSDLoc(); 2819 2820 // Subtract the minimum value. 2821 SDValue SwitchOp = getValue(B.SValue); 2822 EVT VT = SwitchOp.getValueType(); 2823 SDValue RangeSub = 2824 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2825 2826 // Determine the type of the test operands. 2827 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2828 bool UsePtrType = false; 2829 if (!TLI.isTypeLegal(VT)) { 2830 UsePtrType = true; 2831 } else { 2832 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2833 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2834 // Switch table case range are encoded into series of masks. 2835 // Just use pointer type, it's guaranteed to fit. 2836 UsePtrType = true; 2837 break; 2838 } 2839 } 2840 SDValue Sub = RangeSub; 2841 if (UsePtrType) { 2842 VT = TLI.getPointerTy(DAG.getDataLayout()); 2843 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2844 } 2845 2846 B.RegVT = VT.getSimpleVT(); 2847 B.Reg = FuncInfo.CreateReg(B.RegVT); 2848 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2849 2850 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2851 2852 if (!B.FallthroughUnreachable) 2853 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2854 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2855 SwitchBB->normalizeSuccProbs(); 2856 2857 SDValue Root = CopyTo; 2858 if (!B.FallthroughUnreachable) { 2859 // Conditional branch to the default block. 2860 SDValue RangeCmp = DAG.getSetCC(dl, 2861 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2862 RangeSub.getValueType()), 2863 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2864 ISD::SETUGT); 2865 2866 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2867 DAG.getBasicBlock(B.Default)); 2868 } 2869 2870 // Avoid emitting unnecessary branches to the next block. 2871 if (MBB != NextBlock(SwitchBB)) 2872 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2873 2874 DAG.setRoot(Root); 2875 } 2876 2877 /// visitBitTestCase - this function produces one "bit test" 2878 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2879 MachineBasicBlock* NextMBB, 2880 BranchProbability BranchProbToNext, 2881 unsigned Reg, 2882 BitTestCase &B, 2883 MachineBasicBlock *SwitchBB) { 2884 SDLoc dl = getCurSDLoc(); 2885 MVT VT = BB.RegVT; 2886 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2887 SDValue Cmp; 2888 unsigned PopCount = countPopulation(B.Mask); 2889 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2890 if (PopCount == 1) { 2891 // Testing for a single bit; just compare the shift count with what it 2892 // would need to be to shift a 1 bit in that position. 2893 Cmp = DAG.getSetCC( 2894 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2895 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2896 ISD::SETEQ); 2897 } else if (PopCount == BB.Range) { 2898 // There is only one zero bit in the range, test for it directly. 2899 Cmp = DAG.getSetCC( 2900 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2901 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2902 ISD::SETNE); 2903 } else { 2904 // Make desired shift 2905 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2906 DAG.getConstant(1, dl, VT), ShiftOp); 2907 2908 // Emit bit tests and jumps 2909 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2910 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2911 Cmp = DAG.getSetCC( 2912 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2913 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2914 } 2915 2916 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2917 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2918 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2919 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2920 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2921 // one as they are relative probabilities (and thus work more like weights), 2922 // and hence we need to normalize them to let the sum of them become one. 2923 SwitchBB->normalizeSuccProbs(); 2924 2925 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2926 MVT::Other, getControlRoot(), 2927 Cmp, DAG.getBasicBlock(B.TargetBB)); 2928 2929 // Avoid emitting unnecessary branches to the next block. 2930 if (NextMBB != NextBlock(SwitchBB)) 2931 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2932 DAG.getBasicBlock(NextMBB)); 2933 2934 DAG.setRoot(BrAnd); 2935 } 2936 2937 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2938 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2939 2940 // Retrieve successors. Look through artificial IR level blocks like 2941 // catchswitch for successors. 2942 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2943 const BasicBlock *EHPadBB = I.getSuccessor(1); 2944 2945 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2946 // have to do anything here to lower funclet bundles. 2947 assert(!I.hasOperandBundlesOtherThan( 2948 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 2949 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 2950 LLVMContext::OB_cfguardtarget, 2951 LLVMContext::OB_clang_arc_attachedcall}) && 2952 "Cannot lower invokes with arbitrary operand bundles yet!"); 2953 2954 const Value *Callee(I.getCalledOperand()); 2955 const Function *Fn = dyn_cast<Function>(Callee); 2956 if (isa<InlineAsm>(Callee)) 2957 visitInlineAsm(I, EHPadBB); 2958 else if (Fn && Fn->isIntrinsic()) { 2959 switch (Fn->getIntrinsicID()) { 2960 default: 2961 llvm_unreachable("Cannot invoke this intrinsic"); 2962 case Intrinsic::donothing: 2963 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2964 case Intrinsic::seh_try_begin: 2965 case Intrinsic::seh_scope_begin: 2966 case Intrinsic::seh_try_end: 2967 case Intrinsic::seh_scope_end: 2968 break; 2969 case Intrinsic::experimental_patchpoint_void: 2970 case Intrinsic::experimental_patchpoint_i64: 2971 visitPatchpoint(I, EHPadBB); 2972 break; 2973 case Intrinsic::experimental_gc_statepoint: 2974 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 2975 break; 2976 case Intrinsic::wasm_rethrow: { 2977 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2978 // special because it can be invoked, so we manually lower it to a DAG 2979 // node here. 2980 SmallVector<SDValue, 8> Ops; 2981 Ops.push_back(getRoot()); // inchain 2982 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2983 Ops.push_back( 2984 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 2985 TLI.getPointerTy(DAG.getDataLayout()))); 2986 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2987 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2988 break; 2989 } 2990 } 2991 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2992 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2993 // Eventually we will support lowering the @llvm.experimental.deoptimize 2994 // intrinsic, and right now there are no plans to support other intrinsics 2995 // with deopt state. 2996 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2997 } else { 2998 LowerCallTo(I, getValue(Callee), false, false, EHPadBB); 2999 } 3000 3001 // If the value of the invoke is used outside of its defining block, make it 3002 // available as a virtual register. 3003 // We already took care of the exported value for the statepoint instruction 3004 // during call to the LowerStatepoint. 3005 if (!isa<GCStatepointInst>(I)) { 3006 CopyToExportRegsIfNeeded(&I); 3007 } 3008 3009 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 3010 BranchProbabilityInfo *BPI = FuncInfo.BPI; 3011 BranchProbability EHPadBBProb = 3012 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 3013 : BranchProbability::getZero(); 3014 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 3015 3016 // Update successor info. 3017 addSuccessorWithProb(InvokeMBB, Return); 3018 for (auto &UnwindDest : UnwindDests) { 3019 UnwindDest.first->setIsEHPad(); 3020 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 3021 } 3022 InvokeMBB->normalizeSuccProbs(); 3023 3024 // Drop into normal successor. 3025 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 3026 DAG.getBasicBlock(Return))); 3027 } 3028 3029 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 3030 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 3031 3032 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3033 // have to do anything here to lower funclet bundles. 3034 assert(!I.hasOperandBundlesOtherThan( 3035 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 3036 "Cannot lower callbrs with arbitrary operand bundles yet!"); 3037 3038 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 3039 visitInlineAsm(I); 3040 CopyToExportRegsIfNeeded(&I); 3041 3042 // Retrieve successors. 3043 SmallPtrSet<BasicBlock *, 8> Dests; 3044 Dests.insert(I.getDefaultDest()); 3045 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 3046 3047 // Update successor info. 3048 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 3049 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 3050 BasicBlock *Dest = I.getIndirectDest(i); 3051 MachineBasicBlock *Target = FuncInfo.MBBMap[Dest]; 3052 Target->setIsInlineAsmBrIndirectTarget(); 3053 Target->setMachineBlockAddressTaken(); 3054 Target->setLabelMustBeEmitted(); 3055 // Don't add duplicate machine successors. 3056 if (Dests.insert(Dest).second) 3057 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 3058 } 3059 CallBrMBB->normalizeSuccProbs(); 3060 3061 // Drop into default successor. 3062 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 3063 MVT::Other, getControlRoot(), 3064 DAG.getBasicBlock(Return))); 3065 } 3066 3067 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 3068 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 3069 } 3070 3071 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 3072 assert(FuncInfo.MBB->isEHPad() && 3073 "Call to landingpad not in landing pad!"); 3074 3075 // If there aren't registers to copy the values into (e.g., during SjLj 3076 // exceptions), then don't bother to create these DAG nodes. 3077 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3078 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 3079 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 3080 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 3081 return; 3082 3083 // If landingpad's return type is token type, we don't create DAG nodes 3084 // for its exception pointer and selector value. The extraction of exception 3085 // pointer or selector value from token type landingpads is not currently 3086 // supported. 3087 if (LP.getType()->isTokenTy()) 3088 return; 3089 3090 SmallVector<EVT, 2> ValueVTs; 3091 SDLoc dl = getCurSDLoc(); 3092 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3093 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3094 3095 // Get the two live-in registers as SDValues. The physregs have already been 3096 // copied into virtual registers. 3097 SDValue Ops[2]; 3098 if (FuncInfo.ExceptionPointerVirtReg) { 3099 Ops[0] = DAG.getZExtOrTrunc( 3100 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3101 FuncInfo.ExceptionPointerVirtReg, 3102 TLI.getPointerTy(DAG.getDataLayout())), 3103 dl, ValueVTs[0]); 3104 } else { 3105 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3106 } 3107 Ops[1] = DAG.getZExtOrTrunc( 3108 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3109 FuncInfo.ExceptionSelectorVirtReg, 3110 TLI.getPointerTy(DAG.getDataLayout())), 3111 dl, ValueVTs[1]); 3112 3113 // Merge into one. 3114 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3115 DAG.getVTList(ValueVTs), Ops); 3116 setValue(&LP, Res); 3117 } 3118 3119 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3120 MachineBasicBlock *Last) { 3121 // Update JTCases. 3122 for (JumpTableBlock &JTB : SL->JTCases) 3123 if (JTB.first.HeaderBB == First) 3124 JTB.first.HeaderBB = Last; 3125 3126 // Update BitTestCases. 3127 for (BitTestBlock &BTB : SL->BitTestCases) 3128 if (BTB.Parent == First) 3129 BTB.Parent = Last; 3130 } 3131 3132 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3133 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3134 3135 // Update machine-CFG edges with unique successors. 3136 SmallSet<BasicBlock*, 32> Done; 3137 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3138 BasicBlock *BB = I.getSuccessor(i); 3139 bool Inserted = Done.insert(BB).second; 3140 if (!Inserted) 3141 continue; 3142 3143 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3144 addSuccessorWithProb(IndirectBrMBB, Succ); 3145 } 3146 IndirectBrMBB->normalizeSuccProbs(); 3147 3148 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3149 MVT::Other, getControlRoot(), 3150 getValue(I.getAddress()))); 3151 } 3152 3153 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3154 if (!DAG.getTarget().Options.TrapUnreachable) 3155 return; 3156 3157 // We may be able to ignore unreachable behind a noreturn call. 3158 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3159 const BasicBlock &BB = *I.getParent(); 3160 if (&I != &BB.front()) { 3161 BasicBlock::const_iterator PredI = 3162 std::prev(BasicBlock::const_iterator(&I)); 3163 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 3164 if (Call->doesNotReturn()) 3165 return; 3166 } 3167 } 3168 } 3169 3170 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3171 } 3172 3173 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3174 SDNodeFlags Flags; 3175 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3176 Flags.copyFMF(*FPOp); 3177 3178 SDValue Op = getValue(I.getOperand(0)); 3179 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3180 Op, Flags); 3181 setValue(&I, UnNodeValue); 3182 } 3183 3184 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3185 SDNodeFlags Flags; 3186 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3187 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3188 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3189 } 3190 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3191 Flags.setExact(ExactOp->isExact()); 3192 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3193 Flags.copyFMF(*FPOp); 3194 3195 SDValue Op1 = getValue(I.getOperand(0)); 3196 SDValue Op2 = getValue(I.getOperand(1)); 3197 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3198 Op1, Op2, Flags); 3199 setValue(&I, BinNodeValue); 3200 } 3201 3202 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3203 SDValue Op1 = getValue(I.getOperand(0)); 3204 SDValue Op2 = getValue(I.getOperand(1)); 3205 3206 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3207 Op1.getValueType(), DAG.getDataLayout()); 3208 3209 // Coerce the shift amount to the right type if we can. This exposes the 3210 // truncate or zext to optimization early. 3211 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3212 assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) && 3213 "Unexpected shift type"); 3214 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy); 3215 } 3216 3217 bool nuw = false; 3218 bool nsw = false; 3219 bool exact = false; 3220 3221 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3222 3223 if (const OverflowingBinaryOperator *OFBinOp = 3224 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3225 nuw = OFBinOp->hasNoUnsignedWrap(); 3226 nsw = OFBinOp->hasNoSignedWrap(); 3227 } 3228 if (const PossiblyExactOperator *ExactOp = 3229 dyn_cast<const PossiblyExactOperator>(&I)) 3230 exact = ExactOp->isExact(); 3231 } 3232 SDNodeFlags Flags; 3233 Flags.setExact(exact); 3234 Flags.setNoSignedWrap(nsw); 3235 Flags.setNoUnsignedWrap(nuw); 3236 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3237 Flags); 3238 setValue(&I, Res); 3239 } 3240 3241 void SelectionDAGBuilder::visitSDiv(const User &I) { 3242 SDValue Op1 = getValue(I.getOperand(0)); 3243 SDValue Op2 = getValue(I.getOperand(1)); 3244 3245 SDNodeFlags Flags; 3246 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3247 cast<PossiblyExactOperator>(&I)->isExact()); 3248 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3249 Op2, Flags)); 3250 } 3251 3252 void SelectionDAGBuilder::visitICmp(const User &I) { 3253 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3254 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3255 predicate = IC->getPredicate(); 3256 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3257 predicate = ICmpInst::Predicate(IC->getPredicate()); 3258 SDValue Op1 = getValue(I.getOperand(0)); 3259 SDValue Op2 = getValue(I.getOperand(1)); 3260 ISD::CondCode Opcode = getICmpCondCode(predicate); 3261 3262 auto &TLI = DAG.getTargetLoweringInfo(); 3263 EVT MemVT = 3264 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3265 3266 // If a pointer's DAG type is larger than its memory type then the DAG values 3267 // are zero-extended. This breaks signed comparisons so truncate back to the 3268 // underlying type before doing the compare. 3269 if (Op1.getValueType() != MemVT) { 3270 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3271 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3272 } 3273 3274 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3275 I.getType()); 3276 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3277 } 3278 3279 void SelectionDAGBuilder::visitFCmp(const User &I) { 3280 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3281 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3282 predicate = FC->getPredicate(); 3283 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3284 predicate = FCmpInst::Predicate(FC->getPredicate()); 3285 SDValue Op1 = getValue(I.getOperand(0)); 3286 SDValue Op2 = getValue(I.getOperand(1)); 3287 3288 ISD::CondCode Condition = getFCmpCondCode(predicate); 3289 auto *FPMO = cast<FPMathOperator>(&I); 3290 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3291 Condition = getFCmpCodeWithoutNaN(Condition); 3292 3293 SDNodeFlags Flags; 3294 Flags.copyFMF(*FPMO); 3295 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3296 3297 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3298 I.getType()); 3299 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3300 } 3301 3302 // Check if the condition of the select has one use or two users that are both 3303 // selects with the same condition. 3304 static bool hasOnlySelectUsers(const Value *Cond) { 3305 return llvm::all_of(Cond->users(), [](const Value *V) { 3306 return isa<SelectInst>(V); 3307 }); 3308 } 3309 3310 void SelectionDAGBuilder::visitSelect(const User &I) { 3311 SmallVector<EVT, 4> ValueVTs; 3312 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3313 ValueVTs); 3314 unsigned NumValues = ValueVTs.size(); 3315 if (NumValues == 0) return; 3316 3317 SmallVector<SDValue, 4> Values(NumValues); 3318 SDValue Cond = getValue(I.getOperand(0)); 3319 SDValue LHSVal = getValue(I.getOperand(1)); 3320 SDValue RHSVal = getValue(I.getOperand(2)); 3321 SmallVector<SDValue, 1> BaseOps(1, Cond); 3322 ISD::NodeType OpCode = 3323 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3324 3325 bool IsUnaryAbs = false; 3326 bool Negate = false; 3327 3328 SDNodeFlags Flags; 3329 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3330 Flags.copyFMF(*FPOp); 3331 3332 // Min/max matching is only viable if all output VTs are the same. 3333 if (all_equal(ValueVTs)) { 3334 EVT VT = ValueVTs[0]; 3335 LLVMContext &Ctx = *DAG.getContext(); 3336 auto &TLI = DAG.getTargetLoweringInfo(); 3337 3338 // We care about the legality of the operation after it has been type 3339 // legalized. 3340 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3341 VT = TLI.getTypeToTransformTo(Ctx, VT); 3342 3343 // If the vselect is legal, assume we want to leave this as a vector setcc + 3344 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3345 // min/max is legal on the scalar type. 3346 bool UseScalarMinMax = VT.isVector() && 3347 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3348 3349 Value *LHS, *RHS; 3350 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3351 ISD::NodeType Opc = ISD::DELETED_NODE; 3352 switch (SPR.Flavor) { 3353 case SPF_UMAX: Opc = ISD::UMAX; break; 3354 case SPF_UMIN: Opc = ISD::UMIN; break; 3355 case SPF_SMAX: Opc = ISD::SMAX; break; 3356 case SPF_SMIN: Opc = ISD::SMIN; break; 3357 case SPF_FMINNUM: 3358 switch (SPR.NaNBehavior) { 3359 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3360 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3361 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3362 case SPNB_RETURNS_ANY: { 3363 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3364 Opc = ISD::FMINNUM; 3365 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3366 Opc = ISD::FMINIMUM; 3367 else if (UseScalarMinMax) 3368 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3369 ISD::FMINNUM : ISD::FMINIMUM; 3370 break; 3371 } 3372 } 3373 break; 3374 case SPF_FMAXNUM: 3375 switch (SPR.NaNBehavior) { 3376 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3377 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3378 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3379 case SPNB_RETURNS_ANY: 3380 3381 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3382 Opc = ISD::FMAXNUM; 3383 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3384 Opc = ISD::FMAXIMUM; 3385 else if (UseScalarMinMax) 3386 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3387 ISD::FMAXNUM : ISD::FMAXIMUM; 3388 break; 3389 } 3390 break; 3391 case SPF_NABS: 3392 Negate = true; 3393 [[fallthrough]]; 3394 case SPF_ABS: 3395 IsUnaryAbs = true; 3396 Opc = ISD::ABS; 3397 break; 3398 default: break; 3399 } 3400 3401 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3402 (TLI.isOperationLegalOrCustom(Opc, VT) || 3403 (UseScalarMinMax && 3404 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3405 // If the underlying comparison instruction is used by any other 3406 // instruction, the consumed instructions won't be destroyed, so it is 3407 // not profitable to convert to a min/max. 3408 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3409 OpCode = Opc; 3410 LHSVal = getValue(LHS); 3411 RHSVal = getValue(RHS); 3412 BaseOps.clear(); 3413 } 3414 3415 if (IsUnaryAbs) { 3416 OpCode = Opc; 3417 LHSVal = getValue(LHS); 3418 BaseOps.clear(); 3419 } 3420 } 3421 3422 if (IsUnaryAbs) { 3423 for (unsigned i = 0; i != NumValues; ++i) { 3424 SDLoc dl = getCurSDLoc(); 3425 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3426 Values[i] = 3427 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3428 if (Negate) 3429 Values[i] = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), 3430 Values[i]); 3431 } 3432 } else { 3433 for (unsigned i = 0; i != NumValues; ++i) { 3434 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3435 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3436 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3437 Values[i] = DAG.getNode( 3438 OpCode, getCurSDLoc(), 3439 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3440 } 3441 } 3442 3443 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3444 DAG.getVTList(ValueVTs), Values)); 3445 } 3446 3447 void SelectionDAGBuilder::visitTrunc(const User &I) { 3448 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3449 SDValue N = getValue(I.getOperand(0)); 3450 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3451 I.getType()); 3452 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3453 } 3454 3455 void SelectionDAGBuilder::visitZExt(const User &I) { 3456 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3457 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3458 SDValue N = getValue(I.getOperand(0)); 3459 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3460 I.getType()); 3461 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3462 } 3463 3464 void SelectionDAGBuilder::visitSExt(const User &I) { 3465 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3466 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3467 SDValue N = getValue(I.getOperand(0)); 3468 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3469 I.getType()); 3470 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3471 } 3472 3473 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3474 // FPTrunc is never a no-op cast, no need to check 3475 SDValue N = getValue(I.getOperand(0)); 3476 SDLoc dl = getCurSDLoc(); 3477 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3478 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3479 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3480 DAG.getTargetConstant( 3481 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3482 } 3483 3484 void SelectionDAGBuilder::visitFPExt(const User &I) { 3485 // FPExt is never a no-op cast, no need to check 3486 SDValue N = getValue(I.getOperand(0)); 3487 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3488 I.getType()); 3489 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3490 } 3491 3492 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3493 // FPToUI is never a no-op cast, no need to check 3494 SDValue N = getValue(I.getOperand(0)); 3495 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3496 I.getType()); 3497 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3498 } 3499 3500 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3501 // FPToSI is never a no-op cast, no need to check 3502 SDValue N = getValue(I.getOperand(0)); 3503 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3504 I.getType()); 3505 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3506 } 3507 3508 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3509 // UIToFP is never a no-op cast, no need to check 3510 SDValue N = getValue(I.getOperand(0)); 3511 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3512 I.getType()); 3513 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3514 } 3515 3516 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3517 // SIToFP is never a no-op cast, no need to check 3518 SDValue N = getValue(I.getOperand(0)); 3519 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3520 I.getType()); 3521 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3522 } 3523 3524 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3525 // What to do depends on the size of the integer and the size of the pointer. 3526 // We can either truncate, zero extend, or no-op, accordingly. 3527 SDValue N = getValue(I.getOperand(0)); 3528 auto &TLI = DAG.getTargetLoweringInfo(); 3529 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3530 I.getType()); 3531 EVT PtrMemVT = 3532 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3533 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3534 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3535 setValue(&I, N); 3536 } 3537 3538 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3539 // What to do depends on the size of the integer and the size of the pointer. 3540 // We can either truncate, zero extend, or no-op, accordingly. 3541 SDValue N = getValue(I.getOperand(0)); 3542 auto &TLI = DAG.getTargetLoweringInfo(); 3543 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3544 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3545 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3546 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3547 setValue(&I, N); 3548 } 3549 3550 void SelectionDAGBuilder::visitBitCast(const User &I) { 3551 SDValue N = getValue(I.getOperand(0)); 3552 SDLoc dl = getCurSDLoc(); 3553 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3554 I.getType()); 3555 3556 // BitCast assures us that source and destination are the same size so this is 3557 // either a BITCAST or a no-op. 3558 if (DestVT != N.getValueType()) 3559 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3560 DestVT, N)); // convert types. 3561 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3562 // might fold any kind of constant expression to an integer constant and that 3563 // is not what we are looking for. Only recognize a bitcast of a genuine 3564 // constant integer as an opaque constant. 3565 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3566 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3567 /*isOpaque*/true)); 3568 else 3569 setValue(&I, N); // noop cast. 3570 } 3571 3572 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3573 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3574 const Value *SV = I.getOperand(0); 3575 SDValue N = getValue(SV); 3576 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3577 3578 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3579 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3580 3581 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3582 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3583 3584 setValue(&I, N); 3585 } 3586 3587 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3588 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3589 SDValue InVec = getValue(I.getOperand(0)); 3590 SDValue InVal = getValue(I.getOperand(1)); 3591 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3592 TLI.getVectorIdxTy(DAG.getDataLayout())); 3593 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3594 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3595 InVec, InVal, InIdx)); 3596 } 3597 3598 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3599 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3600 SDValue InVec = getValue(I.getOperand(0)); 3601 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3602 TLI.getVectorIdxTy(DAG.getDataLayout())); 3603 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3604 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3605 InVec, InIdx)); 3606 } 3607 3608 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3609 SDValue Src1 = getValue(I.getOperand(0)); 3610 SDValue Src2 = getValue(I.getOperand(1)); 3611 ArrayRef<int> Mask; 3612 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3613 Mask = SVI->getShuffleMask(); 3614 else 3615 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3616 SDLoc DL = getCurSDLoc(); 3617 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3618 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3619 EVT SrcVT = Src1.getValueType(); 3620 3621 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3622 VT.isScalableVector()) { 3623 // Canonical splat form of first element of first input vector. 3624 SDValue FirstElt = 3625 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3626 DAG.getVectorIdxConstant(0, DL)); 3627 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3628 return; 3629 } 3630 3631 // For now, we only handle splats for scalable vectors. 3632 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3633 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3634 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3635 3636 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3637 unsigned MaskNumElts = Mask.size(); 3638 3639 if (SrcNumElts == MaskNumElts) { 3640 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3641 return; 3642 } 3643 3644 // Normalize the shuffle vector since mask and vector length don't match. 3645 if (SrcNumElts < MaskNumElts) { 3646 // Mask is longer than the source vectors. We can use concatenate vector to 3647 // make the mask and vectors lengths match. 3648 3649 if (MaskNumElts % SrcNumElts == 0) { 3650 // Mask length is a multiple of the source vector length. 3651 // Check if the shuffle is some kind of concatenation of the input 3652 // vectors. 3653 unsigned NumConcat = MaskNumElts / SrcNumElts; 3654 bool IsConcat = true; 3655 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3656 for (unsigned i = 0; i != MaskNumElts; ++i) { 3657 int Idx = Mask[i]; 3658 if (Idx < 0) 3659 continue; 3660 // Ensure the indices in each SrcVT sized piece are sequential and that 3661 // the same source is used for the whole piece. 3662 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3663 (ConcatSrcs[i / SrcNumElts] >= 0 && 3664 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3665 IsConcat = false; 3666 break; 3667 } 3668 // Remember which source this index came from. 3669 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3670 } 3671 3672 // The shuffle is concatenating multiple vectors together. Just emit 3673 // a CONCAT_VECTORS operation. 3674 if (IsConcat) { 3675 SmallVector<SDValue, 8> ConcatOps; 3676 for (auto Src : ConcatSrcs) { 3677 if (Src < 0) 3678 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3679 else if (Src == 0) 3680 ConcatOps.push_back(Src1); 3681 else 3682 ConcatOps.push_back(Src2); 3683 } 3684 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3685 return; 3686 } 3687 } 3688 3689 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3690 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3691 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3692 PaddedMaskNumElts); 3693 3694 // Pad both vectors with undefs to make them the same length as the mask. 3695 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3696 3697 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3698 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3699 MOps1[0] = Src1; 3700 MOps2[0] = Src2; 3701 3702 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3703 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3704 3705 // Readjust mask for new input vector length. 3706 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3707 for (unsigned i = 0; i != MaskNumElts; ++i) { 3708 int Idx = Mask[i]; 3709 if (Idx >= (int)SrcNumElts) 3710 Idx -= SrcNumElts - PaddedMaskNumElts; 3711 MappedOps[i] = Idx; 3712 } 3713 3714 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3715 3716 // If the concatenated vector was padded, extract a subvector with the 3717 // correct number of elements. 3718 if (MaskNumElts != PaddedMaskNumElts) 3719 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3720 DAG.getVectorIdxConstant(0, DL)); 3721 3722 setValue(&I, Result); 3723 return; 3724 } 3725 3726 if (SrcNumElts > MaskNumElts) { 3727 // Analyze the access pattern of the vector to see if we can extract 3728 // two subvectors and do the shuffle. 3729 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3730 bool CanExtract = true; 3731 for (int Idx : Mask) { 3732 unsigned Input = 0; 3733 if (Idx < 0) 3734 continue; 3735 3736 if (Idx >= (int)SrcNumElts) { 3737 Input = 1; 3738 Idx -= SrcNumElts; 3739 } 3740 3741 // If all the indices come from the same MaskNumElts sized portion of 3742 // the sources we can use extract. Also make sure the extract wouldn't 3743 // extract past the end of the source. 3744 int NewStartIdx = alignDown(Idx, MaskNumElts); 3745 if (NewStartIdx + MaskNumElts > SrcNumElts || 3746 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3747 CanExtract = false; 3748 // Make sure we always update StartIdx as we use it to track if all 3749 // elements are undef. 3750 StartIdx[Input] = NewStartIdx; 3751 } 3752 3753 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3754 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3755 return; 3756 } 3757 if (CanExtract) { 3758 // Extract appropriate subvector and generate a vector shuffle 3759 for (unsigned Input = 0; Input < 2; ++Input) { 3760 SDValue &Src = Input == 0 ? Src1 : Src2; 3761 if (StartIdx[Input] < 0) 3762 Src = DAG.getUNDEF(VT); 3763 else { 3764 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3765 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3766 } 3767 } 3768 3769 // Calculate new mask. 3770 SmallVector<int, 8> MappedOps(Mask); 3771 for (int &Idx : MappedOps) { 3772 if (Idx >= (int)SrcNumElts) 3773 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3774 else if (Idx >= 0) 3775 Idx -= StartIdx[0]; 3776 } 3777 3778 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3779 return; 3780 } 3781 } 3782 3783 // We can't use either concat vectors or extract subvectors so fall back to 3784 // replacing the shuffle with extract and build vector. 3785 // to insert and build vector. 3786 EVT EltVT = VT.getVectorElementType(); 3787 SmallVector<SDValue,8> Ops; 3788 for (int Idx : Mask) { 3789 SDValue Res; 3790 3791 if (Idx < 0) { 3792 Res = DAG.getUNDEF(EltVT); 3793 } else { 3794 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3795 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3796 3797 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3798 DAG.getVectorIdxConstant(Idx, DL)); 3799 } 3800 3801 Ops.push_back(Res); 3802 } 3803 3804 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3805 } 3806 3807 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) { 3808 ArrayRef<unsigned> Indices = I.getIndices(); 3809 const Value *Op0 = I.getOperand(0); 3810 const Value *Op1 = I.getOperand(1); 3811 Type *AggTy = I.getType(); 3812 Type *ValTy = Op1->getType(); 3813 bool IntoUndef = isa<UndefValue>(Op0); 3814 bool FromUndef = isa<UndefValue>(Op1); 3815 3816 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3817 3818 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3819 SmallVector<EVT, 4> AggValueVTs; 3820 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3821 SmallVector<EVT, 4> ValValueVTs; 3822 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3823 3824 unsigned NumAggValues = AggValueVTs.size(); 3825 unsigned NumValValues = ValValueVTs.size(); 3826 SmallVector<SDValue, 4> Values(NumAggValues); 3827 3828 // Ignore an insertvalue that produces an empty object 3829 if (!NumAggValues) { 3830 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3831 return; 3832 } 3833 3834 SDValue Agg = getValue(Op0); 3835 unsigned i = 0; 3836 // Copy the beginning value(s) from the original aggregate. 3837 for (; i != LinearIndex; ++i) 3838 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3839 SDValue(Agg.getNode(), Agg.getResNo() + i); 3840 // Copy values from the inserted value(s). 3841 if (NumValValues) { 3842 SDValue Val = getValue(Op1); 3843 for (; i != LinearIndex + NumValValues; ++i) 3844 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3845 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3846 } 3847 // Copy remaining value(s) from the original aggregate. 3848 for (; i != NumAggValues; ++i) 3849 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3850 SDValue(Agg.getNode(), Agg.getResNo() + i); 3851 3852 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3853 DAG.getVTList(AggValueVTs), Values)); 3854 } 3855 3856 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) { 3857 ArrayRef<unsigned> Indices = I.getIndices(); 3858 const Value *Op0 = I.getOperand(0); 3859 Type *AggTy = Op0->getType(); 3860 Type *ValTy = I.getType(); 3861 bool OutOfUndef = isa<UndefValue>(Op0); 3862 3863 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3864 3865 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3866 SmallVector<EVT, 4> ValValueVTs; 3867 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3868 3869 unsigned NumValValues = ValValueVTs.size(); 3870 3871 // Ignore a extractvalue that produces an empty object 3872 if (!NumValValues) { 3873 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3874 return; 3875 } 3876 3877 SmallVector<SDValue, 4> Values(NumValValues); 3878 3879 SDValue Agg = getValue(Op0); 3880 // Copy out the selected value(s). 3881 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3882 Values[i - LinearIndex] = 3883 OutOfUndef ? 3884 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3885 SDValue(Agg.getNode(), Agg.getResNo() + i); 3886 3887 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3888 DAG.getVTList(ValValueVTs), Values)); 3889 } 3890 3891 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3892 Value *Op0 = I.getOperand(0); 3893 // Note that the pointer operand may be a vector of pointers. Take the scalar 3894 // element which holds a pointer. 3895 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3896 SDValue N = getValue(Op0); 3897 SDLoc dl = getCurSDLoc(); 3898 auto &TLI = DAG.getTargetLoweringInfo(); 3899 3900 // Normalize Vector GEP - all scalar operands should be converted to the 3901 // splat vector. 3902 bool IsVectorGEP = I.getType()->isVectorTy(); 3903 ElementCount VectorElementCount = 3904 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3905 : ElementCount::getFixed(0); 3906 3907 if (IsVectorGEP && !N.getValueType().isVector()) { 3908 LLVMContext &Context = *DAG.getContext(); 3909 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3910 if (VectorElementCount.isScalable()) 3911 N = DAG.getSplatVector(VT, dl, N); 3912 else 3913 N = DAG.getSplatBuildVector(VT, dl, N); 3914 } 3915 3916 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3917 GTI != E; ++GTI) { 3918 const Value *Idx = GTI.getOperand(); 3919 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3920 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3921 if (Field) { 3922 // N = N + Offset 3923 uint64_t Offset = 3924 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field); 3925 3926 // In an inbounds GEP with an offset that is nonnegative even when 3927 // interpreted as signed, assume there is no unsigned overflow. 3928 SDNodeFlags Flags; 3929 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3930 Flags.setNoUnsignedWrap(true); 3931 3932 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3933 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3934 } 3935 } else { 3936 // IdxSize is the width of the arithmetic according to IR semantics. 3937 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3938 // (and fix up the result later). 3939 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3940 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3941 TypeSize ElementSize = 3942 DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType()); 3943 // We intentionally mask away the high bits here; ElementSize may not 3944 // fit in IdxTy. 3945 APInt ElementMul(IdxSize, ElementSize.getKnownMinSize()); 3946 bool ElementScalable = ElementSize.isScalable(); 3947 3948 // If this is a scalar constant or a splat vector of constants, 3949 // handle it quickly. 3950 const auto *C = dyn_cast<Constant>(Idx); 3951 if (C && isa<VectorType>(C->getType())) 3952 C = C->getSplatValue(); 3953 3954 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 3955 if (CI && CI->isZero()) 3956 continue; 3957 if (CI && !ElementScalable) { 3958 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 3959 LLVMContext &Context = *DAG.getContext(); 3960 SDValue OffsVal; 3961 if (IsVectorGEP) 3962 OffsVal = DAG.getConstant( 3963 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 3964 else 3965 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 3966 3967 // In an inbounds GEP with an offset that is nonnegative even when 3968 // interpreted as signed, assume there is no unsigned overflow. 3969 SDNodeFlags Flags; 3970 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3971 Flags.setNoUnsignedWrap(true); 3972 3973 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3974 3975 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3976 continue; 3977 } 3978 3979 // N = N + Idx * ElementMul; 3980 SDValue IdxN = getValue(Idx); 3981 3982 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 3983 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 3984 VectorElementCount); 3985 if (VectorElementCount.isScalable()) 3986 IdxN = DAG.getSplatVector(VT, dl, IdxN); 3987 else 3988 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3989 } 3990 3991 // If the index is smaller or larger than intptr_t, truncate or extend 3992 // it. 3993 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3994 3995 if (ElementScalable) { 3996 EVT VScaleTy = N.getValueType().getScalarType(); 3997 SDValue VScale = DAG.getNode( 3998 ISD::VSCALE, dl, VScaleTy, 3999 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 4000 if (IsVectorGEP) 4001 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 4002 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 4003 } else { 4004 // If this is a multiply by a power of two, turn it into a shl 4005 // immediately. This is a very common case. 4006 if (ElementMul != 1) { 4007 if (ElementMul.isPowerOf2()) { 4008 unsigned Amt = ElementMul.logBase2(); 4009 IdxN = DAG.getNode(ISD::SHL, dl, 4010 N.getValueType(), IdxN, 4011 DAG.getConstant(Amt, dl, IdxN.getValueType())); 4012 } else { 4013 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 4014 IdxN.getValueType()); 4015 IdxN = DAG.getNode(ISD::MUL, dl, 4016 N.getValueType(), IdxN, Scale); 4017 } 4018 } 4019 } 4020 4021 N = DAG.getNode(ISD::ADD, dl, 4022 N.getValueType(), N, IdxN); 4023 } 4024 } 4025 4026 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 4027 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 4028 if (IsVectorGEP) { 4029 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 4030 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 4031 } 4032 4033 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 4034 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 4035 4036 setValue(&I, N); 4037 } 4038 4039 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 4040 // If this is a fixed sized alloca in the entry block of the function, 4041 // allocate it statically on the stack. 4042 if (FuncInfo.StaticAllocaMap.count(&I)) 4043 return; // getValue will auto-populate this. 4044 4045 SDLoc dl = getCurSDLoc(); 4046 Type *Ty = I.getAllocatedType(); 4047 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4048 auto &DL = DAG.getDataLayout(); 4049 TypeSize TySize = DL.getTypeAllocSize(Ty); 4050 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 4051 4052 SDValue AllocSize = getValue(I.getArraySize()); 4053 4054 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 4055 if (AllocSize.getValueType() != IntPtr) 4056 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 4057 4058 if (TySize.isScalable()) 4059 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4060 DAG.getVScale(dl, IntPtr, 4061 APInt(IntPtr.getScalarSizeInBits(), 4062 TySize.getKnownMinValue()))); 4063 else 4064 AllocSize = 4065 DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4066 DAG.getConstant(TySize.getFixedValue(), dl, IntPtr)); 4067 4068 // Handle alignment. If the requested alignment is less than or equal to 4069 // the stack alignment, ignore it. If the size is greater than or equal to 4070 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4071 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 4072 if (*Alignment <= StackAlign) 4073 Alignment = None; 4074 4075 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4076 // Round the size of the allocation up to the stack alignment size 4077 // by add SA-1 to the size. This doesn't overflow because we're computing 4078 // an address inside an alloca. 4079 SDNodeFlags Flags; 4080 Flags.setNoUnsignedWrap(true); 4081 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4082 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4083 4084 // Mask out the low bits for alignment purposes. 4085 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4086 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 4087 4088 SDValue Ops[] = { 4089 getRoot(), AllocSize, 4090 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4091 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4092 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4093 setValue(&I, DSA); 4094 DAG.setRoot(DSA.getValue(1)); 4095 4096 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4097 } 4098 4099 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4100 if (I.isAtomic()) 4101 return visitAtomicLoad(I); 4102 4103 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4104 const Value *SV = I.getOperand(0); 4105 if (TLI.supportSwiftError()) { 4106 // Swifterror values can come from either a function parameter with 4107 // swifterror attribute or an alloca with swifterror attribute. 4108 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4109 if (Arg->hasSwiftErrorAttr()) 4110 return visitLoadFromSwiftError(I); 4111 } 4112 4113 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4114 if (Alloca->isSwiftError()) 4115 return visitLoadFromSwiftError(I); 4116 } 4117 } 4118 4119 SDValue Ptr = getValue(SV); 4120 4121 Type *Ty = I.getType(); 4122 SmallVector<EVT, 4> ValueVTs, MemVTs; 4123 SmallVector<uint64_t, 4> Offsets; 4124 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4125 unsigned NumValues = ValueVTs.size(); 4126 if (NumValues == 0) 4127 return; 4128 4129 Align Alignment = I.getAlign(); 4130 AAMDNodes AAInfo = I.getAAMetadata(); 4131 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4132 bool isVolatile = I.isVolatile(); 4133 MachineMemOperand::Flags MMOFlags = 4134 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4135 4136 SDValue Root; 4137 bool ConstantMemory = false; 4138 if (isVolatile) 4139 // Serialize volatile loads with other side effects. 4140 Root = getRoot(); 4141 else if (NumValues > MaxParallelChains) 4142 Root = getMemoryRoot(); 4143 else if (AA && 4144 AA->pointsToConstantMemory(MemoryLocation( 4145 SV, 4146 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4147 AAInfo))) { 4148 // Do not serialize (non-volatile) loads of constant memory with anything. 4149 Root = DAG.getEntryNode(); 4150 ConstantMemory = true; 4151 MMOFlags |= MachineMemOperand::MOInvariant; 4152 } else { 4153 // Do not serialize non-volatile loads against each other. 4154 Root = DAG.getRoot(); 4155 } 4156 4157 if (isDereferenceableAndAlignedPointer(SV, Ty, Alignment, DAG.getDataLayout(), 4158 &I, AC, nullptr, LibInfo)) 4159 MMOFlags |= MachineMemOperand::MODereferenceable; 4160 4161 SDLoc dl = getCurSDLoc(); 4162 4163 if (isVolatile) 4164 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4165 4166 // An aggregate load cannot wrap around the address space, so offsets to its 4167 // parts don't wrap either. 4168 SDNodeFlags Flags; 4169 Flags.setNoUnsignedWrap(true); 4170 4171 SmallVector<SDValue, 4> Values(NumValues); 4172 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4173 EVT PtrVT = Ptr.getValueType(); 4174 4175 unsigned ChainI = 0; 4176 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4177 // Serializing loads here may result in excessive register pressure, and 4178 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4179 // could recover a bit by hoisting nodes upward in the chain by recognizing 4180 // they are side-effect free or do not alias. The optimizer should really 4181 // avoid this case by converting large object/array copies to llvm.memcpy 4182 // (MaxParallelChains should always remain as failsafe). 4183 if (ChainI == MaxParallelChains) { 4184 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4185 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4186 makeArrayRef(Chains.data(), ChainI)); 4187 Root = Chain; 4188 ChainI = 0; 4189 } 4190 SDValue A = DAG.getNode(ISD::ADD, dl, 4191 PtrVT, Ptr, 4192 DAG.getConstant(Offsets[i], dl, PtrVT), 4193 Flags); 4194 4195 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4196 MachinePointerInfo(SV, Offsets[i]), Alignment, 4197 MMOFlags, AAInfo, Ranges); 4198 Chains[ChainI] = L.getValue(1); 4199 4200 if (MemVTs[i] != ValueVTs[i]) 4201 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4202 4203 Values[i] = L; 4204 } 4205 4206 if (!ConstantMemory) { 4207 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4208 makeArrayRef(Chains.data(), ChainI)); 4209 if (isVolatile) 4210 DAG.setRoot(Chain); 4211 else 4212 PendingLoads.push_back(Chain); 4213 } 4214 4215 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4216 DAG.getVTList(ValueVTs), Values)); 4217 } 4218 4219 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4220 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4221 "call visitStoreToSwiftError when backend supports swifterror"); 4222 4223 SmallVector<EVT, 4> ValueVTs; 4224 SmallVector<uint64_t, 4> Offsets; 4225 const Value *SrcV = I.getOperand(0); 4226 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4227 SrcV->getType(), ValueVTs, &Offsets); 4228 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4229 "expect a single EVT for swifterror"); 4230 4231 SDValue Src = getValue(SrcV); 4232 // Create a virtual register, then update the virtual register. 4233 Register VReg = 4234 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4235 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4236 // Chain can be getRoot or getControlRoot. 4237 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4238 SDValue(Src.getNode(), Src.getResNo())); 4239 DAG.setRoot(CopyNode); 4240 } 4241 4242 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4243 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4244 "call visitLoadFromSwiftError when backend supports swifterror"); 4245 4246 assert(!I.isVolatile() && 4247 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4248 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4249 "Support volatile, non temporal, invariant for load_from_swift_error"); 4250 4251 const Value *SV = I.getOperand(0); 4252 Type *Ty = I.getType(); 4253 assert( 4254 (!AA || 4255 !AA->pointsToConstantMemory(MemoryLocation( 4256 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4257 I.getAAMetadata()))) && 4258 "load_from_swift_error should not be constant memory"); 4259 4260 SmallVector<EVT, 4> ValueVTs; 4261 SmallVector<uint64_t, 4> Offsets; 4262 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4263 ValueVTs, &Offsets); 4264 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4265 "expect a single EVT for swifterror"); 4266 4267 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4268 SDValue L = DAG.getCopyFromReg( 4269 getRoot(), getCurSDLoc(), 4270 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4271 4272 setValue(&I, L); 4273 } 4274 4275 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4276 if (I.isAtomic()) 4277 return visitAtomicStore(I); 4278 4279 const Value *SrcV = I.getOperand(0); 4280 const Value *PtrV = I.getOperand(1); 4281 4282 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4283 if (TLI.supportSwiftError()) { 4284 // Swifterror values can come from either a function parameter with 4285 // swifterror attribute or an alloca with swifterror attribute. 4286 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4287 if (Arg->hasSwiftErrorAttr()) 4288 return visitStoreToSwiftError(I); 4289 } 4290 4291 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4292 if (Alloca->isSwiftError()) 4293 return visitStoreToSwiftError(I); 4294 } 4295 } 4296 4297 SmallVector<EVT, 4> ValueVTs, MemVTs; 4298 SmallVector<uint64_t, 4> Offsets; 4299 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4300 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4301 unsigned NumValues = ValueVTs.size(); 4302 if (NumValues == 0) 4303 return; 4304 4305 // Get the lowered operands. Note that we do this after 4306 // checking if NumResults is zero, because with zero results 4307 // the operands won't have values in the map. 4308 SDValue Src = getValue(SrcV); 4309 SDValue Ptr = getValue(PtrV); 4310 4311 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4312 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4313 SDLoc dl = getCurSDLoc(); 4314 Align Alignment = I.getAlign(); 4315 AAMDNodes AAInfo = I.getAAMetadata(); 4316 4317 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4318 4319 // An aggregate load cannot wrap around the address space, so offsets to its 4320 // parts don't wrap either. 4321 SDNodeFlags Flags; 4322 Flags.setNoUnsignedWrap(true); 4323 4324 unsigned ChainI = 0; 4325 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4326 // See visitLoad comments. 4327 if (ChainI == MaxParallelChains) { 4328 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4329 makeArrayRef(Chains.data(), ChainI)); 4330 Root = Chain; 4331 ChainI = 0; 4332 } 4333 SDValue Add = 4334 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags); 4335 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4336 if (MemVTs[i] != ValueVTs[i]) 4337 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4338 SDValue St = 4339 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4340 Alignment, MMOFlags, AAInfo); 4341 Chains[ChainI] = St; 4342 } 4343 4344 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4345 makeArrayRef(Chains.data(), ChainI)); 4346 setValue(&I, StoreNode); 4347 DAG.setRoot(StoreNode); 4348 } 4349 4350 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4351 bool IsCompressing) { 4352 SDLoc sdl = getCurSDLoc(); 4353 4354 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4355 MaybeAlign &Alignment) { 4356 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4357 Src0 = I.getArgOperand(0); 4358 Ptr = I.getArgOperand(1); 4359 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4360 Mask = I.getArgOperand(3); 4361 }; 4362 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4363 MaybeAlign &Alignment) { 4364 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4365 Src0 = I.getArgOperand(0); 4366 Ptr = I.getArgOperand(1); 4367 Mask = I.getArgOperand(2); 4368 Alignment = None; 4369 }; 4370 4371 Value *PtrOperand, *MaskOperand, *Src0Operand; 4372 MaybeAlign Alignment; 4373 if (IsCompressing) 4374 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4375 else 4376 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4377 4378 SDValue Ptr = getValue(PtrOperand); 4379 SDValue Src0 = getValue(Src0Operand); 4380 SDValue Mask = getValue(MaskOperand); 4381 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4382 4383 EVT VT = Src0.getValueType(); 4384 if (!Alignment) 4385 Alignment = DAG.getEVTAlign(VT); 4386 4387 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4388 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4389 MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata()); 4390 SDValue StoreNode = 4391 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4392 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4393 DAG.setRoot(StoreNode); 4394 setValue(&I, StoreNode); 4395 } 4396 4397 // Get a uniform base for the Gather/Scatter intrinsic. 4398 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4399 // We try to represent it as a base pointer + vector of indices. 4400 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4401 // The first operand of the GEP may be a single pointer or a vector of pointers 4402 // Example: 4403 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4404 // or 4405 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4406 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4407 // 4408 // When the first GEP operand is a single pointer - it is the uniform base we 4409 // are looking for. If first operand of the GEP is a splat vector - we 4410 // extract the splat value and use it as a uniform base. 4411 // In all other cases the function returns 'false'. 4412 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4413 ISD::MemIndexType &IndexType, SDValue &Scale, 4414 SelectionDAGBuilder *SDB, const BasicBlock *CurBB, 4415 uint64_t ElemSize) { 4416 SelectionDAG& DAG = SDB->DAG; 4417 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4418 const DataLayout &DL = DAG.getDataLayout(); 4419 4420 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type"); 4421 4422 // Handle splat constant pointer. 4423 if (auto *C = dyn_cast<Constant>(Ptr)) { 4424 C = C->getSplatValue(); 4425 if (!C) 4426 return false; 4427 4428 Base = SDB->getValue(C); 4429 4430 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); 4431 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4432 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4433 IndexType = ISD::SIGNED_SCALED; 4434 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4435 return true; 4436 } 4437 4438 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4439 if (!GEP || GEP->getParent() != CurBB) 4440 return false; 4441 4442 if (GEP->getNumOperands() != 2) 4443 return false; 4444 4445 const Value *BasePtr = GEP->getPointerOperand(); 4446 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4447 4448 // Make sure the base is scalar and the index is a vector. 4449 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4450 return false; 4451 4452 uint64_t ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType()); 4453 4454 // Target may not support the required addressing mode. 4455 if (ScaleVal != 1 && 4456 !TLI.isLegalScaleForGatherScatter(ScaleVal, ElemSize)) 4457 return false; 4458 4459 Base = SDB->getValue(BasePtr); 4460 Index = SDB->getValue(IndexVal); 4461 IndexType = ISD::SIGNED_SCALED; 4462 4463 Scale = 4464 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4465 return true; 4466 } 4467 4468 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4469 SDLoc sdl = getCurSDLoc(); 4470 4471 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4472 const Value *Ptr = I.getArgOperand(1); 4473 SDValue Src0 = getValue(I.getArgOperand(0)); 4474 SDValue Mask = getValue(I.getArgOperand(3)); 4475 EVT VT = Src0.getValueType(); 4476 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4477 ->getMaybeAlignValue() 4478 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4479 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4480 4481 SDValue Base; 4482 SDValue Index; 4483 ISD::MemIndexType IndexType; 4484 SDValue Scale; 4485 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4486 I.getParent(), VT.getScalarStoreSize()); 4487 4488 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4489 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4490 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4491 // TODO: Make MachineMemOperands aware of scalable 4492 // vectors. 4493 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata()); 4494 if (!UniformBase) { 4495 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4496 Index = getValue(Ptr); 4497 IndexType = ISD::SIGNED_SCALED; 4498 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4499 } 4500 4501 EVT IdxVT = Index.getValueType(); 4502 EVT EltTy = IdxVT.getVectorElementType(); 4503 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4504 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4505 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4506 } 4507 4508 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4509 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4510 Ops, MMO, IndexType, false); 4511 DAG.setRoot(Scatter); 4512 setValue(&I, Scatter); 4513 } 4514 4515 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4516 SDLoc sdl = getCurSDLoc(); 4517 4518 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4519 MaybeAlign &Alignment) { 4520 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4521 Ptr = I.getArgOperand(0); 4522 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4523 Mask = I.getArgOperand(2); 4524 Src0 = I.getArgOperand(3); 4525 }; 4526 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4527 MaybeAlign &Alignment) { 4528 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4529 Ptr = I.getArgOperand(0); 4530 Alignment = None; 4531 Mask = I.getArgOperand(1); 4532 Src0 = I.getArgOperand(2); 4533 }; 4534 4535 Value *PtrOperand, *MaskOperand, *Src0Operand; 4536 MaybeAlign Alignment; 4537 if (IsExpanding) 4538 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4539 else 4540 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4541 4542 SDValue Ptr = getValue(PtrOperand); 4543 SDValue Src0 = getValue(Src0Operand); 4544 SDValue Mask = getValue(MaskOperand); 4545 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4546 4547 EVT VT = Src0.getValueType(); 4548 if (!Alignment) 4549 Alignment = DAG.getEVTAlign(VT); 4550 4551 AAMDNodes AAInfo = I.getAAMetadata(); 4552 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4553 4554 // Do not serialize masked loads of constant memory with anything. 4555 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 4556 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4557 4558 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4559 4560 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4561 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4562 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 4563 4564 SDValue Load = 4565 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4566 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4567 if (AddToChain) 4568 PendingLoads.push_back(Load.getValue(1)); 4569 setValue(&I, Load); 4570 } 4571 4572 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4573 SDLoc sdl = getCurSDLoc(); 4574 4575 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4576 const Value *Ptr = I.getArgOperand(0); 4577 SDValue Src0 = getValue(I.getArgOperand(3)); 4578 SDValue Mask = getValue(I.getArgOperand(2)); 4579 4580 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4581 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4582 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4583 ->getMaybeAlignValue() 4584 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4585 4586 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4587 4588 SDValue Root = DAG.getRoot(); 4589 SDValue Base; 4590 SDValue Index; 4591 ISD::MemIndexType IndexType; 4592 SDValue Scale; 4593 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4594 I.getParent(), VT.getScalarStoreSize()); 4595 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4596 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4597 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4598 // TODO: Make MachineMemOperands aware of scalable 4599 // vectors. 4600 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges); 4601 4602 if (!UniformBase) { 4603 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4604 Index = getValue(Ptr); 4605 IndexType = ISD::SIGNED_SCALED; 4606 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4607 } 4608 4609 EVT IdxVT = Index.getValueType(); 4610 EVT EltTy = IdxVT.getVectorElementType(); 4611 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4612 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4613 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4614 } 4615 4616 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4617 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4618 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4619 4620 PendingLoads.push_back(Gather.getValue(1)); 4621 setValue(&I, Gather); 4622 } 4623 4624 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4625 SDLoc dl = getCurSDLoc(); 4626 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4627 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4628 SyncScope::ID SSID = I.getSyncScopeID(); 4629 4630 SDValue InChain = getRoot(); 4631 4632 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4633 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4634 4635 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4636 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4637 4638 MachineFunction &MF = DAG.getMachineFunction(); 4639 MachineMemOperand *MMO = MF.getMachineMemOperand( 4640 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4641 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4642 FailureOrdering); 4643 4644 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4645 dl, MemVT, VTs, InChain, 4646 getValue(I.getPointerOperand()), 4647 getValue(I.getCompareOperand()), 4648 getValue(I.getNewValOperand()), MMO); 4649 4650 SDValue OutChain = L.getValue(2); 4651 4652 setValue(&I, L); 4653 DAG.setRoot(OutChain); 4654 } 4655 4656 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4657 SDLoc dl = getCurSDLoc(); 4658 ISD::NodeType NT; 4659 switch (I.getOperation()) { 4660 default: llvm_unreachable("Unknown atomicrmw operation"); 4661 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4662 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4663 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4664 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4665 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4666 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4667 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4668 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4669 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4670 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4671 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4672 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4673 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4674 case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break; 4675 case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break; 4676 } 4677 AtomicOrdering Ordering = I.getOrdering(); 4678 SyncScope::ID SSID = I.getSyncScopeID(); 4679 4680 SDValue InChain = getRoot(); 4681 4682 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4683 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4684 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4685 4686 MachineFunction &MF = DAG.getMachineFunction(); 4687 MachineMemOperand *MMO = MF.getMachineMemOperand( 4688 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4689 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4690 4691 SDValue L = 4692 DAG.getAtomic(NT, dl, MemVT, InChain, 4693 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4694 MMO); 4695 4696 SDValue OutChain = L.getValue(1); 4697 4698 setValue(&I, L); 4699 DAG.setRoot(OutChain); 4700 } 4701 4702 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4703 SDLoc dl = getCurSDLoc(); 4704 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4705 SDValue Ops[3]; 4706 Ops[0] = getRoot(); 4707 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4708 TLI.getFenceOperandTy(DAG.getDataLayout())); 4709 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4710 TLI.getFenceOperandTy(DAG.getDataLayout())); 4711 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops); 4712 setValue(&I, N); 4713 DAG.setRoot(N); 4714 } 4715 4716 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4717 SDLoc dl = getCurSDLoc(); 4718 AtomicOrdering Order = I.getOrdering(); 4719 SyncScope::ID SSID = I.getSyncScopeID(); 4720 4721 SDValue InChain = getRoot(); 4722 4723 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4724 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4725 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4726 4727 if (!TLI.supportsUnalignedAtomics() && 4728 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4729 report_fatal_error("Cannot generate unaligned atomic load"); 4730 4731 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4732 4733 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4734 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4735 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4736 4737 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4738 4739 SDValue Ptr = getValue(I.getPointerOperand()); 4740 4741 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4742 // TODO: Once this is better exercised by tests, it should be merged with 4743 // the normal path for loads to prevent future divergence. 4744 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4745 if (MemVT != VT) 4746 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4747 4748 setValue(&I, L); 4749 SDValue OutChain = L.getValue(1); 4750 if (!I.isUnordered()) 4751 DAG.setRoot(OutChain); 4752 else 4753 PendingLoads.push_back(OutChain); 4754 return; 4755 } 4756 4757 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4758 Ptr, MMO); 4759 4760 SDValue OutChain = L.getValue(1); 4761 if (MemVT != VT) 4762 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4763 4764 setValue(&I, L); 4765 DAG.setRoot(OutChain); 4766 } 4767 4768 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4769 SDLoc dl = getCurSDLoc(); 4770 4771 AtomicOrdering Ordering = I.getOrdering(); 4772 SyncScope::ID SSID = I.getSyncScopeID(); 4773 4774 SDValue InChain = getRoot(); 4775 4776 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4777 EVT MemVT = 4778 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4779 4780 if (!TLI.supportsUnalignedAtomics() && 4781 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4782 report_fatal_error("Cannot generate unaligned atomic store"); 4783 4784 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4785 4786 MachineFunction &MF = DAG.getMachineFunction(); 4787 MachineMemOperand *MMO = MF.getMachineMemOperand( 4788 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4789 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4790 4791 SDValue Val = getValue(I.getValueOperand()); 4792 if (Val.getValueType() != MemVT) 4793 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4794 SDValue Ptr = getValue(I.getPointerOperand()); 4795 4796 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4797 // TODO: Once this is better exercised by tests, it should be merged with 4798 // the normal path for stores to prevent future divergence. 4799 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4800 setValue(&I, S); 4801 DAG.setRoot(S); 4802 return; 4803 } 4804 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4805 Ptr, Val, MMO); 4806 4807 setValue(&I, OutChain); 4808 DAG.setRoot(OutChain); 4809 } 4810 4811 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4812 /// node. 4813 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4814 unsigned Intrinsic) { 4815 // Ignore the callsite's attributes. A specific call site may be marked with 4816 // readnone, but the lowering code will expect the chain based on the 4817 // definition. 4818 const Function *F = I.getCalledFunction(); 4819 bool HasChain = !F->doesNotAccessMemory(); 4820 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4821 4822 // Build the operand list. 4823 SmallVector<SDValue, 8> Ops; 4824 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4825 if (OnlyLoad) { 4826 // We don't need to serialize loads against other loads. 4827 Ops.push_back(DAG.getRoot()); 4828 } else { 4829 Ops.push_back(getRoot()); 4830 } 4831 } 4832 4833 // Info is set by getTgtMemIntrinsic 4834 TargetLowering::IntrinsicInfo Info; 4835 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4836 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4837 DAG.getMachineFunction(), 4838 Intrinsic); 4839 4840 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4841 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4842 Info.opc == ISD::INTRINSIC_W_CHAIN) 4843 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4844 TLI.getPointerTy(DAG.getDataLayout()))); 4845 4846 // Add all operands of the call to the operand list. 4847 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) { 4848 const Value *Arg = I.getArgOperand(i); 4849 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4850 Ops.push_back(getValue(Arg)); 4851 continue; 4852 } 4853 4854 // Use TargetConstant instead of a regular constant for immarg. 4855 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true); 4856 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4857 assert(CI->getBitWidth() <= 64 && 4858 "large intrinsic immediates not handled"); 4859 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4860 } else { 4861 Ops.push_back( 4862 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4863 } 4864 } 4865 4866 SmallVector<EVT, 4> ValueVTs; 4867 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4868 4869 if (HasChain) 4870 ValueVTs.push_back(MVT::Other); 4871 4872 SDVTList VTs = DAG.getVTList(ValueVTs); 4873 4874 // Propagate fast-math-flags from IR to node(s). 4875 SDNodeFlags Flags; 4876 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 4877 Flags.copyFMF(*FPMO); 4878 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 4879 4880 // Create the node. 4881 SDValue Result; 4882 // In some cases, custom collection of operands from CallInst I may be needed. 4883 TLI.CollectTargetIntrinsicOperands(I, Ops, DAG); 4884 if (IsTgtIntrinsic) { 4885 // This is target intrinsic that touches memory 4886 Result = 4887 DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT, 4888 MachinePointerInfo(Info.ptrVal, Info.offset), 4889 Info.align, Info.flags, Info.size, 4890 I.getAAMetadata()); 4891 } else if (!HasChain) { 4892 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4893 } else if (!I.getType()->isVoidTy()) { 4894 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4895 } else { 4896 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4897 } 4898 4899 if (HasChain) { 4900 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4901 if (OnlyLoad) 4902 PendingLoads.push_back(Chain); 4903 else 4904 DAG.setRoot(Chain); 4905 } 4906 4907 if (!I.getType()->isVoidTy()) { 4908 if (!isa<VectorType>(I.getType())) 4909 Result = lowerRangeToAssertZExt(DAG, I, Result); 4910 4911 MaybeAlign Alignment = I.getRetAlign(); 4912 if (!Alignment) 4913 Alignment = F->getAttributes().getRetAlignment(); 4914 // Insert `assertalign` node if there's an alignment. 4915 if (InsertAssertAlign && Alignment) { 4916 Result = 4917 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 4918 } 4919 4920 setValue(&I, Result); 4921 } 4922 } 4923 4924 /// GetSignificand - Get the significand and build it into a floating-point 4925 /// number with exponent of 1: 4926 /// 4927 /// Op = (Op & 0x007fffff) | 0x3f800000; 4928 /// 4929 /// where Op is the hexadecimal representation of floating point value. 4930 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4931 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4932 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4933 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4934 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4935 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4936 } 4937 4938 /// GetExponent - Get the exponent: 4939 /// 4940 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4941 /// 4942 /// where Op is the hexadecimal representation of floating point value. 4943 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4944 const TargetLowering &TLI, const SDLoc &dl) { 4945 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4946 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4947 SDValue t1 = DAG.getNode( 4948 ISD::SRL, dl, MVT::i32, t0, 4949 DAG.getConstant(23, dl, 4950 TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout()))); 4951 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4952 DAG.getConstant(127, dl, MVT::i32)); 4953 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4954 } 4955 4956 /// getF32Constant - Get 32-bit floating point constant. 4957 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4958 const SDLoc &dl) { 4959 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4960 MVT::f32); 4961 } 4962 4963 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4964 SelectionDAG &DAG) { 4965 // TODO: What fast-math-flags should be set on the floating-point nodes? 4966 4967 // IntegerPartOfX = ((int32_t)(t0); 4968 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4969 4970 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4971 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4972 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4973 4974 // IntegerPartOfX <<= 23; 4975 IntegerPartOfX = 4976 DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4977 DAG.getConstant(23, dl, 4978 DAG.getTargetLoweringInfo().getShiftAmountTy( 4979 MVT::i32, DAG.getDataLayout()))); 4980 4981 SDValue TwoToFractionalPartOfX; 4982 if (LimitFloatPrecision <= 6) { 4983 // For floating-point precision of 6: 4984 // 4985 // TwoToFractionalPartOfX = 4986 // 0.997535578f + 4987 // (0.735607626f + 0.252464424f * x) * x; 4988 // 4989 // error 0.0144103317, which is 6 bits 4990 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4991 getF32Constant(DAG, 0x3e814304, dl)); 4992 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4993 getF32Constant(DAG, 0x3f3c50c8, dl)); 4994 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4995 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4996 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4997 } else if (LimitFloatPrecision <= 12) { 4998 // For floating-point precision of 12: 4999 // 5000 // TwoToFractionalPartOfX = 5001 // 0.999892986f + 5002 // (0.696457318f + 5003 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 5004 // 5005 // error 0.000107046256, which is 13 to 14 bits 5006 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5007 getF32Constant(DAG, 0x3da235e3, dl)); 5008 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5009 getF32Constant(DAG, 0x3e65b8f3, dl)); 5010 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5011 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5012 getF32Constant(DAG, 0x3f324b07, dl)); 5013 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5014 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5015 getF32Constant(DAG, 0x3f7ff8fd, dl)); 5016 } else { // LimitFloatPrecision <= 18 5017 // For floating-point precision of 18: 5018 // 5019 // TwoToFractionalPartOfX = 5020 // 0.999999982f + 5021 // (0.693148872f + 5022 // (0.240227044f + 5023 // (0.554906021e-1f + 5024 // (0.961591928e-2f + 5025 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 5026 // error 2.47208000*10^(-7), which is better than 18 bits 5027 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5028 getF32Constant(DAG, 0x3924b03e, dl)); 5029 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5030 getF32Constant(DAG, 0x3ab24b87, dl)); 5031 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5032 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5033 getF32Constant(DAG, 0x3c1d8c17, dl)); 5034 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5035 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5036 getF32Constant(DAG, 0x3d634a1d, dl)); 5037 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5038 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5039 getF32Constant(DAG, 0x3e75fe14, dl)); 5040 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5041 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 5042 getF32Constant(DAG, 0x3f317234, dl)); 5043 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 5044 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 5045 getF32Constant(DAG, 0x3f800000, dl)); 5046 } 5047 5048 // Add the exponent into the result in integer domain. 5049 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 5050 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5051 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 5052 } 5053 5054 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5055 /// limited-precision mode. 5056 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5057 const TargetLowering &TLI, SDNodeFlags Flags) { 5058 if (Op.getValueType() == MVT::f32 && 5059 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5060 5061 // Put the exponent in the right bit position for later addition to the 5062 // final result: 5063 // 5064 // t0 = Op * log2(e) 5065 5066 // TODO: What fast-math-flags should be set here? 5067 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5068 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5069 return getLimitedPrecisionExp2(t0, dl, DAG); 5070 } 5071 5072 // No special expansion. 5073 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5074 } 5075 5076 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5077 /// limited-precision mode. 5078 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5079 const TargetLowering &TLI, SDNodeFlags Flags) { 5080 // TODO: What fast-math-flags should be set on the floating-point nodes? 5081 5082 if (Op.getValueType() == MVT::f32 && 5083 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5084 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5085 5086 // Scale the exponent by log(2). 5087 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5088 SDValue LogOfExponent = 5089 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5090 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5091 5092 // Get the significand and build it into a floating-point number with 5093 // exponent of 1. 5094 SDValue X = GetSignificand(DAG, Op1, dl); 5095 5096 SDValue LogOfMantissa; 5097 if (LimitFloatPrecision <= 6) { 5098 // For floating-point precision of 6: 5099 // 5100 // LogofMantissa = 5101 // -1.1609546f + 5102 // (1.4034025f - 0.23903021f * x) * x; 5103 // 5104 // error 0.0034276066, which is better than 8 bits 5105 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5106 getF32Constant(DAG, 0xbe74c456, dl)); 5107 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5108 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5109 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5110 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5111 getF32Constant(DAG, 0x3f949a29, dl)); 5112 } else if (LimitFloatPrecision <= 12) { 5113 // For floating-point precision of 12: 5114 // 5115 // LogOfMantissa = 5116 // -1.7417939f + 5117 // (2.8212026f + 5118 // (-1.4699568f + 5119 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5120 // 5121 // error 0.000061011436, which is 14 bits 5122 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5123 getF32Constant(DAG, 0xbd67b6d6, dl)); 5124 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5125 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5126 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5127 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5128 getF32Constant(DAG, 0x3fbc278b, dl)); 5129 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5130 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5131 getF32Constant(DAG, 0x40348e95, dl)); 5132 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5133 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5134 getF32Constant(DAG, 0x3fdef31a, dl)); 5135 } else { // LimitFloatPrecision <= 18 5136 // For floating-point precision of 18: 5137 // 5138 // LogOfMantissa = 5139 // -2.1072184f + 5140 // (4.2372794f + 5141 // (-3.7029485f + 5142 // (2.2781945f + 5143 // (-0.87823314f + 5144 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5145 // 5146 // error 0.0000023660568, which is better than 18 bits 5147 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5148 getF32Constant(DAG, 0xbc91e5ac, dl)); 5149 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5150 getF32Constant(DAG, 0x3e4350aa, dl)); 5151 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5152 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5153 getF32Constant(DAG, 0x3f60d3e3, dl)); 5154 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5155 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5156 getF32Constant(DAG, 0x4011cdf0, dl)); 5157 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5158 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5159 getF32Constant(DAG, 0x406cfd1c, dl)); 5160 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5161 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5162 getF32Constant(DAG, 0x408797cb, dl)); 5163 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5164 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5165 getF32Constant(DAG, 0x4006dcab, dl)); 5166 } 5167 5168 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5169 } 5170 5171 // No special expansion. 5172 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5173 } 5174 5175 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5176 /// limited-precision mode. 5177 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5178 const TargetLowering &TLI, SDNodeFlags Flags) { 5179 // TODO: What fast-math-flags should be set on the floating-point nodes? 5180 5181 if (Op.getValueType() == MVT::f32 && 5182 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5183 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5184 5185 // Get the exponent. 5186 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5187 5188 // Get the significand and build it into a floating-point number with 5189 // exponent of 1. 5190 SDValue X = GetSignificand(DAG, Op1, dl); 5191 5192 // Different possible minimax approximations of significand in 5193 // floating-point for various degrees of accuracy over [1,2]. 5194 SDValue Log2ofMantissa; 5195 if (LimitFloatPrecision <= 6) { 5196 // For floating-point precision of 6: 5197 // 5198 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5199 // 5200 // error 0.0049451742, which is more than 7 bits 5201 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5202 getF32Constant(DAG, 0xbeb08fe0, dl)); 5203 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5204 getF32Constant(DAG, 0x40019463, dl)); 5205 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5206 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5207 getF32Constant(DAG, 0x3fd6633d, dl)); 5208 } else if (LimitFloatPrecision <= 12) { 5209 // For floating-point precision of 12: 5210 // 5211 // Log2ofMantissa = 5212 // -2.51285454f + 5213 // (4.07009056f + 5214 // (-2.12067489f + 5215 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5216 // 5217 // error 0.0000876136000, which is better than 13 bits 5218 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5219 getF32Constant(DAG, 0xbda7262e, dl)); 5220 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5221 getF32Constant(DAG, 0x3f25280b, dl)); 5222 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5223 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5224 getF32Constant(DAG, 0x4007b923, dl)); 5225 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5226 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5227 getF32Constant(DAG, 0x40823e2f, dl)); 5228 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5229 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5230 getF32Constant(DAG, 0x4020d29c, dl)); 5231 } else { // LimitFloatPrecision <= 18 5232 // For floating-point precision of 18: 5233 // 5234 // Log2ofMantissa = 5235 // -3.0400495f + 5236 // (6.1129976f + 5237 // (-5.3420409f + 5238 // (3.2865683f + 5239 // (-1.2669343f + 5240 // (0.27515199f - 5241 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5242 // 5243 // error 0.0000018516, which is better than 18 bits 5244 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5245 getF32Constant(DAG, 0xbcd2769e, dl)); 5246 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5247 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5248 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5249 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5250 getF32Constant(DAG, 0x3fa22ae7, dl)); 5251 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5252 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5253 getF32Constant(DAG, 0x40525723, dl)); 5254 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5255 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5256 getF32Constant(DAG, 0x40aaf200, dl)); 5257 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5258 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5259 getF32Constant(DAG, 0x40c39dad, dl)); 5260 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5261 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5262 getF32Constant(DAG, 0x4042902c, dl)); 5263 } 5264 5265 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5266 } 5267 5268 // No special expansion. 5269 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5270 } 5271 5272 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5273 /// limited-precision mode. 5274 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5275 const TargetLowering &TLI, SDNodeFlags Flags) { 5276 // TODO: What fast-math-flags should be set on the floating-point nodes? 5277 5278 if (Op.getValueType() == MVT::f32 && 5279 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5280 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5281 5282 // Scale the exponent by log10(2) [0.30102999f]. 5283 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5284 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5285 getF32Constant(DAG, 0x3e9a209a, dl)); 5286 5287 // Get the significand and build it into a floating-point number with 5288 // exponent of 1. 5289 SDValue X = GetSignificand(DAG, Op1, dl); 5290 5291 SDValue Log10ofMantissa; 5292 if (LimitFloatPrecision <= 6) { 5293 // For floating-point precision of 6: 5294 // 5295 // Log10ofMantissa = 5296 // -0.50419619f + 5297 // (0.60948995f - 0.10380950f * x) * x; 5298 // 5299 // error 0.0014886165, which is 6 bits 5300 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5301 getF32Constant(DAG, 0xbdd49a13, dl)); 5302 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5303 getF32Constant(DAG, 0x3f1c0789, dl)); 5304 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5305 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5306 getF32Constant(DAG, 0x3f011300, dl)); 5307 } else if (LimitFloatPrecision <= 12) { 5308 // For floating-point precision of 12: 5309 // 5310 // Log10ofMantissa = 5311 // -0.64831180f + 5312 // (0.91751397f + 5313 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5314 // 5315 // error 0.00019228036, which is better than 12 bits 5316 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5317 getF32Constant(DAG, 0x3d431f31, dl)); 5318 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5319 getF32Constant(DAG, 0x3ea21fb2, dl)); 5320 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5321 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5322 getF32Constant(DAG, 0x3f6ae232, dl)); 5323 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5324 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5325 getF32Constant(DAG, 0x3f25f7c3, dl)); 5326 } else { // LimitFloatPrecision <= 18 5327 // For floating-point precision of 18: 5328 // 5329 // Log10ofMantissa = 5330 // -0.84299375f + 5331 // (1.5327582f + 5332 // (-1.0688956f + 5333 // (0.49102474f + 5334 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5335 // 5336 // error 0.0000037995730, which is better than 18 bits 5337 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5338 getF32Constant(DAG, 0x3c5d51ce, dl)); 5339 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5340 getF32Constant(DAG, 0x3e00685a, dl)); 5341 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5342 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5343 getF32Constant(DAG, 0x3efb6798, dl)); 5344 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5345 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5346 getF32Constant(DAG, 0x3f88d192, dl)); 5347 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5348 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5349 getF32Constant(DAG, 0x3fc4316c, dl)); 5350 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5351 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5352 getF32Constant(DAG, 0x3f57ce70, dl)); 5353 } 5354 5355 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5356 } 5357 5358 // No special expansion. 5359 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5360 } 5361 5362 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5363 /// limited-precision mode. 5364 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5365 const TargetLowering &TLI, SDNodeFlags Flags) { 5366 if (Op.getValueType() == MVT::f32 && 5367 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5368 return getLimitedPrecisionExp2(Op, dl, DAG); 5369 5370 // No special expansion. 5371 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5372 } 5373 5374 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5375 /// limited-precision mode with x == 10.0f. 5376 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5377 SelectionDAG &DAG, const TargetLowering &TLI, 5378 SDNodeFlags Flags) { 5379 bool IsExp10 = false; 5380 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5381 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5382 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5383 APFloat Ten(10.0f); 5384 IsExp10 = LHSC->isExactlyValue(Ten); 5385 } 5386 } 5387 5388 // TODO: What fast-math-flags should be set on the FMUL node? 5389 if (IsExp10) { 5390 // Put the exponent in the right bit position for later addition to the 5391 // final result: 5392 // 5393 // #define LOG2OF10 3.3219281f 5394 // t0 = Op * LOG2OF10; 5395 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5396 getF32Constant(DAG, 0x40549a78, dl)); 5397 return getLimitedPrecisionExp2(t0, dl, DAG); 5398 } 5399 5400 // No special expansion. 5401 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5402 } 5403 5404 /// ExpandPowI - Expand a llvm.powi intrinsic. 5405 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5406 SelectionDAG &DAG) { 5407 // If RHS is a constant, we can expand this out to a multiplication tree if 5408 // it's beneficial on the target, otherwise we end up lowering to a call to 5409 // __powidf2 (for example). 5410 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5411 unsigned Val = RHSC->getSExtValue(); 5412 5413 // powi(x, 0) -> 1.0 5414 if (Val == 0) 5415 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5416 5417 if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI( 5418 Val, DAG.shouldOptForSize())) { 5419 // Get the exponent as a positive value. 5420 if ((int)Val < 0) 5421 Val = -Val; 5422 // We use the simple binary decomposition method to generate the multiply 5423 // sequence. There are more optimal ways to do this (for example, 5424 // powi(x,15) generates one more multiply than it should), but this has 5425 // the benefit of being both really simple and much better than a libcall. 5426 SDValue Res; // Logically starts equal to 1.0 5427 SDValue CurSquare = LHS; 5428 // TODO: Intrinsics should have fast-math-flags that propagate to these 5429 // nodes. 5430 while (Val) { 5431 if (Val & 1) { 5432 if (Res.getNode()) 5433 Res = 5434 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare); 5435 else 5436 Res = CurSquare; // 1.0*CurSquare. 5437 } 5438 5439 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5440 CurSquare, CurSquare); 5441 Val >>= 1; 5442 } 5443 5444 // If the original was negative, invert the result, producing 1/(x*x*x). 5445 if (RHSC->getSExtValue() < 0) 5446 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5447 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5448 return Res; 5449 } 5450 } 5451 5452 // Otherwise, expand to a libcall. 5453 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5454 } 5455 5456 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5457 SDValue LHS, SDValue RHS, SDValue Scale, 5458 SelectionDAG &DAG, const TargetLowering &TLI) { 5459 EVT VT = LHS.getValueType(); 5460 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5461 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5462 LLVMContext &Ctx = *DAG.getContext(); 5463 5464 // If the type is legal but the operation isn't, this node might survive all 5465 // the way to operation legalization. If we end up there and we do not have 5466 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5467 // node. 5468 5469 // Coax the legalizer into expanding the node during type legalization instead 5470 // by bumping the size by one bit. This will force it to Promote, enabling the 5471 // early expansion and avoiding the need to expand later. 5472 5473 // We don't have to do this if Scale is 0; that can always be expanded, unless 5474 // it's a saturating signed operation. Those can experience true integer 5475 // division overflow, a case which we must avoid. 5476 5477 // FIXME: We wouldn't have to do this (or any of the early 5478 // expansion/promotion) if it was possible to expand a libcall of an 5479 // illegal type during operation legalization. But it's not, so things 5480 // get a bit hacky. 5481 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5482 if ((ScaleInt > 0 || (Saturating && Signed)) && 5483 (TLI.isTypeLegal(VT) || 5484 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5485 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5486 Opcode, VT, ScaleInt); 5487 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5488 EVT PromVT; 5489 if (VT.isScalarInteger()) 5490 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5491 else if (VT.isVector()) { 5492 PromVT = VT.getVectorElementType(); 5493 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5494 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5495 } else 5496 llvm_unreachable("Wrong VT for DIVFIX?"); 5497 if (Signed) { 5498 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5499 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5500 } else { 5501 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5502 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5503 } 5504 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5505 // For saturating operations, we need to shift up the LHS to get the 5506 // proper saturation width, and then shift down again afterwards. 5507 if (Saturating) 5508 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5509 DAG.getConstant(1, DL, ShiftTy)); 5510 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5511 if (Saturating) 5512 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5513 DAG.getConstant(1, DL, ShiftTy)); 5514 return DAG.getZExtOrTrunc(Res, DL, VT); 5515 } 5516 } 5517 5518 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5519 } 5520 5521 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5522 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5523 static void 5524 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5525 const SDValue &N) { 5526 switch (N.getOpcode()) { 5527 case ISD::CopyFromReg: { 5528 SDValue Op = N.getOperand(1); 5529 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5530 Op.getValueType().getSizeInBits()); 5531 return; 5532 } 5533 case ISD::BITCAST: 5534 case ISD::AssertZext: 5535 case ISD::AssertSext: 5536 case ISD::TRUNCATE: 5537 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5538 return; 5539 case ISD::BUILD_PAIR: 5540 case ISD::BUILD_VECTOR: 5541 case ISD::CONCAT_VECTORS: 5542 for (SDValue Op : N->op_values()) 5543 getUnderlyingArgRegs(Regs, Op); 5544 return; 5545 default: 5546 return; 5547 } 5548 } 5549 5550 /// If the DbgValueInst is a dbg_value of a function argument, create the 5551 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5552 /// instruction selection, they will be inserted to the entry BB. 5553 /// We don't currently support this for variadic dbg_values, as they shouldn't 5554 /// appear for function arguments or in the prologue. 5555 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5556 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5557 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) { 5558 const Argument *Arg = dyn_cast<Argument>(V); 5559 if (!Arg) 5560 return false; 5561 5562 MachineFunction &MF = DAG.getMachineFunction(); 5563 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5564 5565 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind 5566 // we've been asked to pursue. 5567 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr, 5568 bool Indirect) { 5569 if (Reg.isVirtual() && MF.useDebugInstrRef()) { 5570 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF 5571 // pointing at the VReg, which will be patched up later. 5572 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF); 5573 auto MIB = BuildMI(MF, DL, Inst); 5574 MIB.addReg(Reg); 5575 MIB.addImm(0); 5576 MIB.addMetadata(Variable); 5577 auto *NewDIExpr = FragExpr; 5578 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into 5579 // the DIExpression. 5580 if (Indirect) 5581 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore); 5582 MIB.addMetadata(NewDIExpr); 5583 return MIB; 5584 } else { 5585 // Create a completely standard DBG_VALUE. 5586 auto &Inst = TII->get(TargetOpcode::DBG_VALUE); 5587 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr); 5588 } 5589 }; 5590 5591 if (Kind == FuncArgumentDbgValueKind::Value) { 5592 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5593 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5594 // the entry block. 5595 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5596 if (!IsInEntryBlock) 5597 return false; 5598 5599 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5600 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5601 // variable that also is a param. 5602 // 5603 // Although, if we are at the top of the entry block already, we can still 5604 // emit using ArgDbgValue. This might catch some situations when the 5605 // dbg.value refers to an argument that isn't used in the entry block, so 5606 // any CopyToReg node would be optimized out and the only way to express 5607 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5608 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5609 // we should only emit as ArgDbgValue if the Variable is an argument to the 5610 // current function, and the dbg.value intrinsic is found in the entry 5611 // block. 5612 bool VariableIsFunctionInputArg = Variable->isParameter() && 5613 !DL->getInlinedAt(); 5614 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5615 if (!IsInPrologue && !VariableIsFunctionInputArg) 5616 return false; 5617 5618 // Here we assume that a function argument on IR level only can be used to 5619 // describe one input parameter on source level. If we for example have 5620 // source code like this 5621 // 5622 // struct A { long x, y; }; 5623 // void foo(struct A a, long b) { 5624 // ... 5625 // b = a.x; 5626 // ... 5627 // } 5628 // 5629 // and IR like this 5630 // 5631 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5632 // entry: 5633 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5634 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5635 // call void @llvm.dbg.value(metadata i32 %b, "b", 5636 // ... 5637 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5638 // ... 5639 // 5640 // then the last dbg.value is describing a parameter "b" using a value that 5641 // is an argument. But since we already has used %a1 to describe a parameter 5642 // we should not handle that last dbg.value here (that would result in an 5643 // incorrect hoisting of the DBG_VALUE to the function entry). 5644 // Notice that we allow one dbg.value per IR level argument, to accommodate 5645 // for the situation with fragments above. 5646 if (VariableIsFunctionInputArg) { 5647 unsigned ArgNo = Arg->getArgNo(); 5648 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5649 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5650 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5651 return false; 5652 FuncInfo.DescribedArgs.set(ArgNo); 5653 } 5654 } 5655 5656 bool IsIndirect = false; 5657 Optional<MachineOperand> Op; 5658 // Some arguments' frame index is recorded during argument lowering. 5659 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5660 if (FI != std::numeric_limits<int>::max()) 5661 Op = MachineOperand::CreateFI(FI); 5662 5663 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 5664 if (!Op && N.getNode()) { 5665 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5666 Register Reg; 5667 if (ArgRegsAndSizes.size() == 1) 5668 Reg = ArgRegsAndSizes.front().first; 5669 5670 if (Reg && Reg.isVirtual()) { 5671 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5672 Register PR = RegInfo.getLiveInPhysReg(Reg); 5673 if (PR) 5674 Reg = PR; 5675 } 5676 if (Reg) { 5677 Op = MachineOperand::CreateReg(Reg, false); 5678 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5679 } 5680 } 5681 5682 if (!Op && N.getNode()) { 5683 // Check if frame index is available. 5684 SDValue LCandidate = peekThroughBitcasts(N); 5685 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5686 if (FrameIndexSDNode *FINode = 5687 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5688 Op = MachineOperand::CreateFI(FINode->getIndex()); 5689 } 5690 5691 if (!Op) { 5692 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5693 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 5694 SplitRegs) { 5695 unsigned Offset = 0; 5696 for (const auto &RegAndSize : SplitRegs) { 5697 // If the expression is already a fragment, the current register 5698 // offset+size might extend beyond the fragment. In this case, only 5699 // the register bits that are inside the fragment are relevant. 5700 int RegFragmentSizeInBits = RegAndSize.second; 5701 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5702 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5703 // The register is entirely outside the expression fragment, 5704 // so is irrelevant for debug info. 5705 if (Offset >= ExprFragmentSizeInBits) 5706 break; 5707 // The register is partially outside the expression fragment, only 5708 // the low bits within the fragment are relevant for debug info. 5709 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5710 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5711 } 5712 } 5713 5714 auto FragmentExpr = DIExpression::createFragmentExpression( 5715 Expr, Offset, RegFragmentSizeInBits); 5716 Offset += RegAndSize.second; 5717 // If a valid fragment expression cannot be created, the variable's 5718 // correct value cannot be determined and so it is set as Undef. 5719 if (!FragmentExpr) { 5720 SDDbgValue *SDV = DAG.getConstantDbgValue( 5721 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5722 DAG.AddDbgValue(SDV, false); 5723 continue; 5724 } 5725 MachineInstr *NewMI = 5726 MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, 5727 Kind != FuncArgumentDbgValueKind::Value); 5728 FuncInfo.ArgDbgValues.push_back(NewMI); 5729 } 5730 }; 5731 5732 // Check if ValueMap has reg number. 5733 DenseMap<const Value *, Register>::const_iterator 5734 VMI = FuncInfo.ValueMap.find(V); 5735 if (VMI != FuncInfo.ValueMap.end()) { 5736 const auto &TLI = DAG.getTargetLoweringInfo(); 5737 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5738 V->getType(), None); 5739 if (RFV.occupiesMultipleRegs()) { 5740 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5741 return true; 5742 } 5743 5744 Op = MachineOperand::CreateReg(VMI->second, false); 5745 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5746 } else if (ArgRegsAndSizes.size() > 1) { 5747 // This was split due to the calling convention, and no virtual register 5748 // mapping exists for the value. 5749 splitMultiRegDbgValue(ArgRegsAndSizes); 5750 return true; 5751 } 5752 } 5753 5754 if (!Op) 5755 return false; 5756 5757 assert(Variable->isValidLocationForIntrinsic(DL) && 5758 "Expected inlined-at fields to agree"); 5759 MachineInstr *NewMI = nullptr; 5760 5761 if (Op->isReg()) 5762 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect); 5763 else 5764 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op, 5765 Variable, Expr); 5766 5767 // Otherwise, use ArgDbgValues. 5768 FuncInfo.ArgDbgValues.push_back(NewMI); 5769 return true; 5770 } 5771 5772 /// Return the appropriate SDDbgValue based on N. 5773 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5774 DILocalVariable *Variable, 5775 DIExpression *Expr, 5776 const DebugLoc &dl, 5777 unsigned DbgSDNodeOrder) { 5778 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5779 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5780 // stack slot locations. 5781 // 5782 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5783 // debug values here after optimization: 5784 // 5785 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5786 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5787 // 5788 // Both describe the direct values of their associated variables. 5789 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5790 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5791 } 5792 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5793 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5794 } 5795 5796 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5797 switch (Intrinsic) { 5798 case Intrinsic::smul_fix: 5799 return ISD::SMULFIX; 5800 case Intrinsic::umul_fix: 5801 return ISD::UMULFIX; 5802 case Intrinsic::smul_fix_sat: 5803 return ISD::SMULFIXSAT; 5804 case Intrinsic::umul_fix_sat: 5805 return ISD::UMULFIXSAT; 5806 case Intrinsic::sdiv_fix: 5807 return ISD::SDIVFIX; 5808 case Intrinsic::udiv_fix: 5809 return ISD::UDIVFIX; 5810 case Intrinsic::sdiv_fix_sat: 5811 return ISD::SDIVFIXSAT; 5812 case Intrinsic::udiv_fix_sat: 5813 return ISD::UDIVFIXSAT; 5814 default: 5815 llvm_unreachable("Unhandled fixed point intrinsic"); 5816 } 5817 } 5818 5819 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5820 const char *FunctionName) { 5821 assert(FunctionName && "FunctionName must not be nullptr"); 5822 SDValue Callee = DAG.getExternalSymbol( 5823 FunctionName, 5824 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5825 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 5826 } 5827 5828 /// Given a @llvm.call.preallocated.setup, return the corresponding 5829 /// preallocated call. 5830 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5831 assert(cast<CallBase>(PreallocatedSetup) 5832 ->getCalledFunction() 5833 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5834 "expected call_preallocated_setup Value"); 5835 for (const auto *U : PreallocatedSetup->users()) { 5836 auto *UseCall = cast<CallBase>(U); 5837 const Function *Fn = UseCall->getCalledFunction(); 5838 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5839 return UseCall; 5840 } 5841 } 5842 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5843 } 5844 5845 /// Lower the call to the specified intrinsic function. 5846 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5847 unsigned Intrinsic) { 5848 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5849 SDLoc sdl = getCurSDLoc(); 5850 DebugLoc dl = getCurDebugLoc(); 5851 SDValue Res; 5852 5853 SDNodeFlags Flags; 5854 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 5855 Flags.copyFMF(*FPOp); 5856 5857 switch (Intrinsic) { 5858 default: 5859 // By default, turn this into a target intrinsic node. 5860 visitTargetIntrinsic(I, Intrinsic); 5861 return; 5862 case Intrinsic::vscale: { 5863 match(&I, m_VScale(DAG.getDataLayout())); 5864 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5865 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1))); 5866 return; 5867 } 5868 case Intrinsic::vastart: visitVAStart(I); return; 5869 case Intrinsic::vaend: visitVAEnd(I); return; 5870 case Intrinsic::vacopy: visitVACopy(I); return; 5871 case Intrinsic::returnaddress: 5872 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5873 TLI.getValueType(DAG.getDataLayout(), I.getType()), 5874 getValue(I.getArgOperand(0)))); 5875 return; 5876 case Intrinsic::addressofreturnaddress: 5877 setValue(&I, 5878 DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5879 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 5880 return; 5881 case Intrinsic::sponentry: 5882 setValue(&I, 5883 DAG.getNode(ISD::SPONENTRY, sdl, 5884 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 5885 return; 5886 case Intrinsic::frameaddress: 5887 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5888 TLI.getFrameIndexTy(DAG.getDataLayout()), 5889 getValue(I.getArgOperand(0)))); 5890 return; 5891 case Intrinsic::read_volatile_register: 5892 case Intrinsic::read_register: { 5893 Value *Reg = I.getArgOperand(0); 5894 SDValue Chain = getRoot(); 5895 SDValue RegName = 5896 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5897 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5898 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5899 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5900 setValue(&I, Res); 5901 DAG.setRoot(Res.getValue(1)); 5902 return; 5903 } 5904 case Intrinsic::write_register: { 5905 Value *Reg = I.getArgOperand(0); 5906 Value *RegValue = I.getArgOperand(1); 5907 SDValue Chain = getRoot(); 5908 SDValue RegName = 5909 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5910 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5911 RegName, getValue(RegValue))); 5912 return; 5913 } 5914 case Intrinsic::memcpy: { 5915 const auto &MCI = cast<MemCpyInst>(I); 5916 SDValue Op1 = getValue(I.getArgOperand(0)); 5917 SDValue Op2 = getValue(I.getArgOperand(1)); 5918 SDValue Op3 = getValue(I.getArgOperand(2)); 5919 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5920 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5921 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5922 Align Alignment = std::min(DstAlign, SrcAlign); 5923 bool isVol = MCI.isVolatile(); 5924 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5925 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5926 // node. 5927 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5928 SDValue MC = DAG.getMemcpy( 5929 Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5930 /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)), 5931 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 5932 updateDAGForMaybeTailCall(MC); 5933 return; 5934 } 5935 case Intrinsic::memcpy_inline: { 5936 const auto &MCI = cast<MemCpyInlineInst>(I); 5937 SDValue Dst = getValue(I.getArgOperand(0)); 5938 SDValue Src = getValue(I.getArgOperand(1)); 5939 SDValue Size = getValue(I.getArgOperand(2)); 5940 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 5941 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 5942 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5943 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5944 Align Alignment = std::min(DstAlign, SrcAlign); 5945 bool isVol = MCI.isVolatile(); 5946 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5947 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5948 // node. 5949 SDValue MC = DAG.getMemcpy( 5950 getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 5951 /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)), 5952 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 5953 updateDAGForMaybeTailCall(MC); 5954 return; 5955 } 5956 case Intrinsic::memset: { 5957 const auto &MSI = cast<MemSetInst>(I); 5958 SDValue Op1 = getValue(I.getArgOperand(0)); 5959 SDValue Op2 = getValue(I.getArgOperand(1)); 5960 SDValue Op3 = getValue(I.getArgOperand(2)); 5961 // @llvm.memset defines 0 and 1 to both mean no alignment. 5962 Align Alignment = MSI.getDestAlign().valueOrOne(); 5963 bool isVol = MSI.isVolatile(); 5964 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5965 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5966 SDValue MS = DAG.getMemset( 5967 Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false, 5968 isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata()); 5969 updateDAGForMaybeTailCall(MS); 5970 return; 5971 } 5972 case Intrinsic::memset_inline: { 5973 const auto &MSII = cast<MemSetInlineInst>(I); 5974 SDValue Dst = getValue(I.getArgOperand(0)); 5975 SDValue Value = getValue(I.getArgOperand(1)); 5976 SDValue Size = getValue(I.getArgOperand(2)); 5977 assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size"); 5978 // @llvm.memset defines 0 and 1 to both mean no alignment. 5979 Align DstAlign = MSII.getDestAlign().valueOrOne(); 5980 bool isVol = MSII.isVolatile(); 5981 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5982 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5983 SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol, 5984 /* AlwaysInline */ true, isTC, 5985 MachinePointerInfo(I.getArgOperand(0)), 5986 I.getAAMetadata()); 5987 updateDAGForMaybeTailCall(MC); 5988 return; 5989 } 5990 case Intrinsic::memmove: { 5991 const auto &MMI = cast<MemMoveInst>(I); 5992 SDValue Op1 = getValue(I.getArgOperand(0)); 5993 SDValue Op2 = getValue(I.getArgOperand(1)); 5994 SDValue Op3 = getValue(I.getArgOperand(2)); 5995 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5996 Align DstAlign = MMI.getDestAlign().valueOrOne(); 5997 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 5998 Align Alignment = std::min(DstAlign, SrcAlign); 5999 bool isVol = MMI.isVolatile(); 6000 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6001 // FIXME: Support passing different dest/src alignments to the memmove DAG 6002 // node. 6003 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6004 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6005 isTC, MachinePointerInfo(I.getArgOperand(0)), 6006 MachinePointerInfo(I.getArgOperand(1)), 6007 I.getAAMetadata(), AA); 6008 updateDAGForMaybeTailCall(MM); 6009 return; 6010 } 6011 case Intrinsic::memcpy_element_unordered_atomic: { 6012 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 6013 SDValue Dst = getValue(MI.getRawDest()); 6014 SDValue Src = getValue(MI.getRawSource()); 6015 SDValue Length = getValue(MI.getLength()); 6016 6017 Type *LengthTy = MI.getLength()->getType(); 6018 unsigned ElemSz = MI.getElementSizeInBytes(); 6019 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6020 SDValue MC = 6021 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6022 isTC, MachinePointerInfo(MI.getRawDest()), 6023 MachinePointerInfo(MI.getRawSource())); 6024 updateDAGForMaybeTailCall(MC); 6025 return; 6026 } 6027 case Intrinsic::memmove_element_unordered_atomic: { 6028 auto &MI = cast<AtomicMemMoveInst>(I); 6029 SDValue Dst = getValue(MI.getRawDest()); 6030 SDValue Src = getValue(MI.getRawSource()); 6031 SDValue Length = getValue(MI.getLength()); 6032 6033 Type *LengthTy = MI.getLength()->getType(); 6034 unsigned ElemSz = MI.getElementSizeInBytes(); 6035 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6036 SDValue MC = 6037 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6038 isTC, MachinePointerInfo(MI.getRawDest()), 6039 MachinePointerInfo(MI.getRawSource())); 6040 updateDAGForMaybeTailCall(MC); 6041 return; 6042 } 6043 case Intrinsic::memset_element_unordered_atomic: { 6044 auto &MI = cast<AtomicMemSetInst>(I); 6045 SDValue Dst = getValue(MI.getRawDest()); 6046 SDValue Val = getValue(MI.getValue()); 6047 SDValue Length = getValue(MI.getLength()); 6048 6049 Type *LengthTy = MI.getLength()->getType(); 6050 unsigned ElemSz = MI.getElementSizeInBytes(); 6051 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6052 SDValue MC = 6053 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz, 6054 isTC, MachinePointerInfo(MI.getRawDest())); 6055 updateDAGForMaybeTailCall(MC); 6056 return; 6057 } 6058 case Intrinsic::call_preallocated_setup: { 6059 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 6060 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6061 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 6062 getRoot(), SrcValue); 6063 setValue(&I, Res); 6064 DAG.setRoot(Res); 6065 return; 6066 } 6067 case Intrinsic::call_preallocated_arg: { 6068 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 6069 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6070 SDValue Ops[3]; 6071 Ops[0] = getRoot(); 6072 Ops[1] = SrcValue; 6073 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 6074 MVT::i32); // arg index 6075 SDValue Res = DAG.getNode( 6076 ISD::PREALLOCATED_ARG, sdl, 6077 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 6078 setValue(&I, Res); 6079 DAG.setRoot(Res.getValue(1)); 6080 return; 6081 } 6082 case Intrinsic::dbg_addr: 6083 case Intrinsic::dbg_declare: { 6084 // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e. 6085 // they are non-variadic. 6086 const auto &DI = cast<DbgVariableIntrinsic>(I); 6087 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 6088 DILocalVariable *Variable = DI.getVariable(); 6089 DIExpression *Expression = DI.getExpression(); 6090 dropDanglingDebugInfo(Variable, Expression); 6091 assert(Variable && "Missing variable"); 6092 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 6093 << "\n"); 6094 // Check if address has undef value. 6095 const Value *Address = DI.getVariableLocationOp(0); 6096 if (!Address || isa<UndefValue>(Address) || 6097 (Address->use_empty() && !isa<Argument>(Address))) { 6098 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6099 << " (bad/undef/unused-arg address)\n"); 6100 return; 6101 } 6102 6103 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 6104 6105 // Check if this variable can be described by a frame index, typically 6106 // either as a static alloca or a byval parameter. 6107 int FI = std::numeric_limits<int>::max(); 6108 if (const auto *AI = 6109 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 6110 if (AI->isStaticAlloca()) { 6111 auto I = FuncInfo.StaticAllocaMap.find(AI); 6112 if (I != FuncInfo.StaticAllocaMap.end()) 6113 FI = I->second; 6114 } 6115 } else if (const auto *Arg = dyn_cast<Argument>( 6116 Address->stripInBoundsConstantOffsets())) { 6117 FI = FuncInfo.getArgumentFrameIndex(Arg); 6118 } 6119 6120 // llvm.dbg.addr is control dependent and always generates indirect 6121 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 6122 // the MachineFunction variable table. 6123 if (FI != std::numeric_limits<int>::max()) { 6124 if (Intrinsic == Intrinsic::dbg_addr) { 6125 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 6126 Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true, 6127 dl, SDNodeOrder); 6128 DAG.AddDbgValue(SDV, isParameter); 6129 } else { 6130 LLVM_DEBUG(dbgs() << "Skipping " << DI 6131 << " (variable info stashed in MF side table)\n"); 6132 } 6133 return; 6134 } 6135 6136 SDValue &N = NodeMap[Address]; 6137 if (!N.getNode() && isa<Argument>(Address)) 6138 // Check unused arguments map. 6139 N = UnusedArgNodeMap[Address]; 6140 SDDbgValue *SDV; 6141 if (N.getNode()) { 6142 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 6143 Address = BCI->getOperand(0); 6144 // Parameters are handled specially. 6145 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 6146 if (isParameter && FINode) { 6147 // Byval parameter. We have a frame index at this point. 6148 SDV = 6149 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 6150 /*IsIndirect*/ true, dl, SDNodeOrder); 6151 } else if (isa<Argument>(Address)) { 6152 // Address is an argument, so try to emit its dbg value using 6153 // virtual register info from the FuncInfo.ValueMap. 6154 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 6155 FuncArgumentDbgValueKind::Declare, N); 6156 return; 6157 } else { 6158 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 6159 true, dl, SDNodeOrder); 6160 } 6161 DAG.AddDbgValue(SDV, isParameter); 6162 } else { 6163 // If Address is an argument then try to emit its dbg value using 6164 // virtual register info from the FuncInfo.ValueMap. 6165 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 6166 FuncArgumentDbgValueKind::Declare, N)) { 6167 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6168 << " (could not emit func-arg dbg_value)\n"); 6169 } 6170 } 6171 return; 6172 } 6173 case Intrinsic::dbg_label: { 6174 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6175 DILabel *Label = DI.getLabel(); 6176 assert(Label && "Missing label"); 6177 6178 SDDbgLabel *SDV; 6179 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6180 DAG.AddDbgLabel(SDV); 6181 return; 6182 } 6183 case Intrinsic::dbg_value: { 6184 const DbgValueInst &DI = cast<DbgValueInst>(I); 6185 assert(DI.getVariable() && "Missing variable"); 6186 6187 DILocalVariable *Variable = DI.getVariable(); 6188 DIExpression *Expression = DI.getExpression(); 6189 dropDanglingDebugInfo(Variable, Expression); 6190 SmallVector<Value *, 4> Values(DI.getValues()); 6191 if (Values.empty()) 6192 return; 6193 6194 if (llvm::is_contained(Values, nullptr)) 6195 return; 6196 6197 bool IsVariadic = DI.hasArgList(); 6198 if (!handleDebugValue(Values, Variable, Expression, dl, DI.getDebugLoc(), 6199 SDNodeOrder, IsVariadic)) 6200 addDanglingDebugInfo(&DI, dl, SDNodeOrder); 6201 return; 6202 } 6203 6204 case Intrinsic::eh_typeid_for: { 6205 // Find the type id for the given typeinfo. 6206 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6207 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6208 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6209 setValue(&I, Res); 6210 return; 6211 } 6212 6213 case Intrinsic::eh_return_i32: 6214 case Intrinsic::eh_return_i64: 6215 DAG.getMachineFunction().setCallsEHReturn(true); 6216 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6217 MVT::Other, 6218 getControlRoot(), 6219 getValue(I.getArgOperand(0)), 6220 getValue(I.getArgOperand(1)))); 6221 return; 6222 case Intrinsic::eh_unwind_init: 6223 DAG.getMachineFunction().setCallsUnwindInit(true); 6224 return; 6225 case Intrinsic::eh_dwarf_cfa: 6226 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6227 TLI.getPointerTy(DAG.getDataLayout()), 6228 getValue(I.getArgOperand(0)))); 6229 return; 6230 case Intrinsic::eh_sjlj_callsite: { 6231 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6232 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0)); 6233 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6234 6235 MMI.setCurrentCallSite(CI->getZExtValue()); 6236 return; 6237 } 6238 case Intrinsic::eh_sjlj_functioncontext: { 6239 // Get and store the index of the function context. 6240 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6241 AllocaInst *FnCtx = 6242 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6243 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6244 MFI.setFunctionContextIndex(FI); 6245 return; 6246 } 6247 case Intrinsic::eh_sjlj_setjmp: { 6248 SDValue Ops[2]; 6249 Ops[0] = getRoot(); 6250 Ops[1] = getValue(I.getArgOperand(0)); 6251 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6252 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6253 setValue(&I, Op.getValue(0)); 6254 DAG.setRoot(Op.getValue(1)); 6255 return; 6256 } 6257 case Intrinsic::eh_sjlj_longjmp: 6258 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6259 getRoot(), getValue(I.getArgOperand(0)))); 6260 return; 6261 case Intrinsic::eh_sjlj_setup_dispatch: 6262 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6263 getRoot())); 6264 return; 6265 case Intrinsic::masked_gather: 6266 visitMaskedGather(I); 6267 return; 6268 case Intrinsic::masked_load: 6269 visitMaskedLoad(I); 6270 return; 6271 case Intrinsic::masked_scatter: 6272 visitMaskedScatter(I); 6273 return; 6274 case Intrinsic::masked_store: 6275 visitMaskedStore(I); 6276 return; 6277 case Intrinsic::masked_expandload: 6278 visitMaskedLoad(I, true /* IsExpanding */); 6279 return; 6280 case Intrinsic::masked_compressstore: 6281 visitMaskedStore(I, true /* IsCompressing */); 6282 return; 6283 case Intrinsic::powi: 6284 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6285 getValue(I.getArgOperand(1)), DAG)); 6286 return; 6287 case Intrinsic::log: 6288 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6289 return; 6290 case Intrinsic::log2: 6291 setValue(&I, 6292 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6293 return; 6294 case Intrinsic::log10: 6295 setValue(&I, 6296 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6297 return; 6298 case Intrinsic::exp: 6299 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6300 return; 6301 case Intrinsic::exp2: 6302 setValue(&I, 6303 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6304 return; 6305 case Intrinsic::pow: 6306 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6307 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6308 return; 6309 case Intrinsic::sqrt: 6310 case Intrinsic::fabs: 6311 case Intrinsic::sin: 6312 case Intrinsic::cos: 6313 case Intrinsic::floor: 6314 case Intrinsic::ceil: 6315 case Intrinsic::trunc: 6316 case Intrinsic::rint: 6317 case Intrinsic::nearbyint: 6318 case Intrinsic::round: 6319 case Intrinsic::roundeven: 6320 case Intrinsic::canonicalize: { 6321 unsigned Opcode; 6322 switch (Intrinsic) { 6323 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6324 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6325 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6326 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6327 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6328 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6329 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6330 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6331 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6332 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6333 case Intrinsic::round: Opcode = ISD::FROUND; break; 6334 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6335 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6336 } 6337 6338 setValue(&I, DAG.getNode(Opcode, sdl, 6339 getValue(I.getArgOperand(0)).getValueType(), 6340 getValue(I.getArgOperand(0)), Flags)); 6341 return; 6342 } 6343 case Intrinsic::lround: 6344 case Intrinsic::llround: 6345 case Intrinsic::lrint: 6346 case Intrinsic::llrint: { 6347 unsigned Opcode; 6348 switch (Intrinsic) { 6349 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6350 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6351 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6352 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6353 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6354 } 6355 6356 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6357 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6358 getValue(I.getArgOperand(0)))); 6359 return; 6360 } 6361 case Intrinsic::minnum: 6362 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6363 getValue(I.getArgOperand(0)).getValueType(), 6364 getValue(I.getArgOperand(0)), 6365 getValue(I.getArgOperand(1)), Flags)); 6366 return; 6367 case Intrinsic::maxnum: 6368 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6369 getValue(I.getArgOperand(0)).getValueType(), 6370 getValue(I.getArgOperand(0)), 6371 getValue(I.getArgOperand(1)), Flags)); 6372 return; 6373 case Intrinsic::minimum: 6374 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6375 getValue(I.getArgOperand(0)).getValueType(), 6376 getValue(I.getArgOperand(0)), 6377 getValue(I.getArgOperand(1)), Flags)); 6378 return; 6379 case Intrinsic::maximum: 6380 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6381 getValue(I.getArgOperand(0)).getValueType(), 6382 getValue(I.getArgOperand(0)), 6383 getValue(I.getArgOperand(1)), Flags)); 6384 return; 6385 case Intrinsic::copysign: 6386 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6387 getValue(I.getArgOperand(0)).getValueType(), 6388 getValue(I.getArgOperand(0)), 6389 getValue(I.getArgOperand(1)), Flags)); 6390 return; 6391 case Intrinsic::arithmetic_fence: { 6392 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl, 6393 getValue(I.getArgOperand(0)).getValueType(), 6394 getValue(I.getArgOperand(0)), Flags)); 6395 return; 6396 } 6397 case Intrinsic::fma: 6398 setValue(&I, DAG.getNode( 6399 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6400 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6401 getValue(I.getArgOperand(2)), Flags)); 6402 return; 6403 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6404 case Intrinsic::INTRINSIC: 6405 #include "llvm/IR/ConstrainedOps.def" 6406 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6407 return; 6408 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6409 #include "llvm/IR/VPIntrinsics.def" 6410 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6411 return; 6412 case Intrinsic::fptrunc_round: { 6413 // Get the last argument, the metadata and convert it to an integer in the 6414 // call 6415 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata(); 6416 Optional<RoundingMode> RoundMode = 6417 convertStrToRoundingMode(cast<MDString>(MD)->getString()); 6418 6419 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6420 6421 // Propagate fast-math-flags from IR to node(s). 6422 SDNodeFlags Flags; 6423 Flags.copyFMF(*cast<FPMathOperator>(&I)); 6424 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 6425 6426 SDValue Result; 6427 Result = DAG.getNode( 6428 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)), 6429 DAG.getTargetConstant((int)*RoundMode, sdl, 6430 TLI.getPointerTy(DAG.getDataLayout()))); 6431 setValue(&I, Result); 6432 6433 return; 6434 } 6435 case Intrinsic::fmuladd: { 6436 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6437 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6438 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6439 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6440 getValue(I.getArgOperand(0)).getValueType(), 6441 getValue(I.getArgOperand(0)), 6442 getValue(I.getArgOperand(1)), 6443 getValue(I.getArgOperand(2)), Flags)); 6444 } else { 6445 // TODO: Intrinsic calls should have fast-math-flags. 6446 SDValue Mul = DAG.getNode( 6447 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6448 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6449 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6450 getValue(I.getArgOperand(0)).getValueType(), 6451 Mul, getValue(I.getArgOperand(2)), Flags); 6452 setValue(&I, Add); 6453 } 6454 return; 6455 } 6456 case Intrinsic::convert_to_fp16: 6457 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6458 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6459 getValue(I.getArgOperand(0)), 6460 DAG.getTargetConstant(0, sdl, 6461 MVT::i32)))); 6462 return; 6463 case Intrinsic::convert_from_fp16: 6464 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6465 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6466 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6467 getValue(I.getArgOperand(0))))); 6468 return; 6469 case Intrinsic::fptosi_sat: { 6470 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6471 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 6472 getValue(I.getArgOperand(0)), 6473 DAG.getValueType(VT.getScalarType()))); 6474 return; 6475 } 6476 case Intrinsic::fptoui_sat: { 6477 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6478 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 6479 getValue(I.getArgOperand(0)), 6480 DAG.getValueType(VT.getScalarType()))); 6481 return; 6482 } 6483 case Intrinsic::set_rounding: 6484 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6485 {getRoot(), getValue(I.getArgOperand(0))}); 6486 setValue(&I, Res); 6487 DAG.setRoot(Res.getValue(0)); 6488 return; 6489 case Intrinsic::is_fpclass: { 6490 const DataLayout DLayout = DAG.getDataLayout(); 6491 EVT DestVT = TLI.getValueType(DLayout, I.getType()); 6492 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType()); 6493 unsigned Test = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6494 MachineFunction &MF = DAG.getMachineFunction(); 6495 const Function &F = MF.getFunction(); 6496 SDValue Op = getValue(I.getArgOperand(0)); 6497 SDNodeFlags Flags; 6498 Flags.setNoFPExcept( 6499 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP)); 6500 // If ISD::IS_FPCLASS should be expanded, do it right now, because the 6501 // expansion can use illegal types. Making expansion early allows 6502 // legalizing these types prior to selection. 6503 if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) { 6504 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG); 6505 setValue(&I, Result); 6506 return; 6507 } 6508 6509 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32); 6510 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags); 6511 setValue(&I, V); 6512 return; 6513 } 6514 case Intrinsic::pcmarker: { 6515 SDValue Tmp = getValue(I.getArgOperand(0)); 6516 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6517 return; 6518 } 6519 case Intrinsic::readcyclecounter: { 6520 SDValue Op = getRoot(); 6521 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6522 DAG.getVTList(MVT::i64, MVT::Other), Op); 6523 setValue(&I, Res); 6524 DAG.setRoot(Res.getValue(1)); 6525 return; 6526 } 6527 case Intrinsic::bitreverse: 6528 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6529 getValue(I.getArgOperand(0)).getValueType(), 6530 getValue(I.getArgOperand(0)))); 6531 return; 6532 case Intrinsic::bswap: 6533 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6534 getValue(I.getArgOperand(0)).getValueType(), 6535 getValue(I.getArgOperand(0)))); 6536 return; 6537 case Intrinsic::cttz: { 6538 SDValue Arg = getValue(I.getArgOperand(0)); 6539 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6540 EVT Ty = Arg.getValueType(); 6541 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6542 sdl, Ty, Arg)); 6543 return; 6544 } 6545 case Intrinsic::ctlz: { 6546 SDValue Arg = getValue(I.getArgOperand(0)); 6547 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6548 EVT Ty = Arg.getValueType(); 6549 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6550 sdl, Ty, Arg)); 6551 return; 6552 } 6553 case Intrinsic::ctpop: { 6554 SDValue Arg = getValue(I.getArgOperand(0)); 6555 EVT Ty = Arg.getValueType(); 6556 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6557 return; 6558 } 6559 case Intrinsic::fshl: 6560 case Intrinsic::fshr: { 6561 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6562 SDValue X = getValue(I.getArgOperand(0)); 6563 SDValue Y = getValue(I.getArgOperand(1)); 6564 SDValue Z = getValue(I.getArgOperand(2)); 6565 EVT VT = X.getValueType(); 6566 6567 if (X == Y) { 6568 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6569 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6570 } else { 6571 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6572 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6573 } 6574 return; 6575 } 6576 case Intrinsic::sadd_sat: { 6577 SDValue Op1 = getValue(I.getArgOperand(0)); 6578 SDValue Op2 = getValue(I.getArgOperand(1)); 6579 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6580 return; 6581 } 6582 case Intrinsic::uadd_sat: { 6583 SDValue Op1 = getValue(I.getArgOperand(0)); 6584 SDValue Op2 = getValue(I.getArgOperand(1)); 6585 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6586 return; 6587 } 6588 case Intrinsic::ssub_sat: { 6589 SDValue Op1 = getValue(I.getArgOperand(0)); 6590 SDValue Op2 = getValue(I.getArgOperand(1)); 6591 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6592 return; 6593 } 6594 case Intrinsic::usub_sat: { 6595 SDValue Op1 = getValue(I.getArgOperand(0)); 6596 SDValue Op2 = getValue(I.getArgOperand(1)); 6597 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6598 return; 6599 } 6600 case Intrinsic::sshl_sat: { 6601 SDValue Op1 = getValue(I.getArgOperand(0)); 6602 SDValue Op2 = getValue(I.getArgOperand(1)); 6603 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6604 return; 6605 } 6606 case Intrinsic::ushl_sat: { 6607 SDValue Op1 = getValue(I.getArgOperand(0)); 6608 SDValue Op2 = getValue(I.getArgOperand(1)); 6609 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6610 return; 6611 } 6612 case Intrinsic::smul_fix: 6613 case Intrinsic::umul_fix: 6614 case Intrinsic::smul_fix_sat: 6615 case Intrinsic::umul_fix_sat: { 6616 SDValue Op1 = getValue(I.getArgOperand(0)); 6617 SDValue Op2 = getValue(I.getArgOperand(1)); 6618 SDValue Op3 = getValue(I.getArgOperand(2)); 6619 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6620 Op1.getValueType(), Op1, Op2, Op3)); 6621 return; 6622 } 6623 case Intrinsic::sdiv_fix: 6624 case Intrinsic::udiv_fix: 6625 case Intrinsic::sdiv_fix_sat: 6626 case Intrinsic::udiv_fix_sat: { 6627 SDValue Op1 = getValue(I.getArgOperand(0)); 6628 SDValue Op2 = getValue(I.getArgOperand(1)); 6629 SDValue Op3 = getValue(I.getArgOperand(2)); 6630 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6631 Op1, Op2, Op3, DAG, TLI)); 6632 return; 6633 } 6634 case Intrinsic::smax: { 6635 SDValue Op1 = getValue(I.getArgOperand(0)); 6636 SDValue Op2 = getValue(I.getArgOperand(1)); 6637 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6638 return; 6639 } 6640 case Intrinsic::smin: { 6641 SDValue Op1 = getValue(I.getArgOperand(0)); 6642 SDValue Op2 = getValue(I.getArgOperand(1)); 6643 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6644 return; 6645 } 6646 case Intrinsic::umax: { 6647 SDValue Op1 = getValue(I.getArgOperand(0)); 6648 SDValue Op2 = getValue(I.getArgOperand(1)); 6649 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6650 return; 6651 } 6652 case Intrinsic::umin: { 6653 SDValue Op1 = getValue(I.getArgOperand(0)); 6654 SDValue Op2 = getValue(I.getArgOperand(1)); 6655 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6656 return; 6657 } 6658 case Intrinsic::abs: { 6659 // TODO: Preserve "int min is poison" arg in SDAG? 6660 SDValue Op1 = getValue(I.getArgOperand(0)); 6661 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6662 return; 6663 } 6664 case Intrinsic::stacksave: { 6665 SDValue Op = getRoot(); 6666 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6667 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6668 setValue(&I, Res); 6669 DAG.setRoot(Res.getValue(1)); 6670 return; 6671 } 6672 case Intrinsic::stackrestore: 6673 Res = getValue(I.getArgOperand(0)); 6674 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6675 return; 6676 case Intrinsic::get_dynamic_area_offset: { 6677 SDValue Op = getRoot(); 6678 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6679 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6680 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6681 // target. 6682 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 6683 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6684 " intrinsic!"); 6685 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6686 Op); 6687 DAG.setRoot(Op); 6688 setValue(&I, Res); 6689 return; 6690 } 6691 case Intrinsic::stackguard: { 6692 MachineFunction &MF = DAG.getMachineFunction(); 6693 const Module &M = *MF.getFunction().getParent(); 6694 SDValue Chain = getRoot(); 6695 if (TLI.useLoadStackGuardNode()) { 6696 Res = getLoadStackGuard(DAG, sdl, Chain); 6697 } else { 6698 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6699 const Value *Global = TLI.getSDagStackGuard(M); 6700 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType()); 6701 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6702 MachinePointerInfo(Global, 0), Align, 6703 MachineMemOperand::MOVolatile); 6704 } 6705 if (TLI.useStackGuardXorFP()) 6706 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6707 DAG.setRoot(Chain); 6708 setValue(&I, Res); 6709 return; 6710 } 6711 case Intrinsic::stackprotector: { 6712 // Emit code into the DAG to store the stack guard onto the stack. 6713 MachineFunction &MF = DAG.getMachineFunction(); 6714 MachineFrameInfo &MFI = MF.getFrameInfo(); 6715 SDValue Src, Chain = getRoot(); 6716 6717 if (TLI.useLoadStackGuardNode()) 6718 Src = getLoadStackGuard(DAG, sdl, Chain); 6719 else 6720 Src = getValue(I.getArgOperand(0)); // The guard's value. 6721 6722 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6723 6724 int FI = FuncInfo.StaticAllocaMap[Slot]; 6725 MFI.setStackProtectorIndex(FI); 6726 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6727 6728 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6729 6730 // Store the stack protector onto the stack. 6731 Res = DAG.getStore( 6732 Chain, sdl, Src, FIN, 6733 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 6734 MaybeAlign(), MachineMemOperand::MOVolatile); 6735 setValue(&I, Res); 6736 DAG.setRoot(Res); 6737 return; 6738 } 6739 case Intrinsic::objectsize: 6740 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6741 6742 case Intrinsic::is_constant: 6743 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6744 6745 case Intrinsic::annotation: 6746 case Intrinsic::ptr_annotation: 6747 case Intrinsic::launder_invariant_group: 6748 case Intrinsic::strip_invariant_group: 6749 // Drop the intrinsic, but forward the value 6750 setValue(&I, getValue(I.getOperand(0))); 6751 return; 6752 6753 case Intrinsic::assume: 6754 case Intrinsic::experimental_noalias_scope_decl: 6755 case Intrinsic::var_annotation: 6756 case Intrinsic::sideeffect: 6757 // Discard annotate attributes, noalias scope declarations, assumptions, and 6758 // artificial side-effects. 6759 return; 6760 6761 case Intrinsic::codeview_annotation: { 6762 // Emit a label associated with this metadata. 6763 MachineFunction &MF = DAG.getMachineFunction(); 6764 MCSymbol *Label = 6765 MF.getMMI().getContext().createTempSymbol("annotation", true); 6766 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6767 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6768 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6769 DAG.setRoot(Res); 6770 return; 6771 } 6772 6773 case Intrinsic::init_trampoline: { 6774 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6775 6776 SDValue Ops[6]; 6777 Ops[0] = getRoot(); 6778 Ops[1] = getValue(I.getArgOperand(0)); 6779 Ops[2] = getValue(I.getArgOperand(1)); 6780 Ops[3] = getValue(I.getArgOperand(2)); 6781 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6782 Ops[5] = DAG.getSrcValue(F); 6783 6784 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6785 6786 DAG.setRoot(Res); 6787 return; 6788 } 6789 case Intrinsic::adjust_trampoline: 6790 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6791 TLI.getPointerTy(DAG.getDataLayout()), 6792 getValue(I.getArgOperand(0)))); 6793 return; 6794 case Intrinsic::gcroot: { 6795 assert(DAG.getMachineFunction().getFunction().hasGC() && 6796 "only valid in functions with gc specified, enforced by Verifier"); 6797 assert(GFI && "implied by previous"); 6798 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6799 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6800 6801 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6802 GFI->addStackRoot(FI->getIndex(), TypeMap); 6803 return; 6804 } 6805 case Intrinsic::gcread: 6806 case Intrinsic::gcwrite: 6807 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6808 case Intrinsic::flt_rounds: 6809 Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot()); 6810 setValue(&I, Res); 6811 DAG.setRoot(Res.getValue(1)); 6812 return; 6813 6814 case Intrinsic::expect: 6815 // Just replace __builtin_expect(exp, c) with EXP. 6816 setValue(&I, getValue(I.getArgOperand(0))); 6817 return; 6818 6819 case Intrinsic::ubsantrap: 6820 case Intrinsic::debugtrap: 6821 case Intrinsic::trap: { 6822 StringRef TrapFuncName = 6823 I.getAttributes().getFnAttr("trap-func-name").getValueAsString(); 6824 if (TrapFuncName.empty()) { 6825 switch (Intrinsic) { 6826 case Intrinsic::trap: 6827 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 6828 break; 6829 case Intrinsic::debugtrap: 6830 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 6831 break; 6832 case Intrinsic::ubsantrap: 6833 DAG.setRoot(DAG.getNode( 6834 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 6835 DAG.getTargetConstant( 6836 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 6837 MVT::i32))); 6838 break; 6839 default: llvm_unreachable("unknown trap intrinsic"); 6840 } 6841 return; 6842 } 6843 TargetLowering::ArgListTy Args; 6844 if (Intrinsic == Intrinsic::ubsantrap) { 6845 Args.push_back(TargetLoweringBase::ArgListEntry()); 6846 Args[0].Val = I.getArgOperand(0); 6847 Args[0].Node = getValue(Args[0].Val); 6848 Args[0].Ty = Args[0].Val->getType(); 6849 } 6850 6851 TargetLowering::CallLoweringInfo CLI(DAG); 6852 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6853 CallingConv::C, I.getType(), 6854 DAG.getExternalSymbol(TrapFuncName.data(), 6855 TLI.getPointerTy(DAG.getDataLayout())), 6856 std::move(Args)); 6857 6858 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6859 DAG.setRoot(Result.second); 6860 return; 6861 } 6862 6863 case Intrinsic::uadd_with_overflow: 6864 case Intrinsic::sadd_with_overflow: 6865 case Intrinsic::usub_with_overflow: 6866 case Intrinsic::ssub_with_overflow: 6867 case Intrinsic::umul_with_overflow: 6868 case Intrinsic::smul_with_overflow: { 6869 ISD::NodeType Op; 6870 switch (Intrinsic) { 6871 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6872 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6873 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6874 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6875 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6876 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6877 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6878 } 6879 SDValue Op1 = getValue(I.getArgOperand(0)); 6880 SDValue Op2 = getValue(I.getArgOperand(1)); 6881 6882 EVT ResultVT = Op1.getValueType(); 6883 EVT OverflowVT = MVT::i1; 6884 if (ResultVT.isVector()) 6885 OverflowVT = EVT::getVectorVT( 6886 *Context, OverflowVT, ResultVT.getVectorElementCount()); 6887 6888 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6889 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6890 return; 6891 } 6892 case Intrinsic::prefetch: { 6893 SDValue Ops[5]; 6894 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6895 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6896 Ops[0] = DAG.getRoot(); 6897 Ops[1] = getValue(I.getArgOperand(0)); 6898 Ops[2] = getValue(I.getArgOperand(1)); 6899 Ops[3] = getValue(I.getArgOperand(2)); 6900 Ops[4] = getValue(I.getArgOperand(3)); 6901 SDValue Result = DAG.getMemIntrinsicNode( 6902 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 6903 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 6904 /* align */ None, Flags); 6905 6906 // Chain the prefetch in parallell with any pending loads, to stay out of 6907 // the way of later optimizations. 6908 PendingLoads.push_back(Result); 6909 Result = getRoot(); 6910 DAG.setRoot(Result); 6911 return; 6912 } 6913 case Intrinsic::lifetime_start: 6914 case Intrinsic::lifetime_end: { 6915 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6916 // Stack coloring is not enabled in O0, discard region information. 6917 if (TM.getOptLevel() == CodeGenOpt::None) 6918 return; 6919 6920 const int64_t ObjectSize = 6921 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6922 Value *const ObjectPtr = I.getArgOperand(1); 6923 SmallVector<const Value *, 4> Allocas; 6924 getUnderlyingObjects(ObjectPtr, Allocas); 6925 6926 for (const Value *Alloca : Allocas) { 6927 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 6928 6929 // Could not find an Alloca. 6930 if (!LifetimeObject) 6931 continue; 6932 6933 // First check that the Alloca is static, otherwise it won't have a 6934 // valid frame index. 6935 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6936 if (SI == FuncInfo.StaticAllocaMap.end()) 6937 return; 6938 6939 const int FrameIndex = SI->second; 6940 int64_t Offset; 6941 if (GetPointerBaseWithConstantOffset( 6942 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6943 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6944 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6945 Offset); 6946 DAG.setRoot(Res); 6947 } 6948 return; 6949 } 6950 case Intrinsic::pseudoprobe: { 6951 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 6952 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6953 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 6954 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 6955 DAG.setRoot(Res); 6956 return; 6957 } 6958 case Intrinsic::invariant_start: 6959 // Discard region information. 6960 setValue(&I, 6961 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType()))); 6962 return; 6963 case Intrinsic::invariant_end: 6964 // Discard region information. 6965 return; 6966 case Intrinsic::clear_cache: 6967 /// FunctionName may be null. 6968 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6969 lowerCallToExternalSymbol(I, FunctionName); 6970 return; 6971 case Intrinsic::donothing: 6972 case Intrinsic::seh_try_begin: 6973 case Intrinsic::seh_scope_begin: 6974 case Intrinsic::seh_try_end: 6975 case Intrinsic::seh_scope_end: 6976 // ignore 6977 return; 6978 case Intrinsic::experimental_stackmap: 6979 visitStackmap(I); 6980 return; 6981 case Intrinsic::experimental_patchpoint_void: 6982 case Intrinsic::experimental_patchpoint_i64: 6983 visitPatchpoint(I); 6984 return; 6985 case Intrinsic::experimental_gc_statepoint: 6986 LowerStatepoint(cast<GCStatepointInst>(I)); 6987 return; 6988 case Intrinsic::experimental_gc_result: 6989 visitGCResult(cast<GCResultInst>(I)); 6990 return; 6991 case Intrinsic::experimental_gc_relocate: 6992 visitGCRelocate(cast<GCRelocateInst>(I)); 6993 return; 6994 case Intrinsic::instrprof_cover: 6995 llvm_unreachable("instrprof failed to lower a cover"); 6996 case Intrinsic::instrprof_increment: 6997 llvm_unreachable("instrprof failed to lower an increment"); 6998 case Intrinsic::instrprof_value_profile: 6999 llvm_unreachable("instrprof failed to lower a value profiling call"); 7000 case Intrinsic::localescape: { 7001 MachineFunction &MF = DAG.getMachineFunction(); 7002 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 7003 7004 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 7005 // is the same on all targets. 7006 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) { 7007 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 7008 if (isa<ConstantPointerNull>(Arg)) 7009 continue; // Skip null pointers. They represent a hole in index space. 7010 AllocaInst *Slot = cast<AllocaInst>(Arg); 7011 assert(FuncInfo.StaticAllocaMap.count(Slot) && 7012 "can only escape static allocas"); 7013 int FI = FuncInfo.StaticAllocaMap[Slot]; 7014 MCSymbol *FrameAllocSym = 7015 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7016 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 7017 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 7018 TII->get(TargetOpcode::LOCAL_ESCAPE)) 7019 .addSym(FrameAllocSym) 7020 .addFrameIndex(FI); 7021 } 7022 7023 return; 7024 } 7025 7026 case Intrinsic::localrecover: { 7027 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 7028 MachineFunction &MF = DAG.getMachineFunction(); 7029 7030 // Get the symbol that defines the frame offset. 7031 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 7032 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 7033 unsigned IdxVal = 7034 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 7035 MCSymbol *FrameAllocSym = 7036 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7037 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 7038 7039 Value *FP = I.getArgOperand(1); 7040 SDValue FPVal = getValue(FP); 7041 EVT PtrVT = FPVal.getValueType(); 7042 7043 // Create a MCSymbol for the label to avoid any target lowering 7044 // that would make this PC relative. 7045 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 7046 SDValue OffsetVal = 7047 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 7048 7049 // Add the offset to the FP. 7050 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 7051 setValue(&I, Add); 7052 7053 return; 7054 } 7055 7056 case Intrinsic::eh_exceptionpointer: 7057 case Intrinsic::eh_exceptioncode: { 7058 // Get the exception pointer vreg, copy from it, and resize it to fit. 7059 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 7060 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 7061 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 7062 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 7063 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT); 7064 if (Intrinsic == Intrinsic::eh_exceptioncode) 7065 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32); 7066 setValue(&I, N); 7067 return; 7068 } 7069 case Intrinsic::xray_customevent: { 7070 // Here we want to make sure that the intrinsic behaves as if it has a 7071 // specific calling convention, and only for x86_64. 7072 // FIXME: Support other platforms later. 7073 const auto &Triple = DAG.getTarget().getTargetTriple(); 7074 if (Triple.getArch() != Triple::x86_64) 7075 return; 7076 7077 SmallVector<SDValue, 8> Ops; 7078 7079 // We want to say that we always want the arguments in registers. 7080 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 7081 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 7082 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7083 SDValue Chain = getRoot(); 7084 Ops.push_back(LogEntryVal); 7085 Ops.push_back(StrSizeVal); 7086 Ops.push_back(Chain); 7087 7088 // We need to enforce the calling convention for the callsite, so that 7089 // argument ordering is enforced correctly, and that register allocation can 7090 // see that some registers may be assumed clobbered and have to preserve 7091 // them across calls to the intrinsic. 7092 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 7093 sdl, NodeTys, Ops); 7094 SDValue patchableNode = SDValue(MN, 0); 7095 DAG.setRoot(patchableNode); 7096 setValue(&I, patchableNode); 7097 return; 7098 } 7099 case Intrinsic::xray_typedevent: { 7100 // Here we want to make sure that the intrinsic behaves as if it has a 7101 // specific calling convention, and only for x86_64. 7102 // FIXME: Support other platforms later. 7103 const auto &Triple = DAG.getTarget().getTargetTriple(); 7104 if (Triple.getArch() != Triple::x86_64) 7105 return; 7106 7107 SmallVector<SDValue, 8> Ops; 7108 7109 // We want to say that we always want the arguments in registers. 7110 // It's unclear to me how manipulating the selection DAG here forces callers 7111 // to provide arguments in registers instead of on the stack. 7112 SDValue LogTypeId = getValue(I.getArgOperand(0)); 7113 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 7114 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 7115 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7116 SDValue Chain = getRoot(); 7117 Ops.push_back(LogTypeId); 7118 Ops.push_back(LogEntryVal); 7119 Ops.push_back(StrSizeVal); 7120 Ops.push_back(Chain); 7121 7122 // We need to enforce the calling convention for the callsite, so that 7123 // argument ordering is enforced correctly, and that register allocation can 7124 // see that some registers may be assumed clobbered and have to preserve 7125 // them across calls to the intrinsic. 7126 MachineSDNode *MN = DAG.getMachineNode( 7127 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops); 7128 SDValue patchableNode = SDValue(MN, 0); 7129 DAG.setRoot(patchableNode); 7130 setValue(&I, patchableNode); 7131 return; 7132 } 7133 case Intrinsic::experimental_deoptimize: 7134 LowerDeoptimizeCall(&I); 7135 return; 7136 case Intrinsic::experimental_stepvector: 7137 visitStepVector(I); 7138 return; 7139 case Intrinsic::vector_reduce_fadd: 7140 case Intrinsic::vector_reduce_fmul: 7141 case Intrinsic::vector_reduce_add: 7142 case Intrinsic::vector_reduce_mul: 7143 case Intrinsic::vector_reduce_and: 7144 case Intrinsic::vector_reduce_or: 7145 case Intrinsic::vector_reduce_xor: 7146 case Intrinsic::vector_reduce_smax: 7147 case Intrinsic::vector_reduce_smin: 7148 case Intrinsic::vector_reduce_umax: 7149 case Intrinsic::vector_reduce_umin: 7150 case Intrinsic::vector_reduce_fmax: 7151 case Intrinsic::vector_reduce_fmin: 7152 visitVectorReduce(I, Intrinsic); 7153 return; 7154 7155 case Intrinsic::icall_branch_funnel: { 7156 SmallVector<SDValue, 16> Ops; 7157 Ops.push_back(getValue(I.getArgOperand(0))); 7158 7159 int64_t Offset; 7160 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7161 I.getArgOperand(1), Offset, DAG.getDataLayout())); 7162 if (!Base) 7163 report_fatal_error( 7164 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7165 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0)); 7166 7167 struct BranchFunnelTarget { 7168 int64_t Offset; 7169 SDValue Target; 7170 }; 7171 SmallVector<BranchFunnelTarget, 8> Targets; 7172 7173 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) { 7174 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7175 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7176 if (ElemBase != Base) 7177 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7178 "to the same GlobalValue"); 7179 7180 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7181 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7182 if (!GA) 7183 report_fatal_error( 7184 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7185 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7186 GA->getGlobal(), sdl, Val.getValueType(), 7187 GA->getOffset())}); 7188 } 7189 llvm::sort(Targets, 7190 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7191 return T1.Offset < T2.Offset; 7192 }); 7193 7194 for (auto &T : Targets) { 7195 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32)); 7196 Ops.push_back(T.Target); 7197 } 7198 7199 Ops.push_back(DAG.getRoot()); // Chain 7200 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl, 7201 MVT::Other, Ops), 7202 0); 7203 DAG.setRoot(N); 7204 setValue(&I, N); 7205 HasTailCall = true; 7206 return; 7207 } 7208 7209 case Intrinsic::wasm_landingpad_index: 7210 // Information this intrinsic contained has been transferred to 7211 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7212 // delete it now. 7213 return; 7214 7215 case Intrinsic::aarch64_settag: 7216 case Intrinsic::aarch64_settag_zero: { 7217 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7218 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7219 SDValue Val = TSI.EmitTargetCodeForSetTag( 7220 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)), 7221 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7222 ZeroMemory); 7223 DAG.setRoot(Val); 7224 setValue(&I, Val); 7225 return; 7226 } 7227 case Intrinsic::ptrmask: { 7228 SDValue Ptr = getValue(I.getOperand(0)); 7229 SDValue Const = getValue(I.getOperand(1)); 7230 7231 EVT PtrVT = Ptr.getValueType(); 7232 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, 7233 DAG.getZExtOrTrunc(Const, sdl, PtrVT))); 7234 return; 7235 } 7236 case Intrinsic::threadlocal_address: { 7237 setValue(&I, getValue(I.getOperand(0))); 7238 return; 7239 } 7240 case Intrinsic::get_active_lane_mask: { 7241 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7242 SDValue Index = getValue(I.getOperand(0)); 7243 EVT ElementVT = Index.getValueType(); 7244 7245 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) { 7246 visitTargetIntrinsic(I, Intrinsic); 7247 return; 7248 } 7249 7250 SDValue TripCount = getValue(I.getOperand(1)); 7251 auto VecTy = CCVT.changeVectorElementType(ElementVT); 7252 7253 SDValue VectorIndex, VectorTripCount; 7254 if (VecTy.isScalableVector()) { 7255 VectorIndex = DAG.getSplatVector(VecTy, sdl, Index); 7256 VectorTripCount = DAG.getSplatVector(VecTy, sdl, TripCount); 7257 } else { 7258 VectorIndex = DAG.getSplatBuildVector(VecTy, sdl, Index); 7259 VectorTripCount = DAG.getSplatBuildVector(VecTy, sdl, TripCount); 7260 } 7261 SDValue VectorStep = DAG.getStepVector(sdl, VecTy); 7262 SDValue VectorInduction = DAG.getNode( 7263 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep); 7264 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction, 7265 VectorTripCount, ISD::CondCode::SETULT); 7266 setValue(&I, SetCC); 7267 return; 7268 } 7269 case Intrinsic::vector_insert: { 7270 SDValue Vec = getValue(I.getOperand(0)); 7271 SDValue SubVec = getValue(I.getOperand(1)); 7272 SDValue Index = getValue(I.getOperand(2)); 7273 7274 // The intrinsic's index type is i64, but the SDNode requires an index type 7275 // suitable for the target. Convert the index as required. 7276 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7277 if (Index.getValueType() != VectorIdxTy) 7278 Index = DAG.getVectorIdxConstant( 7279 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7280 7281 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7282 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec, 7283 Index)); 7284 return; 7285 } 7286 case Intrinsic::vector_extract: { 7287 SDValue Vec = getValue(I.getOperand(0)); 7288 SDValue Index = getValue(I.getOperand(1)); 7289 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7290 7291 // The intrinsic's index type is i64, but the SDNode requires an index type 7292 // suitable for the target. Convert the index as required. 7293 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7294 if (Index.getValueType() != VectorIdxTy) 7295 Index = DAG.getVectorIdxConstant( 7296 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7297 7298 setValue(&I, 7299 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index)); 7300 return; 7301 } 7302 case Intrinsic::experimental_vector_reverse: 7303 visitVectorReverse(I); 7304 return; 7305 case Intrinsic::experimental_vector_splice: 7306 visitVectorSplice(I); 7307 return; 7308 } 7309 } 7310 7311 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7312 const ConstrainedFPIntrinsic &FPI) { 7313 SDLoc sdl = getCurSDLoc(); 7314 7315 // We do not need to serialize constrained FP intrinsics against 7316 // each other or against (nonvolatile) loads, so they can be 7317 // chained like loads. 7318 SDValue Chain = DAG.getRoot(); 7319 SmallVector<SDValue, 4> Opers; 7320 Opers.push_back(Chain); 7321 if (FPI.isUnaryOp()) { 7322 Opers.push_back(getValue(FPI.getArgOperand(0))); 7323 } else if (FPI.isTernaryOp()) { 7324 Opers.push_back(getValue(FPI.getArgOperand(0))); 7325 Opers.push_back(getValue(FPI.getArgOperand(1))); 7326 Opers.push_back(getValue(FPI.getArgOperand(2))); 7327 } else { 7328 Opers.push_back(getValue(FPI.getArgOperand(0))); 7329 Opers.push_back(getValue(FPI.getArgOperand(1))); 7330 } 7331 7332 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7333 assert(Result.getNode()->getNumValues() == 2); 7334 7335 // Push node to the appropriate list so that future instructions can be 7336 // chained up correctly. 7337 SDValue OutChain = Result.getValue(1); 7338 switch (EB) { 7339 case fp::ExceptionBehavior::ebIgnore: 7340 // The only reason why ebIgnore nodes still need to be chained is that 7341 // they might depend on the current rounding mode, and therefore must 7342 // not be moved across instruction that may change that mode. 7343 [[fallthrough]]; 7344 case fp::ExceptionBehavior::ebMayTrap: 7345 // These must not be moved across calls or instructions that may change 7346 // floating-point exception masks. 7347 PendingConstrainedFP.push_back(OutChain); 7348 break; 7349 case fp::ExceptionBehavior::ebStrict: 7350 // These must not be moved across calls or instructions that may change 7351 // floating-point exception masks or read floating-point exception flags. 7352 // In addition, they cannot be optimized out even if unused. 7353 PendingConstrainedFPStrict.push_back(OutChain); 7354 break; 7355 } 7356 }; 7357 7358 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7359 EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType()); 7360 SDVTList VTs = DAG.getVTList(VT, MVT::Other); 7361 fp::ExceptionBehavior EB = *FPI.getExceptionBehavior(); 7362 7363 SDNodeFlags Flags; 7364 if (EB == fp::ExceptionBehavior::ebIgnore) 7365 Flags.setNoFPExcept(true); 7366 7367 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7368 Flags.copyFMF(*FPOp); 7369 7370 unsigned Opcode; 7371 switch (FPI.getIntrinsicID()) { 7372 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7373 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7374 case Intrinsic::INTRINSIC: \ 7375 Opcode = ISD::STRICT_##DAGN; \ 7376 break; 7377 #include "llvm/IR/ConstrainedOps.def" 7378 case Intrinsic::experimental_constrained_fmuladd: { 7379 Opcode = ISD::STRICT_FMA; 7380 // Break fmuladd into fmul and fadd. 7381 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7382 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 7383 Opers.pop_back(); 7384 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7385 pushOutChain(Mul, EB); 7386 Opcode = ISD::STRICT_FADD; 7387 Opers.clear(); 7388 Opers.push_back(Mul.getValue(1)); 7389 Opers.push_back(Mul.getValue(0)); 7390 Opers.push_back(getValue(FPI.getArgOperand(2))); 7391 } 7392 break; 7393 } 7394 } 7395 7396 // A few strict DAG nodes carry additional operands that are not 7397 // set up by the default code above. 7398 switch (Opcode) { 7399 default: break; 7400 case ISD::STRICT_FP_ROUND: 7401 Opers.push_back( 7402 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7403 break; 7404 case ISD::STRICT_FSETCC: 7405 case ISD::STRICT_FSETCCS: { 7406 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7407 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 7408 if (TM.Options.NoNaNsFPMath) 7409 Condition = getFCmpCodeWithoutNaN(Condition); 7410 Opers.push_back(DAG.getCondCode(Condition)); 7411 break; 7412 } 7413 } 7414 7415 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7416 pushOutChain(Result, EB); 7417 7418 SDValue FPResult = Result.getValue(0); 7419 setValue(&FPI, FPResult); 7420 } 7421 7422 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 7423 Optional<unsigned> ResOPC; 7424 switch (VPIntrin.getIntrinsicID()) { 7425 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \ 7426 case Intrinsic::VPID: \ 7427 ResOPC = ISD::VPSD; \ 7428 break; 7429 #include "llvm/IR/VPIntrinsics.def" 7430 } 7431 7432 if (!ResOPC) 7433 llvm_unreachable( 7434 "Inconsistency: no SDNode available for this VPIntrinsic!"); 7435 7436 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD || 7437 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) { 7438 if (VPIntrin.getFastMathFlags().allowReassoc()) 7439 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD 7440 : ISD::VP_REDUCE_FMUL; 7441 } 7442 7443 return *ResOPC; 7444 } 7445 7446 void SelectionDAGBuilder::visitVPLoad(const VPIntrinsic &VPIntrin, EVT VT, 7447 SmallVector<SDValue, 7> &OpValues) { 7448 SDLoc DL = getCurSDLoc(); 7449 Value *PtrOperand = VPIntrin.getArgOperand(0); 7450 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7451 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7452 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7453 SDValue LD; 7454 bool AddToChain = true; 7455 // Do not serialize variable-length loads of constant memory with 7456 // anything. 7457 if (!Alignment) 7458 Alignment = DAG.getEVTAlign(VT); 7459 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7460 AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7461 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7462 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7463 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7464 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7465 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2], 7466 MMO, false /*IsExpanding */); 7467 if (AddToChain) 7468 PendingLoads.push_back(LD.getValue(1)); 7469 setValue(&VPIntrin, LD); 7470 } 7471 7472 void SelectionDAGBuilder::visitVPGather(const VPIntrinsic &VPIntrin, EVT VT, 7473 SmallVector<SDValue, 7> &OpValues) { 7474 SDLoc DL = getCurSDLoc(); 7475 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7476 Value *PtrOperand = VPIntrin.getArgOperand(0); 7477 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7478 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7479 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7480 SDValue LD; 7481 if (!Alignment) 7482 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7483 unsigned AS = 7484 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7485 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7486 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 7487 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7488 SDValue Base, Index, Scale; 7489 ISD::MemIndexType IndexType; 7490 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7491 this, VPIntrin.getParent(), 7492 VT.getScalarStoreSize()); 7493 if (!UniformBase) { 7494 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7495 Index = getValue(PtrOperand); 7496 IndexType = ISD::SIGNED_SCALED; 7497 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7498 } 7499 EVT IdxVT = Index.getValueType(); 7500 EVT EltTy = IdxVT.getVectorElementType(); 7501 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7502 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7503 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7504 } 7505 LD = DAG.getGatherVP( 7506 DAG.getVTList(VT, MVT::Other), VT, DL, 7507 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO, 7508 IndexType); 7509 PendingLoads.push_back(LD.getValue(1)); 7510 setValue(&VPIntrin, LD); 7511 } 7512 7513 void SelectionDAGBuilder::visitVPStore(const VPIntrinsic &VPIntrin, 7514 SmallVector<SDValue, 7> &OpValues) { 7515 SDLoc DL = getCurSDLoc(); 7516 Value *PtrOperand = VPIntrin.getArgOperand(1); 7517 EVT VT = OpValues[0].getValueType(); 7518 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7519 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7520 SDValue ST; 7521 if (!Alignment) 7522 Alignment = DAG.getEVTAlign(VT); 7523 SDValue Ptr = OpValues[1]; 7524 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 7525 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7526 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7527 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7528 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset, 7529 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED, 7530 /* IsTruncating */ false, /*IsCompressing*/ false); 7531 DAG.setRoot(ST); 7532 setValue(&VPIntrin, ST); 7533 } 7534 7535 void SelectionDAGBuilder::visitVPScatter(const VPIntrinsic &VPIntrin, 7536 SmallVector<SDValue, 7> &OpValues) { 7537 SDLoc DL = getCurSDLoc(); 7538 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7539 Value *PtrOperand = VPIntrin.getArgOperand(1); 7540 EVT VT = OpValues[0].getValueType(); 7541 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7542 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7543 SDValue ST; 7544 if (!Alignment) 7545 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7546 unsigned AS = 7547 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7548 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7549 MachinePointerInfo(AS), MachineMemOperand::MOStore, 7550 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7551 SDValue Base, Index, Scale; 7552 ISD::MemIndexType IndexType; 7553 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7554 this, VPIntrin.getParent(), 7555 VT.getScalarStoreSize()); 7556 if (!UniformBase) { 7557 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7558 Index = getValue(PtrOperand); 7559 IndexType = ISD::SIGNED_SCALED; 7560 Scale = 7561 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7562 } 7563 EVT IdxVT = Index.getValueType(); 7564 EVT EltTy = IdxVT.getVectorElementType(); 7565 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7566 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7567 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7568 } 7569 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL, 7570 {getMemoryRoot(), OpValues[0], Base, Index, Scale, 7571 OpValues[2], OpValues[3]}, 7572 MMO, IndexType); 7573 DAG.setRoot(ST); 7574 setValue(&VPIntrin, ST); 7575 } 7576 7577 void SelectionDAGBuilder::visitVPStridedLoad( 7578 const VPIntrinsic &VPIntrin, EVT VT, SmallVectorImpl<SDValue> &OpValues) { 7579 SDLoc DL = getCurSDLoc(); 7580 Value *PtrOperand = VPIntrin.getArgOperand(0); 7581 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7582 if (!Alignment) 7583 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7584 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7585 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7586 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7587 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7588 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7589 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7590 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7591 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7592 7593 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], 7594 OpValues[2], OpValues[3], MMO, 7595 false /*IsExpanding*/); 7596 7597 if (AddToChain) 7598 PendingLoads.push_back(LD.getValue(1)); 7599 setValue(&VPIntrin, LD); 7600 } 7601 7602 void SelectionDAGBuilder::visitVPStridedStore( 7603 const VPIntrinsic &VPIntrin, SmallVectorImpl<SDValue> &OpValues) { 7604 SDLoc DL = getCurSDLoc(); 7605 Value *PtrOperand = VPIntrin.getArgOperand(1); 7606 EVT VT = OpValues[0].getValueType(); 7607 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7608 if (!Alignment) 7609 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7610 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7611 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7612 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7613 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7614 7615 SDValue ST = DAG.getStridedStoreVP( 7616 getMemoryRoot(), DL, OpValues[0], OpValues[1], 7617 DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3], 7618 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false, 7619 /*IsCompressing*/ false); 7620 7621 DAG.setRoot(ST); 7622 setValue(&VPIntrin, ST); 7623 } 7624 7625 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) { 7626 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7627 SDLoc DL = getCurSDLoc(); 7628 7629 ISD::CondCode Condition; 7630 CmpInst::Predicate CondCode = VPIntrin.getPredicate(); 7631 bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy(); 7632 if (IsFP) { 7633 // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan) 7634 // flags, but calls that don't return floating-point types can't be 7635 // FPMathOperators, like vp.fcmp. This affects constrained fcmp too. 7636 Condition = getFCmpCondCode(CondCode); 7637 if (TM.Options.NoNaNsFPMath) 7638 Condition = getFCmpCodeWithoutNaN(Condition); 7639 } else { 7640 Condition = getICmpCondCode(CondCode); 7641 } 7642 7643 SDValue Op1 = getValue(VPIntrin.getOperand(0)); 7644 SDValue Op2 = getValue(VPIntrin.getOperand(1)); 7645 // #2 is the condition code 7646 SDValue MaskOp = getValue(VPIntrin.getOperand(3)); 7647 SDValue EVL = getValue(VPIntrin.getOperand(4)); 7648 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7649 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7650 "Unexpected target EVL type"); 7651 EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL); 7652 7653 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7654 VPIntrin.getType()); 7655 setValue(&VPIntrin, 7656 DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL)); 7657 } 7658 7659 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 7660 const VPIntrinsic &VPIntrin) { 7661 SDLoc DL = getCurSDLoc(); 7662 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 7663 7664 auto IID = VPIntrin.getIntrinsicID(); 7665 7666 if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin)) 7667 return visitVPCmp(*CmpI); 7668 7669 SmallVector<EVT, 4> ValueVTs; 7670 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7671 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 7672 SDVTList VTs = DAG.getVTList(ValueVTs); 7673 7674 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID); 7675 7676 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7677 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7678 "Unexpected target EVL type"); 7679 7680 // Request operands. 7681 SmallVector<SDValue, 7> OpValues; 7682 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) { 7683 auto Op = getValue(VPIntrin.getArgOperand(I)); 7684 if (I == EVLParamPos) 7685 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op); 7686 OpValues.push_back(Op); 7687 } 7688 7689 switch (Opcode) { 7690 default: { 7691 SDNodeFlags SDFlags; 7692 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 7693 SDFlags.copyFMF(*FPMO); 7694 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags); 7695 setValue(&VPIntrin, Result); 7696 break; 7697 } 7698 case ISD::VP_LOAD: 7699 visitVPLoad(VPIntrin, ValueVTs[0], OpValues); 7700 break; 7701 case ISD::VP_GATHER: 7702 visitVPGather(VPIntrin, ValueVTs[0], OpValues); 7703 break; 7704 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: 7705 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues); 7706 break; 7707 case ISD::VP_STORE: 7708 visitVPStore(VPIntrin, OpValues); 7709 break; 7710 case ISD::VP_SCATTER: 7711 visitVPScatter(VPIntrin, OpValues); 7712 break; 7713 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: 7714 visitVPStridedStore(VPIntrin, OpValues); 7715 break; 7716 case ISD::VP_FMULADD: { 7717 assert(OpValues.size() == 5 && "Unexpected number of operands"); 7718 SDNodeFlags SDFlags; 7719 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 7720 SDFlags.copyFMF(*FPMO); 7721 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 7722 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) { 7723 setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags)); 7724 } else { 7725 SDValue Mul = DAG.getNode( 7726 ISD::VP_FMUL, DL, VTs, 7727 {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags); 7728 SDValue Add = 7729 DAG.getNode(ISD::VP_FADD, DL, VTs, 7730 {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags); 7731 setValue(&VPIntrin, Add); 7732 } 7733 break; 7734 } 7735 } 7736 } 7737 7738 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 7739 const BasicBlock *EHPadBB, 7740 MCSymbol *&BeginLabel) { 7741 MachineFunction &MF = DAG.getMachineFunction(); 7742 MachineModuleInfo &MMI = MF.getMMI(); 7743 7744 // Insert a label before the invoke call to mark the try range. This can be 7745 // used to detect deletion of the invoke via the MachineModuleInfo. 7746 BeginLabel = MMI.getContext().createTempSymbol(); 7747 7748 // For SjLj, keep track of which landing pads go with which invokes 7749 // so as to maintain the ordering of pads in the LSDA. 7750 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7751 if (CallSiteIndex) { 7752 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7753 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7754 7755 // Now that the call site is handled, stop tracking it. 7756 MMI.setCurrentCallSite(0); 7757 } 7758 7759 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 7760 } 7761 7762 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 7763 const BasicBlock *EHPadBB, 7764 MCSymbol *BeginLabel) { 7765 assert(BeginLabel && "BeginLabel should've been set"); 7766 7767 MachineFunction &MF = DAG.getMachineFunction(); 7768 MachineModuleInfo &MMI = MF.getMMI(); 7769 7770 // Insert a label at the end of the invoke call to mark the try range. This 7771 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7772 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7773 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 7774 7775 // Inform MachineModuleInfo of range. 7776 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7777 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7778 // actually use outlined funclets and their LSDA info style. 7779 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7780 assert(II && "II should've been set"); 7781 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 7782 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 7783 } else if (!isScopedEHPersonality(Pers)) { 7784 assert(EHPadBB); 7785 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7786 } 7787 7788 return Chain; 7789 } 7790 7791 std::pair<SDValue, SDValue> 7792 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7793 const BasicBlock *EHPadBB) { 7794 MCSymbol *BeginLabel = nullptr; 7795 7796 if (EHPadBB) { 7797 // Both PendingLoads and PendingExports must be flushed here; 7798 // this call might not return. 7799 (void)getRoot(); 7800 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 7801 CLI.setChain(getRoot()); 7802 } 7803 7804 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7805 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7806 7807 assert((CLI.IsTailCall || Result.second.getNode()) && 7808 "Non-null chain expected with non-tail call!"); 7809 assert((Result.second.getNode() || !Result.first.getNode()) && 7810 "Null value expected with tail call!"); 7811 7812 if (!Result.second.getNode()) { 7813 // As a special case, a null chain means that a tail call has been emitted 7814 // and the DAG root is already updated. 7815 HasTailCall = true; 7816 7817 // Since there's no actual continuation from this block, nothing can be 7818 // relying on us setting vregs for them. 7819 PendingExports.clear(); 7820 } else { 7821 DAG.setRoot(Result.second); 7822 } 7823 7824 if (EHPadBB) { 7825 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 7826 BeginLabel)); 7827 } 7828 7829 return Result; 7830 } 7831 7832 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 7833 bool isTailCall, 7834 bool isMustTailCall, 7835 const BasicBlock *EHPadBB) { 7836 auto &DL = DAG.getDataLayout(); 7837 FunctionType *FTy = CB.getFunctionType(); 7838 Type *RetTy = CB.getType(); 7839 7840 TargetLowering::ArgListTy Args; 7841 Args.reserve(CB.arg_size()); 7842 7843 const Value *SwiftErrorVal = nullptr; 7844 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7845 7846 if (isTailCall) { 7847 // Avoid emitting tail calls in functions with the disable-tail-calls 7848 // attribute. 7849 auto *Caller = CB.getParent()->getParent(); 7850 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7851 "true" && !isMustTailCall) 7852 isTailCall = false; 7853 7854 // We can't tail call inside a function with a swifterror argument. Lowering 7855 // does not support this yet. It would have to move into the swifterror 7856 // register before the call. 7857 if (TLI.supportSwiftError() && 7858 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7859 isTailCall = false; 7860 } 7861 7862 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 7863 TargetLowering::ArgListEntry Entry; 7864 const Value *V = *I; 7865 7866 // Skip empty types 7867 if (V->getType()->isEmptyTy()) 7868 continue; 7869 7870 SDValue ArgNode = getValue(V); 7871 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7872 7873 Entry.setAttributes(&CB, I - CB.arg_begin()); 7874 7875 // Use swifterror virtual register as input to the call. 7876 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7877 SwiftErrorVal = V; 7878 // We find the virtual register for the actual swifterror argument. 7879 // Instead of using the Value, we use the virtual register instead. 7880 Entry.Node = 7881 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 7882 EVT(TLI.getPointerTy(DL))); 7883 } 7884 7885 Args.push_back(Entry); 7886 7887 // If we have an explicit sret argument that is an Instruction, (i.e., it 7888 // might point to function-local memory), we can't meaningfully tail-call. 7889 if (Entry.IsSRet && isa<Instruction>(V)) 7890 isTailCall = false; 7891 } 7892 7893 // If call site has a cfguardtarget operand bundle, create and add an 7894 // additional ArgListEntry. 7895 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7896 TargetLowering::ArgListEntry Entry; 7897 Value *V = Bundle->Inputs[0]; 7898 SDValue ArgNode = getValue(V); 7899 Entry.Node = ArgNode; 7900 Entry.Ty = V->getType(); 7901 Entry.IsCFGuardTarget = true; 7902 Args.push_back(Entry); 7903 } 7904 7905 // Check if target-independent constraints permit a tail call here. 7906 // Target-dependent constraints are checked within TLI->LowerCallTo. 7907 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 7908 isTailCall = false; 7909 7910 // Disable tail calls if there is an swifterror argument. Targets have not 7911 // been updated to support tail calls. 7912 if (TLI.supportSwiftError() && SwiftErrorVal) 7913 isTailCall = false; 7914 7915 ConstantInt *CFIType = nullptr; 7916 if (CB.isIndirectCall()) { 7917 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) { 7918 if (!TLI.supportKCFIBundles()) 7919 report_fatal_error( 7920 "Target doesn't support calls with kcfi operand bundles."); 7921 CFIType = cast<ConstantInt>(Bundle->Inputs[0]); 7922 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type"); 7923 } 7924 } 7925 7926 TargetLowering::CallLoweringInfo CLI(DAG); 7927 CLI.setDebugLoc(getCurSDLoc()) 7928 .setChain(getRoot()) 7929 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 7930 .setTailCall(isTailCall) 7931 .setConvergent(CB.isConvergent()) 7932 .setIsPreallocated( 7933 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0) 7934 .setCFIType(CFIType); 7935 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7936 7937 if (Result.first.getNode()) { 7938 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 7939 setValue(&CB, Result.first); 7940 } 7941 7942 // The last element of CLI.InVals has the SDValue for swifterror return. 7943 // Here we copy it to a virtual register and update SwiftErrorMap for 7944 // book-keeping. 7945 if (SwiftErrorVal && TLI.supportSwiftError()) { 7946 // Get the last element of InVals. 7947 SDValue Src = CLI.InVals.back(); 7948 Register VReg = 7949 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 7950 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7951 DAG.setRoot(CopyNode); 7952 } 7953 } 7954 7955 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7956 SelectionDAGBuilder &Builder) { 7957 // Check to see if this load can be trivially constant folded, e.g. if the 7958 // input is from a string literal. 7959 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7960 // Cast pointer to the type we really want to load. 7961 Type *LoadTy = 7962 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7963 if (LoadVT.isVector()) 7964 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7965 7966 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7967 PointerType::getUnqual(LoadTy)); 7968 7969 if (const Constant *LoadCst = 7970 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput), 7971 LoadTy, Builder.DAG.getDataLayout())) 7972 return Builder.getValue(LoadCst); 7973 } 7974 7975 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7976 // still constant memory, the input chain can be the entry node. 7977 SDValue Root; 7978 bool ConstantMemory = false; 7979 7980 // Do not serialize (non-volatile) loads of constant memory with anything. 7981 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7982 Root = Builder.DAG.getEntryNode(); 7983 ConstantMemory = true; 7984 } else { 7985 // Do not serialize non-volatile loads against each other. 7986 Root = Builder.DAG.getRoot(); 7987 } 7988 7989 SDValue Ptr = Builder.getValue(PtrVal); 7990 SDValue LoadVal = 7991 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 7992 MachinePointerInfo(PtrVal), Align(1)); 7993 7994 if (!ConstantMemory) 7995 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7996 return LoadVal; 7997 } 7998 7999 /// Record the value for an instruction that produces an integer result, 8000 /// converting the type where necessary. 8001 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 8002 SDValue Value, 8003 bool IsSigned) { 8004 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8005 I.getType(), true); 8006 if (IsSigned) 8007 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 8008 else 8009 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 8010 setValue(&I, Value); 8011 } 8012 8013 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 8014 /// true and lower it. Otherwise return false, and it will be lowered like a 8015 /// normal call. 8016 /// The caller already checked that \p I calls the appropriate LibFunc with a 8017 /// correct prototype. 8018 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 8019 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 8020 const Value *Size = I.getArgOperand(2); 8021 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size)); 8022 if (CSize && CSize->getZExtValue() == 0) { 8023 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8024 I.getType(), true); 8025 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 8026 return true; 8027 } 8028 8029 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8030 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 8031 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 8032 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 8033 if (Res.first.getNode()) { 8034 processIntegerCallValue(I, Res.first, true); 8035 PendingLoads.push_back(Res.second); 8036 return true; 8037 } 8038 8039 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 8040 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 8041 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 8042 return false; 8043 8044 // If the target has a fast compare for the given size, it will return a 8045 // preferred load type for that size. Require that the load VT is legal and 8046 // that the target supports unaligned loads of that type. Otherwise, return 8047 // INVALID. 8048 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 8049 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8050 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 8051 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 8052 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 8053 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 8054 // TODO: Check alignment of src and dest ptrs. 8055 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 8056 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 8057 if (!TLI.isTypeLegal(LVT) || 8058 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 8059 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 8060 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 8061 } 8062 8063 return LVT; 8064 }; 8065 8066 // This turns into unaligned loads. We only do this if the target natively 8067 // supports the MVT we'll be loading or if it is small enough (<= 4) that 8068 // we'll only produce a small number of byte loads. 8069 MVT LoadVT; 8070 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 8071 switch (NumBitsToCompare) { 8072 default: 8073 return false; 8074 case 16: 8075 LoadVT = MVT::i16; 8076 break; 8077 case 32: 8078 LoadVT = MVT::i32; 8079 break; 8080 case 64: 8081 case 128: 8082 case 256: 8083 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 8084 break; 8085 } 8086 8087 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 8088 return false; 8089 8090 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 8091 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 8092 8093 // Bitcast to a wide integer type if the loads are vectors. 8094 if (LoadVT.isVector()) { 8095 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 8096 LoadL = DAG.getBitcast(CmpVT, LoadL); 8097 LoadR = DAG.getBitcast(CmpVT, LoadR); 8098 } 8099 8100 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 8101 processIntegerCallValue(I, Cmp, false); 8102 return true; 8103 } 8104 8105 /// See if we can lower a memchr call into an optimized form. If so, return 8106 /// true and lower it. Otherwise return false, and it will be lowered like a 8107 /// normal call. 8108 /// The caller already checked that \p I calls the appropriate LibFunc with a 8109 /// correct prototype. 8110 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 8111 const Value *Src = I.getArgOperand(0); 8112 const Value *Char = I.getArgOperand(1); 8113 const Value *Length = I.getArgOperand(2); 8114 8115 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8116 std::pair<SDValue, SDValue> Res = 8117 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 8118 getValue(Src), getValue(Char), getValue(Length), 8119 MachinePointerInfo(Src)); 8120 if (Res.first.getNode()) { 8121 setValue(&I, Res.first); 8122 PendingLoads.push_back(Res.second); 8123 return true; 8124 } 8125 8126 return false; 8127 } 8128 8129 /// See if we can lower a mempcpy call into an optimized form. If so, return 8130 /// true and lower it. Otherwise return false, and it will be lowered like a 8131 /// normal call. 8132 /// The caller already checked that \p I calls the appropriate LibFunc with a 8133 /// correct prototype. 8134 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 8135 SDValue Dst = getValue(I.getArgOperand(0)); 8136 SDValue Src = getValue(I.getArgOperand(1)); 8137 SDValue Size = getValue(I.getArgOperand(2)); 8138 8139 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 8140 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 8141 // DAG::getMemcpy needs Alignment to be defined. 8142 Align Alignment = std::min(DstAlign, SrcAlign); 8143 8144 bool isVol = false; 8145 SDLoc sdl = getCurSDLoc(); 8146 8147 // In the mempcpy context we need to pass in a false value for isTailCall 8148 // because the return pointer needs to be adjusted by the size of 8149 // the copied memory. 8150 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 8151 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false, 8152 /*isTailCall=*/false, 8153 MachinePointerInfo(I.getArgOperand(0)), 8154 MachinePointerInfo(I.getArgOperand(1)), 8155 I.getAAMetadata()); 8156 assert(MC.getNode() != nullptr && 8157 "** memcpy should not be lowered as TailCall in mempcpy context **"); 8158 DAG.setRoot(MC); 8159 8160 // Check if Size needs to be truncated or extended. 8161 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 8162 8163 // Adjust return pointer to point just past the last dst byte. 8164 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 8165 Dst, Size); 8166 setValue(&I, DstPlusSize); 8167 return true; 8168 } 8169 8170 /// See if we can lower a strcpy call into an optimized form. If so, return 8171 /// true and lower it, otherwise return false and it will be lowered like a 8172 /// normal call. 8173 /// The caller already checked that \p I calls the appropriate LibFunc with a 8174 /// correct prototype. 8175 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 8176 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8177 8178 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8179 std::pair<SDValue, SDValue> Res = 8180 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 8181 getValue(Arg0), getValue(Arg1), 8182 MachinePointerInfo(Arg0), 8183 MachinePointerInfo(Arg1), isStpcpy); 8184 if (Res.first.getNode()) { 8185 setValue(&I, Res.first); 8186 DAG.setRoot(Res.second); 8187 return true; 8188 } 8189 8190 return false; 8191 } 8192 8193 /// See if we can lower a strcmp call into an optimized form. If so, return 8194 /// true and lower it, otherwise return false and it will be lowered like a 8195 /// normal call. 8196 /// The caller already checked that \p I calls the appropriate LibFunc with a 8197 /// correct prototype. 8198 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 8199 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8200 8201 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8202 std::pair<SDValue, SDValue> Res = 8203 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 8204 getValue(Arg0), getValue(Arg1), 8205 MachinePointerInfo(Arg0), 8206 MachinePointerInfo(Arg1)); 8207 if (Res.first.getNode()) { 8208 processIntegerCallValue(I, Res.first, true); 8209 PendingLoads.push_back(Res.second); 8210 return true; 8211 } 8212 8213 return false; 8214 } 8215 8216 /// See if we can lower a strlen call into an optimized form. If so, return 8217 /// true and lower it, otherwise return false and it will be lowered like a 8218 /// normal call. 8219 /// The caller already checked that \p I calls the appropriate LibFunc with a 8220 /// correct prototype. 8221 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 8222 const Value *Arg0 = I.getArgOperand(0); 8223 8224 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8225 std::pair<SDValue, SDValue> Res = 8226 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 8227 getValue(Arg0), MachinePointerInfo(Arg0)); 8228 if (Res.first.getNode()) { 8229 processIntegerCallValue(I, Res.first, false); 8230 PendingLoads.push_back(Res.second); 8231 return true; 8232 } 8233 8234 return false; 8235 } 8236 8237 /// See if we can lower a strnlen call into an optimized form. If so, return 8238 /// true and lower it, otherwise return false and it will be lowered like a 8239 /// normal call. 8240 /// The caller already checked that \p I calls the appropriate LibFunc with a 8241 /// correct prototype. 8242 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 8243 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8244 8245 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8246 std::pair<SDValue, SDValue> Res = 8247 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 8248 getValue(Arg0), getValue(Arg1), 8249 MachinePointerInfo(Arg0)); 8250 if (Res.first.getNode()) { 8251 processIntegerCallValue(I, Res.first, false); 8252 PendingLoads.push_back(Res.second); 8253 return true; 8254 } 8255 8256 return false; 8257 } 8258 8259 /// See if we can lower a unary floating-point operation into an SDNode with 8260 /// the specified Opcode. If so, return true and lower it, otherwise return 8261 /// false and it will be lowered like a normal call. 8262 /// The caller already checked that \p I calls the appropriate LibFunc with a 8263 /// correct prototype. 8264 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 8265 unsigned Opcode) { 8266 // We already checked this call's prototype; verify it doesn't modify errno. 8267 if (!I.onlyReadsMemory()) 8268 return false; 8269 8270 SDNodeFlags Flags; 8271 Flags.copyFMF(cast<FPMathOperator>(I)); 8272 8273 SDValue Tmp = getValue(I.getArgOperand(0)); 8274 setValue(&I, 8275 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 8276 return true; 8277 } 8278 8279 /// See if we can lower a binary floating-point operation into an SDNode with 8280 /// the specified Opcode. If so, return true and lower it. Otherwise return 8281 /// false, and it will be lowered like a normal call. 8282 /// The caller already checked that \p I calls the appropriate LibFunc with a 8283 /// correct prototype. 8284 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 8285 unsigned Opcode) { 8286 // We already checked this call's prototype; verify it doesn't modify errno. 8287 if (!I.onlyReadsMemory()) 8288 return false; 8289 8290 SDNodeFlags Flags; 8291 Flags.copyFMF(cast<FPMathOperator>(I)); 8292 8293 SDValue Tmp0 = getValue(I.getArgOperand(0)); 8294 SDValue Tmp1 = getValue(I.getArgOperand(1)); 8295 EVT VT = Tmp0.getValueType(); 8296 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 8297 return true; 8298 } 8299 8300 void SelectionDAGBuilder::visitCall(const CallInst &I) { 8301 // Handle inline assembly differently. 8302 if (I.isInlineAsm()) { 8303 visitInlineAsm(I); 8304 return; 8305 } 8306 8307 if (Function *F = I.getCalledFunction()) { 8308 diagnoseDontCall(I); 8309 8310 if (F->isDeclaration()) { 8311 // Is this an LLVM intrinsic or a target-specific intrinsic? 8312 unsigned IID = F->getIntrinsicID(); 8313 if (!IID) 8314 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 8315 IID = II->getIntrinsicID(F); 8316 8317 if (IID) { 8318 visitIntrinsicCall(I, IID); 8319 return; 8320 } 8321 } 8322 8323 // Check for well-known libc/libm calls. If the function is internal, it 8324 // can't be a library call. Don't do the check if marked as nobuiltin for 8325 // some reason or the call site requires strict floating point semantics. 8326 LibFunc Func; 8327 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 8328 F->hasName() && LibInfo->getLibFunc(*F, Func) && 8329 LibInfo->hasOptimizedCodeGen(Func)) { 8330 switch (Func) { 8331 default: break; 8332 case LibFunc_bcmp: 8333 if (visitMemCmpBCmpCall(I)) 8334 return; 8335 break; 8336 case LibFunc_copysign: 8337 case LibFunc_copysignf: 8338 case LibFunc_copysignl: 8339 // We already checked this call's prototype; verify it doesn't modify 8340 // errno. 8341 if (I.onlyReadsMemory()) { 8342 SDValue LHS = getValue(I.getArgOperand(0)); 8343 SDValue RHS = getValue(I.getArgOperand(1)); 8344 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 8345 LHS.getValueType(), LHS, RHS)); 8346 return; 8347 } 8348 break; 8349 case LibFunc_fabs: 8350 case LibFunc_fabsf: 8351 case LibFunc_fabsl: 8352 if (visitUnaryFloatCall(I, ISD::FABS)) 8353 return; 8354 break; 8355 case LibFunc_fmin: 8356 case LibFunc_fminf: 8357 case LibFunc_fminl: 8358 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 8359 return; 8360 break; 8361 case LibFunc_fmax: 8362 case LibFunc_fmaxf: 8363 case LibFunc_fmaxl: 8364 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 8365 return; 8366 break; 8367 case LibFunc_sin: 8368 case LibFunc_sinf: 8369 case LibFunc_sinl: 8370 if (visitUnaryFloatCall(I, ISD::FSIN)) 8371 return; 8372 break; 8373 case LibFunc_cos: 8374 case LibFunc_cosf: 8375 case LibFunc_cosl: 8376 if (visitUnaryFloatCall(I, ISD::FCOS)) 8377 return; 8378 break; 8379 case LibFunc_sqrt: 8380 case LibFunc_sqrtf: 8381 case LibFunc_sqrtl: 8382 case LibFunc_sqrt_finite: 8383 case LibFunc_sqrtf_finite: 8384 case LibFunc_sqrtl_finite: 8385 if (visitUnaryFloatCall(I, ISD::FSQRT)) 8386 return; 8387 break; 8388 case LibFunc_floor: 8389 case LibFunc_floorf: 8390 case LibFunc_floorl: 8391 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 8392 return; 8393 break; 8394 case LibFunc_nearbyint: 8395 case LibFunc_nearbyintf: 8396 case LibFunc_nearbyintl: 8397 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 8398 return; 8399 break; 8400 case LibFunc_ceil: 8401 case LibFunc_ceilf: 8402 case LibFunc_ceill: 8403 if (visitUnaryFloatCall(I, ISD::FCEIL)) 8404 return; 8405 break; 8406 case LibFunc_rint: 8407 case LibFunc_rintf: 8408 case LibFunc_rintl: 8409 if (visitUnaryFloatCall(I, ISD::FRINT)) 8410 return; 8411 break; 8412 case LibFunc_round: 8413 case LibFunc_roundf: 8414 case LibFunc_roundl: 8415 if (visitUnaryFloatCall(I, ISD::FROUND)) 8416 return; 8417 break; 8418 case LibFunc_trunc: 8419 case LibFunc_truncf: 8420 case LibFunc_truncl: 8421 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 8422 return; 8423 break; 8424 case LibFunc_log2: 8425 case LibFunc_log2f: 8426 case LibFunc_log2l: 8427 if (visitUnaryFloatCall(I, ISD::FLOG2)) 8428 return; 8429 break; 8430 case LibFunc_exp2: 8431 case LibFunc_exp2f: 8432 case LibFunc_exp2l: 8433 if (visitUnaryFloatCall(I, ISD::FEXP2)) 8434 return; 8435 break; 8436 case LibFunc_memcmp: 8437 if (visitMemCmpBCmpCall(I)) 8438 return; 8439 break; 8440 case LibFunc_mempcpy: 8441 if (visitMemPCpyCall(I)) 8442 return; 8443 break; 8444 case LibFunc_memchr: 8445 if (visitMemChrCall(I)) 8446 return; 8447 break; 8448 case LibFunc_strcpy: 8449 if (visitStrCpyCall(I, false)) 8450 return; 8451 break; 8452 case LibFunc_stpcpy: 8453 if (visitStrCpyCall(I, true)) 8454 return; 8455 break; 8456 case LibFunc_strcmp: 8457 if (visitStrCmpCall(I)) 8458 return; 8459 break; 8460 case LibFunc_strlen: 8461 if (visitStrLenCall(I)) 8462 return; 8463 break; 8464 case LibFunc_strnlen: 8465 if (visitStrNLenCall(I)) 8466 return; 8467 break; 8468 } 8469 } 8470 } 8471 8472 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 8473 // have to do anything here to lower funclet bundles. 8474 // CFGuardTarget bundles are lowered in LowerCallTo. 8475 assert(!I.hasOperandBundlesOtherThan( 8476 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 8477 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 8478 LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) && 8479 "Cannot lower calls with arbitrary operand bundles!"); 8480 8481 SDValue Callee = getValue(I.getCalledOperand()); 8482 8483 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 8484 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 8485 else 8486 // Check if we can potentially perform a tail call. More detailed checking 8487 // is be done within LowerCallTo, after more information about the call is 8488 // known. 8489 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 8490 } 8491 8492 namespace { 8493 8494 /// AsmOperandInfo - This contains information for each constraint that we are 8495 /// lowering. 8496 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 8497 public: 8498 /// CallOperand - If this is the result output operand or a clobber 8499 /// this is null, otherwise it is the incoming operand to the CallInst. 8500 /// This gets modified as the asm is processed. 8501 SDValue CallOperand; 8502 8503 /// AssignedRegs - If this is a register or register class operand, this 8504 /// contains the set of register corresponding to the operand. 8505 RegsForValue AssignedRegs; 8506 8507 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 8508 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 8509 } 8510 8511 /// Whether or not this operand accesses memory 8512 bool hasMemory(const TargetLowering &TLI) const { 8513 // Indirect operand accesses access memory. 8514 if (isIndirect) 8515 return true; 8516 8517 for (const auto &Code : Codes) 8518 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 8519 return true; 8520 8521 return false; 8522 } 8523 }; 8524 8525 8526 } // end anonymous namespace 8527 8528 /// Make sure that the output operand \p OpInfo and its corresponding input 8529 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 8530 /// out). 8531 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 8532 SDISelAsmOperandInfo &MatchingOpInfo, 8533 SelectionDAG &DAG) { 8534 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 8535 return; 8536 8537 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 8538 const auto &TLI = DAG.getTargetLoweringInfo(); 8539 8540 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 8541 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 8542 OpInfo.ConstraintVT); 8543 std::pair<unsigned, const TargetRegisterClass *> InputRC = 8544 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 8545 MatchingOpInfo.ConstraintVT); 8546 if ((OpInfo.ConstraintVT.isInteger() != 8547 MatchingOpInfo.ConstraintVT.isInteger()) || 8548 (MatchRC.second != InputRC.second)) { 8549 // FIXME: error out in a more elegant fashion 8550 report_fatal_error("Unsupported asm: input constraint" 8551 " with a matching output constraint of" 8552 " incompatible type!"); 8553 } 8554 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 8555 } 8556 8557 /// Get a direct memory input to behave well as an indirect operand. 8558 /// This may introduce stores, hence the need for a \p Chain. 8559 /// \return The (possibly updated) chain. 8560 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 8561 SDISelAsmOperandInfo &OpInfo, 8562 SelectionDAG &DAG) { 8563 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8564 8565 // If we don't have an indirect input, put it in the constpool if we can, 8566 // otherwise spill it to a stack slot. 8567 // TODO: This isn't quite right. We need to handle these according to 8568 // the addressing mode that the constraint wants. Also, this may take 8569 // an additional register for the computation and we don't want that 8570 // either. 8571 8572 // If the operand is a float, integer, or vector constant, spill to a 8573 // constant pool entry to get its address. 8574 const Value *OpVal = OpInfo.CallOperandVal; 8575 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 8576 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 8577 OpInfo.CallOperand = DAG.getConstantPool( 8578 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 8579 return Chain; 8580 } 8581 8582 // Otherwise, create a stack slot and emit a store to it before the asm. 8583 Type *Ty = OpVal->getType(); 8584 auto &DL = DAG.getDataLayout(); 8585 uint64_t TySize = DL.getTypeAllocSize(Ty); 8586 MachineFunction &MF = DAG.getMachineFunction(); 8587 int SSFI = MF.getFrameInfo().CreateStackObject( 8588 TySize, DL.getPrefTypeAlign(Ty), false); 8589 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 8590 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 8591 MachinePointerInfo::getFixedStack(MF, SSFI), 8592 TLI.getMemValueType(DL, Ty)); 8593 OpInfo.CallOperand = StackSlot; 8594 8595 return Chain; 8596 } 8597 8598 /// GetRegistersForValue - Assign registers (virtual or physical) for the 8599 /// specified operand. We prefer to assign virtual registers, to allow the 8600 /// register allocator to handle the assignment process. However, if the asm 8601 /// uses features that we can't model on machineinstrs, we have SDISel do the 8602 /// allocation. This produces generally horrible, but correct, code. 8603 /// 8604 /// OpInfo describes the operand 8605 /// RefOpInfo describes the matching operand if any, the operand otherwise 8606 static llvm::Optional<unsigned> 8607 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 8608 SDISelAsmOperandInfo &OpInfo, 8609 SDISelAsmOperandInfo &RefOpInfo) { 8610 LLVMContext &Context = *DAG.getContext(); 8611 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8612 8613 MachineFunction &MF = DAG.getMachineFunction(); 8614 SmallVector<unsigned, 4> Regs; 8615 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8616 8617 // No work to do for memory/address operands. 8618 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8619 OpInfo.ConstraintType == TargetLowering::C_Address) 8620 return None; 8621 8622 // If this is a constraint for a single physreg, or a constraint for a 8623 // register class, find it. 8624 unsigned AssignedReg; 8625 const TargetRegisterClass *RC; 8626 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 8627 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 8628 // RC is unset only on failure. Return immediately. 8629 if (!RC) 8630 return None; 8631 8632 // Get the actual register value type. This is important, because the user 8633 // may have asked for (e.g.) the AX register in i32 type. We need to 8634 // remember that AX is actually i16 to get the right extension. 8635 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 8636 8637 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) { 8638 // If this is an FP operand in an integer register (or visa versa), or more 8639 // generally if the operand value disagrees with the register class we plan 8640 // to stick it in, fix the operand type. 8641 // 8642 // If this is an input value, the bitcast to the new type is done now. 8643 // Bitcast for output value is done at the end of visitInlineAsm(). 8644 if ((OpInfo.Type == InlineAsm::isOutput || 8645 OpInfo.Type == InlineAsm::isInput) && 8646 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 8647 // Try to convert to the first EVT that the reg class contains. If the 8648 // types are identical size, use a bitcast to convert (e.g. two differing 8649 // vector types). Note: output bitcast is done at the end of 8650 // visitInlineAsm(). 8651 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 8652 // Exclude indirect inputs while they are unsupported because the code 8653 // to perform the load is missing and thus OpInfo.CallOperand still 8654 // refers to the input address rather than the pointed-to value. 8655 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 8656 OpInfo.CallOperand = 8657 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 8658 OpInfo.ConstraintVT = RegVT; 8659 // If the operand is an FP value and we want it in integer registers, 8660 // use the corresponding integer type. This turns an f64 value into 8661 // i64, which can be passed with two i32 values on a 32-bit machine. 8662 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 8663 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 8664 if (OpInfo.Type == InlineAsm::isInput) 8665 OpInfo.CallOperand = 8666 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 8667 OpInfo.ConstraintVT = VT; 8668 } 8669 } 8670 } 8671 8672 // No need to allocate a matching input constraint since the constraint it's 8673 // matching to has already been allocated. 8674 if (OpInfo.isMatchingInputConstraint()) 8675 return None; 8676 8677 EVT ValueVT = OpInfo.ConstraintVT; 8678 if (OpInfo.ConstraintVT == MVT::Other) 8679 ValueVT = RegVT; 8680 8681 // Initialize NumRegs. 8682 unsigned NumRegs = 1; 8683 if (OpInfo.ConstraintVT != MVT::Other) 8684 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT); 8685 8686 // If this is a constraint for a specific physical register, like {r17}, 8687 // assign it now. 8688 8689 // If this associated to a specific register, initialize iterator to correct 8690 // place. If virtual, make sure we have enough registers 8691 8692 // Initialize iterator if necessary 8693 TargetRegisterClass::iterator I = RC->begin(); 8694 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8695 8696 // Do not check for single registers. 8697 if (AssignedReg) { 8698 I = std::find(I, RC->end(), AssignedReg); 8699 if (I == RC->end()) { 8700 // RC does not contain the selected register, which indicates a 8701 // mismatch between the register and the required type/bitwidth. 8702 return {AssignedReg}; 8703 } 8704 } 8705 8706 for (; NumRegs; --NumRegs, ++I) { 8707 assert(I != RC->end() && "Ran out of registers to allocate!"); 8708 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8709 Regs.push_back(R); 8710 } 8711 8712 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8713 return None; 8714 } 8715 8716 static unsigned 8717 findMatchingInlineAsmOperand(unsigned OperandNo, 8718 const std::vector<SDValue> &AsmNodeOperands) { 8719 // Scan until we find the definition we already emitted of this operand. 8720 unsigned CurOp = InlineAsm::Op_FirstOperand; 8721 for (; OperandNo; --OperandNo) { 8722 // Advance to the next operand. 8723 unsigned OpFlag = 8724 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8725 assert((InlineAsm::isRegDefKind(OpFlag) || 8726 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8727 InlineAsm::isMemKind(OpFlag)) && 8728 "Skipped past definitions?"); 8729 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8730 } 8731 return CurOp; 8732 } 8733 8734 namespace { 8735 8736 class ExtraFlags { 8737 unsigned Flags = 0; 8738 8739 public: 8740 explicit ExtraFlags(const CallBase &Call) { 8741 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8742 if (IA->hasSideEffects()) 8743 Flags |= InlineAsm::Extra_HasSideEffects; 8744 if (IA->isAlignStack()) 8745 Flags |= InlineAsm::Extra_IsAlignStack; 8746 if (Call.isConvergent()) 8747 Flags |= InlineAsm::Extra_IsConvergent; 8748 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8749 } 8750 8751 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8752 // Ideally, we would only check against memory constraints. However, the 8753 // meaning of an Other constraint can be target-specific and we can't easily 8754 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8755 // for Other constraints as well. 8756 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8757 OpInfo.ConstraintType == TargetLowering::C_Other) { 8758 if (OpInfo.Type == InlineAsm::isInput) 8759 Flags |= InlineAsm::Extra_MayLoad; 8760 else if (OpInfo.Type == InlineAsm::isOutput) 8761 Flags |= InlineAsm::Extra_MayStore; 8762 else if (OpInfo.Type == InlineAsm::isClobber) 8763 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8764 } 8765 } 8766 8767 unsigned get() const { return Flags; } 8768 }; 8769 8770 } // end anonymous namespace 8771 8772 /// visitInlineAsm - Handle a call to an InlineAsm object. 8773 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 8774 const BasicBlock *EHPadBB) { 8775 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8776 8777 /// ConstraintOperands - Information about all of the constraints. 8778 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 8779 8780 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8781 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8782 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 8783 8784 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8785 // AsmDialect, MayLoad, MayStore). 8786 bool HasSideEffect = IA->hasSideEffects(); 8787 ExtraFlags ExtraInfo(Call); 8788 8789 for (auto &T : TargetConstraints) { 8790 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8791 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8792 8793 if (OpInfo.CallOperandVal) 8794 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8795 8796 if (!HasSideEffect) 8797 HasSideEffect = OpInfo.hasMemory(TLI); 8798 8799 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8800 // FIXME: Could we compute this on OpInfo rather than T? 8801 8802 // Compute the constraint code and ConstraintType to use. 8803 TLI.ComputeConstraintToUse(T, SDValue()); 8804 8805 if (T.ConstraintType == TargetLowering::C_Immediate && 8806 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8807 // We've delayed emitting a diagnostic like the "n" constraint because 8808 // inlining could cause an integer showing up. 8809 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 8810 "' expects an integer constant " 8811 "expression"); 8812 8813 ExtraInfo.update(T); 8814 } 8815 8816 // We won't need to flush pending loads if this asm doesn't touch 8817 // memory and is nonvolatile. 8818 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8819 8820 bool EmitEHLabels = isa<InvokeInst>(Call) && IA->canThrow(); 8821 if (EmitEHLabels) { 8822 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 8823 } 8824 bool IsCallBr = isa<CallBrInst>(Call); 8825 8826 if (IsCallBr || EmitEHLabels) { 8827 // If this is a callbr or invoke we need to flush pending exports since 8828 // inlineasm_br and invoke are terminators. 8829 // We need to do this before nodes are glued to the inlineasm_br node. 8830 Chain = getControlRoot(); 8831 } 8832 8833 MCSymbol *BeginLabel = nullptr; 8834 if (EmitEHLabels) { 8835 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 8836 } 8837 8838 // Second pass over the constraints: compute which constraint option to use. 8839 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8840 // If this is an output operand with a matching input operand, look up the 8841 // matching input. If their types mismatch, e.g. one is an integer, the 8842 // other is floating point, or their sizes are different, flag it as an 8843 // error. 8844 if (OpInfo.hasMatchingInput()) { 8845 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8846 patchMatchingInput(OpInfo, Input, DAG); 8847 } 8848 8849 // Compute the constraint code and ConstraintType to use. 8850 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8851 8852 if ((OpInfo.ConstraintType == TargetLowering::C_Memory && 8853 OpInfo.Type == InlineAsm::isClobber) || 8854 OpInfo.ConstraintType == TargetLowering::C_Address) 8855 continue; 8856 8857 // If this is a memory input, and if the operand is not indirect, do what we 8858 // need to provide an address for the memory input. 8859 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8860 !OpInfo.isIndirect) { 8861 assert((OpInfo.isMultipleAlternative || 8862 (OpInfo.Type == InlineAsm::isInput)) && 8863 "Can only indirectify direct input operands!"); 8864 8865 // Memory operands really want the address of the value. 8866 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8867 8868 // There is no longer a Value* corresponding to this operand. 8869 OpInfo.CallOperandVal = nullptr; 8870 8871 // It is now an indirect operand. 8872 OpInfo.isIndirect = true; 8873 } 8874 8875 } 8876 8877 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8878 std::vector<SDValue> AsmNodeOperands; 8879 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8880 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8881 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 8882 8883 // If we have a !srcloc metadata node associated with it, we want to attach 8884 // this to the ultimately generated inline asm machineinstr. To do this, we 8885 // pass in the third operand as this (potentially null) inline asm MDNode. 8886 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 8887 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8888 8889 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8890 // bits as operand 3. 8891 AsmNodeOperands.push_back(DAG.getTargetConstant( 8892 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8893 8894 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8895 // this, assign virtual and physical registers for inputs and otput. 8896 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8897 // Assign Registers. 8898 SDISelAsmOperandInfo &RefOpInfo = 8899 OpInfo.isMatchingInputConstraint() 8900 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8901 : OpInfo; 8902 const auto RegError = 8903 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8904 if (RegError) { 8905 const MachineFunction &MF = DAG.getMachineFunction(); 8906 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8907 const char *RegName = TRI.getName(RegError.value()); 8908 emitInlineAsmError(Call, "register '" + Twine(RegName) + 8909 "' allocated for constraint '" + 8910 Twine(OpInfo.ConstraintCode) + 8911 "' does not match required type"); 8912 return; 8913 } 8914 8915 auto DetectWriteToReservedRegister = [&]() { 8916 const MachineFunction &MF = DAG.getMachineFunction(); 8917 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8918 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 8919 if (Register::isPhysicalRegister(Reg) && 8920 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 8921 const char *RegName = TRI.getName(Reg); 8922 emitInlineAsmError(Call, "write to reserved register '" + 8923 Twine(RegName) + "'"); 8924 return true; 8925 } 8926 } 8927 return false; 8928 }; 8929 assert((OpInfo.ConstraintType != TargetLowering::C_Address || 8930 (OpInfo.Type == InlineAsm::isInput && 8931 !OpInfo.isMatchingInputConstraint())) && 8932 "Only address as input operand is allowed."); 8933 8934 switch (OpInfo.Type) { 8935 case InlineAsm::isOutput: 8936 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8937 unsigned ConstraintID = 8938 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8939 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8940 "Failed to convert memory constraint code to constraint id."); 8941 8942 // Add information to the INLINEASM node to know about this output. 8943 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8944 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8945 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8946 MVT::i32)); 8947 AsmNodeOperands.push_back(OpInfo.CallOperand); 8948 } else { 8949 // Otherwise, this outputs to a register (directly for C_Register / 8950 // C_RegisterClass, and a target-defined fashion for 8951 // C_Immediate/C_Other). Find a register that we can use. 8952 if (OpInfo.AssignedRegs.Regs.empty()) { 8953 emitInlineAsmError( 8954 Call, "couldn't allocate output register for constraint '" + 8955 Twine(OpInfo.ConstraintCode) + "'"); 8956 return; 8957 } 8958 8959 if (DetectWriteToReservedRegister()) 8960 return; 8961 8962 // Add information to the INLINEASM node to know that this register is 8963 // set. 8964 OpInfo.AssignedRegs.AddInlineAsmOperands( 8965 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8966 : InlineAsm::Kind_RegDef, 8967 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8968 } 8969 break; 8970 8971 case InlineAsm::isInput: 8972 case InlineAsm::isLabel: { 8973 SDValue InOperandVal = OpInfo.CallOperand; 8974 8975 if (OpInfo.isMatchingInputConstraint()) { 8976 // If this is required to match an output register we have already set, 8977 // just use its register. 8978 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8979 AsmNodeOperands); 8980 unsigned OpFlag = 8981 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8982 if (InlineAsm::isRegDefKind(OpFlag) || 8983 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8984 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8985 if (OpInfo.isIndirect) { 8986 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8987 emitInlineAsmError(Call, "inline asm not supported yet: " 8988 "don't know how to handle tied " 8989 "indirect register inputs"); 8990 return; 8991 } 8992 8993 SmallVector<unsigned, 4> Regs; 8994 MachineFunction &MF = DAG.getMachineFunction(); 8995 MachineRegisterInfo &MRI = MF.getRegInfo(); 8996 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8997 auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]); 8998 Register TiedReg = R->getReg(); 8999 MVT RegVT = R->getSimpleValueType(0); 9000 const TargetRegisterClass *RC = 9001 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg) 9002 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT) 9003 : TRI.getMinimalPhysRegClass(TiedReg); 9004 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 9005 for (unsigned i = 0; i != NumRegs; ++i) 9006 Regs.push_back(MRI.createVirtualRegister(RC)); 9007 9008 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 9009 9010 SDLoc dl = getCurSDLoc(); 9011 // Use the produced MatchedRegs object to 9012 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call); 9013 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 9014 true, OpInfo.getMatchedOperand(), dl, 9015 DAG, AsmNodeOperands); 9016 break; 9017 } 9018 9019 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 9020 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 9021 "Unexpected number of operands"); 9022 // Add information to the INLINEASM node to know about this input. 9023 // See InlineAsm.h isUseOperandTiedToDef. 9024 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 9025 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 9026 OpInfo.getMatchedOperand()); 9027 AsmNodeOperands.push_back(DAG.getTargetConstant( 9028 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9029 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 9030 break; 9031 } 9032 9033 // Treat indirect 'X' constraint as memory. 9034 if (OpInfo.ConstraintType == TargetLowering::C_Other && 9035 OpInfo.isIndirect) 9036 OpInfo.ConstraintType = TargetLowering::C_Memory; 9037 9038 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 9039 OpInfo.ConstraintType == TargetLowering::C_Other) { 9040 std::vector<SDValue> Ops; 9041 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 9042 Ops, DAG); 9043 if (Ops.empty()) { 9044 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 9045 if (isa<ConstantSDNode>(InOperandVal)) { 9046 emitInlineAsmError(Call, "value out of range for constraint '" + 9047 Twine(OpInfo.ConstraintCode) + "'"); 9048 return; 9049 } 9050 9051 emitInlineAsmError(Call, 9052 "invalid operand for inline asm constraint '" + 9053 Twine(OpInfo.ConstraintCode) + "'"); 9054 return; 9055 } 9056 9057 // Add information to the INLINEASM node to know about this input. 9058 unsigned ResOpType = 9059 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 9060 AsmNodeOperands.push_back(DAG.getTargetConstant( 9061 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9062 llvm::append_range(AsmNodeOperands, Ops); 9063 break; 9064 } 9065 9066 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 9067 OpInfo.ConstraintType == TargetLowering::C_Address) { 9068 assert((OpInfo.isIndirect || 9069 OpInfo.ConstraintType != TargetLowering::C_Memory) && 9070 "Operand must be indirect to be a mem!"); 9071 assert(InOperandVal.getValueType() == 9072 TLI.getPointerTy(DAG.getDataLayout()) && 9073 "Memory operands expect pointer values"); 9074 9075 unsigned ConstraintID = 9076 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9077 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9078 "Failed to convert memory constraint code to constraint id."); 9079 9080 // Add information to the INLINEASM node to know about this input. 9081 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9082 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 9083 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 9084 getCurSDLoc(), 9085 MVT::i32)); 9086 AsmNodeOperands.push_back(InOperandVal); 9087 break; 9088 } 9089 9090 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 9091 OpInfo.ConstraintType == TargetLowering::C_Register) && 9092 "Unknown constraint type!"); 9093 9094 // TODO: Support this. 9095 if (OpInfo.isIndirect) { 9096 emitInlineAsmError( 9097 Call, "Don't know how to handle indirect register inputs yet " 9098 "for constraint '" + 9099 Twine(OpInfo.ConstraintCode) + "'"); 9100 return; 9101 } 9102 9103 // Copy the input into the appropriate registers. 9104 if (OpInfo.AssignedRegs.Regs.empty()) { 9105 emitInlineAsmError(Call, 9106 "couldn't allocate input reg for constraint '" + 9107 Twine(OpInfo.ConstraintCode) + "'"); 9108 return; 9109 } 9110 9111 if (DetectWriteToReservedRegister()) 9112 return; 9113 9114 SDLoc dl = getCurSDLoc(); 9115 9116 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 9117 &Call); 9118 9119 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 9120 dl, DAG, AsmNodeOperands); 9121 break; 9122 } 9123 case InlineAsm::isClobber: 9124 // Add the clobbered value to the operand list, so that the register 9125 // allocator is aware that the physreg got clobbered. 9126 if (!OpInfo.AssignedRegs.Regs.empty()) 9127 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 9128 false, 0, getCurSDLoc(), DAG, 9129 AsmNodeOperands); 9130 break; 9131 } 9132 } 9133 9134 // Finish up input operands. Set the input chain and add the flag last. 9135 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 9136 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 9137 9138 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 9139 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 9140 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 9141 Flag = Chain.getValue(1); 9142 9143 // Do additional work to generate outputs. 9144 9145 SmallVector<EVT, 1> ResultVTs; 9146 SmallVector<SDValue, 1> ResultValues; 9147 SmallVector<SDValue, 8> OutChains; 9148 9149 llvm::Type *CallResultType = Call.getType(); 9150 ArrayRef<Type *> ResultTypes; 9151 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 9152 ResultTypes = StructResult->elements(); 9153 else if (!CallResultType->isVoidTy()) 9154 ResultTypes = makeArrayRef(CallResultType); 9155 9156 auto CurResultType = ResultTypes.begin(); 9157 auto handleRegAssign = [&](SDValue V) { 9158 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 9159 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 9160 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 9161 ++CurResultType; 9162 // If the type of the inline asm call site return value is different but has 9163 // same size as the type of the asm output bitcast it. One example of this 9164 // is for vectors with different width / number of elements. This can 9165 // happen for register classes that can contain multiple different value 9166 // types. The preg or vreg allocated may not have the same VT as was 9167 // expected. 9168 // 9169 // This can also happen for a return value that disagrees with the register 9170 // class it is put in, eg. a double in a general-purpose register on a 9171 // 32-bit machine. 9172 if (ResultVT != V.getValueType() && 9173 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 9174 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 9175 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 9176 V.getValueType().isInteger()) { 9177 // If a result value was tied to an input value, the computed result 9178 // may have a wider width than the expected result. Extract the 9179 // relevant portion. 9180 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 9181 } 9182 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 9183 ResultVTs.push_back(ResultVT); 9184 ResultValues.push_back(V); 9185 }; 9186 9187 // Deal with output operands. 9188 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9189 if (OpInfo.Type == InlineAsm::isOutput) { 9190 SDValue Val; 9191 // Skip trivial output operands. 9192 if (OpInfo.AssignedRegs.Regs.empty()) 9193 continue; 9194 9195 switch (OpInfo.ConstraintType) { 9196 case TargetLowering::C_Register: 9197 case TargetLowering::C_RegisterClass: 9198 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 9199 Chain, &Flag, &Call); 9200 break; 9201 case TargetLowering::C_Immediate: 9202 case TargetLowering::C_Other: 9203 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 9204 OpInfo, DAG); 9205 break; 9206 case TargetLowering::C_Memory: 9207 break; // Already handled. 9208 case TargetLowering::C_Address: 9209 break; // Silence warning. 9210 case TargetLowering::C_Unknown: 9211 assert(false && "Unexpected unknown constraint"); 9212 } 9213 9214 // Indirect output manifest as stores. Record output chains. 9215 if (OpInfo.isIndirect) { 9216 const Value *Ptr = OpInfo.CallOperandVal; 9217 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 9218 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 9219 MachinePointerInfo(Ptr)); 9220 OutChains.push_back(Store); 9221 } else { 9222 // generate CopyFromRegs to associated registers. 9223 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 9224 if (Val.getOpcode() == ISD::MERGE_VALUES) { 9225 for (const SDValue &V : Val->op_values()) 9226 handleRegAssign(V); 9227 } else 9228 handleRegAssign(Val); 9229 } 9230 } 9231 } 9232 9233 // Set results. 9234 if (!ResultValues.empty()) { 9235 assert(CurResultType == ResultTypes.end() && 9236 "Mismatch in number of ResultTypes"); 9237 assert(ResultValues.size() == ResultTypes.size() && 9238 "Mismatch in number of output operands in asm result"); 9239 9240 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 9241 DAG.getVTList(ResultVTs), ResultValues); 9242 setValue(&Call, V); 9243 } 9244 9245 // Collect store chains. 9246 if (!OutChains.empty()) 9247 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 9248 9249 if (EmitEHLabels) { 9250 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 9251 } 9252 9253 // Only Update Root if inline assembly has a memory effect. 9254 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 9255 EmitEHLabels) 9256 DAG.setRoot(Chain); 9257 } 9258 9259 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 9260 const Twine &Message) { 9261 LLVMContext &Ctx = *DAG.getContext(); 9262 Ctx.emitError(&Call, Message); 9263 9264 // Make sure we leave the DAG in a valid state 9265 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9266 SmallVector<EVT, 1> ValueVTs; 9267 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 9268 9269 if (ValueVTs.empty()) 9270 return; 9271 9272 SmallVector<SDValue, 1> Ops; 9273 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 9274 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 9275 9276 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 9277 } 9278 9279 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 9280 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 9281 MVT::Other, getRoot(), 9282 getValue(I.getArgOperand(0)), 9283 DAG.getSrcValue(I.getArgOperand(0)))); 9284 } 9285 9286 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 9287 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9288 const DataLayout &DL = DAG.getDataLayout(); 9289 SDValue V = DAG.getVAArg( 9290 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 9291 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 9292 DL.getABITypeAlign(I.getType()).value()); 9293 DAG.setRoot(V.getValue(1)); 9294 9295 if (I.getType()->isPointerTy()) 9296 V = DAG.getPtrExtOrTrunc( 9297 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 9298 setValue(&I, V); 9299 } 9300 9301 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 9302 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 9303 MVT::Other, getRoot(), 9304 getValue(I.getArgOperand(0)), 9305 DAG.getSrcValue(I.getArgOperand(0)))); 9306 } 9307 9308 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 9309 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 9310 MVT::Other, getRoot(), 9311 getValue(I.getArgOperand(0)), 9312 getValue(I.getArgOperand(1)), 9313 DAG.getSrcValue(I.getArgOperand(0)), 9314 DAG.getSrcValue(I.getArgOperand(1)))); 9315 } 9316 9317 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 9318 const Instruction &I, 9319 SDValue Op) { 9320 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 9321 if (!Range) 9322 return Op; 9323 9324 ConstantRange CR = getConstantRangeFromMetadata(*Range); 9325 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 9326 return Op; 9327 9328 APInt Lo = CR.getUnsignedMin(); 9329 if (!Lo.isMinValue()) 9330 return Op; 9331 9332 APInt Hi = CR.getUnsignedMax(); 9333 unsigned Bits = std::max(Hi.getActiveBits(), 9334 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 9335 9336 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9337 9338 SDLoc SL = getCurSDLoc(); 9339 9340 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 9341 DAG.getValueType(SmallVT)); 9342 unsigned NumVals = Op.getNode()->getNumValues(); 9343 if (NumVals == 1) 9344 return ZExt; 9345 9346 SmallVector<SDValue, 4> Ops; 9347 9348 Ops.push_back(ZExt); 9349 for (unsigned I = 1; I != NumVals; ++I) 9350 Ops.push_back(Op.getValue(I)); 9351 9352 return DAG.getMergeValues(Ops, SL); 9353 } 9354 9355 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 9356 /// the call being lowered. 9357 /// 9358 /// This is a helper for lowering intrinsics that follow a target calling 9359 /// convention or require stack pointer adjustment. Only a subset of the 9360 /// intrinsic's operands need to participate in the calling convention. 9361 void SelectionDAGBuilder::populateCallLoweringInfo( 9362 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 9363 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 9364 bool IsPatchPoint) { 9365 TargetLowering::ArgListTy Args; 9366 Args.reserve(NumArgs); 9367 9368 // Populate the argument list. 9369 // Attributes for args start at offset 1, after the return attribute. 9370 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 9371 ArgI != ArgE; ++ArgI) { 9372 const Value *V = Call->getOperand(ArgI); 9373 9374 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 9375 9376 TargetLowering::ArgListEntry Entry; 9377 Entry.Node = getValue(V); 9378 Entry.Ty = V->getType(); 9379 Entry.setAttributes(Call, ArgI); 9380 Args.push_back(Entry); 9381 } 9382 9383 CLI.setDebugLoc(getCurSDLoc()) 9384 .setChain(getRoot()) 9385 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 9386 .setDiscardResult(Call->use_empty()) 9387 .setIsPatchPoint(IsPatchPoint) 9388 .setIsPreallocated( 9389 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 9390 } 9391 9392 /// Add a stack map intrinsic call's live variable operands to a stackmap 9393 /// or patchpoint target node's operand list. 9394 /// 9395 /// Constants are converted to TargetConstants purely as an optimization to 9396 /// avoid constant materialization and register allocation. 9397 /// 9398 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 9399 /// generate addess computation nodes, and so FinalizeISel can convert the 9400 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 9401 /// address materialization and register allocation, but may also be required 9402 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 9403 /// alloca in the entry block, then the runtime may assume that the alloca's 9404 /// StackMap location can be read immediately after compilation and that the 9405 /// location is valid at any point during execution (this is similar to the 9406 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 9407 /// only available in a register, then the runtime would need to trap when 9408 /// execution reaches the StackMap in order to read the alloca's location. 9409 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 9410 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 9411 SelectionDAGBuilder &Builder) { 9412 SelectionDAG &DAG = Builder.DAG; 9413 for (unsigned I = StartIdx; I < Call.arg_size(); I++) { 9414 SDValue Op = Builder.getValue(Call.getArgOperand(I)); 9415 9416 // Things on the stack are pointer-typed, meaning that they are already 9417 // legal and can be emitted directly to target nodes. 9418 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) { 9419 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType())); 9420 } else { 9421 // Otherwise emit a target independent node to be legalised. 9422 Ops.push_back(Builder.getValue(Call.getArgOperand(I))); 9423 } 9424 } 9425 } 9426 9427 /// Lower llvm.experimental.stackmap. 9428 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 9429 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>, 9430 // [live variables...]) 9431 9432 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 9433 9434 SDValue Chain, InFlag, Callee; 9435 SmallVector<SDValue, 32> Ops; 9436 9437 SDLoc DL = getCurSDLoc(); 9438 Callee = getValue(CI.getCalledOperand()); 9439 9440 // The stackmap intrinsic only records the live variables (the arguments 9441 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 9442 // intrinsic, this won't be lowered to a function call. This means we don't 9443 // have to worry about calling conventions and target specific lowering code. 9444 // Instead we perform the call lowering right here. 9445 // 9446 // chain, flag = CALLSEQ_START(chain, 0, 0) 9447 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 9448 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 9449 // 9450 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 9451 InFlag = Chain.getValue(1); 9452 9453 // Add the STACKMAP operands, starting with DAG house-keeping. 9454 Ops.push_back(Chain); 9455 Ops.push_back(InFlag); 9456 9457 // Add the <id>, <numShadowBytes> operands. 9458 // 9459 // These do not require legalisation, and can be emitted directly to target 9460 // constant nodes. 9461 SDValue ID = getValue(CI.getArgOperand(0)); 9462 assert(ID.getValueType() == MVT::i64); 9463 SDValue IDConst = DAG.getTargetConstant( 9464 cast<ConstantSDNode>(ID)->getZExtValue(), DL, ID.getValueType()); 9465 Ops.push_back(IDConst); 9466 9467 SDValue Shad = getValue(CI.getArgOperand(1)); 9468 assert(Shad.getValueType() == MVT::i32); 9469 SDValue ShadConst = DAG.getTargetConstant( 9470 cast<ConstantSDNode>(Shad)->getZExtValue(), DL, Shad.getValueType()); 9471 Ops.push_back(ShadConst); 9472 9473 // Add the live variables. 9474 addStackMapLiveVars(CI, 2, DL, Ops, *this); 9475 9476 // Create the STACKMAP node. 9477 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9478 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops); 9479 InFlag = Chain.getValue(1); 9480 9481 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InFlag, DL); 9482 9483 // Stackmaps don't generate values, so nothing goes into the NodeMap. 9484 9485 // Set the root to the target-lowered call chain. 9486 DAG.setRoot(Chain); 9487 9488 // Inform the Frame Information that we have a stackmap in this function. 9489 FuncInfo.MF->getFrameInfo().setHasStackMap(); 9490 } 9491 9492 /// Lower llvm.experimental.patchpoint directly to its target opcode. 9493 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 9494 const BasicBlock *EHPadBB) { 9495 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 9496 // i32 <numBytes>, 9497 // i8* <target>, 9498 // i32 <numArgs>, 9499 // [Args...], 9500 // [live variables...]) 9501 9502 CallingConv::ID CC = CB.getCallingConv(); 9503 bool IsAnyRegCC = CC == CallingConv::AnyReg; 9504 bool HasDef = !CB.getType()->isVoidTy(); 9505 SDLoc dl = getCurSDLoc(); 9506 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 9507 9508 // Handle immediate and symbolic callees. 9509 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 9510 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 9511 /*isTarget=*/true); 9512 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 9513 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 9514 SDLoc(SymbolicCallee), 9515 SymbolicCallee->getValueType(0)); 9516 9517 // Get the real number of arguments participating in the call <numArgs> 9518 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 9519 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 9520 9521 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 9522 // Intrinsics include all meta-operands up to but not including CC. 9523 unsigned NumMetaOpers = PatchPointOpers::CCPos; 9524 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 9525 "Not enough arguments provided to the patchpoint intrinsic"); 9526 9527 // For AnyRegCC the arguments are lowered later on manually. 9528 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 9529 Type *ReturnTy = 9530 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 9531 9532 TargetLowering::CallLoweringInfo CLI(DAG); 9533 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 9534 ReturnTy, true); 9535 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 9536 9537 SDNode *CallEnd = Result.second.getNode(); 9538 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 9539 CallEnd = CallEnd->getOperand(0).getNode(); 9540 9541 /// Get a call instruction from the call sequence chain. 9542 /// Tail calls are not allowed. 9543 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 9544 "Expected a callseq node."); 9545 SDNode *Call = CallEnd->getOperand(0).getNode(); 9546 bool HasGlue = Call->getGluedNode(); 9547 9548 // Replace the target specific call node with the patchable intrinsic. 9549 SmallVector<SDValue, 8> Ops; 9550 9551 // Push the chain. 9552 Ops.push_back(*(Call->op_begin())); 9553 9554 // Optionally, push the glue (if any). 9555 if (HasGlue) 9556 Ops.push_back(*(Call->op_end() - 1)); 9557 9558 // Push the register mask info. 9559 if (HasGlue) 9560 Ops.push_back(*(Call->op_end() - 2)); 9561 else 9562 Ops.push_back(*(Call->op_end() - 1)); 9563 9564 // Add the <id> and <numBytes> constants. 9565 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 9566 Ops.push_back(DAG.getTargetConstant( 9567 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 9568 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 9569 Ops.push_back(DAG.getTargetConstant( 9570 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 9571 MVT::i32)); 9572 9573 // Add the callee. 9574 Ops.push_back(Callee); 9575 9576 // Adjust <numArgs> to account for any arguments that have been passed on the 9577 // stack instead. 9578 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 9579 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 9580 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 9581 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 9582 9583 // Add the calling convention 9584 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 9585 9586 // Add the arguments we omitted previously. The register allocator should 9587 // place these in any free register. 9588 if (IsAnyRegCC) 9589 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 9590 Ops.push_back(getValue(CB.getArgOperand(i))); 9591 9592 // Push the arguments from the call instruction. 9593 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 9594 Ops.append(Call->op_begin() + 2, e); 9595 9596 // Push live variables for the stack map. 9597 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 9598 9599 SDVTList NodeTys; 9600 if (IsAnyRegCC && HasDef) { 9601 // Create the return types based on the intrinsic definition 9602 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9603 SmallVector<EVT, 3> ValueVTs; 9604 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 9605 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 9606 9607 // There is always a chain and a glue type at the end 9608 ValueVTs.push_back(MVT::Other); 9609 ValueVTs.push_back(MVT::Glue); 9610 NodeTys = DAG.getVTList(ValueVTs); 9611 } else 9612 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9613 9614 // Replace the target specific call node with a PATCHPOINT node. 9615 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops); 9616 9617 // Update the NodeMap. 9618 if (HasDef) { 9619 if (IsAnyRegCC) 9620 setValue(&CB, SDValue(PPV.getNode(), 0)); 9621 else 9622 setValue(&CB, Result.first); 9623 } 9624 9625 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 9626 // call sequence. Furthermore the location of the chain and glue can change 9627 // when the AnyReg calling convention is used and the intrinsic returns a 9628 // value. 9629 if (IsAnyRegCC && HasDef) { 9630 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 9631 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)}; 9632 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 9633 } else 9634 DAG.ReplaceAllUsesWith(Call, PPV.getNode()); 9635 DAG.DeleteNode(Call); 9636 9637 // Inform the Frame Information that we have a patchpoint in this function. 9638 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 9639 } 9640 9641 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 9642 unsigned Intrinsic) { 9643 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9644 SDValue Op1 = getValue(I.getArgOperand(0)); 9645 SDValue Op2; 9646 if (I.arg_size() > 1) 9647 Op2 = getValue(I.getArgOperand(1)); 9648 SDLoc dl = getCurSDLoc(); 9649 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 9650 SDValue Res; 9651 SDNodeFlags SDFlags; 9652 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 9653 SDFlags.copyFMF(*FPMO); 9654 9655 switch (Intrinsic) { 9656 case Intrinsic::vector_reduce_fadd: 9657 if (SDFlags.hasAllowReassociation()) 9658 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 9659 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 9660 SDFlags); 9661 else 9662 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 9663 break; 9664 case Intrinsic::vector_reduce_fmul: 9665 if (SDFlags.hasAllowReassociation()) 9666 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 9667 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 9668 SDFlags); 9669 else 9670 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 9671 break; 9672 case Intrinsic::vector_reduce_add: 9673 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 9674 break; 9675 case Intrinsic::vector_reduce_mul: 9676 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 9677 break; 9678 case Intrinsic::vector_reduce_and: 9679 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 9680 break; 9681 case Intrinsic::vector_reduce_or: 9682 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 9683 break; 9684 case Intrinsic::vector_reduce_xor: 9685 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 9686 break; 9687 case Intrinsic::vector_reduce_smax: 9688 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 9689 break; 9690 case Intrinsic::vector_reduce_smin: 9691 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 9692 break; 9693 case Intrinsic::vector_reduce_umax: 9694 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 9695 break; 9696 case Intrinsic::vector_reduce_umin: 9697 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 9698 break; 9699 case Intrinsic::vector_reduce_fmax: 9700 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 9701 break; 9702 case Intrinsic::vector_reduce_fmin: 9703 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 9704 break; 9705 default: 9706 llvm_unreachable("Unhandled vector reduce intrinsic"); 9707 } 9708 setValue(&I, Res); 9709 } 9710 9711 /// Returns an AttributeList representing the attributes applied to the return 9712 /// value of the given call. 9713 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9714 SmallVector<Attribute::AttrKind, 2> Attrs; 9715 if (CLI.RetSExt) 9716 Attrs.push_back(Attribute::SExt); 9717 if (CLI.RetZExt) 9718 Attrs.push_back(Attribute::ZExt); 9719 if (CLI.IsInReg) 9720 Attrs.push_back(Attribute::InReg); 9721 9722 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9723 Attrs); 9724 } 9725 9726 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9727 /// implementation, which just calls LowerCall. 9728 /// FIXME: When all targets are 9729 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9730 std::pair<SDValue, SDValue> 9731 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9732 // Handle the incoming return values from the call. 9733 CLI.Ins.clear(); 9734 Type *OrigRetTy = CLI.RetTy; 9735 SmallVector<EVT, 4> RetTys; 9736 SmallVector<uint64_t, 4> Offsets; 9737 auto &DL = CLI.DAG.getDataLayout(); 9738 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 9739 9740 if (CLI.IsPostTypeLegalization) { 9741 // If we are lowering a libcall after legalization, split the return type. 9742 SmallVector<EVT, 4> OldRetTys; 9743 SmallVector<uint64_t, 4> OldOffsets; 9744 RetTys.swap(OldRetTys); 9745 Offsets.swap(OldOffsets); 9746 9747 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9748 EVT RetVT = OldRetTys[i]; 9749 uint64_t Offset = OldOffsets[i]; 9750 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9751 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9752 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9753 RetTys.append(NumRegs, RegisterVT); 9754 for (unsigned j = 0; j != NumRegs; ++j) 9755 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9756 } 9757 } 9758 9759 SmallVector<ISD::OutputArg, 4> Outs; 9760 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9761 9762 bool CanLowerReturn = 9763 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9764 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9765 9766 SDValue DemoteStackSlot; 9767 int DemoteStackIdx = -100; 9768 if (!CanLowerReturn) { 9769 // FIXME: equivalent assert? 9770 // assert(!CS.hasInAllocaArgument() && 9771 // "sret demotion is incompatible with inalloca"); 9772 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9773 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 9774 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9775 DemoteStackIdx = 9776 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 9777 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9778 DL.getAllocaAddrSpace()); 9779 9780 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9781 ArgListEntry Entry; 9782 Entry.Node = DemoteStackSlot; 9783 Entry.Ty = StackSlotPtrType; 9784 Entry.IsSExt = false; 9785 Entry.IsZExt = false; 9786 Entry.IsInReg = false; 9787 Entry.IsSRet = true; 9788 Entry.IsNest = false; 9789 Entry.IsByVal = false; 9790 Entry.IsByRef = false; 9791 Entry.IsReturned = false; 9792 Entry.IsSwiftSelf = false; 9793 Entry.IsSwiftAsync = false; 9794 Entry.IsSwiftError = false; 9795 Entry.IsCFGuardTarget = false; 9796 Entry.Alignment = Alignment; 9797 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9798 CLI.NumFixedArgs += 1; 9799 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9800 9801 // sret demotion isn't compatible with tail-calls, since the sret argument 9802 // points into the callers stack frame. 9803 CLI.IsTailCall = false; 9804 } else { 9805 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9806 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL); 9807 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9808 ISD::ArgFlagsTy Flags; 9809 if (NeedsRegBlock) { 9810 Flags.setInConsecutiveRegs(); 9811 if (I == RetTys.size() - 1) 9812 Flags.setInConsecutiveRegsLast(); 9813 } 9814 EVT VT = RetTys[I]; 9815 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9816 CLI.CallConv, VT); 9817 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9818 CLI.CallConv, VT); 9819 for (unsigned i = 0; i != NumRegs; ++i) { 9820 ISD::InputArg MyFlags; 9821 MyFlags.Flags = Flags; 9822 MyFlags.VT = RegisterVT; 9823 MyFlags.ArgVT = VT; 9824 MyFlags.Used = CLI.IsReturnValueUsed; 9825 if (CLI.RetTy->isPointerTy()) { 9826 MyFlags.Flags.setPointer(); 9827 MyFlags.Flags.setPointerAddrSpace( 9828 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9829 } 9830 if (CLI.RetSExt) 9831 MyFlags.Flags.setSExt(); 9832 if (CLI.RetZExt) 9833 MyFlags.Flags.setZExt(); 9834 if (CLI.IsInReg) 9835 MyFlags.Flags.setInReg(); 9836 CLI.Ins.push_back(MyFlags); 9837 } 9838 } 9839 } 9840 9841 // We push in swifterror return as the last element of CLI.Ins. 9842 ArgListTy &Args = CLI.getArgs(); 9843 if (supportSwiftError()) { 9844 for (const ArgListEntry &Arg : Args) { 9845 if (Arg.IsSwiftError) { 9846 ISD::InputArg MyFlags; 9847 MyFlags.VT = getPointerTy(DL); 9848 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9849 MyFlags.Flags.setSwiftError(); 9850 CLI.Ins.push_back(MyFlags); 9851 } 9852 } 9853 } 9854 9855 // Handle all of the outgoing arguments. 9856 CLI.Outs.clear(); 9857 CLI.OutVals.clear(); 9858 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9859 SmallVector<EVT, 4> ValueVTs; 9860 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9861 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9862 Type *FinalType = Args[i].Ty; 9863 if (Args[i].IsByVal) 9864 FinalType = Args[i].IndirectType; 9865 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9866 FinalType, CLI.CallConv, CLI.IsVarArg, DL); 9867 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9868 ++Value) { 9869 EVT VT = ValueVTs[Value]; 9870 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9871 SDValue Op = SDValue(Args[i].Node.getNode(), 9872 Args[i].Node.getResNo() + Value); 9873 ISD::ArgFlagsTy Flags; 9874 9875 // Certain targets (such as MIPS), may have a different ABI alignment 9876 // for a type depending on the context. Give the target a chance to 9877 // specify the alignment it wants. 9878 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 9879 Flags.setOrigAlign(OriginalAlignment); 9880 9881 if (Args[i].Ty->isPointerTy()) { 9882 Flags.setPointer(); 9883 Flags.setPointerAddrSpace( 9884 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9885 } 9886 if (Args[i].IsZExt) 9887 Flags.setZExt(); 9888 if (Args[i].IsSExt) 9889 Flags.setSExt(); 9890 if (Args[i].IsInReg) { 9891 // If we are using vectorcall calling convention, a structure that is 9892 // passed InReg - is surely an HVA 9893 if (CLI.CallConv == CallingConv::X86_VectorCall && 9894 isa<StructType>(FinalType)) { 9895 // The first value of a structure is marked 9896 if (0 == Value) 9897 Flags.setHvaStart(); 9898 Flags.setHva(); 9899 } 9900 // Set InReg Flag 9901 Flags.setInReg(); 9902 } 9903 if (Args[i].IsSRet) 9904 Flags.setSRet(); 9905 if (Args[i].IsSwiftSelf) 9906 Flags.setSwiftSelf(); 9907 if (Args[i].IsSwiftAsync) 9908 Flags.setSwiftAsync(); 9909 if (Args[i].IsSwiftError) 9910 Flags.setSwiftError(); 9911 if (Args[i].IsCFGuardTarget) 9912 Flags.setCFGuardTarget(); 9913 if (Args[i].IsByVal) 9914 Flags.setByVal(); 9915 if (Args[i].IsByRef) 9916 Flags.setByRef(); 9917 if (Args[i].IsPreallocated) { 9918 Flags.setPreallocated(); 9919 // Set the byval flag for CCAssignFn callbacks that don't know about 9920 // preallocated. This way we can know how many bytes we should've 9921 // allocated and how many bytes a callee cleanup function will pop. If 9922 // we port preallocated to more targets, we'll have to add custom 9923 // preallocated handling in the various CC lowering callbacks. 9924 Flags.setByVal(); 9925 } 9926 if (Args[i].IsInAlloca) { 9927 Flags.setInAlloca(); 9928 // Set the byval flag for CCAssignFn callbacks that don't know about 9929 // inalloca. This way we can know how many bytes we should've allocated 9930 // and how many bytes a callee cleanup function will pop. If we port 9931 // inalloca to more targets, we'll have to add custom inalloca handling 9932 // in the various CC lowering callbacks. 9933 Flags.setByVal(); 9934 } 9935 Align MemAlign; 9936 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 9937 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType); 9938 Flags.setByValSize(FrameSize); 9939 9940 // info is not there but there are cases it cannot get right. 9941 if (auto MA = Args[i].Alignment) 9942 MemAlign = *MA; 9943 else 9944 MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL)); 9945 } else if (auto MA = Args[i].Alignment) { 9946 MemAlign = *MA; 9947 } else { 9948 MemAlign = OriginalAlignment; 9949 } 9950 Flags.setMemAlign(MemAlign); 9951 if (Args[i].IsNest) 9952 Flags.setNest(); 9953 if (NeedsRegBlock) 9954 Flags.setInConsecutiveRegs(); 9955 9956 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9957 CLI.CallConv, VT); 9958 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9959 CLI.CallConv, VT); 9960 SmallVector<SDValue, 4> Parts(NumParts); 9961 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9962 9963 if (Args[i].IsSExt) 9964 ExtendKind = ISD::SIGN_EXTEND; 9965 else if (Args[i].IsZExt) 9966 ExtendKind = ISD::ZERO_EXTEND; 9967 9968 // Conservatively only handle 'returned' on non-vectors that can be lowered, 9969 // for now. 9970 if (Args[i].IsReturned && !Op.getValueType().isVector() && 9971 CanLowerReturn) { 9972 assert((CLI.RetTy == Args[i].Ty || 9973 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 9974 CLI.RetTy->getPointerAddressSpace() == 9975 Args[i].Ty->getPointerAddressSpace())) && 9976 RetTys.size() == NumValues && "unexpected use of 'returned'"); 9977 // Before passing 'returned' to the target lowering code, ensure that 9978 // either the register MVT and the actual EVT are the same size or that 9979 // the return value and argument are extended in the same way; in these 9980 // cases it's safe to pass the argument register value unchanged as the 9981 // return register value (although it's at the target's option whether 9982 // to do so) 9983 // TODO: allow code generation to take advantage of partially preserved 9984 // registers rather than clobbering the entire register when the 9985 // parameter extension method is not compatible with the return 9986 // extension method 9987 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9988 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9989 CLI.RetZExt == Args[i].IsZExt)) 9990 Flags.setReturned(); 9991 } 9992 9993 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 9994 CLI.CallConv, ExtendKind); 9995 9996 for (unsigned j = 0; j != NumParts; ++j) { 9997 // if it isn't first piece, alignment must be 1 9998 // For scalable vectors the scalable part is currently handled 9999 // by individual targets, so we just use the known minimum size here. 10000 ISD::OutputArg MyFlags( 10001 Flags, Parts[j].getValueType().getSimpleVT(), VT, 10002 i < CLI.NumFixedArgs, i, 10003 j * Parts[j].getValueType().getStoreSize().getKnownMinSize()); 10004 if (NumParts > 1 && j == 0) 10005 MyFlags.Flags.setSplit(); 10006 else if (j != 0) { 10007 MyFlags.Flags.setOrigAlign(Align(1)); 10008 if (j == NumParts - 1) 10009 MyFlags.Flags.setSplitEnd(); 10010 } 10011 10012 CLI.Outs.push_back(MyFlags); 10013 CLI.OutVals.push_back(Parts[j]); 10014 } 10015 10016 if (NeedsRegBlock && Value == NumValues - 1) 10017 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 10018 } 10019 } 10020 10021 SmallVector<SDValue, 4> InVals; 10022 CLI.Chain = LowerCall(CLI, InVals); 10023 10024 // Update CLI.InVals to use outside of this function. 10025 CLI.InVals = InVals; 10026 10027 // Verify that the target's LowerCall behaved as expected. 10028 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 10029 "LowerCall didn't return a valid chain!"); 10030 assert((!CLI.IsTailCall || InVals.empty()) && 10031 "LowerCall emitted a return value for a tail call!"); 10032 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 10033 "LowerCall didn't emit the correct number of values!"); 10034 10035 // For a tail call, the return value is merely live-out and there aren't 10036 // any nodes in the DAG representing it. Return a special value to 10037 // indicate that a tail call has been emitted and no more Instructions 10038 // should be processed in the current block. 10039 if (CLI.IsTailCall) { 10040 CLI.DAG.setRoot(CLI.Chain); 10041 return std::make_pair(SDValue(), SDValue()); 10042 } 10043 10044 #ifndef NDEBUG 10045 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 10046 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 10047 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 10048 "LowerCall emitted a value with the wrong type!"); 10049 } 10050 #endif 10051 10052 SmallVector<SDValue, 4> ReturnValues; 10053 if (!CanLowerReturn) { 10054 // The instruction result is the result of loading from the 10055 // hidden sret parameter. 10056 SmallVector<EVT, 1> PVTs; 10057 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 10058 10059 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 10060 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 10061 EVT PtrVT = PVTs[0]; 10062 10063 unsigned NumValues = RetTys.size(); 10064 ReturnValues.resize(NumValues); 10065 SmallVector<SDValue, 4> Chains(NumValues); 10066 10067 // An aggregate return value cannot wrap around the address space, so 10068 // offsets to its parts don't wrap either. 10069 SDNodeFlags Flags; 10070 Flags.setNoUnsignedWrap(true); 10071 10072 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10073 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 10074 for (unsigned i = 0; i < NumValues; ++i) { 10075 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 10076 CLI.DAG.getConstant(Offsets[i], CLI.DL, 10077 PtrVT), Flags); 10078 SDValue L = CLI.DAG.getLoad( 10079 RetTys[i], CLI.DL, CLI.Chain, Add, 10080 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 10081 DemoteStackIdx, Offsets[i]), 10082 HiddenSRetAlign); 10083 ReturnValues[i] = L; 10084 Chains[i] = L.getValue(1); 10085 } 10086 10087 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 10088 } else { 10089 // Collect the legal value parts into potentially illegal values 10090 // that correspond to the original function's return values. 10091 Optional<ISD::NodeType> AssertOp; 10092 if (CLI.RetSExt) 10093 AssertOp = ISD::AssertSext; 10094 else if (CLI.RetZExt) 10095 AssertOp = ISD::AssertZext; 10096 unsigned CurReg = 0; 10097 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 10098 EVT VT = RetTys[I]; 10099 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10100 CLI.CallConv, VT); 10101 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10102 CLI.CallConv, VT); 10103 10104 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 10105 NumRegs, RegisterVT, VT, nullptr, 10106 CLI.CallConv, AssertOp)); 10107 CurReg += NumRegs; 10108 } 10109 10110 // For a function returning void, there is no return value. We can't create 10111 // such a node, so we just return a null return value in that case. In 10112 // that case, nothing will actually look at the value. 10113 if (ReturnValues.empty()) 10114 return std::make_pair(SDValue(), CLI.Chain); 10115 } 10116 10117 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 10118 CLI.DAG.getVTList(RetTys), ReturnValues); 10119 return std::make_pair(Res, CLI.Chain); 10120 } 10121 10122 /// Places new result values for the node in Results (their number 10123 /// and types must exactly match those of the original return values of 10124 /// the node), or leaves Results empty, which indicates that the node is not 10125 /// to be custom lowered after all. 10126 void TargetLowering::LowerOperationWrapper(SDNode *N, 10127 SmallVectorImpl<SDValue> &Results, 10128 SelectionDAG &DAG) const { 10129 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 10130 10131 if (!Res.getNode()) 10132 return; 10133 10134 // If the original node has one result, take the return value from 10135 // LowerOperation as is. It might not be result number 0. 10136 if (N->getNumValues() == 1) { 10137 Results.push_back(Res); 10138 return; 10139 } 10140 10141 // If the original node has multiple results, then the return node should 10142 // have the same number of results. 10143 assert((N->getNumValues() == Res->getNumValues()) && 10144 "Lowering returned the wrong number of results!"); 10145 10146 // Places new result values base on N result number. 10147 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 10148 Results.push_back(Res.getValue(I)); 10149 } 10150 10151 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10152 llvm_unreachable("LowerOperation not implemented for this target!"); 10153 } 10154 10155 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, 10156 unsigned Reg, 10157 ISD::NodeType ExtendType) { 10158 SDValue Op = getNonRegisterValue(V); 10159 assert((Op.getOpcode() != ISD::CopyFromReg || 10160 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 10161 "Copy from a reg to the same reg!"); 10162 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 10163 10164 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10165 // If this is an InlineAsm we have to match the registers required, not the 10166 // notional registers required by the type. 10167 10168 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 10169 None); // This is not an ABI copy. 10170 SDValue Chain = DAG.getEntryNode(); 10171 10172 if (ExtendType == ISD::ANY_EXTEND) { 10173 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V); 10174 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end()) 10175 ExtendType = PreferredExtendIt->second; 10176 } 10177 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 10178 PendingExports.push_back(Chain); 10179 } 10180 10181 #include "llvm/CodeGen/SelectionDAGISel.h" 10182 10183 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 10184 /// entry block, return true. This includes arguments used by switches, since 10185 /// the switch may expand into multiple basic blocks. 10186 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 10187 // With FastISel active, we may be splitting blocks, so force creation 10188 // of virtual registers for all non-dead arguments. 10189 if (FastISel) 10190 return A->use_empty(); 10191 10192 const BasicBlock &Entry = A->getParent()->front(); 10193 for (const User *U : A->users()) 10194 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 10195 return false; // Use not in entry block. 10196 10197 return true; 10198 } 10199 10200 using ArgCopyElisionMapTy = 10201 DenseMap<const Argument *, 10202 std::pair<const AllocaInst *, const StoreInst *>>; 10203 10204 /// Scan the entry block of the function in FuncInfo for arguments that look 10205 /// like copies into a local alloca. Record any copied arguments in 10206 /// ArgCopyElisionCandidates. 10207 static void 10208 findArgumentCopyElisionCandidates(const DataLayout &DL, 10209 FunctionLoweringInfo *FuncInfo, 10210 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 10211 // Record the state of every static alloca used in the entry block. Argument 10212 // allocas are all used in the entry block, so we need approximately as many 10213 // entries as we have arguments. 10214 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 10215 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 10216 unsigned NumArgs = FuncInfo->Fn->arg_size(); 10217 StaticAllocas.reserve(NumArgs * 2); 10218 10219 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 10220 if (!V) 10221 return nullptr; 10222 V = V->stripPointerCasts(); 10223 const auto *AI = dyn_cast<AllocaInst>(V); 10224 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 10225 return nullptr; 10226 auto Iter = StaticAllocas.insert({AI, Unknown}); 10227 return &Iter.first->second; 10228 }; 10229 10230 // Look for stores of arguments to static allocas. Look through bitcasts and 10231 // GEPs to handle type coercions, as long as the alloca is fully initialized 10232 // by the store. Any non-store use of an alloca escapes it and any subsequent 10233 // unanalyzed store might write it. 10234 // FIXME: Handle structs initialized with multiple stores. 10235 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 10236 // Look for stores, and handle non-store uses conservatively. 10237 const auto *SI = dyn_cast<StoreInst>(&I); 10238 if (!SI) { 10239 // We will look through cast uses, so ignore them completely. 10240 if (I.isCast()) 10241 continue; 10242 // Ignore debug info and pseudo op intrinsics, they don't escape or store 10243 // to allocas. 10244 if (I.isDebugOrPseudoInst()) 10245 continue; 10246 // This is an unknown instruction. Assume it escapes or writes to all 10247 // static alloca operands. 10248 for (const Use &U : I.operands()) { 10249 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 10250 *Info = StaticAllocaInfo::Clobbered; 10251 } 10252 continue; 10253 } 10254 10255 // If the stored value is a static alloca, mark it as escaped. 10256 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 10257 *Info = StaticAllocaInfo::Clobbered; 10258 10259 // Check if the destination is a static alloca. 10260 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 10261 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 10262 if (!Info) 10263 continue; 10264 const AllocaInst *AI = cast<AllocaInst>(Dst); 10265 10266 // Skip allocas that have been initialized or clobbered. 10267 if (*Info != StaticAllocaInfo::Unknown) 10268 continue; 10269 10270 // Check if the stored value is an argument, and that this store fully 10271 // initializes the alloca. 10272 // If the argument type has padding bits we can't directly forward a pointer 10273 // as the upper bits may contain garbage. 10274 // Don't elide copies from the same argument twice. 10275 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 10276 const auto *Arg = dyn_cast<Argument>(Val); 10277 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 10278 Arg->getType()->isEmptyTy() || 10279 DL.getTypeStoreSize(Arg->getType()) != 10280 DL.getTypeAllocSize(AI->getAllocatedType()) || 10281 !DL.typeSizeEqualsStoreSize(Arg->getType()) || 10282 ArgCopyElisionCandidates.count(Arg)) { 10283 *Info = StaticAllocaInfo::Clobbered; 10284 continue; 10285 } 10286 10287 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 10288 << '\n'); 10289 10290 // Mark this alloca and store for argument copy elision. 10291 *Info = StaticAllocaInfo::Elidable; 10292 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 10293 10294 // Stop scanning if we've seen all arguments. This will happen early in -O0 10295 // builds, which is useful, because -O0 builds have large entry blocks and 10296 // many allocas. 10297 if (ArgCopyElisionCandidates.size() == NumArgs) 10298 break; 10299 } 10300 } 10301 10302 /// Try to elide argument copies from memory into a local alloca. Succeeds if 10303 /// ArgVal is a load from a suitable fixed stack object. 10304 static void tryToElideArgumentCopy( 10305 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 10306 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 10307 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 10308 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 10309 SDValue ArgVal, bool &ArgHasUses) { 10310 // Check if this is a load from a fixed stack object. 10311 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 10312 if (!LNode) 10313 return; 10314 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 10315 if (!FINode) 10316 return; 10317 10318 // Check that the fixed stack object is the right size and alignment. 10319 // Look at the alignment that the user wrote on the alloca instead of looking 10320 // at the stack object. 10321 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 10322 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 10323 const AllocaInst *AI = ArgCopyIter->second.first; 10324 int FixedIndex = FINode->getIndex(); 10325 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 10326 int OldIndex = AllocaIndex; 10327 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 10328 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 10329 LLVM_DEBUG( 10330 dbgs() << " argument copy elision failed due to bad fixed stack " 10331 "object size\n"); 10332 return; 10333 } 10334 Align RequiredAlignment = AI->getAlign(); 10335 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 10336 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 10337 "greater than stack argument alignment (" 10338 << DebugStr(RequiredAlignment) << " vs " 10339 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 10340 return; 10341 } 10342 10343 // Perform the elision. Delete the old stack object and replace its only use 10344 // in the variable info map. Mark the stack object as mutable. 10345 LLVM_DEBUG({ 10346 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 10347 << " Replacing frame index " << OldIndex << " with " << FixedIndex 10348 << '\n'; 10349 }); 10350 MFI.RemoveStackObject(OldIndex); 10351 MFI.setIsImmutableObjectIndex(FixedIndex, false); 10352 AllocaIndex = FixedIndex; 10353 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 10354 Chains.push_back(ArgVal.getValue(1)); 10355 10356 // Avoid emitting code for the store implementing the copy. 10357 const StoreInst *SI = ArgCopyIter->second.second; 10358 ElidedArgCopyInstrs.insert(SI); 10359 10360 // Check for uses of the argument again so that we can avoid exporting ArgVal 10361 // if it is't used by anything other than the store. 10362 for (const Value *U : Arg.users()) { 10363 if (U != SI) { 10364 ArgHasUses = true; 10365 break; 10366 } 10367 } 10368 } 10369 10370 void SelectionDAGISel::LowerArguments(const Function &F) { 10371 SelectionDAG &DAG = SDB->DAG; 10372 SDLoc dl = SDB->getCurSDLoc(); 10373 const DataLayout &DL = DAG.getDataLayout(); 10374 SmallVector<ISD::InputArg, 16> Ins; 10375 10376 // In Naked functions we aren't going to save any registers. 10377 if (F.hasFnAttribute(Attribute::Naked)) 10378 return; 10379 10380 if (!FuncInfo->CanLowerReturn) { 10381 // Put in an sret pointer parameter before all the other parameters. 10382 SmallVector<EVT, 1> ValueVTs; 10383 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10384 F.getReturnType()->getPointerTo( 10385 DAG.getDataLayout().getAllocaAddrSpace()), 10386 ValueVTs); 10387 10388 // NOTE: Assuming that a pointer will never break down to more than one VT 10389 // or one register. 10390 ISD::ArgFlagsTy Flags; 10391 Flags.setSRet(); 10392 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 10393 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 10394 ISD::InputArg::NoArgIndex, 0); 10395 Ins.push_back(RetArg); 10396 } 10397 10398 // Look for stores of arguments to static allocas. Mark such arguments with a 10399 // flag to ask the target to give us the memory location of that argument if 10400 // available. 10401 ArgCopyElisionMapTy ArgCopyElisionCandidates; 10402 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 10403 ArgCopyElisionCandidates); 10404 10405 // Set up the incoming argument description vector. 10406 for (const Argument &Arg : F.args()) { 10407 unsigned ArgNo = Arg.getArgNo(); 10408 SmallVector<EVT, 4> ValueVTs; 10409 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10410 bool isArgValueUsed = !Arg.use_empty(); 10411 unsigned PartBase = 0; 10412 Type *FinalType = Arg.getType(); 10413 if (Arg.hasAttribute(Attribute::ByVal)) 10414 FinalType = Arg.getParamByValType(); 10415 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 10416 FinalType, F.getCallingConv(), F.isVarArg(), DL); 10417 for (unsigned Value = 0, NumValues = ValueVTs.size(); 10418 Value != NumValues; ++Value) { 10419 EVT VT = ValueVTs[Value]; 10420 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 10421 ISD::ArgFlagsTy Flags; 10422 10423 10424 if (Arg.getType()->isPointerTy()) { 10425 Flags.setPointer(); 10426 Flags.setPointerAddrSpace( 10427 cast<PointerType>(Arg.getType())->getAddressSpace()); 10428 } 10429 if (Arg.hasAttribute(Attribute::ZExt)) 10430 Flags.setZExt(); 10431 if (Arg.hasAttribute(Attribute::SExt)) 10432 Flags.setSExt(); 10433 if (Arg.hasAttribute(Attribute::InReg)) { 10434 // If we are using vectorcall calling convention, a structure that is 10435 // passed InReg - is surely an HVA 10436 if (F.getCallingConv() == CallingConv::X86_VectorCall && 10437 isa<StructType>(Arg.getType())) { 10438 // The first value of a structure is marked 10439 if (0 == Value) 10440 Flags.setHvaStart(); 10441 Flags.setHva(); 10442 } 10443 // Set InReg Flag 10444 Flags.setInReg(); 10445 } 10446 if (Arg.hasAttribute(Attribute::StructRet)) 10447 Flags.setSRet(); 10448 if (Arg.hasAttribute(Attribute::SwiftSelf)) 10449 Flags.setSwiftSelf(); 10450 if (Arg.hasAttribute(Attribute::SwiftAsync)) 10451 Flags.setSwiftAsync(); 10452 if (Arg.hasAttribute(Attribute::SwiftError)) 10453 Flags.setSwiftError(); 10454 if (Arg.hasAttribute(Attribute::ByVal)) 10455 Flags.setByVal(); 10456 if (Arg.hasAttribute(Attribute::ByRef)) 10457 Flags.setByRef(); 10458 if (Arg.hasAttribute(Attribute::InAlloca)) { 10459 Flags.setInAlloca(); 10460 // Set the byval flag for CCAssignFn callbacks that don't know about 10461 // inalloca. This way we can know how many bytes we should've allocated 10462 // and how many bytes a callee cleanup function will pop. If we port 10463 // inalloca to more targets, we'll have to add custom inalloca handling 10464 // in the various CC lowering callbacks. 10465 Flags.setByVal(); 10466 } 10467 if (Arg.hasAttribute(Attribute::Preallocated)) { 10468 Flags.setPreallocated(); 10469 // Set the byval flag for CCAssignFn callbacks that don't know about 10470 // preallocated. This way we can know how many bytes we should've 10471 // allocated and how many bytes a callee cleanup function will pop. If 10472 // we port preallocated to more targets, we'll have to add custom 10473 // preallocated handling in the various CC lowering callbacks. 10474 Flags.setByVal(); 10475 } 10476 10477 // Certain targets (such as MIPS), may have a different ABI alignment 10478 // for a type depending on the context. Give the target a chance to 10479 // specify the alignment it wants. 10480 const Align OriginalAlignment( 10481 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 10482 Flags.setOrigAlign(OriginalAlignment); 10483 10484 Align MemAlign; 10485 Type *ArgMemTy = nullptr; 10486 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 10487 Flags.isByRef()) { 10488 if (!ArgMemTy) 10489 ArgMemTy = Arg.getPointeeInMemoryValueType(); 10490 10491 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 10492 10493 // For in-memory arguments, size and alignment should be passed from FE. 10494 // BE will guess if this info is not there but there are cases it cannot 10495 // get right. 10496 if (auto ParamAlign = Arg.getParamStackAlign()) 10497 MemAlign = *ParamAlign; 10498 else if ((ParamAlign = Arg.getParamAlign())) 10499 MemAlign = *ParamAlign; 10500 else 10501 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 10502 if (Flags.isByRef()) 10503 Flags.setByRefSize(MemSize); 10504 else 10505 Flags.setByValSize(MemSize); 10506 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 10507 MemAlign = *ParamAlign; 10508 } else { 10509 MemAlign = OriginalAlignment; 10510 } 10511 Flags.setMemAlign(MemAlign); 10512 10513 if (Arg.hasAttribute(Attribute::Nest)) 10514 Flags.setNest(); 10515 if (NeedsRegBlock) 10516 Flags.setInConsecutiveRegs(); 10517 if (ArgCopyElisionCandidates.count(&Arg)) 10518 Flags.setCopyElisionCandidate(); 10519 if (Arg.hasAttribute(Attribute::Returned)) 10520 Flags.setReturned(); 10521 10522 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 10523 *CurDAG->getContext(), F.getCallingConv(), VT); 10524 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 10525 *CurDAG->getContext(), F.getCallingConv(), VT); 10526 for (unsigned i = 0; i != NumRegs; ++i) { 10527 // For scalable vectors, use the minimum size; individual targets 10528 // are responsible for handling scalable vector arguments and 10529 // return values. 10530 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 10531 ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize()); 10532 if (NumRegs > 1 && i == 0) 10533 MyFlags.Flags.setSplit(); 10534 // if it isn't first piece, alignment must be 1 10535 else if (i > 0) { 10536 MyFlags.Flags.setOrigAlign(Align(1)); 10537 if (i == NumRegs - 1) 10538 MyFlags.Flags.setSplitEnd(); 10539 } 10540 Ins.push_back(MyFlags); 10541 } 10542 if (NeedsRegBlock && Value == NumValues - 1) 10543 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 10544 PartBase += VT.getStoreSize().getKnownMinSize(); 10545 } 10546 } 10547 10548 // Call the target to set up the argument values. 10549 SmallVector<SDValue, 8> InVals; 10550 SDValue NewRoot = TLI->LowerFormalArguments( 10551 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 10552 10553 // Verify that the target's LowerFormalArguments behaved as expected. 10554 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 10555 "LowerFormalArguments didn't return a valid chain!"); 10556 assert(InVals.size() == Ins.size() && 10557 "LowerFormalArguments didn't emit the correct number of values!"); 10558 LLVM_DEBUG({ 10559 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 10560 assert(InVals[i].getNode() && 10561 "LowerFormalArguments emitted a null value!"); 10562 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 10563 "LowerFormalArguments emitted a value with the wrong type!"); 10564 } 10565 }); 10566 10567 // Update the DAG with the new chain value resulting from argument lowering. 10568 DAG.setRoot(NewRoot); 10569 10570 // Set up the argument values. 10571 unsigned i = 0; 10572 if (!FuncInfo->CanLowerReturn) { 10573 // Create a virtual register for the sret pointer, and put in a copy 10574 // from the sret argument into it. 10575 SmallVector<EVT, 1> ValueVTs; 10576 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10577 F.getReturnType()->getPointerTo( 10578 DAG.getDataLayout().getAllocaAddrSpace()), 10579 ValueVTs); 10580 MVT VT = ValueVTs[0].getSimpleVT(); 10581 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 10582 Optional<ISD::NodeType> AssertOp; 10583 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 10584 nullptr, F.getCallingConv(), AssertOp); 10585 10586 MachineFunction& MF = SDB->DAG.getMachineFunction(); 10587 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 10588 Register SRetReg = 10589 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 10590 FuncInfo->DemoteRegister = SRetReg; 10591 NewRoot = 10592 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 10593 DAG.setRoot(NewRoot); 10594 10595 // i indexes lowered arguments. Bump it past the hidden sret argument. 10596 ++i; 10597 } 10598 10599 SmallVector<SDValue, 4> Chains; 10600 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 10601 for (const Argument &Arg : F.args()) { 10602 SmallVector<SDValue, 4> ArgValues; 10603 SmallVector<EVT, 4> ValueVTs; 10604 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10605 unsigned NumValues = ValueVTs.size(); 10606 if (NumValues == 0) 10607 continue; 10608 10609 bool ArgHasUses = !Arg.use_empty(); 10610 10611 // Elide the copying store if the target loaded this argument from a 10612 // suitable fixed stack object. 10613 if (Ins[i].Flags.isCopyElisionCandidate()) { 10614 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 10615 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 10616 InVals[i], ArgHasUses); 10617 } 10618 10619 // If this argument is unused then remember its value. It is used to generate 10620 // debugging information. 10621 bool isSwiftErrorArg = 10622 TLI->supportSwiftError() && 10623 Arg.hasAttribute(Attribute::SwiftError); 10624 if (!ArgHasUses && !isSwiftErrorArg) { 10625 SDB->setUnusedArgValue(&Arg, InVals[i]); 10626 10627 // Also remember any frame index for use in FastISel. 10628 if (FrameIndexSDNode *FI = 10629 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 10630 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10631 } 10632 10633 for (unsigned Val = 0; Val != NumValues; ++Val) { 10634 EVT VT = ValueVTs[Val]; 10635 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 10636 F.getCallingConv(), VT); 10637 unsigned NumParts = TLI->getNumRegistersForCallingConv( 10638 *CurDAG->getContext(), F.getCallingConv(), VT); 10639 10640 // Even an apparent 'unused' swifterror argument needs to be returned. So 10641 // we do generate a copy for it that can be used on return from the 10642 // function. 10643 if (ArgHasUses || isSwiftErrorArg) { 10644 Optional<ISD::NodeType> AssertOp; 10645 if (Arg.hasAttribute(Attribute::SExt)) 10646 AssertOp = ISD::AssertSext; 10647 else if (Arg.hasAttribute(Attribute::ZExt)) 10648 AssertOp = ISD::AssertZext; 10649 10650 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 10651 PartVT, VT, nullptr, 10652 F.getCallingConv(), AssertOp)); 10653 } 10654 10655 i += NumParts; 10656 } 10657 10658 // We don't need to do anything else for unused arguments. 10659 if (ArgValues.empty()) 10660 continue; 10661 10662 // Note down frame index. 10663 if (FrameIndexSDNode *FI = 10664 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 10665 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10666 10667 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 10668 SDB->getCurSDLoc()); 10669 10670 SDB->setValue(&Arg, Res); 10671 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 10672 // We want to associate the argument with the frame index, among 10673 // involved operands, that correspond to the lowest address. The 10674 // getCopyFromParts function, called earlier, is swapping the order of 10675 // the operands to BUILD_PAIR depending on endianness. The result of 10676 // that swapping is that the least significant bits of the argument will 10677 // be in the first operand of the BUILD_PAIR node, and the most 10678 // significant bits will be in the second operand. 10679 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 10680 if (LoadSDNode *LNode = 10681 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 10682 if (FrameIndexSDNode *FI = 10683 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 10684 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10685 } 10686 10687 // Analyses past this point are naive and don't expect an assertion. 10688 if (Res.getOpcode() == ISD::AssertZext) 10689 Res = Res.getOperand(0); 10690 10691 // Update the SwiftErrorVRegDefMap. 10692 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 10693 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10694 if (Register::isVirtualRegister(Reg)) 10695 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 10696 Reg); 10697 } 10698 10699 // If this argument is live outside of the entry block, insert a copy from 10700 // wherever we got it to the vreg that other BB's will reference it as. 10701 if (Res.getOpcode() == ISD::CopyFromReg) { 10702 // If we can, though, try to skip creating an unnecessary vreg. 10703 // FIXME: This isn't very clean... it would be nice to make this more 10704 // general. 10705 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10706 if (Register::isVirtualRegister(Reg)) { 10707 FuncInfo->ValueMap[&Arg] = Reg; 10708 continue; 10709 } 10710 } 10711 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 10712 FuncInfo->InitializeRegForValue(&Arg); 10713 SDB->CopyToExportRegsIfNeeded(&Arg); 10714 } 10715 } 10716 10717 if (!Chains.empty()) { 10718 Chains.push_back(NewRoot); 10719 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 10720 } 10721 10722 DAG.setRoot(NewRoot); 10723 10724 assert(i == InVals.size() && "Argument register count mismatch!"); 10725 10726 // If any argument copy elisions occurred and we have debug info, update the 10727 // stale frame indices used in the dbg.declare variable info table. 10728 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 10729 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 10730 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 10731 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 10732 if (I != ArgCopyElisionFrameIndexMap.end()) 10733 VI.Slot = I->second; 10734 } 10735 } 10736 10737 // Finally, if the target has anything special to do, allow it to do so. 10738 emitFunctionEntryCode(); 10739 } 10740 10741 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 10742 /// ensure constants are generated when needed. Remember the virtual registers 10743 /// that need to be added to the Machine PHI nodes as input. We cannot just 10744 /// directly add them, because expansion might result in multiple MBB's for one 10745 /// BB. As such, the start of the BB might correspond to a different MBB than 10746 /// the end. 10747 void 10748 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 10749 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10750 const Instruction *TI = LLVMBB->getTerminator(); 10751 10752 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 10753 10754 // Check PHI nodes in successors that expect a value to be available from this 10755 // block. 10756 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 10757 const BasicBlock *SuccBB = TI->getSuccessor(succ); 10758 if (!isa<PHINode>(SuccBB->begin())) continue; 10759 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 10760 10761 // If this terminator has multiple identical successors (common for 10762 // switches), only handle each succ once. 10763 if (!SuccsHandled.insert(SuccMBB).second) 10764 continue; 10765 10766 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 10767 10768 // At this point we know that there is a 1-1 correspondence between LLVM PHI 10769 // nodes and Machine PHI nodes, but the incoming operands have not been 10770 // emitted yet. 10771 for (const PHINode &PN : SuccBB->phis()) { 10772 // Ignore dead phi's. 10773 if (PN.use_empty()) 10774 continue; 10775 10776 // Skip empty types 10777 if (PN.getType()->isEmptyTy()) 10778 continue; 10779 10780 unsigned Reg; 10781 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 10782 10783 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 10784 unsigned &RegOut = ConstantsOut[C]; 10785 if (RegOut == 0) { 10786 RegOut = FuncInfo.CreateRegs(C); 10787 // We need to zero/sign extend ConstantInt phi operands to match 10788 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo. 10789 ISD::NodeType ExtendType = ISD::ANY_EXTEND; 10790 if (auto *CI = dyn_cast<ConstantInt>(C)) 10791 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND 10792 : ISD::ZERO_EXTEND; 10793 CopyValueToVirtualRegister(C, RegOut, ExtendType); 10794 } 10795 Reg = RegOut; 10796 } else { 10797 DenseMap<const Value *, Register>::iterator I = 10798 FuncInfo.ValueMap.find(PHIOp); 10799 if (I != FuncInfo.ValueMap.end()) 10800 Reg = I->second; 10801 else { 10802 assert(isa<AllocaInst>(PHIOp) && 10803 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 10804 "Didn't codegen value into a register!??"); 10805 Reg = FuncInfo.CreateRegs(PHIOp); 10806 CopyValueToVirtualRegister(PHIOp, Reg); 10807 } 10808 } 10809 10810 // Remember that this register needs to added to the machine PHI node as 10811 // the input for this MBB. 10812 SmallVector<EVT, 4> ValueVTs; 10813 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 10814 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 10815 EVT VT = ValueVTs[vti]; 10816 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 10817 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 10818 FuncInfo.PHINodesToUpdate.push_back( 10819 std::make_pair(&*MBBI++, Reg + i)); 10820 Reg += NumRegisters; 10821 } 10822 } 10823 } 10824 10825 ConstantsOut.clear(); 10826 } 10827 10828 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 10829 MachineFunction::iterator I(MBB); 10830 if (++I == FuncInfo.MF->end()) 10831 return nullptr; 10832 return &*I; 10833 } 10834 10835 /// During lowering new call nodes can be created (such as memset, etc.). 10836 /// Those will become new roots of the current DAG, but complications arise 10837 /// when they are tail calls. In such cases, the call lowering will update 10838 /// the root, but the builder still needs to know that a tail call has been 10839 /// lowered in order to avoid generating an additional return. 10840 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 10841 // If the node is null, we do have a tail call. 10842 if (MaybeTC.getNode() != nullptr) 10843 DAG.setRoot(MaybeTC); 10844 else 10845 HasTailCall = true; 10846 } 10847 10848 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10849 MachineBasicBlock *SwitchMBB, 10850 MachineBasicBlock *DefaultMBB) { 10851 MachineFunction *CurMF = FuncInfo.MF; 10852 MachineBasicBlock *NextMBB = nullptr; 10853 MachineFunction::iterator BBI(W.MBB); 10854 if (++BBI != FuncInfo.MF->end()) 10855 NextMBB = &*BBI; 10856 10857 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10858 10859 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10860 10861 if (Size == 2 && W.MBB == SwitchMBB) { 10862 // If any two of the cases has the same destination, and if one value 10863 // is the same as the other, but has one bit unset that the other has set, 10864 // use bit manipulation to do two compares at once. For example: 10865 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10866 // TODO: This could be extended to merge any 2 cases in switches with 3 10867 // cases. 10868 // TODO: Handle cases where W.CaseBB != SwitchBB. 10869 CaseCluster &Small = *W.FirstCluster; 10870 CaseCluster &Big = *W.LastCluster; 10871 10872 if (Small.Low == Small.High && Big.Low == Big.High && 10873 Small.MBB == Big.MBB) { 10874 const APInt &SmallValue = Small.Low->getValue(); 10875 const APInt &BigValue = Big.Low->getValue(); 10876 10877 // Check that there is only one bit different. 10878 APInt CommonBit = BigValue ^ SmallValue; 10879 if (CommonBit.isPowerOf2()) { 10880 SDValue CondLHS = getValue(Cond); 10881 EVT VT = CondLHS.getValueType(); 10882 SDLoc DL = getCurSDLoc(); 10883 10884 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10885 DAG.getConstant(CommonBit, DL, VT)); 10886 SDValue Cond = DAG.getSetCC( 10887 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10888 ISD::SETEQ); 10889 10890 // Update successor info. 10891 // Both Small and Big will jump to Small.BB, so we sum up the 10892 // probabilities. 10893 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10894 if (BPI) 10895 addSuccessorWithProb( 10896 SwitchMBB, DefaultMBB, 10897 // The default destination is the first successor in IR. 10898 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10899 else 10900 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10901 10902 // Insert the true branch. 10903 SDValue BrCond = 10904 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10905 DAG.getBasicBlock(Small.MBB)); 10906 // Insert the false branch. 10907 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10908 DAG.getBasicBlock(DefaultMBB)); 10909 10910 DAG.setRoot(BrCond); 10911 return; 10912 } 10913 } 10914 } 10915 10916 if (TM.getOptLevel() != CodeGenOpt::None) { 10917 // Here, we order cases by probability so the most likely case will be 10918 // checked first. However, two clusters can have the same probability in 10919 // which case their relative ordering is non-deterministic. So we use Low 10920 // as a tie-breaker as clusters are guaranteed to never overlap. 10921 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10922 [](const CaseCluster &a, const CaseCluster &b) { 10923 return a.Prob != b.Prob ? 10924 a.Prob > b.Prob : 10925 a.Low->getValue().slt(b.Low->getValue()); 10926 }); 10927 10928 // Rearrange the case blocks so that the last one falls through if possible 10929 // without changing the order of probabilities. 10930 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10931 --I; 10932 if (I->Prob > W.LastCluster->Prob) 10933 break; 10934 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10935 std::swap(*I, *W.LastCluster); 10936 break; 10937 } 10938 } 10939 } 10940 10941 // Compute total probability. 10942 BranchProbability DefaultProb = W.DefaultProb; 10943 BranchProbability UnhandledProbs = DefaultProb; 10944 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10945 UnhandledProbs += I->Prob; 10946 10947 MachineBasicBlock *CurMBB = W.MBB; 10948 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10949 bool FallthroughUnreachable = false; 10950 MachineBasicBlock *Fallthrough; 10951 if (I == W.LastCluster) { 10952 // For the last cluster, fall through to the default destination. 10953 Fallthrough = DefaultMBB; 10954 FallthroughUnreachable = isa<UnreachableInst>( 10955 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10956 } else { 10957 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10958 CurMF->insert(BBI, Fallthrough); 10959 // Put Cond in a virtual register to make it available from the new blocks. 10960 ExportFromCurrentBlock(Cond); 10961 } 10962 UnhandledProbs -= I->Prob; 10963 10964 switch (I->Kind) { 10965 case CC_JumpTable: { 10966 // FIXME: Optimize away range check based on pivot comparisons. 10967 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 10968 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 10969 10970 // The jump block hasn't been inserted yet; insert it here. 10971 MachineBasicBlock *JumpMBB = JT->MBB; 10972 CurMF->insert(BBI, JumpMBB); 10973 10974 auto JumpProb = I->Prob; 10975 auto FallthroughProb = UnhandledProbs; 10976 10977 // If the default statement is a target of the jump table, we evenly 10978 // distribute the default probability to successors of CurMBB. Also 10979 // update the probability on the edge from JumpMBB to Fallthrough. 10980 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10981 SE = JumpMBB->succ_end(); 10982 SI != SE; ++SI) { 10983 if (*SI == DefaultMBB) { 10984 JumpProb += DefaultProb / 2; 10985 FallthroughProb -= DefaultProb / 2; 10986 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10987 JumpMBB->normalizeSuccProbs(); 10988 break; 10989 } 10990 } 10991 10992 if (FallthroughUnreachable) 10993 JTH->FallthroughUnreachable = true; 10994 10995 if (!JTH->FallthroughUnreachable) 10996 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10997 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10998 CurMBB->normalizeSuccProbs(); 10999 11000 // The jump table header will be inserted in our current block, do the 11001 // range check, and fall through to our fallthrough block. 11002 JTH->HeaderBB = CurMBB; 11003 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 11004 11005 // If we're in the right place, emit the jump table header right now. 11006 if (CurMBB == SwitchMBB) { 11007 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 11008 JTH->Emitted = true; 11009 } 11010 break; 11011 } 11012 case CC_BitTests: { 11013 // FIXME: Optimize away range check based on pivot comparisons. 11014 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 11015 11016 // The bit test blocks haven't been inserted yet; insert them here. 11017 for (BitTestCase &BTC : BTB->Cases) 11018 CurMF->insert(BBI, BTC.ThisBB); 11019 11020 // Fill in fields of the BitTestBlock. 11021 BTB->Parent = CurMBB; 11022 BTB->Default = Fallthrough; 11023 11024 BTB->DefaultProb = UnhandledProbs; 11025 // If the cases in bit test don't form a contiguous range, we evenly 11026 // distribute the probability on the edge to Fallthrough to two 11027 // successors of CurMBB. 11028 if (!BTB->ContiguousRange) { 11029 BTB->Prob += DefaultProb / 2; 11030 BTB->DefaultProb -= DefaultProb / 2; 11031 } 11032 11033 if (FallthroughUnreachable) 11034 BTB->FallthroughUnreachable = true; 11035 11036 // If we're in the right place, emit the bit test header right now. 11037 if (CurMBB == SwitchMBB) { 11038 visitBitTestHeader(*BTB, SwitchMBB); 11039 BTB->Emitted = true; 11040 } 11041 break; 11042 } 11043 case CC_Range: { 11044 const Value *RHS, *LHS, *MHS; 11045 ISD::CondCode CC; 11046 if (I->Low == I->High) { 11047 // Check Cond == I->Low. 11048 CC = ISD::SETEQ; 11049 LHS = Cond; 11050 RHS=I->Low; 11051 MHS = nullptr; 11052 } else { 11053 // Check I->Low <= Cond <= I->High. 11054 CC = ISD::SETLE; 11055 LHS = I->Low; 11056 MHS = Cond; 11057 RHS = I->High; 11058 } 11059 11060 // If Fallthrough is unreachable, fold away the comparison. 11061 if (FallthroughUnreachable) 11062 CC = ISD::SETTRUE; 11063 11064 // The false probability is the sum of all unhandled cases. 11065 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 11066 getCurSDLoc(), I->Prob, UnhandledProbs); 11067 11068 if (CurMBB == SwitchMBB) 11069 visitSwitchCase(CB, SwitchMBB); 11070 else 11071 SL->SwitchCases.push_back(CB); 11072 11073 break; 11074 } 11075 } 11076 CurMBB = Fallthrough; 11077 } 11078 } 11079 11080 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 11081 CaseClusterIt First, 11082 CaseClusterIt Last) { 11083 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 11084 if (X.Prob != CC.Prob) 11085 return X.Prob > CC.Prob; 11086 11087 // Ties are broken by comparing the case value. 11088 return X.Low->getValue().slt(CC.Low->getValue()); 11089 }); 11090 } 11091 11092 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 11093 const SwitchWorkListItem &W, 11094 Value *Cond, 11095 MachineBasicBlock *SwitchMBB) { 11096 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 11097 "Clusters not sorted?"); 11098 11099 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 11100 11101 // Balance the tree based on branch probabilities to create a near-optimal (in 11102 // terms of search time given key frequency) binary search tree. See e.g. Kurt 11103 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 11104 CaseClusterIt LastLeft = W.FirstCluster; 11105 CaseClusterIt FirstRight = W.LastCluster; 11106 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 11107 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 11108 11109 // Move LastLeft and FirstRight towards each other from opposite directions to 11110 // find a partitioning of the clusters which balances the probability on both 11111 // sides. If LeftProb and RightProb are equal, alternate which side is 11112 // taken to ensure 0-probability nodes are distributed evenly. 11113 unsigned I = 0; 11114 while (LastLeft + 1 < FirstRight) { 11115 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 11116 LeftProb += (++LastLeft)->Prob; 11117 else 11118 RightProb += (--FirstRight)->Prob; 11119 I++; 11120 } 11121 11122 while (true) { 11123 // Our binary search tree differs from a typical BST in that ours can have up 11124 // to three values in each leaf. The pivot selection above doesn't take that 11125 // into account, which means the tree might require more nodes and be less 11126 // efficient. We compensate for this here. 11127 11128 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 11129 unsigned NumRight = W.LastCluster - FirstRight + 1; 11130 11131 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 11132 // If one side has less than 3 clusters, and the other has more than 3, 11133 // consider taking a cluster from the other side. 11134 11135 if (NumLeft < NumRight) { 11136 // Consider moving the first cluster on the right to the left side. 11137 CaseCluster &CC = *FirstRight; 11138 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11139 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11140 if (LeftSideRank <= RightSideRank) { 11141 // Moving the cluster to the left does not demote it. 11142 ++LastLeft; 11143 ++FirstRight; 11144 continue; 11145 } 11146 } else { 11147 assert(NumRight < NumLeft); 11148 // Consider moving the last element on the left to the right side. 11149 CaseCluster &CC = *LastLeft; 11150 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11151 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11152 if (RightSideRank <= LeftSideRank) { 11153 // Moving the cluster to the right does not demot it. 11154 --LastLeft; 11155 --FirstRight; 11156 continue; 11157 } 11158 } 11159 } 11160 break; 11161 } 11162 11163 assert(LastLeft + 1 == FirstRight); 11164 assert(LastLeft >= W.FirstCluster); 11165 assert(FirstRight <= W.LastCluster); 11166 11167 // Use the first element on the right as pivot since we will make less-than 11168 // comparisons against it. 11169 CaseClusterIt PivotCluster = FirstRight; 11170 assert(PivotCluster > W.FirstCluster); 11171 assert(PivotCluster <= W.LastCluster); 11172 11173 CaseClusterIt FirstLeft = W.FirstCluster; 11174 CaseClusterIt LastRight = W.LastCluster; 11175 11176 const ConstantInt *Pivot = PivotCluster->Low; 11177 11178 // New blocks will be inserted immediately after the current one. 11179 MachineFunction::iterator BBI(W.MBB); 11180 ++BBI; 11181 11182 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 11183 // we can branch to its destination directly if it's squeezed exactly in 11184 // between the known lower bound and Pivot - 1. 11185 MachineBasicBlock *LeftMBB; 11186 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 11187 FirstLeft->Low == W.GE && 11188 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 11189 LeftMBB = FirstLeft->MBB; 11190 } else { 11191 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11192 FuncInfo.MF->insert(BBI, LeftMBB); 11193 WorkList.push_back( 11194 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 11195 // Put Cond in a virtual register to make it available from the new blocks. 11196 ExportFromCurrentBlock(Cond); 11197 } 11198 11199 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 11200 // single cluster, RHS.Low == Pivot, and we can branch to its destination 11201 // directly if RHS.High equals the current upper bound. 11202 MachineBasicBlock *RightMBB; 11203 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 11204 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 11205 RightMBB = FirstRight->MBB; 11206 } else { 11207 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11208 FuncInfo.MF->insert(BBI, RightMBB); 11209 WorkList.push_back( 11210 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 11211 // Put Cond in a virtual register to make it available from the new blocks. 11212 ExportFromCurrentBlock(Cond); 11213 } 11214 11215 // Create the CaseBlock record that will be used to lower the branch. 11216 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 11217 getCurSDLoc(), LeftProb, RightProb); 11218 11219 if (W.MBB == SwitchMBB) 11220 visitSwitchCase(CB, SwitchMBB); 11221 else 11222 SL->SwitchCases.push_back(CB); 11223 } 11224 11225 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 11226 // from the swith statement. 11227 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 11228 BranchProbability PeeledCaseProb) { 11229 if (PeeledCaseProb == BranchProbability::getOne()) 11230 return BranchProbability::getZero(); 11231 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 11232 11233 uint32_t Numerator = CaseProb.getNumerator(); 11234 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 11235 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 11236 } 11237 11238 // Try to peel the top probability case if it exceeds the threshold. 11239 // Return current MachineBasicBlock for the switch statement if the peeling 11240 // does not occur. 11241 // If the peeling is performed, return the newly created MachineBasicBlock 11242 // for the peeled switch statement. Also update Clusters to remove the peeled 11243 // case. PeeledCaseProb is the BranchProbability for the peeled case. 11244 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 11245 const SwitchInst &SI, CaseClusterVector &Clusters, 11246 BranchProbability &PeeledCaseProb) { 11247 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11248 // Don't perform if there is only one cluster or optimizing for size. 11249 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 11250 TM.getOptLevel() == CodeGenOpt::None || 11251 SwitchMBB->getParent()->getFunction().hasMinSize()) 11252 return SwitchMBB; 11253 11254 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 11255 unsigned PeeledCaseIndex = 0; 11256 bool SwitchPeeled = false; 11257 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 11258 CaseCluster &CC = Clusters[Index]; 11259 if (CC.Prob < TopCaseProb) 11260 continue; 11261 TopCaseProb = CC.Prob; 11262 PeeledCaseIndex = Index; 11263 SwitchPeeled = true; 11264 } 11265 if (!SwitchPeeled) 11266 return SwitchMBB; 11267 11268 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 11269 << TopCaseProb << "\n"); 11270 11271 // Record the MBB for the peeled switch statement. 11272 MachineFunction::iterator BBI(SwitchMBB); 11273 ++BBI; 11274 MachineBasicBlock *PeeledSwitchMBB = 11275 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 11276 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 11277 11278 ExportFromCurrentBlock(SI.getCondition()); 11279 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 11280 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 11281 nullptr, nullptr, TopCaseProb.getCompl()}; 11282 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 11283 11284 Clusters.erase(PeeledCaseIt); 11285 for (CaseCluster &CC : Clusters) { 11286 LLVM_DEBUG( 11287 dbgs() << "Scale the probablity for one cluster, before scaling: " 11288 << CC.Prob << "\n"); 11289 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 11290 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 11291 } 11292 PeeledCaseProb = TopCaseProb; 11293 return PeeledSwitchMBB; 11294 } 11295 11296 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 11297 // Extract cases from the switch. 11298 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11299 CaseClusterVector Clusters; 11300 Clusters.reserve(SI.getNumCases()); 11301 for (auto I : SI.cases()) { 11302 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 11303 const ConstantInt *CaseVal = I.getCaseValue(); 11304 BranchProbability Prob = 11305 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 11306 : BranchProbability(1, SI.getNumCases() + 1); 11307 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 11308 } 11309 11310 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 11311 11312 // Cluster adjacent cases with the same destination. We do this at all 11313 // optimization levels because it's cheap to do and will make codegen faster 11314 // if there are many clusters. 11315 sortAndRangeify(Clusters); 11316 11317 // The branch probablity of the peeled case. 11318 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 11319 MachineBasicBlock *PeeledSwitchMBB = 11320 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 11321 11322 // If there is only the default destination, jump there directly. 11323 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11324 if (Clusters.empty()) { 11325 assert(PeeledSwitchMBB == SwitchMBB); 11326 SwitchMBB->addSuccessor(DefaultMBB); 11327 if (DefaultMBB != NextBlock(SwitchMBB)) { 11328 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 11329 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 11330 } 11331 return; 11332 } 11333 11334 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 11335 SL->findBitTestClusters(Clusters, &SI); 11336 11337 LLVM_DEBUG({ 11338 dbgs() << "Case clusters: "; 11339 for (const CaseCluster &C : Clusters) { 11340 if (C.Kind == CC_JumpTable) 11341 dbgs() << "JT:"; 11342 if (C.Kind == CC_BitTests) 11343 dbgs() << "BT:"; 11344 11345 C.Low->getValue().print(dbgs(), true); 11346 if (C.Low != C.High) { 11347 dbgs() << '-'; 11348 C.High->getValue().print(dbgs(), true); 11349 } 11350 dbgs() << ' '; 11351 } 11352 dbgs() << '\n'; 11353 }); 11354 11355 assert(!Clusters.empty()); 11356 SwitchWorkList WorkList; 11357 CaseClusterIt First = Clusters.begin(); 11358 CaseClusterIt Last = Clusters.end() - 1; 11359 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 11360 // Scale the branchprobability for DefaultMBB if the peel occurs and 11361 // DefaultMBB is not replaced. 11362 if (PeeledCaseProb != BranchProbability::getZero() && 11363 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 11364 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 11365 WorkList.push_back( 11366 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 11367 11368 while (!WorkList.empty()) { 11369 SwitchWorkListItem W = WorkList.pop_back_val(); 11370 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 11371 11372 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 11373 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 11374 // For optimized builds, lower large range as a balanced binary tree. 11375 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 11376 continue; 11377 } 11378 11379 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 11380 } 11381 } 11382 11383 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 11384 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11385 auto DL = getCurSDLoc(); 11386 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11387 setValue(&I, DAG.getStepVector(DL, ResultVT)); 11388 } 11389 11390 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 11391 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11392 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11393 11394 SDLoc DL = getCurSDLoc(); 11395 SDValue V = getValue(I.getOperand(0)); 11396 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 11397 11398 if (VT.isScalableVector()) { 11399 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 11400 return; 11401 } 11402 11403 // Use VECTOR_SHUFFLE for the fixed-length vector 11404 // to maintain existing behavior. 11405 SmallVector<int, 8> Mask; 11406 unsigned NumElts = VT.getVectorMinNumElements(); 11407 for (unsigned i = 0; i != NumElts; ++i) 11408 Mask.push_back(NumElts - 1 - i); 11409 11410 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 11411 } 11412 11413 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 11414 SmallVector<EVT, 4> ValueVTs; 11415 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 11416 ValueVTs); 11417 unsigned NumValues = ValueVTs.size(); 11418 if (NumValues == 0) return; 11419 11420 SmallVector<SDValue, 4> Values(NumValues); 11421 SDValue Op = getValue(I.getOperand(0)); 11422 11423 for (unsigned i = 0; i != NumValues; ++i) 11424 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 11425 SDValue(Op.getNode(), Op.getResNo() + i)); 11426 11427 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 11428 DAG.getVTList(ValueVTs), Values)); 11429 } 11430 11431 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 11432 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11433 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11434 11435 SDLoc DL = getCurSDLoc(); 11436 SDValue V1 = getValue(I.getOperand(0)); 11437 SDValue V2 = getValue(I.getOperand(1)); 11438 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 11439 11440 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 11441 if (VT.isScalableVector()) { 11442 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 11443 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 11444 DAG.getConstant(Imm, DL, IdxVT))); 11445 return; 11446 } 11447 11448 unsigned NumElts = VT.getVectorNumElements(); 11449 11450 uint64_t Idx = (NumElts + Imm) % NumElts; 11451 11452 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 11453 SmallVector<int, 8> Mask; 11454 for (unsigned i = 0; i < NumElts; ++i) 11455 Mask.push_back(Idx + i); 11456 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 11457 } 11458