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/BlockFrequencyInfo.h" 28 #include "llvm/Analysis/BranchProbabilityInfo.h" 29 #include "llvm/Analysis/ConstantFolding.h" 30 #include "llvm/Analysis/EHPersonalities.h" 31 #include "llvm/Analysis/Loads.h" 32 #include "llvm/Analysis/MemoryLocation.h" 33 #include "llvm/Analysis/ProfileSummaryInfo.h" 34 #include "llvm/Analysis/TargetLibraryInfo.h" 35 #include "llvm/Analysis/ValueTracking.h" 36 #include "llvm/Analysis/VectorUtils.h" 37 #include "llvm/CodeGen/Analysis.h" 38 #include "llvm/CodeGen/FunctionLoweringInfo.h" 39 #include "llvm/CodeGen/GCMetadata.h" 40 #include "llvm/CodeGen/MachineBasicBlock.h" 41 #include "llvm/CodeGen/MachineFrameInfo.h" 42 #include "llvm/CodeGen/MachineFunction.h" 43 #include "llvm/CodeGen/MachineInstr.h" 44 #include "llvm/CodeGen/MachineInstrBuilder.h" 45 #include "llvm/CodeGen/MachineJumpTableInfo.h" 46 #include "llvm/CodeGen/MachineMemOperand.h" 47 #include "llvm/CodeGen/MachineModuleInfo.h" 48 #include "llvm/CodeGen/MachineOperand.h" 49 #include "llvm/CodeGen/MachineRegisterInfo.h" 50 #include "llvm/CodeGen/RuntimeLibcalls.h" 51 #include "llvm/CodeGen/SelectionDAG.h" 52 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 53 #include "llvm/CodeGen/StackMaps.h" 54 #include "llvm/CodeGen/SwiftErrorValueTracking.h" 55 #include "llvm/CodeGen/TargetFrameLowering.h" 56 #include "llvm/CodeGen/TargetInstrInfo.h" 57 #include "llvm/CodeGen/TargetOpcodes.h" 58 #include "llvm/CodeGen/TargetRegisterInfo.h" 59 #include "llvm/CodeGen/TargetSubtargetInfo.h" 60 #include "llvm/CodeGen/WinEHFuncInfo.h" 61 #include "llvm/IR/Argument.h" 62 #include "llvm/IR/Attributes.h" 63 #include "llvm/IR/BasicBlock.h" 64 #include "llvm/IR/CFG.h" 65 #include "llvm/IR/CallingConv.h" 66 #include "llvm/IR/Constant.h" 67 #include "llvm/IR/ConstantRange.h" 68 #include "llvm/IR/Constants.h" 69 #include "llvm/IR/DataLayout.h" 70 #include "llvm/IR/DebugInfoMetadata.h" 71 #include "llvm/IR/DerivedTypes.h" 72 #include "llvm/IR/Function.h" 73 #include "llvm/IR/GetElementPtrTypeIterator.h" 74 #include "llvm/IR/InlineAsm.h" 75 #include "llvm/IR/InstrTypes.h" 76 #include "llvm/IR/Instructions.h" 77 #include "llvm/IR/IntrinsicInst.h" 78 #include "llvm/IR/Intrinsics.h" 79 #include "llvm/IR/IntrinsicsAArch64.h" 80 #include "llvm/IR/IntrinsicsWebAssembly.h" 81 #include "llvm/IR/LLVMContext.h" 82 #include "llvm/IR/Metadata.h" 83 #include "llvm/IR/Module.h" 84 #include "llvm/IR/Operator.h" 85 #include "llvm/IR/PatternMatch.h" 86 #include "llvm/IR/Statepoint.h" 87 #include "llvm/IR/Type.h" 88 #include "llvm/IR/User.h" 89 #include "llvm/IR/Value.h" 90 #include "llvm/MC/MCContext.h" 91 #include "llvm/MC/MCSymbol.h" 92 #include "llvm/Support/AtomicOrdering.h" 93 #include "llvm/Support/Casting.h" 94 #include "llvm/Support/CommandLine.h" 95 #include "llvm/Support/Compiler.h" 96 #include "llvm/Support/Debug.h" 97 #include "llvm/Support/MathExtras.h" 98 #include "llvm/Support/raw_ostream.h" 99 #include "llvm/Target/TargetIntrinsicInfo.h" 100 #include "llvm/Target/TargetMachine.h" 101 #include "llvm/Target/TargetOptions.h" 102 #include "llvm/Transforms/Utils/Local.h" 103 #include <cstddef> 104 #include <cstring> 105 #include <iterator> 106 #include <limits> 107 #include <numeric> 108 #include <tuple> 109 110 using namespace llvm; 111 using namespace PatternMatch; 112 using namespace SwitchCG; 113 114 #define DEBUG_TYPE "isel" 115 116 /// LimitFloatPrecision - Generate low-precision inline sequences for 117 /// some float libcalls (6, 8 or 12 bits). 118 static unsigned LimitFloatPrecision; 119 120 static cl::opt<bool> 121 InsertAssertAlign("insert-assert-align", cl::init(true), 122 cl::desc("Insert the experimental `assertalign` node."), 123 cl::ReallyHidden); 124 125 static cl::opt<unsigned, true> 126 LimitFPPrecision("limit-float-precision", 127 cl::desc("Generate low-precision inline sequences " 128 "for some float libcalls"), 129 cl::location(LimitFloatPrecision), cl::Hidden, 130 cl::init(0)); 131 132 static cl::opt<unsigned> SwitchPeelThreshold( 133 "switch-peel-threshold", cl::Hidden, cl::init(66), 134 cl::desc("Set the case probability threshold for peeling the case from a " 135 "switch statement. A value greater than 100 will void this " 136 "optimization")); 137 138 // Limit the width of DAG chains. This is important in general to prevent 139 // DAG-based analysis from blowing up. For example, alias analysis and 140 // load clustering may not complete in reasonable time. It is difficult to 141 // recognize and avoid this situation within each individual analysis, and 142 // future analyses are likely to have the same behavior. Limiting DAG width is 143 // the safe approach and will be especially important with global DAGs. 144 // 145 // MaxParallelChains default is arbitrarily high to avoid affecting 146 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 147 // sequence over this should have been converted to llvm.memcpy by the 148 // frontend. It is easy to induce this behavior with .ll code such as: 149 // %buffer = alloca [4096 x i8] 150 // %data = load [4096 x i8]* %argPtr 151 // store [4096 x i8] %data, [4096 x i8]* %buffer 152 static const unsigned MaxParallelChains = 64; 153 154 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 155 const SDValue *Parts, unsigned NumParts, 156 MVT PartVT, EVT ValueVT, const Value *V, 157 Optional<CallingConv::ID> CC); 158 159 /// getCopyFromParts - Create a value that contains the specified legal parts 160 /// combined into the value they represent. If the parts combine to a type 161 /// larger than ValueVT then AssertOp can be used to specify whether the extra 162 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 163 /// (ISD::AssertSext). 164 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 165 const SDValue *Parts, unsigned NumParts, 166 MVT PartVT, EVT ValueVT, const Value *V, 167 Optional<CallingConv::ID> CC = None, 168 Optional<ISD::NodeType> AssertOp = None) { 169 // Let the target assemble the parts if it wants to 170 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 171 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts, 172 PartVT, ValueVT, CC)) 173 return Val; 174 175 if (ValueVT.isVector()) 176 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 177 CC); 178 179 assert(NumParts > 0 && "No parts to assemble!"); 180 SDValue Val = Parts[0]; 181 182 if (NumParts > 1) { 183 // Assemble the value from multiple parts. 184 if (ValueVT.isInteger()) { 185 unsigned PartBits = PartVT.getSizeInBits(); 186 unsigned ValueBits = ValueVT.getSizeInBits(); 187 188 // Assemble the power of 2 part. 189 unsigned RoundParts = 190 (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts; 191 unsigned RoundBits = PartBits * RoundParts; 192 EVT RoundVT = RoundBits == ValueBits ? 193 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 194 SDValue Lo, Hi; 195 196 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 197 198 if (RoundParts > 2) { 199 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 200 PartVT, HalfVT, V); 201 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 202 RoundParts / 2, PartVT, HalfVT, V); 203 } else { 204 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 205 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 206 } 207 208 if (DAG.getDataLayout().isBigEndian()) 209 std::swap(Lo, Hi); 210 211 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 212 213 if (RoundParts < NumParts) { 214 // Assemble the trailing non-power-of-2 part. 215 unsigned OddParts = NumParts - RoundParts; 216 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 217 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 218 OddVT, V, CC); 219 220 // Combine the round and odd parts. 221 Lo = Val; 222 if (DAG.getDataLayout().isBigEndian()) 223 std::swap(Lo, Hi); 224 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 225 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 226 Hi = 227 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 228 DAG.getConstant(Lo.getValueSizeInBits(), DL, 229 TLI.getPointerTy(DAG.getDataLayout()))); 230 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 231 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 232 } 233 } else if (PartVT.isFloatingPoint()) { 234 // FP split into multiple FP parts (for ppcf128) 235 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 236 "Unexpected split"); 237 SDValue Lo, Hi; 238 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 239 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 240 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 241 std::swap(Lo, Hi); 242 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 243 } else { 244 // FP split into integer parts (soft fp) 245 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 246 !PartVT.isVector() && "Unexpected split"); 247 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 248 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 249 } 250 } 251 252 // There is now one part, held in Val. Correct it to match ValueVT. 253 // PartEVT is the type of the register class that holds the value. 254 // ValueVT is the type of the inline asm operation. 255 EVT PartEVT = Val.getValueType(); 256 257 if (PartEVT == ValueVT) 258 return Val; 259 260 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 261 ValueVT.bitsLT(PartEVT)) { 262 // For an FP value in an integer part, we need to truncate to the right 263 // width first. 264 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 265 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 266 } 267 268 // Handle types that have the same size. 269 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 270 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 271 272 // Handle types with different sizes. 273 if (PartEVT.isInteger() && ValueVT.isInteger()) { 274 if (ValueVT.bitsLT(PartEVT)) { 275 // For a truncate, see if we have any information to 276 // indicate whether the truncated bits will always be 277 // zero or sign-extension. 278 if (AssertOp.hasValue()) 279 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 280 DAG.getValueType(ValueVT)); 281 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 282 } 283 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 284 } 285 286 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 287 // FP_ROUND's are always exact here. 288 if (ValueVT.bitsLT(Val.getValueType())) 289 return DAG.getNode( 290 ISD::FP_ROUND, DL, ValueVT, Val, 291 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 292 293 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 294 } 295 296 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 297 // then truncating. 298 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 299 ValueVT.bitsLT(PartEVT)) { 300 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 301 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 302 } 303 304 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 305 } 306 307 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 308 const Twine &ErrMsg) { 309 const Instruction *I = dyn_cast_or_null<Instruction>(V); 310 if (!V) 311 return Ctx.emitError(ErrMsg); 312 313 const char *AsmError = ", possible invalid constraint for vector type"; 314 if (const CallInst *CI = dyn_cast<CallInst>(I)) 315 if (CI->isInlineAsm()) 316 return Ctx.emitError(I, ErrMsg + AsmError); 317 318 return Ctx.emitError(I, ErrMsg); 319 } 320 321 /// getCopyFromPartsVector - Create a value that contains the specified legal 322 /// parts combined into the value they represent. If the parts combine to a 323 /// type larger than ValueVT then AssertOp can be used to specify whether the 324 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 325 /// ValueVT (ISD::AssertSext). 326 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 327 const SDValue *Parts, unsigned NumParts, 328 MVT PartVT, EVT ValueVT, const Value *V, 329 Optional<CallingConv::ID> CallConv) { 330 assert(ValueVT.isVector() && "Not a vector value"); 331 assert(NumParts > 0 && "No parts to assemble!"); 332 const bool IsABIRegCopy = CallConv.hasValue(); 333 334 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 335 SDValue Val = Parts[0]; 336 337 // Handle a multi-element vector. 338 if (NumParts > 1) { 339 EVT IntermediateVT; 340 MVT RegisterVT; 341 unsigned NumIntermediates; 342 unsigned NumRegs; 343 344 if (IsABIRegCopy) { 345 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 346 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 347 NumIntermediates, RegisterVT); 348 } else { 349 NumRegs = 350 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 351 NumIntermediates, RegisterVT); 352 } 353 354 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 355 NumParts = NumRegs; // Silence a compiler warning. 356 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 357 assert(RegisterVT.getSizeInBits() == 358 Parts[0].getSimpleValueType().getSizeInBits() && 359 "Part type sizes don't match!"); 360 361 // Assemble the parts into intermediate operands. 362 SmallVector<SDValue, 8> Ops(NumIntermediates); 363 if (NumIntermediates == NumParts) { 364 // If the register was not expanded, truncate or copy the value, 365 // as appropriate. 366 for (unsigned i = 0; i != NumParts; ++i) 367 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 368 PartVT, IntermediateVT, V, CallConv); 369 } else if (NumParts > 0) { 370 // If the intermediate type was expanded, build the intermediate 371 // operands from the parts. 372 assert(NumParts % NumIntermediates == 0 && 373 "Must expand into a divisible number of parts!"); 374 unsigned Factor = NumParts / NumIntermediates; 375 for (unsigned i = 0; i != NumIntermediates; ++i) 376 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 377 PartVT, IntermediateVT, V, CallConv); 378 } 379 380 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 381 // intermediate operands. 382 EVT BuiltVectorTy = 383 IntermediateVT.isVector() 384 ? EVT::getVectorVT( 385 *DAG.getContext(), IntermediateVT.getScalarType(), 386 IntermediateVT.getVectorElementCount() * NumParts) 387 : EVT::getVectorVT(*DAG.getContext(), 388 IntermediateVT.getScalarType(), 389 NumIntermediates); 390 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 391 : ISD::BUILD_VECTOR, 392 DL, BuiltVectorTy, Ops); 393 } 394 395 // There is now one part, held in Val. Correct it to match ValueVT. 396 EVT PartEVT = Val.getValueType(); 397 398 if (PartEVT == ValueVT) 399 return Val; 400 401 if (PartEVT.isVector()) { 402 // If the element type of the source/dest vectors are the same, but the 403 // parts vector has more elements than the value vector, then we have a 404 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 405 // elements we want. 406 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { 407 assert((PartEVT.getVectorElementCount().getKnownMinValue() > 408 ValueVT.getVectorElementCount().getKnownMinValue()) && 409 (PartEVT.getVectorElementCount().isScalable() == 410 ValueVT.getVectorElementCount().isScalable()) && 411 "Cannot narrow, it would be a lossy transformation"); 412 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 413 DAG.getVectorIdxConstant(0, DL)); 414 } 415 416 // Vector/Vector bitcast. 417 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 418 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 419 420 assert(PartEVT.getVectorElementCount() == ValueVT.getVectorElementCount() && 421 "Cannot handle this kind of promotion"); 422 // Promoted vector extract 423 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 424 425 } 426 427 // Trivial bitcast if the types are the same size and the destination 428 // vector type is legal. 429 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 430 TLI.isTypeLegal(ValueVT)) 431 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 432 433 if (ValueVT.getVectorNumElements() != 1) { 434 // Certain ABIs require that vectors are passed as integers. For vectors 435 // are the same size, this is an obvious bitcast. 436 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 437 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 438 } else if (ValueVT.bitsLT(PartEVT)) { 439 const uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 440 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 441 // Drop the extra bits. 442 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 443 return DAG.getBitcast(ValueVT, Val); 444 } 445 446 diagnosePossiblyInvalidConstraint( 447 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 448 return DAG.getUNDEF(ValueVT); 449 } 450 451 // Handle cases such as i8 -> <1 x i1> 452 EVT ValueSVT = ValueVT.getVectorElementType(); 453 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 454 if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits()) 455 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 456 else 457 Val = ValueVT.isFloatingPoint() 458 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 459 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 460 } 461 462 return DAG.getBuildVector(ValueVT, DL, Val); 463 } 464 465 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 466 SDValue Val, SDValue *Parts, unsigned NumParts, 467 MVT PartVT, const Value *V, 468 Optional<CallingConv::ID> CallConv); 469 470 /// getCopyToParts - Create a series of nodes that contain the specified value 471 /// split into legal parts. If the parts contain more bits than Val, then, for 472 /// integers, ExtendKind can be used to specify how to generate the extra bits. 473 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 474 SDValue *Parts, unsigned NumParts, MVT PartVT, 475 const Value *V, 476 Optional<CallingConv::ID> CallConv = None, 477 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 478 // Let the target split the parts if it wants to 479 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 480 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 481 CallConv)) 482 return; 483 EVT ValueVT = Val.getValueType(); 484 485 // Handle the vector case separately. 486 if (ValueVT.isVector()) 487 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 488 CallConv); 489 490 unsigned PartBits = PartVT.getSizeInBits(); 491 unsigned OrigNumParts = NumParts; 492 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 493 "Copying to an illegal type!"); 494 495 if (NumParts == 0) 496 return; 497 498 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 499 EVT PartEVT = PartVT; 500 if (PartEVT == ValueVT) { 501 assert(NumParts == 1 && "No-op copy with multiple parts!"); 502 Parts[0] = Val; 503 return; 504 } 505 506 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 507 // If the parts cover more bits than the value has, promote the value. 508 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 509 assert(NumParts == 1 && "Do not know what to promote to!"); 510 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 511 } else { 512 if (ValueVT.isFloatingPoint()) { 513 // FP values need to be bitcast, then extended if they are being put 514 // into a larger container. 515 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 516 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 517 } 518 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 519 ValueVT.isInteger() && 520 "Unknown mismatch!"); 521 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 522 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 523 if (PartVT == MVT::x86mmx) 524 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 525 } 526 } else if (PartBits == ValueVT.getSizeInBits()) { 527 // Different types of the same size. 528 assert(NumParts == 1 && PartEVT != ValueVT); 529 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 530 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 531 // If the parts cover less bits than value has, truncate the value. 532 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 533 ValueVT.isInteger() && 534 "Unknown mismatch!"); 535 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 536 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 537 if (PartVT == MVT::x86mmx) 538 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 539 } 540 541 // The value may have changed - recompute ValueVT. 542 ValueVT = Val.getValueType(); 543 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 544 "Failed to tile the value with PartVT!"); 545 546 if (NumParts == 1) { 547 if (PartEVT != ValueVT) { 548 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 549 "scalar-to-vector conversion failed"); 550 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 551 } 552 553 Parts[0] = Val; 554 return; 555 } 556 557 // Expand the value into multiple parts. 558 if (NumParts & (NumParts - 1)) { 559 // The number of parts is not a power of 2. Split off and copy the tail. 560 assert(PartVT.isInteger() && ValueVT.isInteger() && 561 "Do not know what to expand to!"); 562 unsigned RoundParts = 1 << Log2_32(NumParts); 563 unsigned RoundBits = RoundParts * PartBits; 564 unsigned OddParts = NumParts - RoundParts; 565 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 566 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false)); 567 568 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 569 CallConv); 570 571 if (DAG.getDataLayout().isBigEndian()) 572 // The odd parts were reversed by getCopyToParts - unreverse them. 573 std::reverse(Parts + RoundParts, Parts + NumParts); 574 575 NumParts = RoundParts; 576 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 577 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 578 } 579 580 // The number of parts is a power of 2. Repeatedly bisect the value using 581 // EXTRACT_ELEMENT. 582 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 583 EVT::getIntegerVT(*DAG.getContext(), 584 ValueVT.getSizeInBits()), 585 Val); 586 587 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 588 for (unsigned i = 0; i < NumParts; i += StepSize) { 589 unsigned ThisBits = StepSize * PartBits / 2; 590 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 591 SDValue &Part0 = Parts[i]; 592 SDValue &Part1 = Parts[i+StepSize/2]; 593 594 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 595 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 596 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 597 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 598 599 if (ThisBits == PartBits && ThisVT != PartVT) { 600 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 601 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 602 } 603 } 604 } 605 606 if (DAG.getDataLayout().isBigEndian()) 607 std::reverse(Parts, Parts + OrigNumParts); 608 } 609 610 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val, 611 const SDLoc &DL, EVT PartVT) { 612 if (!PartVT.isVector()) 613 return SDValue(); 614 615 EVT ValueVT = Val.getValueType(); 616 ElementCount PartNumElts = PartVT.getVectorElementCount(); 617 ElementCount ValueNumElts = ValueVT.getVectorElementCount(); 618 619 // We only support widening vectors with equivalent element types and 620 // fixed/scalable properties. If a target needs to widen a fixed-length type 621 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below. 622 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) || 623 PartNumElts.isScalable() != ValueNumElts.isScalable() || 624 PartVT.getVectorElementType() != ValueVT.getVectorElementType()) 625 return SDValue(); 626 627 // Widening a scalable vector to another scalable vector is done by inserting 628 // the vector into a larger undef one. 629 if (PartNumElts.isScalable()) 630 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 631 Val, DAG.getVectorIdxConstant(0, DL)); 632 633 EVT ElementVT = PartVT.getVectorElementType(); 634 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 635 // undef elements. 636 SmallVector<SDValue, 16> Ops; 637 DAG.ExtractVectorElements(Val, Ops); 638 SDValue EltUndef = DAG.getUNDEF(ElementVT); 639 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef); 640 641 // FIXME: Use CONCAT for 2x -> 4x. 642 return DAG.getBuildVector(PartVT, DL, Ops); 643 } 644 645 /// getCopyToPartsVector - Create a series of nodes that contain the specified 646 /// value split into legal parts. 647 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 648 SDValue Val, SDValue *Parts, unsigned NumParts, 649 MVT PartVT, const Value *V, 650 Optional<CallingConv::ID> CallConv) { 651 EVT ValueVT = Val.getValueType(); 652 assert(ValueVT.isVector() && "Not a vector"); 653 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 654 const bool IsABIRegCopy = CallConv.hasValue(); 655 656 if (NumParts == 1) { 657 EVT PartEVT = PartVT; 658 if (PartEVT == ValueVT) { 659 // Nothing to do. 660 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 661 // Bitconvert vector->vector case. 662 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 663 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 664 Val = Widened; 665 } else if (PartVT.isVector() && 666 PartEVT.getVectorElementType().bitsGE( 667 ValueVT.getVectorElementType()) && 668 PartEVT.getVectorElementCount() == 669 ValueVT.getVectorElementCount()) { 670 671 // Promoted vector extract 672 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 673 } else { 674 if (ValueVT.getVectorElementCount().isScalar()) { 675 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 676 DAG.getVectorIdxConstant(0, DL)); 677 } else { 678 uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 679 assert(PartVT.getFixedSizeInBits() > ValueSize && 680 "lossy conversion of vector to scalar type"); 681 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 682 Val = DAG.getBitcast(IntermediateType, Val); 683 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 684 } 685 } 686 687 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 688 Parts[0] = Val; 689 return; 690 } 691 692 // Handle a multi-element vector. 693 EVT IntermediateVT; 694 MVT RegisterVT; 695 unsigned NumIntermediates; 696 unsigned NumRegs; 697 if (IsABIRegCopy) { 698 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 699 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 700 NumIntermediates, RegisterVT); 701 } else { 702 NumRegs = 703 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 704 NumIntermediates, RegisterVT); 705 } 706 707 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 708 NumParts = NumRegs; // Silence a compiler warning. 709 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 710 711 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 712 "Mixing scalable and fixed vectors when copying in parts"); 713 714 Optional<ElementCount> DestEltCnt; 715 716 if (IntermediateVT.isVector()) 717 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 718 else 719 DestEltCnt = ElementCount::getFixed(NumIntermediates); 720 721 EVT BuiltVectorTy = EVT::getVectorVT( 722 *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt.getValue()); 723 724 if (ValueVT == BuiltVectorTy) { 725 // Nothing to do. 726 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) { 727 // Bitconvert vector->vector case. 728 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 729 } else if (SDValue Widened = 730 widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) { 731 Val = Widened; 732 } else if (BuiltVectorTy.getVectorElementType().bitsGE( 733 ValueVT.getVectorElementType()) && 734 BuiltVectorTy.getVectorElementCount() == 735 ValueVT.getVectorElementCount()) { 736 // Promoted vector extract 737 Val = DAG.getAnyExtOrTrunc(Val, DL, BuiltVectorTy); 738 } 739 740 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type"); 741 742 // Split the vector into intermediate operands. 743 SmallVector<SDValue, 8> Ops(NumIntermediates); 744 for (unsigned i = 0; i != NumIntermediates; ++i) { 745 if (IntermediateVT.isVector()) { 746 // This does something sensible for scalable vectors - see the 747 // definition of EXTRACT_SUBVECTOR for further details. 748 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 749 Ops[i] = 750 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 751 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 752 } else { 753 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 754 DAG.getVectorIdxConstant(i, DL)); 755 } 756 } 757 758 // Split the intermediate operands into legal parts. 759 if (NumParts == NumIntermediates) { 760 // If the register was not expanded, promote or copy the value, 761 // as appropriate. 762 for (unsigned i = 0; i != NumParts; ++i) 763 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 764 } else if (NumParts > 0) { 765 // If the intermediate type was expanded, split each the value into 766 // legal parts. 767 assert(NumIntermediates != 0 && "division by zero"); 768 assert(NumParts % NumIntermediates == 0 && 769 "Must expand into a divisible number of parts!"); 770 unsigned Factor = NumParts / NumIntermediates; 771 for (unsigned i = 0; i != NumIntermediates; ++i) 772 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 773 CallConv); 774 } 775 } 776 777 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 778 EVT valuevt, Optional<CallingConv::ID> CC) 779 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 780 RegCount(1, regs.size()), CallConv(CC) {} 781 782 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 783 const DataLayout &DL, unsigned Reg, Type *Ty, 784 Optional<CallingConv::ID> CC) { 785 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 786 787 CallConv = CC; 788 789 for (EVT ValueVT : ValueVTs) { 790 unsigned NumRegs = 791 isABIMangled() 792 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) 793 : TLI.getNumRegisters(Context, ValueVT); 794 MVT RegisterVT = 795 isABIMangled() 796 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) 797 : TLI.getRegisterType(Context, ValueVT); 798 for (unsigned i = 0; i != NumRegs; ++i) 799 Regs.push_back(Reg + i); 800 RegVTs.push_back(RegisterVT); 801 RegCount.push_back(NumRegs); 802 Reg += NumRegs; 803 } 804 } 805 806 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 807 FunctionLoweringInfo &FuncInfo, 808 const SDLoc &dl, SDValue &Chain, 809 SDValue *Flag, const Value *V) const { 810 // A Value with type {} or [0 x %t] needs no registers. 811 if (ValueVTs.empty()) 812 return SDValue(); 813 814 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 815 816 // Assemble the legal parts into the final values. 817 SmallVector<SDValue, 4> Values(ValueVTs.size()); 818 SmallVector<SDValue, 8> Parts; 819 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 820 // Copy the legal parts from the registers. 821 EVT ValueVT = ValueVTs[Value]; 822 unsigned NumRegs = RegCount[Value]; 823 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 824 *DAG.getContext(), 825 CallConv.getValue(), RegVTs[Value]) 826 : RegVTs[Value]; 827 828 Parts.resize(NumRegs); 829 for (unsigned i = 0; i != NumRegs; ++i) { 830 SDValue P; 831 if (!Flag) { 832 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 833 } else { 834 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 835 *Flag = P.getValue(2); 836 } 837 838 Chain = P.getValue(1); 839 Parts[i] = P; 840 841 // If the source register was virtual and if we know something about it, 842 // add an assert node. 843 if (!Register::isVirtualRegister(Regs[Part + i]) || 844 !RegisterVT.isInteger()) 845 continue; 846 847 const FunctionLoweringInfo::LiveOutInfo *LOI = 848 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 849 if (!LOI) 850 continue; 851 852 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 853 unsigned NumSignBits = LOI->NumSignBits; 854 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 855 856 if (NumZeroBits == RegSize) { 857 // The current value is a zero. 858 // Explicitly express that as it would be easier for 859 // optimizations to kick in. 860 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 861 continue; 862 } 863 864 // FIXME: We capture more information than the dag can represent. For 865 // now, just use the tightest assertzext/assertsext possible. 866 bool isSExt; 867 EVT FromVT(MVT::Other); 868 if (NumZeroBits) { 869 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 870 isSExt = false; 871 } else if (NumSignBits > 1) { 872 FromVT = 873 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 874 isSExt = true; 875 } else { 876 continue; 877 } 878 // Add an assertion node. 879 assert(FromVT != MVT::Other); 880 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 881 RegisterVT, P, DAG.getValueType(FromVT)); 882 } 883 884 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 885 RegisterVT, ValueVT, V, CallConv); 886 Part += NumRegs; 887 Parts.clear(); 888 } 889 890 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 891 } 892 893 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 894 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 895 const Value *V, 896 ISD::NodeType PreferredExtendType) const { 897 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 898 ISD::NodeType ExtendKind = PreferredExtendType; 899 900 // Get the list of the values's legal parts. 901 unsigned NumRegs = Regs.size(); 902 SmallVector<SDValue, 8> Parts(NumRegs); 903 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 904 unsigned NumParts = RegCount[Value]; 905 906 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 907 *DAG.getContext(), 908 CallConv.getValue(), RegVTs[Value]) 909 : RegVTs[Value]; 910 911 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 912 ExtendKind = ISD::ZERO_EXTEND; 913 914 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 915 NumParts, RegisterVT, V, CallConv, ExtendKind); 916 Part += NumParts; 917 } 918 919 // Copy the parts into the registers. 920 SmallVector<SDValue, 8> Chains(NumRegs); 921 for (unsigned i = 0; i != NumRegs; ++i) { 922 SDValue Part; 923 if (!Flag) { 924 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 925 } else { 926 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 927 *Flag = Part.getValue(1); 928 } 929 930 Chains[i] = Part.getValue(0); 931 } 932 933 if (NumRegs == 1 || Flag) 934 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 935 // flagged to it. That is the CopyToReg nodes and the user are considered 936 // a single scheduling unit. If we create a TokenFactor and return it as 937 // chain, then the TokenFactor is both a predecessor (operand) of the 938 // user as well as a successor (the TF operands are flagged to the user). 939 // c1, f1 = CopyToReg 940 // c2, f2 = CopyToReg 941 // c3 = TokenFactor c1, c2 942 // ... 943 // = op c3, ..., f2 944 Chain = Chains[NumRegs-1]; 945 else 946 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 947 } 948 949 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 950 unsigned MatchingIdx, const SDLoc &dl, 951 SelectionDAG &DAG, 952 std::vector<SDValue> &Ops) const { 953 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 954 955 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 956 if (HasMatching) 957 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 958 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 959 // Put the register class of the virtual registers in the flag word. That 960 // way, later passes can recompute register class constraints for inline 961 // assembly as well as normal instructions. 962 // Don't do this for tied operands that can use the regclass information 963 // from the def. 964 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 965 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 966 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 967 } 968 969 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 970 Ops.push_back(Res); 971 972 if (Code == InlineAsm::Kind_Clobber) { 973 // Clobbers should always have a 1:1 mapping with registers, and may 974 // reference registers that have illegal (e.g. vector) types. Hence, we 975 // shouldn't try to apply any sort of splitting logic to them. 976 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 977 "No 1:1 mapping from clobbers to regs?"); 978 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 979 (void)SP; 980 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 981 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 982 assert( 983 (Regs[I] != SP || 984 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 985 "If we clobbered the stack pointer, MFI should know about it."); 986 } 987 return; 988 } 989 990 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 991 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 992 MVT RegisterVT = RegVTs[Value]; 993 for (unsigned i = 0; i != NumRegs; ++i) { 994 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 995 unsigned TheReg = Regs[Reg++]; 996 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 997 } 998 } 999 } 1000 1001 SmallVector<std::pair<unsigned, TypeSize>, 4> 1002 RegsForValue::getRegsAndSizes() const { 1003 SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec; 1004 unsigned I = 0; 1005 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1006 unsigned RegCount = std::get<0>(CountAndVT); 1007 MVT RegisterVT = std::get<1>(CountAndVT); 1008 TypeSize RegisterSize = RegisterVT.getSizeInBits(); 1009 for (unsigned E = I + RegCount; I != E; ++I) 1010 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1011 } 1012 return OutVec; 1013 } 1014 1015 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1016 const TargetLibraryInfo *li) { 1017 AA = aa; 1018 GFI = gfi; 1019 LibInfo = li; 1020 DL = &DAG.getDataLayout(); 1021 Context = DAG.getContext(); 1022 LPadToCallSiteMap.clear(); 1023 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1024 } 1025 1026 void SelectionDAGBuilder::clear() { 1027 NodeMap.clear(); 1028 UnusedArgNodeMap.clear(); 1029 PendingLoads.clear(); 1030 PendingExports.clear(); 1031 PendingConstrainedFP.clear(); 1032 PendingConstrainedFPStrict.clear(); 1033 CurInst = nullptr; 1034 HasTailCall = false; 1035 SDNodeOrder = LowestSDNodeOrder; 1036 StatepointLowering.clear(); 1037 } 1038 1039 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1040 DanglingDebugInfoMap.clear(); 1041 } 1042 1043 // Update DAG root to include dependencies on Pending chains. 1044 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1045 SDValue Root = DAG.getRoot(); 1046 1047 if (Pending.empty()) 1048 return Root; 1049 1050 // Add current root to PendingChains, unless we already indirectly 1051 // depend on it. 1052 if (Root.getOpcode() != ISD::EntryToken) { 1053 unsigned i = 0, e = Pending.size(); 1054 for (; i != e; ++i) { 1055 assert(Pending[i].getNode()->getNumOperands() > 1); 1056 if (Pending[i].getNode()->getOperand(0) == Root) 1057 break; // Don't add the root if we already indirectly depend on it. 1058 } 1059 1060 if (i == e) 1061 Pending.push_back(Root); 1062 } 1063 1064 if (Pending.size() == 1) 1065 Root = Pending[0]; 1066 else 1067 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1068 1069 DAG.setRoot(Root); 1070 Pending.clear(); 1071 return Root; 1072 } 1073 1074 SDValue SelectionDAGBuilder::getMemoryRoot() { 1075 return updateRoot(PendingLoads); 1076 } 1077 1078 SDValue SelectionDAGBuilder::getRoot() { 1079 // Chain up all pending constrained intrinsics together with all 1080 // pending loads, by simply appending them to PendingLoads and 1081 // then calling getMemoryRoot(). 1082 PendingLoads.reserve(PendingLoads.size() + 1083 PendingConstrainedFP.size() + 1084 PendingConstrainedFPStrict.size()); 1085 PendingLoads.append(PendingConstrainedFP.begin(), 1086 PendingConstrainedFP.end()); 1087 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1088 PendingConstrainedFPStrict.end()); 1089 PendingConstrainedFP.clear(); 1090 PendingConstrainedFPStrict.clear(); 1091 return getMemoryRoot(); 1092 } 1093 1094 SDValue SelectionDAGBuilder::getControlRoot() { 1095 // We need to emit pending fpexcept.strict constrained intrinsics, 1096 // so append them to the PendingExports list. 1097 PendingExports.append(PendingConstrainedFPStrict.begin(), 1098 PendingConstrainedFPStrict.end()); 1099 PendingConstrainedFPStrict.clear(); 1100 return updateRoot(PendingExports); 1101 } 1102 1103 void SelectionDAGBuilder::visit(const Instruction &I) { 1104 // Set up outgoing PHI node register values before emitting the terminator. 1105 if (I.isTerminator()) { 1106 HandlePHINodesInSuccessorBlocks(I.getParent()); 1107 } 1108 1109 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1110 if (!isa<DbgInfoIntrinsic>(I)) 1111 ++SDNodeOrder; 1112 1113 CurInst = &I; 1114 1115 visit(I.getOpcode(), I); 1116 1117 if (!I.isTerminator() && !HasTailCall && 1118 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1119 CopyToExportRegsIfNeeded(&I); 1120 1121 CurInst = nullptr; 1122 } 1123 1124 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1125 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1126 } 1127 1128 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1129 // Note: this doesn't use InstVisitor, because it has to work with 1130 // ConstantExpr's in addition to instructions. 1131 switch (Opcode) { 1132 default: llvm_unreachable("Unknown instruction type encountered!"); 1133 // Build the switch statement using the Instruction.def file. 1134 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1135 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1136 #include "llvm/IR/Instruction.def" 1137 } 1138 } 1139 1140 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI, 1141 DebugLoc DL, unsigned Order) { 1142 // We treat variadic dbg_values differently at this stage. 1143 if (DI->hasArgList()) { 1144 // For variadic dbg_values we will now insert an undef. 1145 // FIXME: We can potentially recover these! 1146 SmallVector<SDDbgOperand, 2> Locs; 1147 for (const Value *V : DI->getValues()) { 1148 auto Undef = UndefValue::get(V->getType()); 1149 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1150 } 1151 SDDbgValue *SDV = DAG.getDbgValueList( 1152 DI->getVariable(), DI->getExpression(), Locs, {}, 1153 /*IsIndirect=*/false, DL, Order, /*IsVariadic=*/true); 1154 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1155 } else { 1156 // TODO: Dangling debug info will eventually either be resolved or produce 1157 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1158 // between the original dbg.value location and its resolved DBG_VALUE, 1159 // which we should ideally fill with an extra Undef DBG_VALUE. 1160 assert(DI->getNumVariableLocationOps() == 1 && 1161 "DbgValueInst without an ArgList should have a single location " 1162 "operand."); 1163 DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, DL, Order); 1164 } 1165 } 1166 1167 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1168 const DIExpression *Expr) { 1169 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1170 const DbgValueInst *DI = DDI.getDI(); 1171 DIVariable *DanglingVariable = DI->getVariable(); 1172 DIExpression *DanglingExpr = DI->getExpression(); 1173 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1174 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1175 return true; 1176 } 1177 return false; 1178 }; 1179 1180 for (auto &DDIMI : DanglingDebugInfoMap) { 1181 DanglingDebugInfoVector &DDIV = DDIMI.second; 1182 1183 // If debug info is to be dropped, run it through final checks to see 1184 // whether it can be salvaged. 1185 for (auto &DDI : DDIV) 1186 if (isMatchingDbgValue(DDI)) 1187 salvageUnresolvedDbgValue(DDI); 1188 1189 erase_if(DDIV, isMatchingDbgValue); 1190 } 1191 } 1192 1193 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1194 // generate the debug data structures now that we've seen its definition. 1195 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1196 SDValue Val) { 1197 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1198 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1199 return; 1200 1201 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1202 for (auto &DDI : DDIV) { 1203 const DbgValueInst *DI = DDI.getDI(); 1204 assert(!DI->hasArgList() && "Not implemented for variadic dbg_values"); 1205 assert(DI && "Ill-formed DanglingDebugInfo"); 1206 DebugLoc dl = DDI.getdl(); 1207 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1208 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1209 DILocalVariable *Variable = DI->getVariable(); 1210 DIExpression *Expr = DI->getExpression(); 1211 assert(Variable->isValidLocationForIntrinsic(dl) && 1212 "Expected inlined-at fields to agree"); 1213 SDDbgValue *SDV; 1214 if (Val.getNode()) { 1215 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1216 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1217 // we couldn't resolve it directly when examining the DbgValue intrinsic 1218 // in the first place we should not be more successful here). Unless we 1219 // have some test case that prove this to be correct we should avoid 1220 // calling EmitFuncArgumentDbgValue here. 1221 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1222 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1223 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1224 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1225 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1226 // inserted after the definition of Val when emitting the instructions 1227 // after ISel. An alternative could be to teach 1228 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1229 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1230 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1231 << ValSDNodeOrder << "\n"); 1232 SDV = getDbgValue(Val, Variable, Expr, dl, 1233 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1234 DAG.AddDbgValue(SDV, false); 1235 } else 1236 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1237 << "in EmitFuncArgumentDbgValue\n"); 1238 } else { 1239 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1240 auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType()); 1241 auto SDV = 1242 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); 1243 DAG.AddDbgValue(SDV, false); 1244 } 1245 } 1246 DDIV.clear(); 1247 } 1248 1249 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1250 // TODO: For the variadic implementation, instead of only checking the fail 1251 // state of `handleDebugValue`, we need know specifically which values were 1252 // invalid, so that we attempt to salvage only those values when processing 1253 // a DIArgList. 1254 assert(!DDI.getDI()->hasArgList() && 1255 "Not implemented for variadic dbg_values"); 1256 Value *V = DDI.getDI()->getValue(0); 1257 DILocalVariable *Var = DDI.getDI()->getVariable(); 1258 DIExpression *Expr = DDI.getDI()->getExpression(); 1259 DebugLoc DL = DDI.getdl(); 1260 DebugLoc InstDL = DDI.getDI()->getDebugLoc(); 1261 unsigned SDOrder = DDI.getSDNodeOrder(); 1262 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1263 // that DW_OP_stack_value is desired. 1264 assert(isa<DbgValueInst>(DDI.getDI())); 1265 bool StackValue = true; 1266 1267 // Can this Value can be encoded without any further work? 1268 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, /*IsVariadic=*/false)) 1269 return; 1270 1271 // Attempt to salvage back through as many instructions as possible. Bail if 1272 // a non-instruction is seen, such as a constant expression or global 1273 // variable. FIXME: Further work could recover those too. 1274 while (isa<Instruction>(V)) { 1275 Instruction &VAsInst = *cast<Instruction>(V); 1276 // Temporary "0", awaiting real implementation. 1277 SmallVector<Value *, 4> AdditionalValues; 1278 DIExpression *SalvagedExpr = 1279 salvageDebugInfoImpl(VAsInst, Expr, StackValue, 0, AdditionalValues); 1280 1281 // If we cannot salvage any further, and haven't yet found a suitable debug 1282 // expression, bail out. 1283 // TODO: If AdditionalValues isn't empty, then the salvage can only be 1284 // represented with a DBG_VALUE_LIST, so we give up. When we have support 1285 // here for variadic dbg_values, remove that condition. 1286 if (!SalvagedExpr || !AdditionalValues.empty()) 1287 break; 1288 1289 // New value and expr now represent this debuginfo. 1290 V = VAsInst.getOperand(0); 1291 Expr = SalvagedExpr; 1292 1293 // Some kind of simplification occurred: check whether the operand of the 1294 // salvaged debug expression can be encoded in this DAG. 1295 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, 1296 /*IsVariadic=*/false)) { 1297 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n " 1298 << DDI.getDI() << "\nBy stripping back to:\n " << V); 1299 return; 1300 } 1301 } 1302 1303 // This was the final opportunity to salvage this debug information, and it 1304 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1305 // any earlier variable location. 1306 auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType()); 1307 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1308 DAG.AddDbgValue(SDV, false); 1309 1310 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI() 1311 << "\n"); 1312 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0) 1313 << "\n"); 1314 } 1315 1316 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1317 DILocalVariable *Var, 1318 DIExpression *Expr, DebugLoc dl, 1319 DebugLoc InstDL, unsigned Order, 1320 bool IsVariadic) { 1321 if (Values.empty()) 1322 return true; 1323 SmallVector<SDDbgOperand> LocationOps; 1324 SmallVector<SDNode *> Dependencies; 1325 for (const Value *V : Values) { 1326 // Constant value. 1327 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1328 isa<ConstantPointerNull>(V)) { 1329 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1330 continue; 1331 } 1332 1333 // If the Value is a frame index, we can create a FrameIndex debug value 1334 // without relying on the DAG at all. 1335 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1336 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1337 if (SI != FuncInfo.StaticAllocaMap.end()) { 1338 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1339 continue; 1340 } 1341 } 1342 1343 // Do not use getValue() in here; we don't want to generate code at 1344 // this point if it hasn't been done yet. 1345 SDValue N = NodeMap[V]; 1346 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1347 N = UnusedArgNodeMap[V]; 1348 if (N.getNode()) { 1349 // Only emit func arg dbg value for non-variadic dbg.values for now. 1350 if (!IsVariadic && EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N)) 1351 return true; 1352 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1353 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1354 // describe stack slot locations. 1355 // 1356 // Consider "int x = 0; int *px = &x;". There are two kinds of 1357 // interesting debug values here after optimization: 1358 // 1359 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1360 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1361 // 1362 // Both describe the direct values of their associated variables. 1363 Dependencies.push_back(N.getNode()); 1364 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1365 continue; 1366 } 1367 LocationOps.emplace_back( 1368 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1369 continue; 1370 } 1371 1372 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1373 // Special rules apply for the first dbg.values of parameter variables in a 1374 // function. Identify them by the fact they reference Argument Values, that 1375 // they're parameters, and they are parameters of the current function. We 1376 // need to let them dangle until they get an SDNode. 1377 bool IsParamOfFunc = 1378 isa<Argument>(V) && Var->isParameter() && !InstDL.getInlinedAt(); 1379 if (IsParamOfFunc) 1380 return false; 1381 1382 // The value is not used in this block yet (or it would have an SDNode). 1383 // We still want the value to appear for the user if possible -- if it has 1384 // an associated VReg, we can refer to that instead. 1385 auto VMI = FuncInfo.ValueMap.find(V); 1386 if (VMI != FuncInfo.ValueMap.end()) { 1387 unsigned Reg = VMI->second; 1388 // If this is a PHI node, it may be split up into several MI PHI nodes 1389 // (in FunctionLoweringInfo::set). 1390 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1391 V->getType(), None); 1392 if (RFV.occupiesMultipleRegs()) { 1393 // FIXME: We could potentially support variadic dbg_values here. 1394 if (IsVariadic) 1395 return false; 1396 unsigned Offset = 0; 1397 unsigned BitsToDescribe = 0; 1398 if (auto VarSize = Var->getSizeInBits()) 1399 BitsToDescribe = *VarSize; 1400 if (auto Fragment = Expr->getFragmentInfo()) 1401 BitsToDescribe = Fragment->SizeInBits; 1402 for (auto RegAndSize : RFV.getRegsAndSizes()) { 1403 // Bail out if all bits are described already. 1404 if (Offset >= BitsToDescribe) 1405 break; 1406 // TODO: handle scalable vectors. 1407 unsigned RegisterSize = RegAndSize.second; 1408 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1409 ? BitsToDescribe - Offset 1410 : RegisterSize; 1411 auto FragmentExpr = DIExpression::createFragmentExpression( 1412 Expr, Offset, FragmentSize); 1413 if (!FragmentExpr) 1414 continue; 1415 SDDbgValue *SDV = DAG.getVRegDbgValue( 1416 Var, *FragmentExpr, RegAndSize.first, false, dl, SDNodeOrder); 1417 DAG.AddDbgValue(SDV, false); 1418 Offset += RegisterSize; 1419 } 1420 return true; 1421 } 1422 // We can use simple vreg locations for variadic dbg_values as well. 1423 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1424 continue; 1425 } 1426 // We failed to create a SDDbgOperand for V. 1427 return false; 1428 } 1429 1430 // We have created a SDDbgOperand for each Value in Values. 1431 // Should use Order instead of SDNodeOrder? 1432 assert(!LocationOps.empty()); 1433 SDDbgValue *SDV = 1434 DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1435 /*IsIndirect=*/false, dl, SDNodeOrder, IsVariadic); 1436 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1437 return true; 1438 } 1439 1440 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1441 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1442 for (auto &Pair : DanglingDebugInfoMap) 1443 for (auto &DDI : Pair.second) 1444 salvageUnresolvedDbgValue(DDI); 1445 clearDanglingDebugInfo(); 1446 } 1447 1448 /// getCopyFromRegs - If there was virtual register allocated for the value V 1449 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1450 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1451 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1452 SDValue Result; 1453 1454 if (It != FuncInfo.ValueMap.end()) { 1455 Register InReg = It->second; 1456 1457 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1458 DAG.getDataLayout(), InReg, Ty, 1459 None); // This is not an ABI copy. 1460 SDValue Chain = DAG.getEntryNode(); 1461 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1462 V); 1463 resolveDanglingDebugInfo(V, Result); 1464 } 1465 1466 return Result; 1467 } 1468 1469 /// getValue - Return an SDValue for the given Value. 1470 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1471 // If we already have an SDValue for this value, use it. It's important 1472 // to do this first, so that we don't create a CopyFromReg if we already 1473 // have a regular SDValue. 1474 SDValue &N = NodeMap[V]; 1475 if (N.getNode()) return N; 1476 1477 // If there's a virtual register allocated and initialized for this 1478 // value, use it. 1479 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1480 return copyFromReg; 1481 1482 // Otherwise create a new SDValue and remember it. 1483 SDValue Val = getValueImpl(V); 1484 NodeMap[V] = Val; 1485 resolveDanglingDebugInfo(V, Val); 1486 return Val; 1487 } 1488 1489 /// getNonRegisterValue - Return an SDValue for the given Value, but 1490 /// don't look in FuncInfo.ValueMap for a virtual register. 1491 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1492 // If we already have an SDValue for this value, use it. 1493 SDValue &N = NodeMap[V]; 1494 if (N.getNode()) { 1495 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1496 // Remove the debug location from the node as the node is about to be used 1497 // in a location which may differ from the original debug location. This 1498 // is relevant to Constant and ConstantFP nodes because they can appear 1499 // as constant expressions inside PHI nodes. 1500 N->setDebugLoc(DebugLoc()); 1501 } 1502 return N; 1503 } 1504 1505 // Otherwise create a new SDValue and remember it. 1506 SDValue Val = getValueImpl(V); 1507 NodeMap[V] = Val; 1508 resolveDanglingDebugInfo(V, Val); 1509 return Val; 1510 } 1511 1512 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1513 /// Create an SDValue for the given value. 1514 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1515 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1516 1517 if (const Constant *C = dyn_cast<Constant>(V)) { 1518 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1519 1520 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1521 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1522 1523 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1524 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1525 1526 if (isa<ConstantPointerNull>(C)) { 1527 unsigned AS = V->getType()->getPointerAddressSpace(); 1528 return DAG.getConstant(0, getCurSDLoc(), 1529 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1530 } 1531 1532 if (match(C, m_VScale(DAG.getDataLayout()))) 1533 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1534 1535 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1536 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1537 1538 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1539 return DAG.getUNDEF(VT); 1540 1541 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1542 visit(CE->getOpcode(), *CE); 1543 SDValue N1 = NodeMap[V]; 1544 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1545 return N1; 1546 } 1547 1548 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1549 SmallVector<SDValue, 4> Constants; 1550 for (const Use &U : C->operands()) { 1551 SDNode *Val = getValue(U).getNode(); 1552 // If the operand is an empty aggregate, there are no values. 1553 if (!Val) continue; 1554 // Add each leaf value from the operand to the Constants list 1555 // to form a flattened list of all the values. 1556 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1557 Constants.push_back(SDValue(Val, i)); 1558 } 1559 1560 return DAG.getMergeValues(Constants, getCurSDLoc()); 1561 } 1562 1563 if (const ConstantDataSequential *CDS = 1564 dyn_cast<ConstantDataSequential>(C)) { 1565 SmallVector<SDValue, 4> Ops; 1566 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1567 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1568 // Add each leaf value from the operand to the Constants list 1569 // to form a flattened list of all the values. 1570 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1571 Ops.push_back(SDValue(Val, i)); 1572 } 1573 1574 if (isa<ArrayType>(CDS->getType())) 1575 return DAG.getMergeValues(Ops, getCurSDLoc()); 1576 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1577 } 1578 1579 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1580 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1581 "Unknown struct or array constant!"); 1582 1583 SmallVector<EVT, 4> ValueVTs; 1584 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1585 unsigned NumElts = ValueVTs.size(); 1586 if (NumElts == 0) 1587 return SDValue(); // empty struct 1588 SmallVector<SDValue, 4> Constants(NumElts); 1589 for (unsigned i = 0; i != NumElts; ++i) { 1590 EVT EltVT = ValueVTs[i]; 1591 if (isa<UndefValue>(C)) 1592 Constants[i] = DAG.getUNDEF(EltVT); 1593 else if (EltVT.isFloatingPoint()) 1594 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1595 else 1596 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1597 } 1598 1599 return DAG.getMergeValues(Constants, getCurSDLoc()); 1600 } 1601 1602 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1603 return DAG.getBlockAddress(BA, VT); 1604 1605 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1606 return getValue(Equiv->getGlobalValue()); 1607 1608 VectorType *VecTy = cast<VectorType>(V->getType()); 1609 1610 // Now that we know the number and type of the elements, get that number of 1611 // elements into the Ops array based on what kind of constant it is. 1612 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1613 SmallVector<SDValue, 16> Ops; 1614 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1615 for (unsigned i = 0; i != NumElements; ++i) 1616 Ops.push_back(getValue(CV->getOperand(i))); 1617 1618 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1619 } else if (isa<ConstantAggregateZero>(C)) { 1620 EVT EltVT = 1621 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1622 1623 SDValue Op; 1624 if (EltVT.isFloatingPoint()) 1625 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1626 else 1627 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1628 1629 if (isa<ScalableVectorType>(VecTy)) 1630 return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op); 1631 else { 1632 SmallVector<SDValue, 16> Ops; 1633 Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op); 1634 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1635 } 1636 } 1637 llvm_unreachable("Unknown vector constant"); 1638 } 1639 1640 // If this is a static alloca, generate it as the frameindex instead of 1641 // computation. 1642 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1643 DenseMap<const AllocaInst*, int>::iterator SI = 1644 FuncInfo.StaticAllocaMap.find(AI); 1645 if (SI != FuncInfo.StaticAllocaMap.end()) 1646 return DAG.getFrameIndex(SI->second, 1647 TLI.getFrameIndexTy(DAG.getDataLayout())); 1648 } 1649 1650 // If this is an instruction which fast-isel has deferred, select it now. 1651 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1652 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1653 1654 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1655 Inst->getType(), None); 1656 SDValue Chain = DAG.getEntryNode(); 1657 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1658 } 1659 1660 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) { 1661 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1662 } 1663 llvm_unreachable("Can't get register for value!"); 1664 } 1665 1666 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1667 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1668 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1669 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1670 bool IsSEH = isAsynchronousEHPersonality(Pers); 1671 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1672 if (!IsSEH) 1673 CatchPadMBB->setIsEHScopeEntry(); 1674 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1675 if (IsMSVCCXX || IsCoreCLR) 1676 CatchPadMBB->setIsEHFuncletEntry(); 1677 } 1678 1679 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1680 // Update machine-CFG edge. 1681 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1682 FuncInfo.MBB->addSuccessor(TargetMBB); 1683 TargetMBB->setIsEHCatchretTarget(true); 1684 DAG.getMachineFunction().setHasEHCatchret(true); 1685 1686 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1687 bool IsSEH = isAsynchronousEHPersonality(Pers); 1688 if (IsSEH) { 1689 // If this is not a fall-through branch or optimizations are switched off, 1690 // emit the branch. 1691 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1692 TM.getOptLevel() == CodeGenOpt::None) 1693 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1694 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1695 return; 1696 } 1697 1698 // Figure out the funclet membership for the catchret's successor. 1699 // This will be used by the FuncletLayout pass to determine how to order the 1700 // BB's. 1701 // A 'catchret' returns to the outer scope's color. 1702 Value *ParentPad = I.getCatchSwitchParentPad(); 1703 const BasicBlock *SuccessorColor; 1704 if (isa<ConstantTokenNone>(ParentPad)) 1705 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1706 else 1707 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1708 assert(SuccessorColor && "No parent funclet for catchret!"); 1709 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1710 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1711 1712 // Create the terminator node. 1713 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1714 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1715 DAG.getBasicBlock(SuccessorColorMBB)); 1716 DAG.setRoot(Ret); 1717 } 1718 1719 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1720 // Don't emit any special code for the cleanuppad instruction. It just marks 1721 // the start of an EH scope/funclet. 1722 FuncInfo.MBB->setIsEHScopeEntry(); 1723 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1724 if (Pers != EHPersonality::Wasm_CXX) { 1725 FuncInfo.MBB->setIsEHFuncletEntry(); 1726 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1727 } 1728 } 1729 1730 // In wasm EH, even though a catchpad may not catch an exception if a tag does 1731 // not match, it is OK to add only the first unwind destination catchpad to the 1732 // successors, because there will be at least one invoke instruction within the 1733 // catch scope that points to the next unwind destination, if one exists, so 1734 // CFGSort cannot mess up with BB sorting order. 1735 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 1736 // call within them, and catchpads only consisting of 'catch (...)' have a 1737 // '__cxa_end_catch' call within them, both of which generate invokes in case 1738 // the next unwind destination exists, i.e., the next unwind destination is not 1739 // the caller.) 1740 // 1741 // Having at most one EH pad successor is also simpler and helps later 1742 // transformations. 1743 // 1744 // For example, 1745 // current: 1746 // invoke void @foo to ... unwind label %catch.dispatch 1747 // catch.dispatch: 1748 // %0 = catchswitch within ... [label %catch.start] unwind label %next 1749 // catch.start: 1750 // ... 1751 // ... in this BB or some other child BB dominated by this BB there will be an 1752 // invoke that points to 'next' BB as an unwind destination 1753 // 1754 // next: ; We don't need to add this to 'current' BB's successor 1755 // ... 1756 static void findWasmUnwindDestinations( 1757 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1758 BranchProbability Prob, 1759 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1760 &UnwindDests) { 1761 while (EHPadBB) { 1762 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1763 if (isa<CleanupPadInst>(Pad)) { 1764 // Stop on cleanup pads. 1765 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1766 UnwindDests.back().first->setIsEHScopeEntry(); 1767 break; 1768 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1769 // Add the catchpad handlers to the possible destinations. We don't 1770 // continue to the unwind destination of the catchswitch for wasm. 1771 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1772 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1773 UnwindDests.back().first->setIsEHScopeEntry(); 1774 } 1775 break; 1776 } else { 1777 continue; 1778 } 1779 } 1780 } 1781 1782 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1783 /// many places it could ultimately go. In the IR, we have a single unwind 1784 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1785 /// This function skips over imaginary basic blocks that hold catchswitch 1786 /// instructions, and finds all the "real" machine 1787 /// basic block destinations. As those destinations may not be successors of 1788 /// EHPadBB, here we also calculate the edge probability to those destinations. 1789 /// The passed-in Prob is the edge probability to EHPadBB. 1790 static void findUnwindDestinations( 1791 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1792 BranchProbability Prob, 1793 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1794 &UnwindDests) { 1795 EHPersonality Personality = 1796 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1797 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1798 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1799 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1800 bool IsSEH = isAsynchronousEHPersonality(Personality); 1801 1802 if (IsWasmCXX) { 1803 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1804 assert(UnwindDests.size() <= 1 && 1805 "There should be at most one unwind destination for wasm"); 1806 return; 1807 } 1808 1809 while (EHPadBB) { 1810 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1811 BasicBlock *NewEHPadBB = nullptr; 1812 if (isa<LandingPadInst>(Pad)) { 1813 // Stop on landingpads. They are not funclets. 1814 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1815 break; 1816 } else if (isa<CleanupPadInst>(Pad)) { 1817 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1818 // personalities. 1819 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1820 UnwindDests.back().first->setIsEHScopeEntry(); 1821 UnwindDests.back().first->setIsEHFuncletEntry(); 1822 break; 1823 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1824 // Add the catchpad handlers to the possible destinations. 1825 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1826 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1827 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1828 if (IsMSVCCXX || IsCoreCLR) 1829 UnwindDests.back().first->setIsEHFuncletEntry(); 1830 if (!IsSEH) 1831 UnwindDests.back().first->setIsEHScopeEntry(); 1832 } 1833 NewEHPadBB = CatchSwitch->getUnwindDest(); 1834 } else { 1835 continue; 1836 } 1837 1838 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1839 if (BPI && NewEHPadBB) 1840 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1841 EHPadBB = NewEHPadBB; 1842 } 1843 } 1844 1845 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1846 // Update successor info. 1847 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1848 auto UnwindDest = I.getUnwindDest(); 1849 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1850 BranchProbability UnwindDestProb = 1851 (BPI && UnwindDest) 1852 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1853 : BranchProbability::getZero(); 1854 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1855 for (auto &UnwindDest : UnwindDests) { 1856 UnwindDest.first->setIsEHPad(); 1857 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1858 } 1859 FuncInfo.MBB->normalizeSuccProbs(); 1860 1861 // Create the terminator node. 1862 SDValue Ret = 1863 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1864 DAG.setRoot(Ret); 1865 } 1866 1867 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1868 report_fatal_error("visitCatchSwitch not yet implemented!"); 1869 } 1870 1871 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1872 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1873 auto &DL = DAG.getDataLayout(); 1874 SDValue Chain = getControlRoot(); 1875 SmallVector<ISD::OutputArg, 8> Outs; 1876 SmallVector<SDValue, 8> OutVals; 1877 1878 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1879 // lower 1880 // 1881 // %val = call <ty> @llvm.experimental.deoptimize() 1882 // ret <ty> %val 1883 // 1884 // differently. 1885 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1886 LowerDeoptimizingReturn(); 1887 return; 1888 } 1889 1890 if (!FuncInfo.CanLowerReturn) { 1891 unsigned DemoteReg = FuncInfo.DemoteRegister; 1892 const Function *F = I.getParent()->getParent(); 1893 1894 // Emit a store of the return value through the virtual register. 1895 // Leave Outs empty so that LowerReturn won't try to load return 1896 // registers the usual way. 1897 SmallVector<EVT, 1> PtrValueVTs; 1898 ComputeValueVTs(TLI, DL, 1899 F->getReturnType()->getPointerTo( 1900 DAG.getDataLayout().getAllocaAddrSpace()), 1901 PtrValueVTs); 1902 1903 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1904 DemoteReg, PtrValueVTs[0]); 1905 SDValue RetOp = getValue(I.getOperand(0)); 1906 1907 SmallVector<EVT, 4> ValueVTs, MemVTs; 1908 SmallVector<uint64_t, 4> Offsets; 1909 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1910 &Offsets); 1911 unsigned NumValues = ValueVTs.size(); 1912 1913 SmallVector<SDValue, 4> Chains(NumValues); 1914 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 1915 for (unsigned i = 0; i != NumValues; ++i) { 1916 // An aggregate return value cannot wrap around the address space, so 1917 // offsets to its parts don't wrap either. 1918 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 1919 TypeSize::Fixed(Offsets[i])); 1920 1921 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 1922 if (MemVTs[i] != ValueVTs[i]) 1923 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 1924 Chains[i] = DAG.getStore( 1925 Chain, getCurSDLoc(), Val, 1926 // FIXME: better loc info would be nice. 1927 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 1928 commonAlignment(BaseAlign, Offsets[i])); 1929 } 1930 1931 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1932 MVT::Other, Chains); 1933 } else if (I.getNumOperands() != 0) { 1934 SmallVector<EVT, 4> ValueVTs; 1935 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1936 unsigned NumValues = ValueVTs.size(); 1937 if (NumValues) { 1938 SDValue RetOp = getValue(I.getOperand(0)); 1939 1940 const Function *F = I.getParent()->getParent(); 1941 1942 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 1943 I.getOperand(0)->getType(), F->getCallingConv(), 1944 /*IsVarArg*/ false); 1945 1946 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1947 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1948 Attribute::SExt)) 1949 ExtendKind = ISD::SIGN_EXTEND; 1950 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1951 Attribute::ZExt)) 1952 ExtendKind = ISD::ZERO_EXTEND; 1953 1954 LLVMContext &Context = F->getContext(); 1955 bool RetInReg = F->getAttributes().hasAttribute( 1956 AttributeList::ReturnIndex, Attribute::InReg); 1957 1958 for (unsigned j = 0; j != NumValues; ++j) { 1959 EVT VT = ValueVTs[j]; 1960 1961 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1962 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1963 1964 CallingConv::ID CC = F->getCallingConv(); 1965 1966 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1967 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1968 SmallVector<SDValue, 4> Parts(NumParts); 1969 getCopyToParts(DAG, getCurSDLoc(), 1970 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1971 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1972 1973 // 'inreg' on function refers to return value 1974 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1975 if (RetInReg) 1976 Flags.setInReg(); 1977 1978 if (I.getOperand(0)->getType()->isPointerTy()) { 1979 Flags.setPointer(); 1980 Flags.setPointerAddrSpace( 1981 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 1982 } 1983 1984 if (NeedsRegBlock) { 1985 Flags.setInConsecutiveRegs(); 1986 if (j == NumValues - 1) 1987 Flags.setInConsecutiveRegsLast(); 1988 } 1989 1990 // Propagate extension type if any 1991 if (ExtendKind == ISD::SIGN_EXTEND) 1992 Flags.setSExt(); 1993 else if (ExtendKind == ISD::ZERO_EXTEND) 1994 Flags.setZExt(); 1995 1996 for (unsigned i = 0; i < NumParts; ++i) { 1997 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1998 VT, /*isfixed=*/true, 0, 0)); 1999 OutVals.push_back(Parts[i]); 2000 } 2001 } 2002 } 2003 } 2004 2005 // Push in swifterror virtual register as the last element of Outs. This makes 2006 // sure swifterror virtual register will be returned in the swifterror 2007 // physical register. 2008 const Function *F = I.getParent()->getParent(); 2009 if (TLI.supportSwiftError() && 2010 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2011 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2012 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2013 Flags.setSwiftError(); 2014 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 2015 EVT(TLI.getPointerTy(DL)) /*argvt*/, 2016 true /*isfixed*/, 1 /*origidx*/, 2017 0 /*partOffs*/)); 2018 // Create SDNode for the swifterror virtual register. 2019 OutVals.push_back( 2020 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2021 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2022 EVT(TLI.getPointerTy(DL)))); 2023 } 2024 2025 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2026 CallingConv::ID CallConv = 2027 DAG.getMachineFunction().getFunction().getCallingConv(); 2028 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2029 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2030 2031 // Verify that the target's LowerReturn behaved as expected. 2032 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2033 "LowerReturn didn't return a valid chain!"); 2034 2035 // Update the DAG with the new chain value resulting from return lowering. 2036 DAG.setRoot(Chain); 2037 } 2038 2039 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2040 /// created for it, emit nodes to copy the value into the virtual 2041 /// registers. 2042 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2043 // Skip empty types 2044 if (V->getType()->isEmptyTy()) 2045 return; 2046 2047 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2048 if (VMI != FuncInfo.ValueMap.end()) { 2049 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 2050 CopyValueToVirtualRegister(V, VMI->second); 2051 } 2052 } 2053 2054 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2055 /// the current basic block, add it to ValueMap now so that we'll get a 2056 /// CopyTo/FromReg. 2057 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2058 // No need to export constants. 2059 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2060 2061 // Already exported? 2062 if (FuncInfo.isExportedInst(V)) return; 2063 2064 unsigned Reg = FuncInfo.InitializeRegForValue(V); 2065 CopyValueToVirtualRegister(V, Reg); 2066 } 2067 2068 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2069 const BasicBlock *FromBB) { 2070 // The operands of the setcc have to be in this block. We don't know 2071 // how to export them from some other block. 2072 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2073 // Can export from current BB. 2074 if (VI->getParent() == FromBB) 2075 return true; 2076 2077 // Is already exported, noop. 2078 return FuncInfo.isExportedInst(V); 2079 } 2080 2081 // If this is an argument, we can export it if the BB is the entry block or 2082 // if it is already exported. 2083 if (isa<Argument>(V)) { 2084 if (FromBB->isEntryBlock()) 2085 return true; 2086 2087 // Otherwise, can only export this if it is already exported. 2088 return FuncInfo.isExportedInst(V); 2089 } 2090 2091 // Otherwise, constants can always be exported. 2092 return true; 2093 } 2094 2095 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2096 BranchProbability 2097 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2098 const MachineBasicBlock *Dst) const { 2099 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2100 const BasicBlock *SrcBB = Src->getBasicBlock(); 2101 const BasicBlock *DstBB = Dst->getBasicBlock(); 2102 if (!BPI) { 2103 // If BPI is not available, set the default probability as 1 / N, where N is 2104 // the number of successors. 2105 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2106 return BranchProbability(1, SuccSize); 2107 } 2108 return BPI->getEdgeProbability(SrcBB, DstBB); 2109 } 2110 2111 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2112 MachineBasicBlock *Dst, 2113 BranchProbability Prob) { 2114 if (!FuncInfo.BPI) 2115 Src->addSuccessorWithoutProb(Dst); 2116 else { 2117 if (Prob.isUnknown()) 2118 Prob = getEdgeProbability(Src, Dst); 2119 Src->addSuccessor(Dst, Prob); 2120 } 2121 } 2122 2123 static bool InBlock(const Value *V, const BasicBlock *BB) { 2124 if (const Instruction *I = dyn_cast<Instruction>(V)) 2125 return I->getParent() == BB; 2126 return true; 2127 } 2128 2129 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2130 /// This function emits a branch and is used at the leaves of an OR or an 2131 /// AND operator tree. 2132 void 2133 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2134 MachineBasicBlock *TBB, 2135 MachineBasicBlock *FBB, 2136 MachineBasicBlock *CurBB, 2137 MachineBasicBlock *SwitchBB, 2138 BranchProbability TProb, 2139 BranchProbability FProb, 2140 bool InvertCond) { 2141 const BasicBlock *BB = CurBB->getBasicBlock(); 2142 2143 // If the leaf of the tree is a comparison, merge the condition into 2144 // the caseblock. 2145 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2146 // The operands of the cmp have to be in this block. We don't know 2147 // how to export them from some other block. If this is the first block 2148 // of the sequence, no exporting is needed. 2149 if (CurBB == SwitchBB || 2150 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2151 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2152 ISD::CondCode Condition; 2153 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2154 ICmpInst::Predicate Pred = 2155 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2156 Condition = getICmpCondCode(Pred); 2157 } else { 2158 const FCmpInst *FC = cast<FCmpInst>(Cond); 2159 FCmpInst::Predicate Pred = 2160 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2161 Condition = getFCmpCondCode(Pred); 2162 if (TM.Options.NoNaNsFPMath) 2163 Condition = getFCmpCodeWithoutNaN(Condition); 2164 } 2165 2166 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2167 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2168 SL->SwitchCases.push_back(CB); 2169 return; 2170 } 2171 } 2172 2173 // Create a CaseBlock record representing this branch. 2174 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2175 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2176 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2177 SL->SwitchCases.push_back(CB); 2178 } 2179 2180 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2181 MachineBasicBlock *TBB, 2182 MachineBasicBlock *FBB, 2183 MachineBasicBlock *CurBB, 2184 MachineBasicBlock *SwitchBB, 2185 Instruction::BinaryOps Opc, 2186 BranchProbability TProb, 2187 BranchProbability FProb, 2188 bool InvertCond) { 2189 // Skip over not part of the tree and remember to invert op and operands at 2190 // next level. 2191 Value *NotCond; 2192 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2193 InBlock(NotCond, CurBB->getBasicBlock())) { 2194 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2195 !InvertCond); 2196 return; 2197 } 2198 2199 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2200 const Value *BOpOp0, *BOpOp1; 2201 // Compute the effective opcode for Cond, taking into account whether it needs 2202 // to be inverted, e.g. 2203 // and (not (or A, B)), C 2204 // gets lowered as 2205 // and (and (not A, not B), C) 2206 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2207 if (BOp) { 2208 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2209 ? Instruction::And 2210 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2211 ? Instruction::Or 2212 : (Instruction::BinaryOps)0); 2213 if (InvertCond) { 2214 if (BOpc == Instruction::And) 2215 BOpc = Instruction::Or; 2216 else if (BOpc == Instruction::Or) 2217 BOpc = Instruction::And; 2218 } 2219 } 2220 2221 // If this node is not part of the or/and tree, emit it as a branch. 2222 // Note that all nodes in the tree should have same opcode. 2223 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2224 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2225 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2226 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2227 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2228 TProb, FProb, InvertCond); 2229 return; 2230 } 2231 2232 // Create TmpBB after CurBB. 2233 MachineFunction::iterator BBI(CurBB); 2234 MachineFunction &MF = DAG.getMachineFunction(); 2235 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2236 CurBB->getParent()->insert(++BBI, TmpBB); 2237 2238 if (Opc == Instruction::Or) { 2239 // Codegen X | Y as: 2240 // BB1: 2241 // jmp_if_X TBB 2242 // jmp TmpBB 2243 // TmpBB: 2244 // jmp_if_Y TBB 2245 // jmp FBB 2246 // 2247 2248 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2249 // The requirement is that 2250 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2251 // = TrueProb for original BB. 2252 // Assuming the original probabilities are A and B, one choice is to set 2253 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2254 // A/(1+B) and 2B/(1+B). This choice assumes that 2255 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2256 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2257 // TmpBB, but the math is more complicated. 2258 2259 auto NewTrueProb = TProb / 2; 2260 auto NewFalseProb = TProb / 2 + FProb; 2261 // Emit the LHS condition. 2262 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2263 NewFalseProb, InvertCond); 2264 2265 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2266 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2267 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2268 // Emit the RHS condition into TmpBB. 2269 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2270 Probs[1], InvertCond); 2271 } else { 2272 assert(Opc == Instruction::And && "Unknown merge op!"); 2273 // Codegen X & Y as: 2274 // BB1: 2275 // jmp_if_X TmpBB 2276 // jmp FBB 2277 // TmpBB: 2278 // jmp_if_Y TBB 2279 // jmp FBB 2280 // 2281 // This requires creation of TmpBB after CurBB. 2282 2283 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2284 // The requirement is that 2285 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2286 // = FalseProb for original BB. 2287 // Assuming the original probabilities are A and B, one choice is to set 2288 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2289 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2290 // TrueProb for BB1 * FalseProb for TmpBB. 2291 2292 auto NewTrueProb = TProb + FProb / 2; 2293 auto NewFalseProb = FProb / 2; 2294 // Emit the LHS condition. 2295 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2296 NewFalseProb, InvertCond); 2297 2298 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2299 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2300 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2301 // Emit the RHS condition into TmpBB. 2302 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2303 Probs[1], InvertCond); 2304 } 2305 } 2306 2307 /// If the set of cases should be emitted as a series of branches, return true. 2308 /// If we should emit this as a bunch of and/or'd together conditions, return 2309 /// false. 2310 bool 2311 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2312 if (Cases.size() != 2) return true; 2313 2314 // If this is two comparisons of the same values or'd or and'd together, they 2315 // will get folded into a single comparison, so don't emit two blocks. 2316 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2317 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2318 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2319 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2320 return false; 2321 } 2322 2323 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2324 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2325 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2326 Cases[0].CC == Cases[1].CC && 2327 isa<Constant>(Cases[0].CmpRHS) && 2328 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2329 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2330 return false; 2331 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2332 return false; 2333 } 2334 2335 return true; 2336 } 2337 2338 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2339 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2340 2341 // Update machine-CFG edges. 2342 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2343 2344 if (I.isUnconditional()) { 2345 // Update machine-CFG edges. 2346 BrMBB->addSuccessor(Succ0MBB); 2347 2348 // If this is not a fall-through branch or optimizations are switched off, 2349 // emit the branch. 2350 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2351 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2352 MVT::Other, getControlRoot(), 2353 DAG.getBasicBlock(Succ0MBB))); 2354 2355 return; 2356 } 2357 2358 // If this condition is one of the special cases we handle, do special stuff 2359 // now. 2360 const Value *CondVal = I.getCondition(); 2361 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2362 2363 // If this is a series of conditions that are or'd or and'd together, emit 2364 // this as a sequence of branches instead of setcc's with and/or operations. 2365 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2366 // unpredictable branches, and vector extracts because those jumps are likely 2367 // expensive for any target), this should improve performance. 2368 // For example, instead of something like: 2369 // cmp A, B 2370 // C = seteq 2371 // cmp D, E 2372 // F = setle 2373 // or C, F 2374 // jnz foo 2375 // Emit: 2376 // cmp A, B 2377 // je foo 2378 // cmp D, E 2379 // jle foo 2380 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2381 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2382 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2383 Value *Vec; 2384 const Value *BOp0, *BOp1; 2385 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2386 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2387 Opcode = Instruction::And; 2388 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2389 Opcode = Instruction::Or; 2390 2391 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2392 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2393 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2394 getEdgeProbability(BrMBB, Succ0MBB), 2395 getEdgeProbability(BrMBB, Succ1MBB), 2396 /*InvertCond=*/false); 2397 // If the compares in later blocks need to use values not currently 2398 // exported from this block, export them now. This block should always 2399 // be the first entry. 2400 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2401 2402 // Allow some cases to be rejected. 2403 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2404 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2405 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2406 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2407 } 2408 2409 // Emit the branch for this block. 2410 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2411 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2412 return; 2413 } 2414 2415 // Okay, we decided not to do this, remove any inserted MBB's and clear 2416 // SwitchCases. 2417 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2418 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2419 2420 SL->SwitchCases.clear(); 2421 } 2422 } 2423 2424 // Create a CaseBlock record representing this branch. 2425 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2426 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2427 2428 // Use visitSwitchCase to actually insert the fast branch sequence for this 2429 // cond branch. 2430 visitSwitchCase(CB, BrMBB); 2431 } 2432 2433 /// visitSwitchCase - Emits the necessary code to represent a single node in 2434 /// the binary search tree resulting from lowering a switch instruction. 2435 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2436 MachineBasicBlock *SwitchBB) { 2437 SDValue Cond; 2438 SDValue CondLHS = getValue(CB.CmpLHS); 2439 SDLoc dl = CB.DL; 2440 2441 if (CB.CC == ISD::SETTRUE) { 2442 // Branch or fall through to TrueBB. 2443 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2444 SwitchBB->normalizeSuccProbs(); 2445 if (CB.TrueBB != NextBlock(SwitchBB)) { 2446 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2447 DAG.getBasicBlock(CB.TrueBB))); 2448 } 2449 return; 2450 } 2451 2452 auto &TLI = DAG.getTargetLoweringInfo(); 2453 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2454 2455 // Build the setcc now. 2456 if (!CB.CmpMHS) { 2457 // Fold "(X == true)" to X and "(X == false)" to !X to 2458 // handle common cases produced by branch lowering. 2459 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2460 CB.CC == ISD::SETEQ) 2461 Cond = CondLHS; 2462 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2463 CB.CC == ISD::SETEQ) { 2464 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2465 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2466 } else { 2467 SDValue CondRHS = getValue(CB.CmpRHS); 2468 2469 // If a pointer's DAG type is larger than its memory type then the DAG 2470 // values are zero-extended. This breaks signed comparisons so truncate 2471 // back to the underlying type before doing the compare. 2472 if (CondLHS.getValueType() != MemVT) { 2473 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2474 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2475 } 2476 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2477 } 2478 } else { 2479 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2480 2481 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2482 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2483 2484 SDValue CmpOp = getValue(CB.CmpMHS); 2485 EVT VT = CmpOp.getValueType(); 2486 2487 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2488 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2489 ISD::SETLE); 2490 } else { 2491 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2492 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2493 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2494 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2495 } 2496 } 2497 2498 // Update successor info 2499 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2500 // TrueBB and FalseBB are always different unless the incoming IR is 2501 // degenerate. This only happens when running llc on weird IR. 2502 if (CB.TrueBB != CB.FalseBB) 2503 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2504 SwitchBB->normalizeSuccProbs(); 2505 2506 // If the lhs block is the next block, invert the condition so that we can 2507 // fall through to the lhs instead of the rhs block. 2508 if (CB.TrueBB == NextBlock(SwitchBB)) { 2509 std::swap(CB.TrueBB, CB.FalseBB); 2510 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2511 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2512 } 2513 2514 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2515 MVT::Other, getControlRoot(), Cond, 2516 DAG.getBasicBlock(CB.TrueBB)); 2517 2518 // Insert the false branch. Do this even if it's a fall through branch, 2519 // this makes it easier to do DAG optimizations which require inverting 2520 // the branch condition. 2521 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2522 DAG.getBasicBlock(CB.FalseBB)); 2523 2524 DAG.setRoot(BrCond); 2525 } 2526 2527 /// visitJumpTable - Emit JumpTable node in the current MBB 2528 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2529 // Emit the code for the jump table 2530 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2531 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2532 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2533 JT.Reg, PTy); 2534 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2535 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2536 MVT::Other, Index.getValue(1), 2537 Table, Index); 2538 DAG.setRoot(BrJumpTable); 2539 } 2540 2541 /// visitJumpTableHeader - This function emits necessary code to produce index 2542 /// in the JumpTable from switch case. 2543 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2544 JumpTableHeader &JTH, 2545 MachineBasicBlock *SwitchBB) { 2546 SDLoc dl = getCurSDLoc(); 2547 2548 // Subtract the lowest switch case value from the value being switched on. 2549 SDValue SwitchOp = getValue(JTH.SValue); 2550 EVT VT = SwitchOp.getValueType(); 2551 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2552 DAG.getConstant(JTH.First, dl, VT)); 2553 2554 // The SDNode we just created, which holds the value being switched on minus 2555 // the smallest case value, needs to be copied to a virtual register so it 2556 // can be used as an index into the jump table in a subsequent basic block. 2557 // This value may be smaller or larger than the target's pointer type, and 2558 // therefore require extension or truncating. 2559 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2560 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2561 2562 unsigned JumpTableReg = 2563 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2564 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2565 JumpTableReg, SwitchOp); 2566 JT.Reg = JumpTableReg; 2567 2568 if (!JTH.OmitRangeCheck) { 2569 // Emit the range check for the jump table, and branch to the default block 2570 // for the switch statement if the value being switched on exceeds the 2571 // largest case in the switch. 2572 SDValue CMP = DAG.getSetCC( 2573 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2574 Sub.getValueType()), 2575 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2576 2577 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2578 MVT::Other, CopyTo, CMP, 2579 DAG.getBasicBlock(JT.Default)); 2580 2581 // Avoid emitting unnecessary branches to the next block. 2582 if (JT.MBB != NextBlock(SwitchBB)) 2583 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2584 DAG.getBasicBlock(JT.MBB)); 2585 2586 DAG.setRoot(BrCond); 2587 } else { 2588 // Avoid emitting unnecessary branches to the next block. 2589 if (JT.MBB != NextBlock(SwitchBB)) 2590 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2591 DAG.getBasicBlock(JT.MBB))); 2592 else 2593 DAG.setRoot(CopyTo); 2594 } 2595 } 2596 2597 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2598 /// variable if there exists one. 2599 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2600 SDValue &Chain) { 2601 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2602 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2603 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2604 MachineFunction &MF = DAG.getMachineFunction(); 2605 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2606 MachineSDNode *Node = 2607 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2608 if (Global) { 2609 MachinePointerInfo MPInfo(Global); 2610 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2611 MachineMemOperand::MODereferenceable; 2612 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2613 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2614 DAG.setNodeMemRefs(Node, {MemRef}); 2615 } 2616 if (PtrTy != PtrMemTy) 2617 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2618 return SDValue(Node, 0); 2619 } 2620 2621 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2622 /// tail spliced into a stack protector check success bb. 2623 /// 2624 /// For a high level explanation of how this fits into the stack protector 2625 /// generation see the comment on the declaration of class 2626 /// StackProtectorDescriptor. 2627 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2628 MachineBasicBlock *ParentBB) { 2629 2630 // First create the loads to the guard/stack slot for the comparison. 2631 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2632 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2633 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2634 2635 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2636 int FI = MFI.getStackProtectorIndex(); 2637 2638 SDValue Guard; 2639 SDLoc dl = getCurSDLoc(); 2640 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2641 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2642 Align Align = DL->getPrefTypeAlign(Type::getInt8PtrTy(M.getContext())); 2643 2644 // Generate code to load the content of the guard slot. 2645 SDValue GuardVal = DAG.getLoad( 2646 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2647 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2648 MachineMemOperand::MOVolatile); 2649 2650 if (TLI.useStackGuardXorFP()) 2651 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2652 2653 // Retrieve guard check function, nullptr if instrumentation is inlined. 2654 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2655 // The target provides a guard check function to validate the guard value. 2656 // Generate a call to that function with the content of the guard slot as 2657 // argument. 2658 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2659 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2660 2661 TargetLowering::ArgListTy Args; 2662 TargetLowering::ArgListEntry Entry; 2663 Entry.Node = GuardVal; 2664 Entry.Ty = FnTy->getParamType(0); 2665 if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg)) 2666 Entry.IsInReg = true; 2667 Args.push_back(Entry); 2668 2669 TargetLowering::CallLoweringInfo CLI(DAG); 2670 CLI.setDebugLoc(getCurSDLoc()) 2671 .setChain(DAG.getEntryNode()) 2672 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2673 getValue(GuardCheckFn), std::move(Args)); 2674 2675 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2676 DAG.setRoot(Result.second); 2677 return; 2678 } 2679 2680 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2681 // Otherwise, emit a volatile load to retrieve the stack guard value. 2682 SDValue Chain = DAG.getEntryNode(); 2683 if (TLI.useLoadStackGuardNode()) { 2684 Guard = getLoadStackGuard(DAG, dl, Chain); 2685 } else { 2686 const Value *IRGuard = TLI.getSDagStackGuard(M); 2687 SDValue GuardPtr = getValue(IRGuard); 2688 2689 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2690 MachinePointerInfo(IRGuard, 0), Align, 2691 MachineMemOperand::MOVolatile); 2692 } 2693 2694 // Perform the comparison via a getsetcc. 2695 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2696 *DAG.getContext(), 2697 Guard.getValueType()), 2698 Guard, GuardVal, ISD::SETNE); 2699 2700 // If the guard/stackslot do not equal, branch to failure MBB. 2701 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2702 MVT::Other, GuardVal.getOperand(0), 2703 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2704 // Otherwise branch to success MBB. 2705 SDValue Br = DAG.getNode(ISD::BR, dl, 2706 MVT::Other, BrCond, 2707 DAG.getBasicBlock(SPD.getSuccessMBB())); 2708 2709 DAG.setRoot(Br); 2710 } 2711 2712 /// Codegen the failure basic block for a stack protector check. 2713 /// 2714 /// A failure stack protector machine basic block consists simply of a call to 2715 /// __stack_chk_fail(). 2716 /// 2717 /// For a high level explanation of how this fits into the stack protector 2718 /// generation see the comment on the declaration of class 2719 /// StackProtectorDescriptor. 2720 void 2721 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2722 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2723 TargetLowering::MakeLibCallOptions CallOptions; 2724 CallOptions.setDiscardResult(true); 2725 SDValue Chain = 2726 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2727 None, CallOptions, getCurSDLoc()).second; 2728 // On PS4, the "return address" must still be within the calling function, 2729 // even if it's at the very end, so emit an explicit TRAP here. 2730 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2731 if (TM.getTargetTriple().isPS4CPU()) 2732 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2733 // WebAssembly needs an unreachable instruction after a non-returning call, 2734 // because the function return type can be different from __stack_chk_fail's 2735 // return type (void). 2736 if (TM.getTargetTriple().isWasm()) 2737 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2738 2739 DAG.setRoot(Chain); 2740 } 2741 2742 /// visitBitTestHeader - This function emits necessary code to produce value 2743 /// suitable for "bit tests" 2744 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2745 MachineBasicBlock *SwitchBB) { 2746 SDLoc dl = getCurSDLoc(); 2747 2748 // Subtract the minimum value. 2749 SDValue SwitchOp = getValue(B.SValue); 2750 EVT VT = SwitchOp.getValueType(); 2751 SDValue RangeSub = 2752 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2753 2754 // Determine the type of the test operands. 2755 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2756 bool UsePtrType = false; 2757 if (!TLI.isTypeLegal(VT)) { 2758 UsePtrType = true; 2759 } else { 2760 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2761 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2762 // Switch table case range are encoded into series of masks. 2763 // Just use pointer type, it's guaranteed to fit. 2764 UsePtrType = true; 2765 break; 2766 } 2767 } 2768 SDValue Sub = RangeSub; 2769 if (UsePtrType) { 2770 VT = TLI.getPointerTy(DAG.getDataLayout()); 2771 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2772 } 2773 2774 B.RegVT = VT.getSimpleVT(); 2775 B.Reg = FuncInfo.CreateReg(B.RegVT); 2776 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2777 2778 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2779 2780 if (!B.OmitRangeCheck) 2781 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2782 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2783 SwitchBB->normalizeSuccProbs(); 2784 2785 SDValue Root = CopyTo; 2786 if (!B.OmitRangeCheck) { 2787 // Conditional branch to the default block. 2788 SDValue RangeCmp = DAG.getSetCC(dl, 2789 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2790 RangeSub.getValueType()), 2791 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2792 ISD::SETUGT); 2793 2794 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2795 DAG.getBasicBlock(B.Default)); 2796 } 2797 2798 // Avoid emitting unnecessary branches to the next block. 2799 if (MBB != NextBlock(SwitchBB)) 2800 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2801 2802 DAG.setRoot(Root); 2803 } 2804 2805 /// visitBitTestCase - this function produces one "bit test" 2806 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2807 MachineBasicBlock* NextMBB, 2808 BranchProbability BranchProbToNext, 2809 unsigned Reg, 2810 BitTestCase &B, 2811 MachineBasicBlock *SwitchBB) { 2812 SDLoc dl = getCurSDLoc(); 2813 MVT VT = BB.RegVT; 2814 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2815 SDValue Cmp; 2816 unsigned PopCount = countPopulation(B.Mask); 2817 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2818 if (PopCount == 1) { 2819 // Testing for a single bit; just compare the shift count with what it 2820 // would need to be to shift a 1 bit in that position. 2821 Cmp = DAG.getSetCC( 2822 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2823 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2824 ISD::SETEQ); 2825 } else if (PopCount == BB.Range) { 2826 // There is only one zero bit in the range, test for it directly. 2827 Cmp = DAG.getSetCC( 2828 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2829 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2830 ISD::SETNE); 2831 } else { 2832 // Make desired shift 2833 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2834 DAG.getConstant(1, dl, VT), ShiftOp); 2835 2836 // Emit bit tests and jumps 2837 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2838 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2839 Cmp = DAG.getSetCC( 2840 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2841 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2842 } 2843 2844 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2845 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2846 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2847 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2848 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2849 // one as they are relative probabilities (and thus work more like weights), 2850 // and hence we need to normalize them to let the sum of them become one. 2851 SwitchBB->normalizeSuccProbs(); 2852 2853 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2854 MVT::Other, getControlRoot(), 2855 Cmp, DAG.getBasicBlock(B.TargetBB)); 2856 2857 // Avoid emitting unnecessary branches to the next block. 2858 if (NextMBB != NextBlock(SwitchBB)) 2859 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2860 DAG.getBasicBlock(NextMBB)); 2861 2862 DAG.setRoot(BrAnd); 2863 } 2864 2865 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2866 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2867 2868 // Retrieve successors. Look through artificial IR level blocks like 2869 // catchswitch for successors. 2870 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2871 const BasicBlock *EHPadBB = I.getSuccessor(1); 2872 2873 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2874 // have to do anything here to lower funclet bundles. 2875 assert(!I.hasOperandBundlesOtherThan( 2876 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 2877 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 2878 LLVMContext::OB_cfguardtarget, 2879 LLVMContext::OB_clang_arc_attachedcall}) && 2880 "Cannot lower invokes with arbitrary operand bundles yet!"); 2881 2882 const Value *Callee(I.getCalledOperand()); 2883 const Function *Fn = dyn_cast<Function>(Callee); 2884 if (isa<InlineAsm>(Callee)) 2885 visitInlineAsm(I, EHPadBB); 2886 else if (Fn && Fn->isIntrinsic()) { 2887 switch (Fn->getIntrinsicID()) { 2888 default: 2889 llvm_unreachable("Cannot invoke this intrinsic"); 2890 case Intrinsic::donothing: 2891 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2892 case Intrinsic::seh_try_begin: 2893 case Intrinsic::seh_scope_begin: 2894 case Intrinsic::seh_try_end: 2895 case Intrinsic::seh_scope_end: 2896 break; 2897 case Intrinsic::experimental_patchpoint_void: 2898 case Intrinsic::experimental_patchpoint_i64: 2899 visitPatchpoint(I, EHPadBB); 2900 break; 2901 case Intrinsic::experimental_gc_statepoint: 2902 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 2903 break; 2904 case Intrinsic::wasm_rethrow: { 2905 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2906 // special because it can be invoked, so we manually lower it to a DAG 2907 // node here. 2908 SmallVector<SDValue, 8> Ops; 2909 Ops.push_back(getRoot()); // inchain 2910 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2911 Ops.push_back( 2912 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 2913 TLI.getPointerTy(DAG.getDataLayout()))); 2914 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2915 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2916 break; 2917 } 2918 } 2919 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2920 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2921 // Eventually we will support lowering the @llvm.experimental.deoptimize 2922 // intrinsic, and right now there are no plans to support other intrinsics 2923 // with deopt state. 2924 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2925 } else { 2926 LowerCallTo(I, getValue(Callee), false, EHPadBB); 2927 } 2928 2929 // If the value of the invoke is used outside of its defining block, make it 2930 // available as a virtual register. 2931 // We already took care of the exported value for the statepoint instruction 2932 // during call to the LowerStatepoint. 2933 if (!isa<GCStatepointInst>(I)) { 2934 CopyToExportRegsIfNeeded(&I); 2935 } 2936 2937 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2938 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2939 BranchProbability EHPadBBProb = 2940 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2941 : BranchProbability::getZero(); 2942 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2943 2944 // Update successor info. 2945 addSuccessorWithProb(InvokeMBB, Return); 2946 for (auto &UnwindDest : UnwindDests) { 2947 UnwindDest.first->setIsEHPad(); 2948 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2949 } 2950 InvokeMBB->normalizeSuccProbs(); 2951 2952 // Drop into normal successor. 2953 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 2954 DAG.getBasicBlock(Return))); 2955 } 2956 2957 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 2958 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 2959 2960 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2961 // have to do anything here to lower funclet bundles. 2962 assert(!I.hasOperandBundlesOtherThan( 2963 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2964 "Cannot lower callbrs with arbitrary operand bundles yet!"); 2965 2966 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 2967 visitInlineAsm(I); 2968 CopyToExportRegsIfNeeded(&I); 2969 2970 // Retrieve successors. 2971 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 2972 2973 // Update successor info. 2974 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 2975 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 2976 MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)]; 2977 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 2978 Target->setIsInlineAsmBrIndirectTarget(); 2979 } 2980 CallBrMBB->normalizeSuccProbs(); 2981 2982 // Drop into default successor. 2983 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2984 MVT::Other, getControlRoot(), 2985 DAG.getBasicBlock(Return))); 2986 } 2987 2988 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2989 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2990 } 2991 2992 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2993 assert(FuncInfo.MBB->isEHPad() && 2994 "Call to landingpad not in landing pad!"); 2995 2996 // If there aren't registers to copy the values into (e.g., during SjLj 2997 // exceptions), then don't bother to create these DAG nodes. 2998 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2999 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 3000 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 3001 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 3002 return; 3003 3004 // If landingpad's return type is token type, we don't create DAG nodes 3005 // for its exception pointer and selector value. The extraction of exception 3006 // pointer or selector value from token type landingpads is not currently 3007 // supported. 3008 if (LP.getType()->isTokenTy()) 3009 return; 3010 3011 SmallVector<EVT, 2> ValueVTs; 3012 SDLoc dl = getCurSDLoc(); 3013 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3014 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3015 3016 // Get the two live-in registers as SDValues. The physregs have already been 3017 // copied into virtual registers. 3018 SDValue Ops[2]; 3019 if (FuncInfo.ExceptionPointerVirtReg) { 3020 Ops[0] = DAG.getZExtOrTrunc( 3021 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3022 FuncInfo.ExceptionPointerVirtReg, 3023 TLI.getPointerTy(DAG.getDataLayout())), 3024 dl, ValueVTs[0]); 3025 } else { 3026 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3027 } 3028 Ops[1] = DAG.getZExtOrTrunc( 3029 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3030 FuncInfo.ExceptionSelectorVirtReg, 3031 TLI.getPointerTy(DAG.getDataLayout())), 3032 dl, ValueVTs[1]); 3033 3034 // Merge into one. 3035 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3036 DAG.getVTList(ValueVTs), Ops); 3037 setValue(&LP, Res); 3038 } 3039 3040 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3041 MachineBasicBlock *Last) { 3042 // Update JTCases. 3043 for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i) 3044 if (SL->JTCases[i].first.HeaderBB == First) 3045 SL->JTCases[i].first.HeaderBB = Last; 3046 3047 // Update BitTestCases. 3048 for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i) 3049 if (SL->BitTestCases[i].Parent == First) 3050 SL->BitTestCases[i].Parent = Last; 3051 } 3052 3053 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3054 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3055 3056 // Update machine-CFG edges with unique successors. 3057 SmallSet<BasicBlock*, 32> Done; 3058 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3059 BasicBlock *BB = I.getSuccessor(i); 3060 bool Inserted = Done.insert(BB).second; 3061 if (!Inserted) 3062 continue; 3063 3064 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3065 addSuccessorWithProb(IndirectBrMBB, Succ); 3066 } 3067 IndirectBrMBB->normalizeSuccProbs(); 3068 3069 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3070 MVT::Other, getControlRoot(), 3071 getValue(I.getAddress()))); 3072 } 3073 3074 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3075 if (!DAG.getTarget().Options.TrapUnreachable) 3076 return; 3077 3078 // We may be able to ignore unreachable behind a noreturn call. 3079 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3080 const BasicBlock &BB = *I.getParent(); 3081 if (&I != &BB.front()) { 3082 BasicBlock::const_iterator PredI = 3083 std::prev(BasicBlock::const_iterator(&I)); 3084 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 3085 if (Call->doesNotReturn()) 3086 return; 3087 } 3088 } 3089 } 3090 3091 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3092 } 3093 3094 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3095 SDNodeFlags Flags; 3096 3097 SDValue Op = getValue(I.getOperand(0)); 3098 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3099 Op, Flags); 3100 setValue(&I, UnNodeValue); 3101 } 3102 3103 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3104 SDNodeFlags Flags; 3105 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3106 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3107 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3108 } 3109 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3110 Flags.setExact(ExactOp->isExact()); 3111 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3112 Flags.copyFMF(*FPOp); 3113 3114 SDValue Op1 = getValue(I.getOperand(0)); 3115 SDValue Op2 = getValue(I.getOperand(1)); 3116 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3117 Op1, Op2, Flags); 3118 setValue(&I, BinNodeValue); 3119 } 3120 3121 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3122 SDValue Op1 = getValue(I.getOperand(0)); 3123 SDValue Op2 = getValue(I.getOperand(1)); 3124 3125 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3126 Op1.getValueType(), DAG.getDataLayout()); 3127 3128 // Coerce the shift amount to the right type if we can. 3129 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3130 unsigned ShiftSize = ShiftTy.getSizeInBits(); 3131 unsigned Op2Size = Op2.getValueSizeInBits(); 3132 SDLoc DL = getCurSDLoc(); 3133 3134 // If the operand is smaller than the shift count type, promote it. 3135 if (ShiftSize > Op2Size) 3136 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 3137 3138 // If the operand is larger than the shift count type but the shift 3139 // count type has enough bits to represent any shift value, truncate 3140 // it now. This is a common case and it exposes the truncate to 3141 // optimization early. 3142 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 3143 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 3144 // Otherwise we'll need to temporarily settle for some other convenient 3145 // type. Type legalization will make adjustments once the shiftee is split. 3146 else 3147 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 3148 } 3149 3150 bool nuw = false; 3151 bool nsw = false; 3152 bool exact = false; 3153 3154 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3155 3156 if (const OverflowingBinaryOperator *OFBinOp = 3157 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3158 nuw = OFBinOp->hasNoUnsignedWrap(); 3159 nsw = OFBinOp->hasNoSignedWrap(); 3160 } 3161 if (const PossiblyExactOperator *ExactOp = 3162 dyn_cast<const PossiblyExactOperator>(&I)) 3163 exact = ExactOp->isExact(); 3164 } 3165 SDNodeFlags Flags; 3166 Flags.setExact(exact); 3167 Flags.setNoSignedWrap(nsw); 3168 Flags.setNoUnsignedWrap(nuw); 3169 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3170 Flags); 3171 setValue(&I, Res); 3172 } 3173 3174 void SelectionDAGBuilder::visitSDiv(const User &I) { 3175 SDValue Op1 = getValue(I.getOperand(0)); 3176 SDValue Op2 = getValue(I.getOperand(1)); 3177 3178 SDNodeFlags Flags; 3179 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3180 cast<PossiblyExactOperator>(&I)->isExact()); 3181 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3182 Op2, Flags)); 3183 } 3184 3185 void SelectionDAGBuilder::visitICmp(const User &I) { 3186 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3187 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3188 predicate = IC->getPredicate(); 3189 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3190 predicate = ICmpInst::Predicate(IC->getPredicate()); 3191 SDValue Op1 = getValue(I.getOperand(0)); 3192 SDValue Op2 = getValue(I.getOperand(1)); 3193 ISD::CondCode Opcode = getICmpCondCode(predicate); 3194 3195 auto &TLI = DAG.getTargetLoweringInfo(); 3196 EVT MemVT = 3197 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3198 3199 // If a pointer's DAG type is larger than its memory type then the DAG values 3200 // are zero-extended. This breaks signed comparisons so truncate back to the 3201 // underlying type before doing the compare. 3202 if (Op1.getValueType() != MemVT) { 3203 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3204 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3205 } 3206 3207 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3208 I.getType()); 3209 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3210 } 3211 3212 void SelectionDAGBuilder::visitFCmp(const User &I) { 3213 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3214 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3215 predicate = FC->getPredicate(); 3216 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3217 predicate = FCmpInst::Predicate(FC->getPredicate()); 3218 SDValue Op1 = getValue(I.getOperand(0)); 3219 SDValue Op2 = getValue(I.getOperand(1)); 3220 3221 ISD::CondCode Condition = getFCmpCondCode(predicate); 3222 auto *FPMO = cast<FPMathOperator>(&I); 3223 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3224 Condition = getFCmpCodeWithoutNaN(Condition); 3225 3226 SDNodeFlags Flags; 3227 Flags.copyFMF(*FPMO); 3228 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3229 3230 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3231 I.getType()); 3232 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3233 } 3234 3235 // Check if the condition of the select has one use or two users that are both 3236 // selects with the same condition. 3237 static bool hasOnlySelectUsers(const Value *Cond) { 3238 return llvm::all_of(Cond->users(), [](const Value *V) { 3239 return isa<SelectInst>(V); 3240 }); 3241 } 3242 3243 void SelectionDAGBuilder::visitSelect(const User &I) { 3244 SmallVector<EVT, 4> ValueVTs; 3245 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3246 ValueVTs); 3247 unsigned NumValues = ValueVTs.size(); 3248 if (NumValues == 0) return; 3249 3250 SmallVector<SDValue, 4> Values(NumValues); 3251 SDValue Cond = getValue(I.getOperand(0)); 3252 SDValue LHSVal = getValue(I.getOperand(1)); 3253 SDValue RHSVal = getValue(I.getOperand(2)); 3254 SmallVector<SDValue, 1> BaseOps(1, Cond); 3255 ISD::NodeType OpCode = 3256 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3257 3258 bool IsUnaryAbs = false; 3259 bool Negate = false; 3260 3261 SDNodeFlags Flags; 3262 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3263 Flags.copyFMF(*FPOp); 3264 3265 // Min/max matching is only viable if all output VTs are the same. 3266 if (is_splat(ValueVTs)) { 3267 EVT VT = ValueVTs[0]; 3268 LLVMContext &Ctx = *DAG.getContext(); 3269 auto &TLI = DAG.getTargetLoweringInfo(); 3270 3271 // We care about the legality of the operation after it has been type 3272 // legalized. 3273 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3274 VT = TLI.getTypeToTransformTo(Ctx, VT); 3275 3276 // If the vselect is legal, assume we want to leave this as a vector setcc + 3277 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3278 // min/max is legal on the scalar type. 3279 bool UseScalarMinMax = VT.isVector() && 3280 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3281 3282 Value *LHS, *RHS; 3283 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3284 ISD::NodeType Opc = ISD::DELETED_NODE; 3285 switch (SPR.Flavor) { 3286 case SPF_UMAX: Opc = ISD::UMAX; break; 3287 case SPF_UMIN: Opc = ISD::UMIN; break; 3288 case SPF_SMAX: Opc = ISD::SMAX; break; 3289 case SPF_SMIN: Opc = ISD::SMIN; break; 3290 case SPF_FMINNUM: 3291 switch (SPR.NaNBehavior) { 3292 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3293 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3294 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3295 case SPNB_RETURNS_ANY: { 3296 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3297 Opc = ISD::FMINNUM; 3298 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3299 Opc = ISD::FMINIMUM; 3300 else if (UseScalarMinMax) 3301 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3302 ISD::FMINNUM : ISD::FMINIMUM; 3303 break; 3304 } 3305 } 3306 break; 3307 case SPF_FMAXNUM: 3308 switch (SPR.NaNBehavior) { 3309 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3310 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3311 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3312 case SPNB_RETURNS_ANY: 3313 3314 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3315 Opc = ISD::FMAXNUM; 3316 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3317 Opc = ISD::FMAXIMUM; 3318 else if (UseScalarMinMax) 3319 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3320 ISD::FMAXNUM : ISD::FMAXIMUM; 3321 break; 3322 } 3323 break; 3324 case SPF_NABS: 3325 Negate = true; 3326 LLVM_FALLTHROUGH; 3327 case SPF_ABS: 3328 IsUnaryAbs = true; 3329 Opc = ISD::ABS; 3330 break; 3331 default: break; 3332 } 3333 3334 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3335 (TLI.isOperationLegalOrCustom(Opc, VT) || 3336 (UseScalarMinMax && 3337 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3338 // If the underlying comparison instruction is used by any other 3339 // instruction, the consumed instructions won't be destroyed, so it is 3340 // not profitable to convert to a min/max. 3341 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3342 OpCode = Opc; 3343 LHSVal = getValue(LHS); 3344 RHSVal = getValue(RHS); 3345 BaseOps.clear(); 3346 } 3347 3348 if (IsUnaryAbs) { 3349 OpCode = Opc; 3350 LHSVal = getValue(LHS); 3351 BaseOps.clear(); 3352 } 3353 } 3354 3355 if (IsUnaryAbs) { 3356 for (unsigned i = 0; i != NumValues; ++i) { 3357 SDLoc dl = getCurSDLoc(); 3358 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3359 Values[i] = 3360 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3361 if (Negate) 3362 Values[i] = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), 3363 Values[i]); 3364 } 3365 } else { 3366 for (unsigned i = 0; i != NumValues; ++i) { 3367 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3368 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3369 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3370 Values[i] = DAG.getNode( 3371 OpCode, getCurSDLoc(), 3372 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3373 } 3374 } 3375 3376 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3377 DAG.getVTList(ValueVTs), Values)); 3378 } 3379 3380 void SelectionDAGBuilder::visitTrunc(const User &I) { 3381 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3382 SDValue N = getValue(I.getOperand(0)); 3383 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3384 I.getType()); 3385 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3386 } 3387 3388 void SelectionDAGBuilder::visitZExt(const User &I) { 3389 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3390 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3391 SDValue N = getValue(I.getOperand(0)); 3392 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3393 I.getType()); 3394 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3395 } 3396 3397 void SelectionDAGBuilder::visitSExt(const User &I) { 3398 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3399 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3400 SDValue N = getValue(I.getOperand(0)); 3401 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3402 I.getType()); 3403 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3404 } 3405 3406 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3407 // FPTrunc is never a no-op cast, no need to check 3408 SDValue N = getValue(I.getOperand(0)); 3409 SDLoc dl = getCurSDLoc(); 3410 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3411 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3412 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3413 DAG.getTargetConstant( 3414 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3415 } 3416 3417 void SelectionDAGBuilder::visitFPExt(const User &I) { 3418 // FPExt is never a no-op cast, no need to check 3419 SDValue N = getValue(I.getOperand(0)); 3420 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3421 I.getType()); 3422 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3423 } 3424 3425 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3426 // FPToUI is never a no-op cast, no need to check 3427 SDValue N = getValue(I.getOperand(0)); 3428 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3429 I.getType()); 3430 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3431 } 3432 3433 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3434 // FPToSI is never a no-op cast, no need to check 3435 SDValue N = getValue(I.getOperand(0)); 3436 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3437 I.getType()); 3438 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3439 } 3440 3441 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3442 // UIToFP is never a no-op cast, no need to check 3443 SDValue N = getValue(I.getOperand(0)); 3444 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3445 I.getType()); 3446 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3447 } 3448 3449 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3450 // SIToFP is never a no-op cast, no need to check 3451 SDValue N = getValue(I.getOperand(0)); 3452 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3453 I.getType()); 3454 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3455 } 3456 3457 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3458 // What to do depends on the size of the integer and the size of the pointer. 3459 // We can either truncate, zero extend, or no-op, accordingly. 3460 SDValue N = getValue(I.getOperand(0)); 3461 auto &TLI = DAG.getTargetLoweringInfo(); 3462 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3463 I.getType()); 3464 EVT PtrMemVT = 3465 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3466 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3467 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3468 setValue(&I, N); 3469 } 3470 3471 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3472 // What to do depends on the size of the integer and the size of the pointer. 3473 // We can either truncate, zero extend, or no-op, accordingly. 3474 SDValue N = getValue(I.getOperand(0)); 3475 auto &TLI = DAG.getTargetLoweringInfo(); 3476 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3477 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3478 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3479 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3480 setValue(&I, N); 3481 } 3482 3483 void SelectionDAGBuilder::visitBitCast(const User &I) { 3484 SDValue N = getValue(I.getOperand(0)); 3485 SDLoc dl = getCurSDLoc(); 3486 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3487 I.getType()); 3488 3489 // BitCast assures us that source and destination are the same size so this is 3490 // either a BITCAST or a no-op. 3491 if (DestVT != N.getValueType()) 3492 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3493 DestVT, N)); // convert types. 3494 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3495 // might fold any kind of constant expression to an integer constant and that 3496 // is not what we are looking for. Only recognize a bitcast of a genuine 3497 // constant integer as an opaque constant. 3498 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3499 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3500 /*isOpaque*/true)); 3501 else 3502 setValue(&I, N); // noop cast. 3503 } 3504 3505 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3506 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3507 const Value *SV = I.getOperand(0); 3508 SDValue N = getValue(SV); 3509 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3510 3511 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3512 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3513 3514 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3515 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3516 3517 setValue(&I, N); 3518 } 3519 3520 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3521 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3522 SDValue InVec = getValue(I.getOperand(0)); 3523 SDValue InVal = getValue(I.getOperand(1)); 3524 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3525 TLI.getVectorIdxTy(DAG.getDataLayout())); 3526 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3527 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3528 InVec, InVal, InIdx)); 3529 } 3530 3531 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3532 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3533 SDValue InVec = getValue(I.getOperand(0)); 3534 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3535 TLI.getVectorIdxTy(DAG.getDataLayout())); 3536 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3537 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3538 InVec, InIdx)); 3539 } 3540 3541 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3542 SDValue Src1 = getValue(I.getOperand(0)); 3543 SDValue Src2 = getValue(I.getOperand(1)); 3544 ArrayRef<int> Mask; 3545 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3546 Mask = SVI->getShuffleMask(); 3547 else 3548 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3549 SDLoc DL = getCurSDLoc(); 3550 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3551 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3552 EVT SrcVT = Src1.getValueType(); 3553 3554 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3555 VT.isScalableVector()) { 3556 // Canonical splat form of first element of first input vector. 3557 SDValue FirstElt = 3558 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3559 DAG.getVectorIdxConstant(0, DL)); 3560 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3561 return; 3562 } 3563 3564 // For now, we only handle splats for scalable vectors. 3565 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3566 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3567 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3568 3569 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3570 unsigned MaskNumElts = Mask.size(); 3571 3572 if (SrcNumElts == MaskNumElts) { 3573 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3574 return; 3575 } 3576 3577 // Normalize the shuffle vector since mask and vector length don't match. 3578 if (SrcNumElts < MaskNumElts) { 3579 // Mask is longer than the source vectors. We can use concatenate vector to 3580 // make the mask and vectors lengths match. 3581 3582 if (MaskNumElts % SrcNumElts == 0) { 3583 // Mask length is a multiple of the source vector length. 3584 // Check if the shuffle is some kind of concatenation of the input 3585 // vectors. 3586 unsigned NumConcat = MaskNumElts / SrcNumElts; 3587 bool IsConcat = true; 3588 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3589 for (unsigned i = 0; i != MaskNumElts; ++i) { 3590 int Idx = Mask[i]; 3591 if (Idx < 0) 3592 continue; 3593 // Ensure the indices in each SrcVT sized piece are sequential and that 3594 // the same source is used for the whole piece. 3595 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3596 (ConcatSrcs[i / SrcNumElts] >= 0 && 3597 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3598 IsConcat = false; 3599 break; 3600 } 3601 // Remember which source this index came from. 3602 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3603 } 3604 3605 // The shuffle is concatenating multiple vectors together. Just emit 3606 // a CONCAT_VECTORS operation. 3607 if (IsConcat) { 3608 SmallVector<SDValue, 8> ConcatOps; 3609 for (auto Src : ConcatSrcs) { 3610 if (Src < 0) 3611 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3612 else if (Src == 0) 3613 ConcatOps.push_back(Src1); 3614 else 3615 ConcatOps.push_back(Src2); 3616 } 3617 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3618 return; 3619 } 3620 } 3621 3622 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3623 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3624 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3625 PaddedMaskNumElts); 3626 3627 // Pad both vectors with undefs to make them the same length as the mask. 3628 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3629 3630 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3631 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3632 MOps1[0] = Src1; 3633 MOps2[0] = Src2; 3634 3635 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3636 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3637 3638 // Readjust mask for new input vector length. 3639 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3640 for (unsigned i = 0; i != MaskNumElts; ++i) { 3641 int Idx = Mask[i]; 3642 if (Idx >= (int)SrcNumElts) 3643 Idx -= SrcNumElts - PaddedMaskNumElts; 3644 MappedOps[i] = Idx; 3645 } 3646 3647 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3648 3649 // If the concatenated vector was padded, extract a subvector with the 3650 // correct number of elements. 3651 if (MaskNumElts != PaddedMaskNumElts) 3652 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3653 DAG.getVectorIdxConstant(0, DL)); 3654 3655 setValue(&I, Result); 3656 return; 3657 } 3658 3659 if (SrcNumElts > MaskNumElts) { 3660 // Analyze the access pattern of the vector to see if we can extract 3661 // two subvectors and do the shuffle. 3662 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3663 bool CanExtract = true; 3664 for (int Idx : Mask) { 3665 unsigned Input = 0; 3666 if (Idx < 0) 3667 continue; 3668 3669 if (Idx >= (int)SrcNumElts) { 3670 Input = 1; 3671 Idx -= SrcNumElts; 3672 } 3673 3674 // If all the indices come from the same MaskNumElts sized portion of 3675 // the sources we can use extract. Also make sure the extract wouldn't 3676 // extract past the end of the source. 3677 int NewStartIdx = alignDown(Idx, MaskNumElts); 3678 if (NewStartIdx + MaskNumElts > SrcNumElts || 3679 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3680 CanExtract = false; 3681 // Make sure we always update StartIdx as we use it to track if all 3682 // elements are undef. 3683 StartIdx[Input] = NewStartIdx; 3684 } 3685 3686 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3687 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3688 return; 3689 } 3690 if (CanExtract) { 3691 // Extract appropriate subvector and generate a vector shuffle 3692 for (unsigned Input = 0; Input < 2; ++Input) { 3693 SDValue &Src = Input == 0 ? Src1 : Src2; 3694 if (StartIdx[Input] < 0) 3695 Src = DAG.getUNDEF(VT); 3696 else { 3697 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3698 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3699 } 3700 } 3701 3702 // Calculate new mask. 3703 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3704 for (int &Idx : MappedOps) { 3705 if (Idx >= (int)SrcNumElts) 3706 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3707 else if (Idx >= 0) 3708 Idx -= StartIdx[0]; 3709 } 3710 3711 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3712 return; 3713 } 3714 } 3715 3716 // We can't use either concat vectors or extract subvectors so fall back to 3717 // replacing the shuffle with extract and build vector. 3718 // to insert and build vector. 3719 EVT EltVT = VT.getVectorElementType(); 3720 SmallVector<SDValue,8> Ops; 3721 for (int Idx : Mask) { 3722 SDValue Res; 3723 3724 if (Idx < 0) { 3725 Res = DAG.getUNDEF(EltVT); 3726 } else { 3727 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3728 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3729 3730 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3731 DAG.getVectorIdxConstant(Idx, DL)); 3732 } 3733 3734 Ops.push_back(Res); 3735 } 3736 3737 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3738 } 3739 3740 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3741 ArrayRef<unsigned> Indices; 3742 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3743 Indices = IV->getIndices(); 3744 else 3745 Indices = cast<ConstantExpr>(&I)->getIndices(); 3746 3747 const Value *Op0 = I.getOperand(0); 3748 const Value *Op1 = I.getOperand(1); 3749 Type *AggTy = I.getType(); 3750 Type *ValTy = Op1->getType(); 3751 bool IntoUndef = isa<UndefValue>(Op0); 3752 bool FromUndef = isa<UndefValue>(Op1); 3753 3754 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3755 3756 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3757 SmallVector<EVT, 4> AggValueVTs; 3758 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3759 SmallVector<EVT, 4> ValValueVTs; 3760 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3761 3762 unsigned NumAggValues = AggValueVTs.size(); 3763 unsigned NumValValues = ValValueVTs.size(); 3764 SmallVector<SDValue, 4> Values(NumAggValues); 3765 3766 // Ignore an insertvalue that produces an empty object 3767 if (!NumAggValues) { 3768 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3769 return; 3770 } 3771 3772 SDValue Agg = getValue(Op0); 3773 unsigned i = 0; 3774 // Copy the beginning value(s) from the original aggregate. 3775 for (; i != LinearIndex; ++i) 3776 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3777 SDValue(Agg.getNode(), Agg.getResNo() + i); 3778 // Copy values from the inserted value(s). 3779 if (NumValValues) { 3780 SDValue Val = getValue(Op1); 3781 for (; i != LinearIndex + NumValValues; ++i) 3782 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3783 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3784 } 3785 // Copy remaining value(s) from the original aggregate. 3786 for (; i != NumAggValues; ++i) 3787 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3788 SDValue(Agg.getNode(), Agg.getResNo() + i); 3789 3790 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3791 DAG.getVTList(AggValueVTs), Values)); 3792 } 3793 3794 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3795 ArrayRef<unsigned> Indices; 3796 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3797 Indices = EV->getIndices(); 3798 else 3799 Indices = cast<ConstantExpr>(&I)->getIndices(); 3800 3801 const Value *Op0 = I.getOperand(0); 3802 Type *AggTy = Op0->getType(); 3803 Type *ValTy = I.getType(); 3804 bool OutOfUndef = isa<UndefValue>(Op0); 3805 3806 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3807 3808 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3809 SmallVector<EVT, 4> ValValueVTs; 3810 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3811 3812 unsigned NumValValues = ValValueVTs.size(); 3813 3814 // Ignore a extractvalue that produces an empty object 3815 if (!NumValValues) { 3816 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3817 return; 3818 } 3819 3820 SmallVector<SDValue, 4> Values(NumValValues); 3821 3822 SDValue Agg = getValue(Op0); 3823 // Copy out the selected value(s). 3824 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3825 Values[i - LinearIndex] = 3826 OutOfUndef ? 3827 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3828 SDValue(Agg.getNode(), Agg.getResNo() + i); 3829 3830 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3831 DAG.getVTList(ValValueVTs), Values)); 3832 } 3833 3834 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3835 Value *Op0 = I.getOperand(0); 3836 // Note that the pointer operand may be a vector of pointers. Take the scalar 3837 // element which holds a pointer. 3838 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3839 SDValue N = getValue(Op0); 3840 SDLoc dl = getCurSDLoc(); 3841 auto &TLI = DAG.getTargetLoweringInfo(); 3842 3843 // Normalize Vector GEP - all scalar operands should be converted to the 3844 // splat vector. 3845 bool IsVectorGEP = I.getType()->isVectorTy(); 3846 ElementCount VectorElementCount = 3847 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3848 : ElementCount::getFixed(0); 3849 3850 if (IsVectorGEP && !N.getValueType().isVector()) { 3851 LLVMContext &Context = *DAG.getContext(); 3852 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3853 if (VectorElementCount.isScalable()) 3854 N = DAG.getSplatVector(VT, dl, N); 3855 else 3856 N = DAG.getSplatBuildVector(VT, dl, N); 3857 } 3858 3859 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3860 GTI != E; ++GTI) { 3861 const Value *Idx = GTI.getOperand(); 3862 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3863 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3864 if (Field) { 3865 // N = N + Offset 3866 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3867 3868 // In an inbounds GEP with an offset that is nonnegative even when 3869 // interpreted as signed, assume there is no unsigned overflow. 3870 SDNodeFlags Flags; 3871 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3872 Flags.setNoUnsignedWrap(true); 3873 3874 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3875 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3876 } 3877 } else { 3878 // IdxSize is the width of the arithmetic according to IR semantics. 3879 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3880 // (and fix up the result later). 3881 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3882 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3883 TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType()); 3884 // We intentionally mask away the high bits here; ElementSize may not 3885 // fit in IdxTy. 3886 APInt ElementMul(IdxSize, ElementSize.getKnownMinSize()); 3887 bool ElementScalable = ElementSize.isScalable(); 3888 3889 // If this is a scalar constant or a splat vector of constants, 3890 // handle it quickly. 3891 const auto *C = dyn_cast<Constant>(Idx); 3892 if (C && isa<VectorType>(C->getType())) 3893 C = C->getSplatValue(); 3894 3895 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 3896 if (CI && CI->isZero()) 3897 continue; 3898 if (CI && !ElementScalable) { 3899 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 3900 LLVMContext &Context = *DAG.getContext(); 3901 SDValue OffsVal; 3902 if (IsVectorGEP) 3903 OffsVal = DAG.getConstant( 3904 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 3905 else 3906 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 3907 3908 // In an inbounds GEP with an offset that is nonnegative even when 3909 // interpreted as signed, assume there is no unsigned overflow. 3910 SDNodeFlags Flags; 3911 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3912 Flags.setNoUnsignedWrap(true); 3913 3914 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3915 3916 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3917 continue; 3918 } 3919 3920 // N = N + Idx * ElementMul; 3921 SDValue IdxN = getValue(Idx); 3922 3923 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 3924 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 3925 VectorElementCount); 3926 if (VectorElementCount.isScalable()) 3927 IdxN = DAG.getSplatVector(VT, dl, IdxN); 3928 else 3929 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3930 } 3931 3932 // If the index is smaller or larger than intptr_t, truncate or extend 3933 // it. 3934 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3935 3936 if (ElementScalable) { 3937 EVT VScaleTy = N.getValueType().getScalarType(); 3938 SDValue VScale = DAG.getNode( 3939 ISD::VSCALE, dl, VScaleTy, 3940 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 3941 if (IsVectorGEP) 3942 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 3943 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 3944 } else { 3945 // If this is a multiply by a power of two, turn it into a shl 3946 // immediately. This is a very common case. 3947 if (ElementMul != 1) { 3948 if (ElementMul.isPowerOf2()) { 3949 unsigned Amt = ElementMul.logBase2(); 3950 IdxN = DAG.getNode(ISD::SHL, dl, 3951 N.getValueType(), IdxN, 3952 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3953 } else { 3954 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 3955 IdxN.getValueType()); 3956 IdxN = DAG.getNode(ISD::MUL, dl, 3957 N.getValueType(), IdxN, Scale); 3958 } 3959 } 3960 } 3961 3962 N = DAG.getNode(ISD::ADD, dl, 3963 N.getValueType(), N, IdxN); 3964 } 3965 } 3966 3967 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 3968 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 3969 if (IsVectorGEP) { 3970 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 3971 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 3972 } 3973 3974 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 3975 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 3976 3977 setValue(&I, N); 3978 } 3979 3980 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3981 // If this is a fixed sized alloca in the entry block of the function, 3982 // allocate it statically on the stack. 3983 if (FuncInfo.StaticAllocaMap.count(&I)) 3984 return; // getValue will auto-populate this. 3985 3986 SDLoc dl = getCurSDLoc(); 3987 Type *Ty = I.getAllocatedType(); 3988 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3989 auto &DL = DAG.getDataLayout(); 3990 uint64_t TySize = DL.getTypeAllocSize(Ty); 3991 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 3992 3993 SDValue AllocSize = getValue(I.getArraySize()); 3994 3995 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3996 if (AllocSize.getValueType() != IntPtr) 3997 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3998 3999 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 4000 AllocSize, 4001 DAG.getConstant(TySize, dl, IntPtr)); 4002 4003 // Handle alignment. If the requested alignment is less than or equal to 4004 // the stack alignment, ignore it. If the size is greater than or equal to 4005 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4006 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 4007 if (*Alignment <= StackAlign) 4008 Alignment = None; 4009 4010 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4011 // Round the size of the allocation up to the stack alignment size 4012 // by add SA-1 to the size. This doesn't overflow because we're computing 4013 // an address inside an alloca. 4014 SDNodeFlags Flags; 4015 Flags.setNoUnsignedWrap(true); 4016 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4017 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4018 4019 // Mask out the low bits for alignment purposes. 4020 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4021 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 4022 4023 SDValue Ops[] = { 4024 getRoot(), AllocSize, 4025 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4026 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4027 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4028 setValue(&I, DSA); 4029 DAG.setRoot(DSA.getValue(1)); 4030 4031 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4032 } 4033 4034 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4035 if (I.isAtomic()) 4036 return visitAtomicLoad(I); 4037 4038 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4039 const Value *SV = I.getOperand(0); 4040 if (TLI.supportSwiftError()) { 4041 // Swifterror values can come from either a function parameter with 4042 // swifterror attribute or an alloca with swifterror attribute. 4043 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4044 if (Arg->hasSwiftErrorAttr()) 4045 return visitLoadFromSwiftError(I); 4046 } 4047 4048 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4049 if (Alloca->isSwiftError()) 4050 return visitLoadFromSwiftError(I); 4051 } 4052 } 4053 4054 SDValue Ptr = getValue(SV); 4055 4056 Type *Ty = I.getType(); 4057 Align Alignment = I.getAlign(); 4058 4059 AAMDNodes AAInfo; 4060 I.getAAMetadata(AAInfo); 4061 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4062 4063 SmallVector<EVT, 4> ValueVTs, MemVTs; 4064 SmallVector<uint64_t, 4> Offsets; 4065 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4066 unsigned NumValues = ValueVTs.size(); 4067 if (NumValues == 0) 4068 return; 4069 4070 bool isVolatile = I.isVolatile(); 4071 4072 SDValue Root; 4073 bool ConstantMemory = false; 4074 if (isVolatile) 4075 // Serialize volatile loads with other side effects. 4076 Root = getRoot(); 4077 else if (NumValues > MaxParallelChains) 4078 Root = getMemoryRoot(); 4079 else if (AA && 4080 AA->pointsToConstantMemory(MemoryLocation( 4081 SV, 4082 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4083 AAInfo))) { 4084 // Do not serialize (non-volatile) loads of constant memory with anything. 4085 Root = DAG.getEntryNode(); 4086 ConstantMemory = true; 4087 } else { 4088 // Do not serialize non-volatile loads against each other. 4089 Root = DAG.getRoot(); 4090 } 4091 4092 SDLoc dl = getCurSDLoc(); 4093 4094 if (isVolatile) 4095 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4096 4097 // An aggregate load cannot wrap around the address space, so offsets to its 4098 // parts don't wrap either. 4099 SDNodeFlags Flags; 4100 Flags.setNoUnsignedWrap(true); 4101 4102 SmallVector<SDValue, 4> Values(NumValues); 4103 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4104 EVT PtrVT = Ptr.getValueType(); 4105 4106 MachineMemOperand::Flags MMOFlags 4107 = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4108 4109 unsigned ChainI = 0; 4110 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4111 // Serializing loads here may result in excessive register pressure, and 4112 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4113 // could recover a bit by hoisting nodes upward in the chain by recognizing 4114 // they are side-effect free or do not alias. The optimizer should really 4115 // avoid this case by converting large object/array copies to llvm.memcpy 4116 // (MaxParallelChains should always remain as failsafe). 4117 if (ChainI == MaxParallelChains) { 4118 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4119 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4120 makeArrayRef(Chains.data(), ChainI)); 4121 Root = Chain; 4122 ChainI = 0; 4123 } 4124 SDValue A = DAG.getNode(ISD::ADD, dl, 4125 PtrVT, Ptr, 4126 DAG.getConstant(Offsets[i], dl, PtrVT), 4127 Flags); 4128 4129 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4130 MachinePointerInfo(SV, Offsets[i]), Alignment, 4131 MMOFlags, AAInfo, Ranges); 4132 Chains[ChainI] = L.getValue(1); 4133 4134 if (MemVTs[i] != ValueVTs[i]) 4135 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4136 4137 Values[i] = L; 4138 } 4139 4140 if (!ConstantMemory) { 4141 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4142 makeArrayRef(Chains.data(), ChainI)); 4143 if (isVolatile) 4144 DAG.setRoot(Chain); 4145 else 4146 PendingLoads.push_back(Chain); 4147 } 4148 4149 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4150 DAG.getVTList(ValueVTs), Values)); 4151 } 4152 4153 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4154 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4155 "call visitStoreToSwiftError when backend supports swifterror"); 4156 4157 SmallVector<EVT, 4> ValueVTs; 4158 SmallVector<uint64_t, 4> Offsets; 4159 const Value *SrcV = I.getOperand(0); 4160 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4161 SrcV->getType(), ValueVTs, &Offsets); 4162 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4163 "expect a single EVT for swifterror"); 4164 4165 SDValue Src = getValue(SrcV); 4166 // Create a virtual register, then update the virtual register. 4167 Register VReg = 4168 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4169 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4170 // Chain can be getRoot or getControlRoot. 4171 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4172 SDValue(Src.getNode(), Src.getResNo())); 4173 DAG.setRoot(CopyNode); 4174 } 4175 4176 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4177 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4178 "call visitLoadFromSwiftError when backend supports swifterror"); 4179 4180 assert(!I.isVolatile() && 4181 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4182 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4183 "Support volatile, non temporal, invariant for load_from_swift_error"); 4184 4185 const Value *SV = I.getOperand(0); 4186 Type *Ty = I.getType(); 4187 AAMDNodes AAInfo; 4188 I.getAAMetadata(AAInfo); 4189 assert( 4190 (!AA || 4191 !AA->pointsToConstantMemory(MemoryLocation( 4192 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4193 AAInfo))) && 4194 "load_from_swift_error should not be constant memory"); 4195 4196 SmallVector<EVT, 4> ValueVTs; 4197 SmallVector<uint64_t, 4> Offsets; 4198 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4199 ValueVTs, &Offsets); 4200 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4201 "expect a single EVT for swifterror"); 4202 4203 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4204 SDValue L = DAG.getCopyFromReg( 4205 getRoot(), getCurSDLoc(), 4206 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4207 4208 setValue(&I, L); 4209 } 4210 4211 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4212 if (I.isAtomic()) 4213 return visitAtomicStore(I); 4214 4215 const Value *SrcV = I.getOperand(0); 4216 const Value *PtrV = I.getOperand(1); 4217 4218 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4219 if (TLI.supportSwiftError()) { 4220 // Swifterror values can come from either a function parameter with 4221 // swifterror attribute or an alloca with swifterror attribute. 4222 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4223 if (Arg->hasSwiftErrorAttr()) 4224 return visitStoreToSwiftError(I); 4225 } 4226 4227 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4228 if (Alloca->isSwiftError()) 4229 return visitStoreToSwiftError(I); 4230 } 4231 } 4232 4233 SmallVector<EVT, 4> ValueVTs, MemVTs; 4234 SmallVector<uint64_t, 4> Offsets; 4235 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4236 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4237 unsigned NumValues = ValueVTs.size(); 4238 if (NumValues == 0) 4239 return; 4240 4241 // Get the lowered operands. Note that we do this after 4242 // checking if NumResults is zero, because with zero results 4243 // the operands won't have values in the map. 4244 SDValue Src = getValue(SrcV); 4245 SDValue Ptr = getValue(PtrV); 4246 4247 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4248 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4249 SDLoc dl = getCurSDLoc(); 4250 Align Alignment = I.getAlign(); 4251 AAMDNodes AAInfo; 4252 I.getAAMetadata(AAInfo); 4253 4254 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4255 4256 // An aggregate load cannot wrap around the address space, so offsets to its 4257 // parts don't wrap either. 4258 SDNodeFlags Flags; 4259 Flags.setNoUnsignedWrap(true); 4260 4261 unsigned ChainI = 0; 4262 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4263 // See visitLoad comments. 4264 if (ChainI == MaxParallelChains) { 4265 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4266 makeArrayRef(Chains.data(), ChainI)); 4267 Root = Chain; 4268 ChainI = 0; 4269 } 4270 SDValue Add = 4271 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags); 4272 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4273 if (MemVTs[i] != ValueVTs[i]) 4274 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4275 SDValue St = 4276 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4277 Alignment, MMOFlags, AAInfo); 4278 Chains[ChainI] = St; 4279 } 4280 4281 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4282 makeArrayRef(Chains.data(), ChainI)); 4283 DAG.setRoot(StoreNode); 4284 } 4285 4286 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4287 bool IsCompressing) { 4288 SDLoc sdl = getCurSDLoc(); 4289 4290 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4291 MaybeAlign &Alignment) { 4292 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4293 Src0 = I.getArgOperand(0); 4294 Ptr = I.getArgOperand(1); 4295 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4296 Mask = I.getArgOperand(3); 4297 }; 4298 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4299 MaybeAlign &Alignment) { 4300 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4301 Src0 = I.getArgOperand(0); 4302 Ptr = I.getArgOperand(1); 4303 Mask = I.getArgOperand(2); 4304 Alignment = None; 4305 }; 4306 4307 Value *PtrOperand, *MaskOperand, *Src0Operand; 4308 MaybeAlign Alignment; 4309 if (IsCompressing) 4310 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4311 else 4312 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4313 4314 SDValue Ptr = getValue(PtrOperand); 4315 SDValue Src0 = getValue(Src0Operand); 4316 SDValue Mask = getValue(MaskOperand); 4317 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4318 4319 EVT VT = Src0.getValueType(); 4320 if (!Alignment) 4321 Alignment = DAG.getEVTAlign(VT); 4322 4323 AAMDNodes AAInfo; 4324 I.getAAMetadata(AAInfo); 4325 4326 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4327 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4328 // TODO: Make MachineMemOperands aware of scalable 4329 // vectors. 4330 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo); 4331 SDValue StoreNode = 4332 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4333 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4334 DAG.setRoot(StoreNode); 4335 setValue(&I, StoreNode); 4336 } 4337 4338 // Get a uniform base for the Gather/Scatter intrinsic. 4339 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4340 // We try to represent it as a base pointer + vector of indices. 4341 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4342 // The first operand of the GEP may be a single pointer or a vector of pointers 4343 // Example: 4344 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4345 // or 4346 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4347 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4348 // 4349 // When the first GEP operand is a single pointer - it is the uniform base we 4350 // are looking for. If first operand of the GEP is a splat vector - we 4351 // extract the splat value and use it as a uniform base. 4352 // In all other cases the function returns 'false'. 4353 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4354 ISD::MemIndexType &IndexType, SDValue &Scale, 4355 SelectionDAGBuilder *SDB, const BasicBlock *CurBB) { 4356 SelectionDAG& DAG = SDB->DAG; 4357 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4358 const DataLayout &DL = DAG.getDataLayout(); 4359 4360 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 4361 4362 // Handle splat constant pointer. 4363 if (auto *C = dyn_cast<Constant>(Ptr)) { 4364 C = C->getSplatValue(); 4365 if (!C) 4366 return false; 4367 4368 Base = SDB->getValue(C); 4369 4370 unsigned NumElts = cast<FixedVectorType>(Ptr->getType())->getNumElements(); 4371 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4372 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4373 IndexType = ISD::SIGNED_SCALED; 4374 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4375 return true; 4376 } 4377 4378 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4379 if (!GEP || GEP->getParent() != CurBB) 4380 return false; 4381 4382 if (GEP->getNumOperands() != 2) 4383 return false; 4384 4385 const Value *BasePtr = GEP->getPointerOperand(); 4386 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4387 4388 // Make sure the base is scalar and the index is a vector. 4389 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4390 return false; 4391 4392 Base = SDB->getValue(BasePtr); 4393 Index = SDB->getValue(IndexVal); 4394 IndexType = ISD::SIGNED_SCALED; 4395 Scale = DAG.getTargetConstant( 4396 DL.getTypeAllocSize(GEP->getResultElementType()), 4397 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4398 return true; 4399 } 4400 4401 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4402 SDLoc sdl = getCurSDLoc(); 4403 4404 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4405 const Value *Ptr = I.getArgOperand(1); 4406 SDValue Src0 = getValue(I.getArgOperand(0)); 4407 SDValue Mask = getValue(I.getArgOperand(3)); 4408 EVT VT = Src0.getValueType(); 4409 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4410 ->getMaybeAlignValue() 4411 .getValueOr(DAG.getEVTAlign(VT)); 4412 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4413 4414 AAMDNodes AAInfo; 4415 I.getAAMetadata(AAInfo); 4416 4417 SDValue Base; 4418 SDValue Index; 4419 ISD::MemIndexType IndexType; 4420 SDValue Scale; 4421 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4422 I.getParent()); 4423 4424 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4425 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4426 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4427 // TODO: Make MachineMemOperands aware of scalable 4428 // vectors. 4429 MemoryLocation::UnknownSize, Alignment, AAInfo); 4430 if (!UniformBase) { 4431 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4432 Index = getValue(Ptr); 4433 IndexType = ISD::SIGNED_UNSCALED; 4434 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4435 } 4436 4437 EVT IdxVT = Index.getValueType(); 4438 EVT EltTy = IdxVT.getVectorElementType(); 4439 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4440 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4441 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4442 } 4443 4444 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4445 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4446 Ops, MMO, IndexType, false); 4447 DAG.setRoot(Scatter); 4448 setValue(&I, Scatter); 4449 } 4450 4451 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4452 SDLoc sdl = getCurSDLoc(); 4453 4454 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4455 MaybeAlign &Alignment) { 4456 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4457 Ptr = I.getArgOperand(0); 4458 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4459 Mask = I.getArgOperand(2); 4460 Src0 = I.getArgOperand(3); 4461 }; 4462 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4463 MaybeAlign &Alignment) { 4464 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4465 Ptr = I.getArgOperand(0); 4466 Alignment = None; 4467 Mask = I.getArgOperand(1); 4468 Src0 = I.getArgOperand(2); 4469 }; 4470 4471 Value *PtrOperand, *MaskOperand, *Src0Operand; 4472 MaybeAlign Alignment; 4473 if (IsExpanding) 4474 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4475 else 4476 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4477 4478 SDValue Ptr = getValue(PtrOperand); 4479 SDValue Src0 = getValue(Src0Operand); 4480 SDValue Mask = getValue(MaskOperand); 4481 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4482 4483 EVT VT = Src0.getValueType(); 4484 if (!Alignment) 4485 Alignment = DAG.getEVTAlign(VT); 4486 4487 AAMDNodes AAInfo; 4488 I.getAAMetadata(AAInfo); 4489 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4490 4491 // Do not serialize masked loads of constant memory with anything. 4492 MemoryLocation ML; 4493 if (VT.isScalableVector()) 4494 ML = MemoryLocation::getAfter(PtrOperand); 4495 else 4496 ML = MemoryLocation(PtrOperand, LocationSize::precise( 4497 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4498 AAInfo); 4499 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4500 4501 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4502 4503 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4504 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4505 // TODO: Make MachineMemOperands aware of scalable 4506 // vectors. 4507 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges); 4508 4509 SDValue Load = 4510 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4511 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4512 if (AddToChain) 4513 PendingLoads.push_back(Load.getValue(1)); 4514 setValue(&I, Load); 4515 } 4516 4517 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4518 SDLoc sdl = getCurSDLoc(); 4519 4520 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4521 const Value *Ptr = I.getArgOperand(0); 4522 SDValue Src0 = getValue(I.getArgOperand(3)); 4523 SDValue Mask = getValue(I.getArgOperand(2)); 4524 4525 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4526 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4527 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4528 ->getMaybeAlignValue() 4529 .getValueOr(DAG.getEVTAlign(VT)); 4530 4531 AAMDNodes AAInfo; 4532 I.getAAMetadata(AAInfo); 4533 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4534 4535 SDValue Root = DAG.getRoot(); 4536 SDValue Base; 4537 SDValue Index; 4538 ISD::MemIndexType IndexType; 4539 SDValue Scale; 4540 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4541 I.getParent()); 4542 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4543 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4544 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4545 // TODO: Make MachineMemOperands aware of scalable 4546 // vectors. 4547 MemoryLocation::UnknownSize, Alignment, AAInfo, Ranges); 4548 4549 if (!UniformBase) { 4550 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4551 Index = getValue(Ptr); 4552 IndexType = ISD::SIGNED_UNSCALED; 4553 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4554 } 4555 4556 EVT IdxVT = Index.getValueType(); 4557 EVT EltTy = IdxVT.getVectorElementType(); 4558 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4559 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4560 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4561 } 4562 4563 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4564 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4565 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4566 4567 PendingLoads.push_back(Gather.getValue(1)); 4568 setValue(&I, Gather); 4569 } 4570 4571 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4572 SDLoc dl = getCurSDLoc(); 4573 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4574 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4575 SyncScope::ID SSID = I.getSyncScopeID(); 4576 4577 SDValue InChain = getRoot(); 4578 4579 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4580 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4581 4582 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4583 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4584 4585 MachineFunction &MF = DAG.getMachineFunction(); 4586 MachineMemOperand *MMO = MF.getMachineMemOperand( 4587 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4588 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4589 FailureOrdering); 4590 4591 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4592 dl, MemVT, VTs, InChain, 4593 getValue(I.getPointerOperand()), 4594 getValue(I.getCompareOperand()), 4595 getValue(I.getNewValOperand()), MMO); 4596 4597 SDValue OutChain = L.getValue(2); 4598 4599 setValue(&I, L); 4600 DAG.setRoot(OutChain); 4601 } 4602 4603 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4604 SDLoc dl = getCurSDLoc(); 4605 ISD::NodeType NT; 4606 switch (I.getOperation()) { 4607 default: llvm_unreachable("Unknown atomicrmw operation"); 4608 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4609 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4610 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4611 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4612 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4613 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4614 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4615 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4616 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4617 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4618 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4619 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4620 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4621 } 4622 AtomicOrdering Ordering = I.getOrdering(); 4623 SyncScope::ID SSID = I.getSyncScopeID(); 4624 4625 SDValue InChain = getRoot(); 4626 4627 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4628 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4629 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4630 4631 MachineFunction &MF = DAG.getMachineFunction(); 4632 MachineMemOperand *MMO = MF.getMachineMemOperand( 4633 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4634 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4635 4636 SDValue L = 4637 DAG.getAtomic(NT, dl, MemVT, InChain, 4638 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4639 MMO); 4640 4641 SDValue OutChain = L.getValue(1); 4642 4643 setValue(&I, L); 4644 DAG.setRoot(OutChain); 4645 } 4646 4647 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4648 SDLoc dl = getCurSDLoc(); 4649 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4650 SDValue Ops[3]; 4651 Ops[0] = getRoot(); 4652 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4653 TLI.getFenceOperandTy(DAG.getDataLayout())); 4654 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4655 TLI.getFenceOperandTy(DAG.getDataLayout())); 4656 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4657 } 4658 4659 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4660 SDLoc dl = getCurSDLoc(); 4661 AtomicOrdering Order = I.getOrdering(); 4662 SyncScope::ID SSID = I.getSyncScopeID(); 4663 4664 SDValue InChain = getRoot(); 4665 4666 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4667 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4668 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4669 4670 if (!TLI.supportsUnalignedAtomics() && 4671 I.getAlignment() < MemVT.getSizeInBits() / 8) 4672 report_fatal_error("Cannot generate unaligned atomic load"); 4673 4674 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4675 4676 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4677 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4678 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4679 4680 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4681 4682 SDValue Ptr = getValue(I.getPointerOperand()); 4683 4684 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4685 // TODO: Once this is better exercised by tests, it should be merged with 4686 // the normal path for loads to prevent future divergence. 4687 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4688 if (MemVT != VT) 4689 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4690 4691 setValue(&I, L); 4692 SDValue OutChain = L.getValue(1); 4693 if (!I.isUnordered()) 4694 DAG.setRoot(OutChain); 4695 else 4696 PendingLoads.push_back(OutChain); 4697 return; 4698 } 4699 4700 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4701 Ptr, MMO); 4702 4703 SDValue OutChain = L.getValue(1); 4704 if (MemVT != VT) 4705 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4706 4707 setValue(&I, L); 4708 DAG.setRoot(OutChain); 4709 } 4710 4711 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4712 SDLoc dl = getCurSDLoc(); 4713 4714 AtomicOrdering Ordering = I.getOrdering(); 4715 SyncScope::ID SSID = I.getSyncScopeID(); 4716 4717 SDValue InChain = getRoot(); 4718 4719 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4720 EVT MemVT = 4721 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4722 4723 if (I.getAlignment() < MemVT.getSizeInBits() / 8) 4724 report_fatal_error("Cannot generate unaligned atomic store"); 4725 4726 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4727 4728 MachineFunction &MF = DAG.getMachineFunction(); 4729 MachineMemOperand *MMO = MF.getMachineMemOperand( 4730 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4731 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4732 4733 SDValue Val = getValue(I.getValueOperand()); 4734 if (Val.getValueType() != MemVT) 4735 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4736 SDValue Ptr = getValue(I.getPointerOperand()); 4737 4738 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4739 // TODO: Once this is better exercised by tests, it should be merged with 4740 // the normal path for stores to prevent future divergence. 4741 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4742 DAG.setRoot(S); 4743 return; 4744 } 4745 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4746 Ptr, Val, MMO); 4747 4748 4749 DAG.setRoot(OutChain); 4750 } 4751 4752 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4753 /// node. 4754 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4755 unsigned Intrinsic) { 4756 // Ignore the callsite's attributes. A specific call site may be marked with 4757 // readnone, but the lowering code will expect the chain based on the 4758 // definition. 4759 const Function *F = I.getCalledFunction(); 4760 bool HasChain = !F->doesNotAccessMemory(); 4761 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4762 4763 // Build the operand list. 4764 SmallVector<SDValue, 8> Ops; 4765 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4766 if (OnlyLoad) { 4767 // We don't need to serialize loads against other loads. 4768 Ops.push_back(DAG.getRoot()); 4769 } else { 4770 Ops.push_back(getRoot()); 4771 } 4772 } 4773 4774 // Info is set by getTgtMemInstrinsic 4775 TargetLowering::IntrinsicInfo Info; 4776 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4777 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4778 DAG.getMachineFunction(), 4779 Intrinsic); 4780 4781 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4782 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4783 Info.opc == ISD::INTRINSIC_W_CHAIN) 4784 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4785 TLI.getPointerTy(DAG.getDataLayout()))); 4786 4787 // Add all operands of the call to the operand list. 4788 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4789 const Value *Arg = I.getArgOperand(i); 4790 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4791 Ops.push_back(getValue(Arg)); 4792 continue; 4793 } 4794 4795 // Use TargetConstant instead of a regular constant for immarg. 4796 EVT VT = TLI.getValueType(*DL, Arg->getType(), true); 4797 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4798 assert(CI->getBitWidth() <= 64 && 4799 "large intrinsic immediates not handled"); 4800 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4801 } else { 4802 Ops.push_back( 4803 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4804 } 4805 } 4806 4807 SmallVector<EVT, 4> ValueVTs; 4808 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4809 4810 if (HasChain) 4811 ValueVTs.push_back(MVT::Other); 4812 4813 SDVTList VTs = DAG.getVTList(ValueVTs); 4814 4815 // Propagate fast-math-flags from IR to node(s). 4816 SDNodeFlags Flags; 4817 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 4818 Flags.copyFMF(*FPMO); 4819 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 4820 4821 // Create the node. 4822 SDValue Result; 4823 if (IsTgtIntrinsic) { 4824 // This is target intrinsic that touches memory 4825 AAMDNodes AAInfo; 4826 I.getAAMetadata(AAInfo); 4827 Result = 4828 DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT, 4829 MachinePointerInfo(Info.ptrVal, Info.offset), 4830 Info.align, Info.flags, Info.size, AAInfo); 4831 } else if (!HasChain) { 4832 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4833 } else if (!I.getType()->isVoidTy()) { 4834 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4835 } else { 4836 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4837 } 4838 4839 if (HasChain) { 4840 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4841 if (OnlyLoad) 4842 PendingLoads.push_back(Chain); 4843 else 4844 DAG.setRoot(Chain); 4845 } 4846 4847 if (!I.getType()->isVoidTy()) { 4848 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4849 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4850 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4851 } else 4852 Result = lowerRangeToAssertZExt(DAG, I, Result); 4853 4854 MaybeAlign Alignment = I.getRetAlign(); 4855 if (!Alignment) 4856 Alignment = F->getAttributes().getRetAlignment(); 4857 // Insert `assertalign` node if there's an alignment. 4858 if (InsertAssertAlign && Alignment) { 4859 Result = 4860 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 4861 } 4862 4863 setValue(&I, Result); 4864 } 4865 } 4866 4867 /// GetSignificand - Get the significand and build it into a floating-point 4868 /// number with exponent of 1: 4869 /// 4870 /// Op = (Op & 0x007fffff) | 0x3f800000; 4871 /// 4872 /// where Op is the hexadecimal representation of floating point value. 4873 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4874 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4875 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4876 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4877 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4878 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4879 } 4880 4881 /// GetExponent - Get the exponent: 4882 /// 4883 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4884 /// 4885 /// where Op is the hexadecimal representation of floating point value. 4886 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4887 const TargetLowering &TLI, const SDLoc &dl) { 4888 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4889 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4890 SDValue t1 = DAG.getNode( 4891 ISD::SRL, dl, MVT::i32, t0, 4892 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4893 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4894 DAG.getConstant(127, dl, MVT::i32)); 4895 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4896 } 4897 4898 /// getF32Constant - Get 32-bit floating point constant. 4899 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4900 const SDLoc &dl) { 4901 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4902 MVT::f32); 4903 } 4904 4905 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4906 SelectionDAG &DAG) { 4907 // TODO: What fast-math-flags should be set on the floating-point nodes? 4908 4909 // IntegerPartOfX = ((int32_t)(t0); 4910 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4911 4912 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4913 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4914 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4915 4916 // IntegerPartOfX <<= 23; 4917 IntegerPartOfX = DAG.getNode( 4918 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4919 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4920 DAG.getDataLayout()))); 4921 4922 SDValue TwoToFractionalPartOfX; 4923 if (LimitFloatPrecision <= 6) { 4924 // For floating-point precision of 6: 4925 // 4926 // TwoToFractionalPartOfX = 4927 // 0.997535578f + 4928 // (0.735607626f + 0.252464424f * x) * x; 4929 // 4930 // error 0.0144103317, which is 6 bits 4931 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4932 getF32Constant(DAG, 0x3e814304, dl)); 4933 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4934 getF32Constant(DAG, 0x3f3c50c8, dl)); 4935 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4936 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4937 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4938 } else if (LimitFloatPrecision <= 12) { 4939 // For floating-point precision of 12: 4940 // 4941 // TwoToFractionalPartOfX = 4942 // 0.999892986f + 4943 // (0.696457318f + 4944 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4945 // 4946 // error 0.000107046256, which is 13 to 14 bits 4947 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4948 getF32Constant(DAG, 0x3da235e3, dl)); 4949 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4950 getF32Constant(DAG, 0x3e65b8f3, dl)); 4951 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4952 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4953 getF32Constant(DAG, 0x3f324b07, dl)); 4954 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4955 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4956 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4957 } else { // LimitFloatPrecision <= 18 4958 // For floating-point precision of 18: 4959 // 4960 // TwoToFractionalPartOfX = 4961 // 0.999999982f + 4962 // (0.693148872f + 4963 // (0.240227044f + 4964 // (0.554906021e-1f + 4965 // (0.961591928e-2f + 4966 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4967 // error 2.47208000*10^(-7), which is better than 18 bits 4968 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4969 getF32Constant(DAG, 0x3924b03e, dl)); 4970 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4971 getF32Constant(DAG, 0x3ab24b87, dl)); 4972 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4973 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4974 getF32Constant(DAG, 0x3c1d8c17, dl)); 4975 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4976 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4977 getF32Constant(DAG, 0x3d634a1d, dl)); 4978 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4979 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4980 getF32Constant(DAG, 0x3e75fe14, dl)); 4981 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4982 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4983 getF32Constant(DAG, 0x3f317234, dl)); 4984 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4985 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4986 getF32Constant(DAG, 0x3f800000, dl)); 4987 } 4988 4989 // Add the exponent into the result in integer domain. 4990 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4991 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4992 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4993 } 4994 4995 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4996 /// limited-precision mode. 4997 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4998 const TargetLowering &TLI, SDNodeFlags Flags) { 4999 if (Op.getValueType() == MVT::f32 && 5000 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5001 5002 // Put the exponent in the right bit position for later addition to the 5003 // final result: 5004 // 5005 // t0 = Op * log2(e) 5006 5007 // TODO: What fast-math-flags should be set here? 5008 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5009 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5010 return getLimitedPrecisionExp2(t0, dl, DAG); 5011 } 5012 5013 // No special expansion. 5014 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5015 } 5016 5017 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5018 /// limited-precision mode. 5019 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5020 const TargetLowering &TLI, SDNodeFlags Flags) { 5021 // TODO: What fast-math-flags should be set on the floating-point nodes? 5022 5023 if (Op.getValueType() == MVT::f32 && 5024 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5025 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5026 5027 // Scale the exponent by log(2). 5028 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5029 SDValue LogOfExponent = 5030 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5031 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5032 5033 // Get the significand and build it into a floating-point number with 5034 // exponent of 1. 5035 SDValue X = GetSignificand(DAG, Op1, dl); 5036 5037 SDValue LogOfMantissa; 5038 if (LimitFloatPrecision <= 6) { 5039 // For floating-point precision of 6: 5040 // 5041 // LogofMantissa = 5042 // -1.1609546f + 5043 // (1.4034025f - 0.23903021f * x) * x; 5044 // 5045 // error 0.0034276066, which is better than 8 bits 5046 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5047 getF32Constant(DAG, 0xbe74c456, dl)); 5048 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5049 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5050 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5051 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5052 getF32Constant(DAG, 0x3f949a29, dl)); 5053 } else if (LimitFloatPrecision <= 12) { 5054 // For floating-point precision of 12: 5055 // 5056 // LogOfMantissa = 5057 // -1.7417939f + 5058 // (2.8212026f + 5059 // (-1.4699568f + 5060 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5061 // 5062 // error 0.000061011436, which is 14 bits 5063 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5064 getF32Constant(DAG, 0xbd67b6d6, dl)); 5065 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5066 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5067 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5068 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5069 getF32Constant(DAG, 0x3fbc278b, dl)); 5070 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5071 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5072 getF32Constant(DAG, 0x40348e95, dl)); 5073 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5074 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5075 getF32Constant(DAG, 0x3fdef31a, dl)); 5076 } else { // LimitFloatPrecision <= 18 5077 // For floating-point precision of 18: 5078 // 5079 // LogOfMantissa = 5080 // -2.1072184f + 5081 // (4.2372794f + 5082 // (-3.7029485f + 5083 // (2.2781945f + 5084 // (-0.87823314f + 5085 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5086 // 5087 // error 0.0000023660568, which is better than 18 bits 5088 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5089 getF32Constant(DAG, 0xbc91e5ac, dl)); 5090 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5091 getF32Constant(DAG, 0x3e4350aa, dl)); 5092 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5093 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5094 getF32Constant(DAG, 0x3f60d3e3, dl)); 5095 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5096 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5097 getF32Constant(DAG, 0x4011cdf0, dl)); 5098 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5099 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5100 getF32Constant(DAG, 0x406cfd1c, dl)); 5101 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5102 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5103 getF32Constant(DAG, 0x408797cb, dl)); 5104 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5105 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5106 getF32Constant(DAG, 0x4006dcab, dl)); 5107 } 5108 5109 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5110 } 5111 5112 // No special expansion. 5113 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5114 } 5115 5116 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5117 /// limited-precision mode. 5118 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5119 const TargetLowering &TLI, SDNodeFlags Flags) { 5120 // TODO: What fast-math-flags should be set on the floating-point nodes? 5121 5122 if (Op.getValueType() == MVT::f32 && 5123 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5124 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5125 5126 // Get the exponent. 5127 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5128 5129 // Get the significand and build it into a floating-point number with 5130 // exponent of 1. 5131 SDValue X = GetSignificand(DAG, Op1, dl); 5132 5133 // Different possible minimax approximations of significand in 5134 // floating-point for various degrees of accuracy over [1,2]. 5135 SDValue Log2ofMantissa; 5136 if (LimitFloatPrecision <= 6) { 5137 // For floating-point precision of 6: 5138 // 5139 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5140 // 5141 // error 0.0049451742, which is more than 7 bits 5142 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5143 getF32Constant(DAG, 0xbeb08fe0, dl)); 5144 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5145 getF32Constant(DAG, 0x40019463, dl)); 5146 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5147 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5148 getF32Constant(DAG, 0x3fd6633d, dl)); 5149 } else if (LimitFloatPrecision <= 12) { 5150 // For floating-point precision of 12: 5151 // 5152 // Log2ofMantissa = 5153 // -2.51285454f + 5154 // (4.07009056f + 5155 // (-2.12067489f + 5156 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5157 // 5158 // error 0.0000876136000, which is better than 13 bits 5159 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5160 getF32Constant(DAG, 0xbda7262e, dl)); 5161 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5162 getF32Constant(DAG, 0x3f25280b, dl)); 5163 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5164 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5165 getF32Constant(DAG, 0x4007b923, dl)); 5166 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5167 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5168 getF32Constant(DAG, 0x40823e2f, dl)); 5169 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5170 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5171 getF32Constant(DAG, 0x4020d29c, dl)); 5172 } else { // LimitFloatPrecision <= 18 5173 // For floating-point precision of 18: 5174 // 5175 // Log2ofMantissa = 5176 // -3.0400495f + 5177 // (6.1129976f + 5178 // (-5.3420409f + 5179 // (3.2865683f + 5180 // (-1.2669343f + 5181 // (0.27515199f - 5182 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5183 // 5184 // error 0.0000018516, which is better than 18 bits 5185 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5186 getF32Constant(DAG, 0xbcd2769e, dl)); 5187 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5188 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5189 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5190 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5191 getF32Constant(DAG, 0x3fa22ae7, dl)); 5192 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5193 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5194 getF32Constant(DAG, 0x40525723, dl)); 5195 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5196 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5197 getF32Constant(DAG, 0x40aaf200, dl)); 5198 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5199 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5200 getF32Constant(DAG, 0x40c39dad, dl)); 5201 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5202 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5203 getF32Constant(DAG, 0x4042902c, dl)); 5204 } 5205 5206 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5207 } 5208 5209 // No special expansion. 5210 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5211 } 5212 5213 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5214 /// limited-precision mode. 5215 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5216 const TargetLowering &TLI, SDNodeFlags Flags) { 5217 // TODO: What fast-math-flags should be set on the floating-point nodes? 5218 5219 if (Op.getValueType() == MVT::f32 && 5220 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5221 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5222 5223 // Scale the exponent by log10(2) [0.30102999f]. 5224 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5225 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5226 getF32Constant(DAG, 0x3e9a209a, dl)); 5227 5228 // Get the significand and build it into a floating-point number with 5229 // exponent of 1. 5230 SDValue X = GetSignificand(DAG, Op1, dl); 5231 5232 SDValue Log10ofMantissa; 5233 if (LimitFloatPrecision <= 6) { 5234 // For floating-point precision of 6: 5235 // 5236 // Log10ofMantissa = 5237 // -0.50419619f + 5238 // (0.60948995f - 0.10380950f * x) * x; 5239 // 5240 // error 0.0014886165, which is 6 bits 5241 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5242 getF32Constant(DAG, 0xbdd49a13, dl)); 5243 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5244 getF32Constant(DAG, 0x3f1c0789, dl)); 5245 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5246 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5247 getF32Constant(DAG, 0x3f011300, dl)); 5248 } else if (LimitFloatPrecision <= 12) { 5249 // For floating-point precision of 12: 5250 // 5251 // Log10ofMantissa = 5252 // -0.64831180f + 5253 // (0.91751397f + 5254 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5255 // 5256 // error 0.00019228036, which is better than 12 bits 5257 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5258 getF32Constant(DAG, 0x3d431f31, dl)); 5259 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5260 getF32Constant(DAG, 0x3ea21fb2, dl)); 5261 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5262 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5263 getF32Constant(DAG, 0x3f6ae232, dl)); 5264 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5265 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5266 getF32Constant(DAG, 0x3f25f7c3, dl)); 5267 } else { // LimitFloatPrecision <= 18 5268 // For floating-point precision of 18: 5269 // 5270 // Log10ofMantissa = 5271 // -0.84299375f + 5272 // (1.5327582f + 5273 // (-1.0688956f + 5274 // (0.49102474f + 5275 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5276 // 5277 // error 0.0000037995730, which is better than 18 bits 5278 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5279 getF32Constant(DAG, 0x3c5d51ce, dl)); 5280 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5281 getF32Constant(DAG, 0x3e00685a, dl)); 5282 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5283 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5284 getF32Constant(DAG, 0x3efb6798, dl)); 5285 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5286 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5287 getF32Constant(DAG, 0x3f88d192, dl)); 5288 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5289 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5290 getF32Constant(DAG, 0x3fc4316c, dl)); 5291 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5292 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5293 getF32Constant(DAG, 0x3f57ce70, dl)); 5294 } 5295 5296 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5297 } 5298 5299 // No special expansion. 5300 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5301 } 5302 5303 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5304 /// limited-precision mode. 5305 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5306 const TargetLowering &TLI, SDNodeFlags Flags) { 5307 if (Op.getValueType() == MVT::f32 && 5308 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5309 return getLimitedPrecisionExp2(Op, dl, DAG); 5310 5311 // No special expansion. 5312 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5313 } 5314 5315 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5316 /// limited-precision mode with x == 10.0f. 5317 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5318 SelectionDAG &DAG, const TargetLowering &TLI, 5319 SDNodeFlags Flags) { 5320 bool IsExp10 = false; 5321 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5322 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5323 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5324 APFloat Ten(10.0f); 5325 IsExp10 = LHSC->isExactlyValue(Ten); 5326 } 5327 } 5328 5329 // TODO: What fast-math-flags should be set on the FMUL node? 5330 if (IsExp10) { 5331 // Put the exponent in the right bit position for later addition to the 5332 // final result: 5333 // 5334 // #define LOG2OF10 3.3219281f 5335 // t0 = Op * LOG2OF10; 5336 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5337 getF32Constant(DAG, 0x40549a78, dl)); 5338 return getLimitedPrecisionExp2(t0, dl, DAG); 5339 } 5340 5341 // No special expansion. 5342 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5343 } 5344 5345 /// ExpandPowI - Expand a llvm.powi intrinsic. 5346 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5347 SelectionDAG &DAG) { 5348 // If RHS is a constant, we can expand this out to a multiplication tree, 5349 // otherwise we end up lowering to a call to __powidf2 (for example). When 5350 // optimizing for size, we only want to do this if the expansion would produce 5351 // a small number of multiplies, otherwise we do the full expansion. 5352 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5353 // Get the exponent as a positive value. 5354 unsigned Val = RHSC->getSExtValue(); 5355 if ((int)Val < 0) Val = -Val; 5356 5357 // powi(x, 0) -> 1.0 5358 if (Val == 0) 5359 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5360 5361 bool OptForSize = DAG.shouldOptForSize(); 5362 if (!OptForSize || 5363 // If optimizing for size, don't insert too many multiplies. 5364 // This inserts up to 5 multiplies. 5365 countPopulation(Val) + Log2_32(Val) < 7) { 5366 // We use the simple binary decomposition method to generate the multiply 5367 // sequence. There are more optimal ways to do this (for example, 5368 // powi(x,15) generates one more multiply than it should), but this has 5369 // the benefit of being both really simple and much better than a libcall. 5370 SDValue Res; // Logically starts equal to 1.0 5371 SDValue CurSquare = LHS; 5372 // TODO: Intrinsics should have fast-math-flags that propagate to these 5373 // nodes. 5374 while (Val) { 5375 if (Val & 1) { 5376 if (Res.getNode()) 5377 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 5378 else 5379 Res = CurSquare; // 1.0*CurSquare. 5380 } 5381 5382 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5383 CurSquare, CurSquare); 5384 Val >>= 1; 5385 } 5386 5387 // If the original was negative, invert the result, producing 1/(x*x*x). 5388 if (RHSC->getSExtValue() < 0) 5389 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5390 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5391 return Res; 5392 } 5393 } 5394 5395 // Otherwise, expand to a libcall. 5396 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5397 } 5398 5399 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5400 SDValue LHS, SDValue RHS, SDValue Scale, 5401 SelectionDAG &DAG, const TargetLowering &TLI) { 5402 EVT VT = LHS.getValueType(); 5403 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5404 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5405 LLVMContext &Ctx = *DAG.getContext(); 5406 5407 // If the type is legal but the operation isn't, this node might survive all 5408 // the way to operation legalization. If we end up there and we do not have 5409 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5410 // node. 5411 5412 // Coax the legalizer into expanding the node during type legalization instead 5413 // by bumping the size by one bit. This will force it to Promote, enabling the 5414 // early expansion and avoiding the need to expand later. 5415 5416 // We don't have to do this if Scale is 0; that can always be expanded, unless 5417 // it's a saturating signed operation. Those can experience true integer 5418 // division overflow, a case which we must avoid. 5419 5420 // FIXME: We wouldn't have to do this (or any of the early 5421 // expansion/promotion) if it was possible to expand a libcall of an 5422 // illegal type during operation legalization. But it's not, so things 5423 // get a bit hacky. 5424 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5425 if ((ScaleInt > 0 || (Saturating && Signed)) && 5426 (TLI.isTypeLegal(VT) || 5427 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5428 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5429 Opcode, VT, ScaleInt); 5430 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5431 EVT PromVT; 5432 if (VT.isScalarInteger()) 5433 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5434 else if (VT.isVector()) { 5435 PromVT = VT.getVectorElementType(); 5436 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5437 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5438 } else 5439 llvm_unreachable("Wrong VT for DIVFIX?"); 5440 if (Signed) { 5441 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5442 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5443 } else { 5444 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5445 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5446 } 5447 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5448 // For saturating operations, we need to shift up the LHS to get the 5449 // proper saturation width, and then shift down again afterwards. 5450 if (Saturating) 5451 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5452 DAG.getConstant(1, DL, ShiftTy)); 5453 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5454 if (Saturating) 5455 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5456 DAG.getConstant(1, DL, ShiftTy)); 5457 return DAG.getZExtOrTrunc(Res, DL, VT); 5458 } 5459 } 5460 5461 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5462 } 5463 5464 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5465 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5466 static void 5467 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5468 const SDValue &N) { 5469 switch (N.getOpcode()) { 5470 case ISD::CopyFromReg: { 5471 SDValue Op = N.getOperand(1); 5472 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5473 Op.getValueType().getSizeInBits()); 5474 return; 5475 } 5476 case ISD::BITCAST: 5477 case ISD::AssertZext: 5478 case ISD::AssertSext: 5479 case ISD::TRUNCATE: 5480 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5481 return; 5482 case ISD::BUILD_PAIR: 5483 case ISD::BUILD_VECTOR: 5484 case ISD::CONCAT_VECTORS: 5485 for (SDValue Op : N->op_values()) 5486 getUnderlyingArgRegs(Regs, Op); 5487 return; 5488 default: 5489 return; 5490 } 5491 } 5492 5493 /// If the DbgValueInst is a dbg_value of a function argument, create the 5494 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5495 /// instruction selection, they will be inserted to the entry BB. 5496 /// We don't currently support this for variadic dbg_values, as they shouldn't 5497 /// appear for function arguments or in the prologue. 5498 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5499 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5500 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 5501 const Argument *Arg = dyn_cast<Argument>(V); 5502 if (!Arg) 5503 return false; 5504 5505 if (!IsDbgDeclare) { 5506 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5507 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5508 // the entry block. 5509 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5510 if (!IsInEntryBlock) 5511 return false; 5512 5513 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5514 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5515 // variable that also is a param. 5516 // 5517 // Although, if we are at the top of the entry block already, we can still 5518 // emit using ArgDbgValue. This might catch some situations when the 5519 // dbg.value refers to an argument that isn't used in the entry block, so 5520 // any CopyToReg node would be optimized out and the only way to express 5521 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5522 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5523 // we should only emit as ArgDbgValue if the Variable is an argument to the 5524 // current function, and the dbg.value intrinsic is found in the entry 5525 // block. 5526 bool VariableIsFunctionInputArg = Variable->isParameter() && 5527 !DL->getInlinedAt(); 5528 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5529 if (!IsInPrologue && !VariableIsFunctionInputArg) 5530 return false; 5531 5532 // Here we assume that a function argument on IR level only can be used to 5533 // describe one input parameter on source level. If we for example have 5534 // source code like this 5535 // 5536 // struct A { long x, y; }; 5537 // void foo(struct A a, long b) { 5538 // ... 5539 // b = a.x; 5540 // ... 5541 // } 5542 // 5543 // and IR like this 5544 // 5545 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5546 // entry: 5547 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5548 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5549 // call void @llvm.dbg.value(metadata i32 %b, "b", 5550 // ... 5551 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5552 // ... 5553 // 5554 // then the last dbg.value is describing a parameter "b" using a value that 5555 // is an argument. But since we already has used %a1 to describe a parameter 5556 // we should not handle that last dbg.value here (that would result in an 5557 // incorrect hoisting of the DBG_VALUE to the function entry). 5558 // Notice that we allow one dbg.value per IR level argument, to accommodate 5559 // for the situation with fragments above. 5560 if (VariableIsFunctionInputArg) { 5561 unsigned ArgNo = Arg->getArgNo(); 5562 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5563 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5564 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5565 return false; 5566 FuncInfo.DescribedArgs.set(ArgNo); 5567 } 5568 } 5569 5570 MachineFunction &MF = DAG.getMachineFunction(); 5571 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5572 5573 bool IsIndirect = false; 5574 Optional<MachineOperand> Op; 5575 // Some arguments' frame index is recorded during argument lowering. 5576 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5577 if (FI != std::numeric_limits<int>::max()) 5578 Op = MachineOperand::CreateFI(FI); 5579 5580 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 5581 if (!Op && N.getNode()) { 5582 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5583 Register Reg; 5584 if (ArgRegsAndSizes.size() == 1) 5585 Reg = ArgRegsAndSizes.front().first; 5586 5587 if (Reg && Reg.isVirtual()) { 5588 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5589 Register PR = RegInfo.getLiveInPhysReg(Reg); 5590 if (PR) 5591 Reg = PR; 5592 } 5593 if (Reg) { 5594 Op = MachineOperand::CreateReg(Reg, false); 5595 IsIndirect = IsDbgDeclare; 5596 } 5597 } 5598 5599 if (!Op && N.getNode()) { 5600 // Check if frame index is available. 5601 SDValue LCandidate = peekThroughBitcasts(N); 5602 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5603 if (FrameIndexSDNode *FINode = 5604 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5605 Op = MachineOperand::CreateFI(FINode->getIndex()); 5606 } 5607 5608 if (!Op) { 5609 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5610 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 5611 SplitRegs) { 5612 unsigned Offset = 0; 5613 for (auto RegAndSize : SplitRegs) { 5614 // If the expression is already a fragment, the current register 5615 // offset+size might extend beyond the fragment. In this case, only 5616 // the register bits that are inside the fragment are relevant. 5617 int RegFragmentSizeInBits = RegAndSize.second; 5618 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5619 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5620 // The register is entirely outside the expression fragment, 5621 // so is irrelevant for debug info. 5622 if (Offset >= ExprFragmentSizeInBits) 5623 break; 5624 // The register is partially outside the expression fragment, only 5625 // the low bits within the fragment are relevant for debug info. 5626 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5627 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5628 } 5629 } 5630 5631 auto FragmentExpr = DIExpression::createFragmentExpression( 5632 Expr, Offset, RegFragmentSizeInBits); 5633 Offset += RegAndSize.second; 5634 // If a valid fragment expression cannot be created, the variable's 5635 // correct value cannot be determined and so it is set as Undef. 5636 if (!FragmentExpr) { 5637 SDDbgValue *SDV = DAG.getConstantDbgValue( 5638 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5639 DAG.AddDbgValue(SDV, false); 5640 continue; 5641 } 5642 FuncInfo.ArgDbgValues.push_back( 5643 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare, 5644 RegAndSize.first, Variable, *FragmentExpr)); 5645 } 5646 }; 5647 5648 // Check if ValueMap has reg number. 5649 DenseMap<const Value *, Register>::const_iterator 5650 VMI = FuncInfo.ValueMap.find(V); 5651 if (VMI != FuncInfo.ValueMap.end()) { 5652 const auto &TLI = DAG.getTargetLoweringInfo(); 5653 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5654 V->getType(), None); 5655 if (RFV.occupiesMultipleRegs()) { 5656 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5657 return true; 5658 } 5659 5660 Op = MachineOperand::CreateReg(VMI->second, false); 5661 IsIndirect = IsDbgDeclare; 5662 } else if (ArgRegsAndSizes.size() > 1) { 5663 // This was split due to the calling convention, and no virtual register 5664 // mapping exists for the value. 5665 splitMultiRegDbgValue(ArgRegsAndSizes); 5666 return true; 5667 } 5668 } 5669 5670 if (!Op) 5671 return false; 5672 5673 assert(Variable->isValidLocationForIntrinsic(DL) && 5674 "Expected inlined-at fields to agree"); 5675 IsIndirect = (Op->isReg()) ? IsIndirect : true; 5676 FuncInfo.ArgDbgValues.push_back( 5677 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 5678 *Op, Variable, Expr)); 5679 5680 return true; 5681 } 5682 5683 /// Return the appropriate SDDbgValue based on N. 5684 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5685 DILocalVariable *Variable, 5686 DIExpression *Expr, 5687 const DebugLoc &dl, 5688 unsigned DbgSDNodeOrder) { 5689 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5690 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5691 // stack slot locations. 5692 // 5693 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5694 // debug values here after optimization: 5695 // 5696 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5697 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5698 // 5699 // Both describe the direct values of their associated variables. 5700 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5701 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5702 } 5703 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5704 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5705 } 5706 5707 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5708 switch (Intrinsic) { 5709 case Intrinsic::smul_fix: 5710 return ISD::SMULFIX; 5711 case Intrinsic::umul_fix: 5712 return ISD::UMULFIX; 5713 case Intrinsic::smul_fix_sat: 5714 return ISD::SMULFIXSAT; 5715 case Intrinsic::umul_fix_sat: 5716 return ISD::UMULFIXSAT; 5717 case Intrinsic::sdiv_fix: 5718 return ISD::SDIVFIX; 5719 case Intrinsic::udiv_fix: 5720 return ISD::UDIVFIX; 5721 case Intrinsic::sdiv_fix_sat: 5722 return ISD::SDIVFIXSAT; 5723 case Intrinsic::udiv_fix_sat: 5724 return ISD::UDIVFIXSAT; 5725 default: 5726 llvm_unreachable("Unhandled fixed point intrinsic"); 5727 } 5728 } 5729 5730 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5731 const char *FunctionName) { 5732 assert(FunctionName && "FunctionName must not be nullptr"); 5733 SDValue Callee = DAG.getExternalSymbol( 5734 FunctionName, 5735 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5736 LowerCallTo(I, Callee, I.isTailCall()); 5737 } 5738 5739 /// Given a @llvm.call.preallocated.setup, return the corresponding 5740 /// preallocated call. 5741 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5742 assert(cast<CallBase>(PreallocatedSetup) 5743 ->getCalledFunction() 5744 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5745 "expected call_preallocated_setup Value"); 5746 for (auto *U : PreallocatedSetup->users()) { 5747 auto *UseCall = cast<CallBase>(U); 5748 const Function *Fn = UseCall->getCalledFunction(); 5749 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5750 return UseCall; 5751 } 5752 } 5753 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5754 } 5755 5756 /// Lower the call to the specified intrinsic function. 5757 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5758 unsigned Intrinsic) { 5759 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5760 SDLoc sdl = getCurSDLoc(); 5761 DebugLoc dl = getCurDebugLoc(); 5762 SDValue Res; 5763 5764 SDNodeFlags Flags; 5765 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 5766 Flags.copyFMF(*FPOp); 5767 5768 switch (Intrinsic) { 5769 default: 5770 // By default, turn this into a target intrinsic node. 5771 visitTargetIntrinsic(I, Intrinsic); 5772 return; 5773 case Intrinsic::vscale: { 5774 match(&I, m_VScale(DAG.getDataLayout())); 5775 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5776 setValue(&I, 5777 DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1))); 5778 return; 5779 } 5780 case Intrinsic::vastart: visitVAStart(I); return; 5781 case Intrinsic::vaend: visitVAEnd(I); return; 5782 case Intrinsic::vacopy: visitVACopy(I); return; 5783 case Intrinsic::returnaddress: 5784 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5785 TLI.getPointerTy(DAG.getDataLayout()), 5786 getValue(I.getArgOperand(0)))); 5787 return; 5788 case Intrinsic::addressofreturnaddress: 5789 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5790 TLI.getPointerTy(DAG.getDataLayout()))); 5791 return; 5792 case Intrinsic::sponentry: 5793 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5794 TLI.getFrameIndexTy(DAG.getDataLayout()))); 5795 return; 5796 case Intrinsic::frameaddress: 5797 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5798 TLI.getFrameIndexTy(DAG.getDataLayout()), 5799 getValue(I.getArgOperand(0)))); 5800 return; 5801 case Intrinsic::read_volatile_register: 5802 case Intrinsic::read_register: { 5803 Value *Reg = I.getArgOperand(0); 5804 SDValue Chain = getRoot(); 5805 SDValue RegName = 5806 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5807 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5808 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5809 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5810 setValue(&I, Res); 5811 DAG.setRoot(Res.getValue(1)); 5812 return; 5813 } 5814 case Intrinsic::write_register: { 5815 Value *Reg = I.getArgOperand(0); 5816 Value *RegValue = I.getArgOperand(1); 5817 SDValue Chain = getRoot(); 5818 SDValue RegName = 5819 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5820 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5821 RegName, getValue(RegValue))); 5822 return; 5823 } 5824 case Intrinsic::memcpy: { 5825 const auto &MCI = cast<MemCpyInst>(I); 5826 SDValue Op1 = getValue(I.getArgOperand(0)); 5827 SDValue Op2 = getValue(I.getArgOperand(1)); 5828 SDValue Op3 = getValue(I.getArgOperand(2)); 5829 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5830 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5831 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5832 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5833 bool isVol = MCI.isVolatile(); 5834 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5835 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5836 // node. 5837 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5838 SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5839 /* AlwaysInline */ false, isTC, 5840 MachinePointerInfo(I.getArgOperand(0)), 5841 MachinePointerInfo(I.getArgOperand(1))); 5842 updateDAGForMaybeTailCall(MC); 5843 return; 5844 } 5845 case Intrinsic::memcpy_inline: { 5846 const auto &MCI = cast<MemCpyInlineInst>(I); 5847 SDValue Dst = getValue(I.getArgOperand(0)); 5848 SDValue Src = getValue(I.getArgOperand(1)); 5849 SDValue Size = getValue(I.getArgOperand(2)); 5850 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 5851 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 5852 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5853 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5854 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5855 bool isVol = MCI.isVolatile(); 5856 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5857 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5858 // node. 5859 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 5860 /* AlwaysInline */ true, isTC, 5861 MachinePointerInfo(I.getArgOperand(0)), 5862 MachinePointerInfo(I.getArgOperand(1))); 5863 updateDAGForMaybeTailCall(MC); 5864 return; 5865 } 5866 case Intrinsic::memset: { 5867 const auto &MSI = cast<MemSetInst>(I); 5868 SDValue Op1 = getValue(I.getArgOperand(0)); 5869 SDValue Op2 = getValue(I.getArgOperand(1)); 5870 SDValue Op3 = getValue(I.getArgOperand(2)); 5871 // @llvm.memset defines 0 and 1 to both mean no alignment. 5872 Align Alignment = MSI.getDestAlign().valueOrOne(); 5873 bool isVol = MSI.isVolatile(); 5874 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5875 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5876 SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC, 5877 MachinePointerInfo(I.getArgOperand(0))); 5878 updateDAGForMaybeTailCall(MS); 5879 return; 5880 } 5881 case Intrinsic::memmove: { 5882 const auto &MMI = cast<MemMoveInst>(I); 5883 SDValue Op1 = getValue(I.getArgOperand(0)); 5884 SDValue Op2 = getValue(I.getArgOperand(1)); 5885 SDValue Op3 = getValue(I.getArgOperand(2)); 5886 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5887 Align DstAlign = MMI.getDestAlign().valueOrOne(); 5888 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 5889 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5890 bool isVol = MMI.isVolatile(); 5891 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5892 // FIXME: Support passing different dest/src alignments to the memmove DAG 5893 // node. 5894 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5895 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5896 isTC, MachinePointerInfo(I.getArgOperand(0)), 5897 MachinePointerInfo(I.getArgOperand(1))); 5898 updateDAGForMaybeTailCall(MM); 5899 return; 5900 } 5901 case Intrinsic::memcpy_element_unordered_atomic: { 5902 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5903 SDValue Dst = getValue(MI.getRawDest()); 5904 SDValue Src = getValue(MI.getRawSource()); 5905 SDValue Length = getValue(MI.getLength()); 5906 5907 unsigned DstAlign = MI.getDestAlignment(); 5908 unsigned SrcAlign = MI.getSourceAlignment(); 5909 Type *LengthTy = MI.getLength()->getType(); 5910 unsigned ElemSz = MI.getElementSizeInBytes(); 5911 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5912 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5913 SrcAlign, Length, LengthTy, ElemSz, isTC, 5914 MachinePointerInfo(MI.getRawDest()), 5915 MachinePointerInfo(MI.getRawSource())); 5916 updateDAGForMaybeTailCall(MC); 5917 return; 5918 } 5919 case Intrinsic::memmove_element_unordered_atomic: { 5920 auto &MI = cast<AtomicMemMoveInst>(I); 5921 SDValue Dst = getValue(MI.getRawDest()); 5922 SDValue Src = getValue(MI.getRawSource()); 5923 SDValue Length = getValue(MI.getLength()); 5924 5925 unsigned DstAlign = MI.getDestAlignment(); 5926 unsigned SrcAlign = MI.getSourceAlignment(); 5927 Type *LengthTy = MI.getLength()->getType(); 5928 unsigned ElemSz = MI.getElementSizeInBytes(); 5929 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5930 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5931 SrcAlign, Length, LengthTy, ElemSz, isTC, 5932 MachinePointerInfo(MI.getRawDest()), 5933 MachinePointerInfo(MI.getRawSource())); 5934 updateDAGForMaybeTailCall(MC); 5935 return; 5936 } 5937 case Intrinsic::memset_element_unordered_atomic: { 5938 auto &MI = cast<AtomicMemSetInst>(I); 5939 SDValue Dst = getValue(MI.getRawDest()); 5940 SDValue Val = getValue(MI.getValue()); 5941 SDValue Length = getValue(MI.getLength()); 5942 5943 unsigned DstAlign = MI.getDestAlignment(); 5944 Type *LengthTy = MI.getLength()->getType(); 5945 unsigned ElemSz = MI.getElementSizeInBytes(); 5946 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5947 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5948 LengthTy, ElemSz, isTC, 5949 MachinePointerInfo(MI.getRawDest())); 5950 updateDAGForMaybeTailCall(MC); 5951 return; 5952 } 5953 case Intrinsic::call_preallocated_setup: { 5954 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 5955 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 5956 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 5957 getRoot(), SrcValue); 5958 setValue(&I, Res); 5959 DAG.setRoot(Res); 5960 return; 5961 } 5962 case Intrinsic::call_preallocated_arg: { 5963 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 5964 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 5965 SDValue Ops[3]; 5966 Ops[0] = getRoot(); 5967 Ops[1] = SrcValue; 5968 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 5969 MVT::i32); // arg index 5970 SDValue Res = DAG.getNode( 5971 ISD::PREALLOCATED_ARG, sdl, 5972 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 5973 setValue(&I, Res); 5974 DAG.setRoot(Res.getValue(1)); 5975 return; 5976 } 5977 case Intrinsic::dbg_addr: 5978 case Intrinsic::dbg_declare: { 5979 // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e. 5980 // they are non-variadic. 5981 const auto &DI = cast<DbgVariableIntrinsic>(I); 5982 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 5983 DILocalVariable *Variable = DI.getVariable(); 5984 DIExpression *Expression = DI.getExpression(); 5985 dropDanglingDebugInfo(Variable, Expression); 5986 assert(Variable && "Missing variable"); 5987 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 5988 << "\n"); 5989 // Check if address has undef value. 5990 const Value *Address = DI.getVariableLocationOp(0); 5991 if (!Address || isa<UndefValue>(Address) || 5992 (Address->use_empty() && !isa<Argument>(Address))) { 5993 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 5994 << " (bad/undef/unused-arg address)\n"); 5995 return; 5996 } 5997 5998 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5999 6000 // Check if this variable can be described by a frame index, typically 6001 // either as a static alloca or a byval parameter. 6002 int FI = std::numeric_limits<int>::max(); 6003 if (const auto *AI = 6004 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 6005 if (AI->isStaticAlloca()) { 6006 auto I = FuncInfo.StaticAllocaMap.find(AI); 6007 if (I != FuncInfo.StaticAllocaMap.end()) 6008 FI = I->second; 6009 } 6010 } else if (const auto *Arg = dyn_cast<Argument>( 6011 Address->stripInBoundsConstantOffsets())) { 6012 FI = FuncInfo.getArgumentFrameIndex(Arg); 6013 } 6014 6015 // llvm.dbg.addr is control dependent and always generates indirect 6016 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 6017 // the MachineFunction variable table. 6018 if (FI != std::numeric_limits<int>::max()) { 6019 if (Intrinsic == Intrinsic::dbg_addr) { 6020 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 6021 Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true, 6022 dl, SDNodeOrder); 6023 DAG.AddDbgValue(SDV, isParameter); 6024 } else { 6025 LLVM_DEBUG(dbgs() << "Skipping " << DI 6026 << " (variable info stashed in MF side table)\n"); 6027 } 6028 return; 6029 } 6030 6031 SDValue &N = NodeMap[Address]; 6032 if (!N.getNode() && isa<Argument>(Address)) 6033 // Check unused arguments map. 6034 N = UnusedArgNodeMap[Address]; 6035 SDDbgValue *SDV; 6036 if (N.getNode()) { 6037 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 6038 Address = BCI->getOperand(0); 6039 // Parameters are handled specially. 6040 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 6041 if (isParameter && FINode) { 6042 // Byval parameter. We have a frame index at this point. 6043 SDV = 6044 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 6045 /*IsIndirect*/ true, dl, SDNodeOrder); 6046 } else if (isa<Argument>(Address)) { 6047 // Address is an argument, so try to emit its dbg value using 6048 // virtual register info from the FuncInfo.ValueMap. 6049 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 6050 return; 6051 } else { 6052 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 6053 true, dl, SDNodeOrder); 6054 } 6055 DAG.AddDbgValue(SDV, isParameter); 6056 } else { 6057 // If Address is an argument then try to emit its dbg value using 6058 // virtual register info from the FuncInfo.ValueMap. 6059 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 6060 N)) { 6061 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6062 << " (could not emit func-arg dbg_value)\n"); 6063 } 6064 } 6065 return; 6066 } 6067 case Intrinsic::dbg_label: { 6068 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6069 DILabel *Label = DI.getLabel(); 6070 assert(Label && "Missing label"); 6071 6072 SDDbgLabel *SDV; 6073 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6074 DAG.AddDbgLabel(SDV); 6075 return; 6076 } 6077 case Intrinsic::dbg_value: { 6078 const DbgValueInst &DI = cast<DbgValueInst>(I); 6079 assert(DI.getVariable() && "Missing variable"); 6080 6081 DILocalVariable *Variable = DI.getVariable(); 6082 DIExpression *Expression = DI.getExpression(); 6083 dropDanglingDebugInfo(Variable, Expression); 6084 SmallVector<Value *, 4> Values(DI.getValues()); 6085 if (Values.empty()) 6086 return; 6087 6088 if (std::count(Values.begin(), Values.end(), nullptr)) 6089 return; 6090 6091 bool IsVariadic = DI.hasArgList(); 6092 if (!handleDebugValue(Values, Variable, Expression, dl, DI.getDebugLoc(), 6093 SDNodeOrder, IsVariadic)) 6094 addDanglingDebugInfo(&DI, dl, SDNodeOrder); 6095 return; 6096 } 6097 6098 case Intrinsic::eh_typeid_for: { 6099 // Find the type id for the given typeinfo. 6100 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6101 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6102 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6103 setValue(&I, Res); 6104 return; 6105 } 6106 6107 case Intrinsic::eh_return_i32: 6108 case Intrinsic::eh_return_i64: 6109 DAG.getMachineFunction().setCallsEHReturn(true); 6110 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6111 MVT::Other, 6112 getControlRoot(), 6113 getValue(I.getArgOperand(0)), 6114 getValue(I.getArgOperand(1)))); 6115 return; 6116 case Intrinsic::eh_unwind_init: 6117 DAG.getMachineFunction().setCallsUnwindInit(true); 6118 return; 6119 case Intrinsic::eh_dwarf_cfa: 6120 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6121 TLI.getPointerTy(DAG.getDataLayout()), 6122 getValue(I.getArgOperand(0)))); 6123 return; 6124 case Intrinsic::eh_sjlj_callsite: { 6125 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6126 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 6127 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 6128 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6129 6130 MMI.setCurrentCallSite(CI->getZExtValue()); 6131 return; 6132 } 6133 case Intrinsic::eh_sjlj_functioncontext: { 6134 // Get and store the index of the function context. 6135 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6136 AllocaInst *FnCtx = 6137 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6138 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6139 MFI.setFunctionContextIndex(FI); 6140 return; 6141 } 6142 case Intrinsic::eh_sjlj_setjmp: { 6143 SDValue Ops[2]; 6144 Ops[0] = getRoot(); 6145 Ops[1] = getValue(I.getArgOperand(0)); 6146 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6147 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6148 setValue(&I, Op.getValue(0)); 6149 DAG.setRoot(Op.getValue(1)); 6150 return; 6151 } 6152 case Intrinsic::eh_sjlj_longjmp: 6153 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6154 getRoot(), getValue(I.getArgOperand(0)))); 6155 return; 6156 case Intrinsic::eh_sjlj_setup_dispatch: 6157 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6158 getRoot())); 6159 return; 6160 case Intrinsic::masked_gather: 6161 visitMaskedGather(I); 6162 return; 6163 case Intrinsic::masked_load: 6164 visitMaskedLoad(I); 6165 return; 6166 case Intrinsic::masked_scatter: 6167 visitMaskedScatter(I); 6168 return; 6169 case Intrinsic::masked_store: 6170 visitMaskedStore(I); 6171 return; 6172 case Intrinsic::masked_expandload: 6173 visitMaskedLoad(I, true /* IsExpanding */); 6174 return; 6175 case Intrinsic::masked_compressstore: 6176 visitMaskedStore(I, true /* IsCompressing */); 6177 return; 6178 case Intrinsic::powi: 6179 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6180 getValue(I.getArgOperand(1)), DAG)); 6181 return; 6182 case Intrinsic::log: 6183 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6184 return; 6185 case Intrinsic::log2: 6186 setValue(&I, 6187 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6188 return; 6189 case Intrinsic::log10: 6190 setValue(&I, 6191 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6192 return; 6193 case Intrinsic::exp: 6194 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6195 return; 6196 case Intrinsic::exp2: 6197 setValue(&I, 6198 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6199 return; 6200 case Intrinsic::pow: 6201 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6202 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6203 return; 6204 case Intrinsic::sqrt: 6205 case Intrinsic::fabs: 6206 case Intrinsic::sin: 6207 case Intrinsic::cos: 6208 case Intrinsic::floor: 6209 case Intrinsic::ceil: 6210 case Intrinsic::trunc: 6211 case Intrinsic::rint: 6212 case Intrinsic::nearbyint: 6213 case Intrinsic::round: 6214 case Intrinsic::roundeven: 6215 case Intrinsic::canonicalize: { 6216 unsigned Opcode; 6217 switch (Intrinsic) { 6218 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6219 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6220 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6221 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6222 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6223 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6224 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6225 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6226 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6227 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6228 case Intrinsic::round: Opcode = ISD::FROUND; break; 6229 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6230 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6231 } 6232 6233 setValue(&I, DAG.getNode(Opcode, sdl, 6234 getValue(I.getArgOperand(0)).getValueType(), 6235 getValue(I.getArgOperand(0)), Flags)); 6236 return; 6237 } 6238 case Intrinsic::lround: 6239 case Intrinsic::llround: 6240 case Intrinsic::lrint: 6241 case Intrinsic::llrint: { 6242 unsigned Opcode; 6243 switch (Intrinsic) { 6244 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6245 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6246 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6247 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6248 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6249 } 6250 6251 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6252 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6253 getValue(I.getArgOperand(0)))); 6254 return; 6255 } 6256 case Intrinsic::minnum: 6257 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6258 getValue(I.getArgOperand(0)).getValueType(), 6259 getValue(I.getArgOperand(0)), 6260 getValue(I.getArgOperand(1)), Flags)); 6261 return; 6262 case Intrinsic::maxnum: 6263 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6264 getValue(I.getArgOperand(0)).getValueType(), 6265 getValue(I.getArgOperand(0)), 6266 getValue(I.getArgOperand(1)), Flags)); 6267 return; 6268 case Intrinsic::minimum: 6269 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6270 getValue(I.getArgOperand(0)).getValueType(), 6271 getValue(I.getArgOperand(0)), 6272 getValue(I.getArgOperand(1)), Flags)); 6273 return; 6274 case Intrinsic::maximum: 6275 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6276 getValue(I.getArgOperand(0)).getValueType(), 6277 getValue(I.getArgOperand(0)), 6278 getValue(I.getArgOperand(1)), Flags)); 6279 return; 6280 case Intrinsic::copysign: 6281 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6282 getValue(I.getArgOperand(0)).getValueType(), 6283 getValue(I.getArgOperand(0)), 6284 getValue(I.getArgOperand(1)), Flags)); 6285 return; 6286 case Intrinsic::fma: 6287 setValue(&I, DAG.getNode( 6288 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6289 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6290 getValue(I.getArgOperand(2)), Flags)); 6291 return; 6292 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6293 case Intrinsic::INTRINSIC: 6294 #include "llvm/IR/ConstrainedOps.def" 6295 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6296 return; 6297 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6298 #include "llvm/IR/VPIntrinsics.def" 6299 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6300 return; 6301 case Intrinsic::fmuladd: { 6302 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6303 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6304 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6305 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6306 getValue(I.getArgOperand(0)).getValueType(), 6307 getValue(I.getArgOperand(0)), 6308 getValue(I.getArgOperand(1)), 6309 getValue(I.getArgOperand(2)), Flags)); 6310 } else { 6311 // TODO: Intrinsic calls should have fast-math-flags. 6312 SDValue Mul = DAG.getNode( 6313 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6314 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6315 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6316 getValue(I.getArgOperand(0)).getValueType(), 6317 Mul, getValue(I.getArgOperand(2)), Flags); 6318 setValue(&I, Add); 6319 } 6320 return; 6321 } 6322 case Intrinsic::convert_to_fp16: 6323 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6324 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6325 getValue(I.getArgOperand(0)), 6326 DAG.getTargetConstant(0, sdl, 6327 MVT::i32)))); 6328 return; 6329 case Intrinsic::convert_from_fp16: 6330 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6331 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6332 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6333 getValue(I.getArgOperand(0))))); 6334 return; 6335 case Intrinsic::fptosi_sat: { 6336 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6337 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 6338 getValue(I.getArgOperand(0)), 6339 DAG.getValueType(VT.getScalarType()))); 6340 return; 6341 } 6342 case Intrinsic::fptoui_sat: { 6343 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6344 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 6345 getValue(I.getArgOperand(0)), 6346 DAG.getValueType(VT.getScalarType()))); 6347 return; 6348 } 6349 case Intrinsic::set_rounding: 6350 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6351 {getRoot(), getValue(I.getArgOperand(0))}); 6352 setValue(&I, Res); 6353 DAG.setRoot(Res.getValue(0)); 6354 return; 6355 case Intrinsic::pcmarker: { 6356 SDValue Tmp = getValue(I.getArgOperand(0)); 6357 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6358 return; 6359 } 6360 case Intrinsic::readcyclecounter: { 6361 SDValue Op = getRoot(); 6362 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6363 DAG.getVTList(MVT::i64, MVT::Other), Op); 6364 setValue(&I, Res); 6365 DAG.setRoot(Res.getValue(1)); 6366 return; 6367 } 6368 case Intrinsic::bitreverse: 6369 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6370 getValue(I.getArgOperand(0)).getValueType(), 6371 getValue(I.getArgOperand(0)))); 6372 return; 6373 case Intrinsic::bswap: 6374 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6375 getValue(I.getArgOperand(0)).getValueType(), 6376 getValue(I.getArgOperand(0)))); 6377 return; 6378 case Intrinsic::cttz: { 6379 SDValue Arg = getValue(I.getArgOperand(0)); 6380 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6381 EVT Ty = Arg.getValueType(); 6382 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6383 sdl, Ty, Arg)); 6384 return; 6385 } 6386 case Intrinsic::ctlz: { 6387 SDValue Arg = getValue(I.getArgOperand(0)); 6388 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6389 EVT Ty = Arg.getValueType(); 6390 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6391 sdl, Ty, Arg)); 6392 return; 6393 } 6394 case Intrinsic::ctpop: { 6395 SDValue Arg = getValue(I.getArgOperand(0)); 6396 EVT Ty = Arg.getValueType(); 6397 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6398 return; 6399 } 6400 case Intrinsic::fshl: 6401 case Intrinsic::fshr: { 6402 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6403 SDValue X = getValue(I.getArgOperand(0)); 6404 SDValue Y = getValue(I.getArgOperand(1)); 6405 SDValue Z = getValue(I.getArgOperand(2)); 6406 EVT VT = X.getValueType(); 6407 6408 if (X == Y) { 6409 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6410 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6411 } else { 6412 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6413 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6414 } 6415 return; 6416 } 6417 case Intrinsic::sadd_sat: { 6418 SDValue Op1 = getValue(I.getArgOperand(0)); 6419 SDValue Op2 = getValue(I.getArgOperand(1)); 6420 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6421 return; 6422 } 6423 case Intrinsic::uadd_sat: { 6424 SDValue Op1 = getValue(I.getArgOperand(0)); 6425 SDValue Op2 = getValue(I.getArgOperand(1)); 6426 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6427 return; 6428 } 6429 case Intrinsic::ssub_sat: { 6430 SDValue Op1 = getValue(I.getArgOperand(0)); 6431 SDValue Op2 = getValue(I.getArgOperand(1)); 6432 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6433 return; 6434 } 6435 case Intrinsic::usub_sat: { 6436 SDValue Op1 = getValue(I.getArgOperand(0)); 6437 SDValue Op2 = getValue(I.getArgOperand(1)); 6438 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6439 return; 6440 } 6441 case Intrinsic::sshl_sat: { 6442 SDValue Op1 = getValue(I.getArgOperand(0)); 6443 SDValue Op2 = getValue(I.getArgOperand(1)); 6444 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6445 return; 6446 } 6447 case Intrinsic::ushl_sat: { 6448 SDValue Op1 = getValue(I.getArgOperand(0)); 6449 SDValue Op2 = getValue(I.getArgOperand(1)); 6450 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6451 return; 6452 } 6453 case Intrinsic::smul_fix: 6454 case Intrinsic::umul_fix: 6455 case Intrinsic::smul_fix_sat: 6456 case Intrinsic::umul_fix_sat: { 6457 SDValue Op1 = getValue(I.getArgOperand(0)); 6458 SDValue Op2 = getValue(I.getArgOperand(1)); 6459 SDValue Op3 = getValue(I.getArgOperand(2)); 6460 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6461 Op1.getValueType(), Op1, Op2, Op3)); 6462 return; 6463 } 6464 case Intrinsic::sdiv_fix: 6465 case Intrinsic::udiv_fix: 6466 case Intrinsic::sdiv_fix_sat: 6467 case Intrinsic::udiv_fix_sat: { 6468 SDValue Op1 = getValue(I.getArgOperand(0)); 6469 SDValue Op2 = getValue(I.getArgOperand(1)); 6470 SDValue Op3 = getValue(I.getArgOperand(2)); 6471 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6472 Op1, Op2, Op3, DAG, TLI)); 6473 return; 6474 } 6475 case Intrinsic::smax: { 6476 SDValue Op1 = getValue(I.getArgOperand(0)); 6477 SDValue Op2 = getValue(I.getArgOperand(1)); 6478 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6479 return; 6480 } 6481 case Intrinsic::smin: { 6482 SDValue Op1 = getValue(I.getArgOperand(0)); 6483 SDValue Op2 = getValue(I.getArgOperand(1)); 6484 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6485 return; 6486 } 6487 case Intrinsic::umax: { 6488 SDValue Op1 = getValue(I.getArgOperand(0)); 6489 SDValue Op2 = getValue(I.getArgOperand(1)); 6490 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6491 return; 6492 } 6493 case Intrinsic::umin: { 6494 SDValue Op1 = getValue(I.getArgOperand(0)); 6495 SDValue Op2 = getValue(I.getArgOperand(1)); 6496 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6497 return; 6498 } 6499 case Intrinsic::abs: { 6500 // TODO: Preserve "int min is poison" arg in SDAG? 6501 SDValue Op1 = getValue(I.getArgOperand(0)); 6502 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6503 return; 6504 } 6505 case Intrinsic::stacksave: { 6506 SDValue Op = getRoot(); 6507 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6508 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6509 setValue(&I, Res); 6510 DAG.setRoot(Res.getValue(1)); 6511 return; 6512 } 6513 case Intrinsic::stackrestore: 6514 Res = getValue(I.getArgOperand(0)); 6515 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6516 return; 6517 case Intrinsic::get_dynamic_area_offset: { 6518 SDValue Op = getRoot(); 6519 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6520 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6521 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6522 // target. 6523 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 6524 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6525 " intrinsic!"); 6526 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6527 Op); 6528 DAG.setRoot(Op); 6529 setValue(&I, Res); 6530 return; 6531 } 6532 case Intrinsic::stackguard: { 6533 MachineFunction &MF = DAG.getMachineFunction(); 6534 const Module &M = *MF.getFunction().getParent(); 6535 SDValue Chain = getRoot(); 6536 if (TLI.useLoadStackGuardNode()) { 6537 Res = getLoadStackGuard(DAG, sdl, Chain); 6538 } else { 6539 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6540 const Value *Global = TLI.getSDagStackGuard(M); 6541 Align Align = DL->getPrefTypeAlign(Global->getType()); 6542 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6543 MachinePointerInfo(Global, 0), Align, 6544 MachineMemOperand::MOVolatile); 6545 } 6546 if (TLI.useStackGuardXorFP()) 6547 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6548 DAG.setRoot(Chain); 6549 setValue(&I, Res); 6550 return; 6551 } 6552 case Intrinsic::stackprotector: { 6553 // Emit code into the DAG to store the stack guard onto the stack. 6554 MachineFunction &MF = DAG.getMachineFunction(); 6555 MachineFrameInfo &MFI = MF.getFrameInfo(); 6556 SDValue Src, Chain = getRoot(); 6557 6558 if (TLI.useLoadStackGuardNode()) 6559 Src = getLoadStackGuard(DAG, sdl, Chain); 6560 else 6561 Src = getValue(I.getArgOperand(0)); // The guard's value. 6562 6563 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6564 6565 int FI = FuncInfo.StaticAllocaMap[Slot]; 6566 MFI.setStackProtectorIndex(FI); 6567 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6568 6569 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6570 6571 // Store the stack protector onto the stack. 6572 Res = DAG.getStore( 6573 Chain, sdl, Src, FIN, 6574 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 6575 MaybeAlign(), MachineMemOperand::MOVolatile); 6576 setValue(&I, Res); 6577 DAG.setRoot(Res); 6578 return; 6579 } 6580 case Intrinsic::objectsize: 6581 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6582 6583 case Intrinsic::is_constant: 6584 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6585 6586 case Intrinsic::annotation: 6587 case Intrinsic::ptr_annotation: 6588 case Intrinsic::launder_invariant_group: 6589 case Intrinsic::strip_invariant_group: 6590 // Drop the intrinsic, but forward the value 6591 setValue(&I, getValue(I.getOperand(0))); 6592 return; 6593 6594 case Intrinsic::assume: 6595 case Intrinsic::experimental_noalias_scope_decl: 6596 case Intrinsic::var_annotation: 6597 case Intrinsic::sideeffect: 6598 // Discard annotate attributes, noalias scope declarations, assumptions, and 6599 // artificial side-effects. 6600 return; 6601 6602 case Intrinsic::codeview_annotation: { 6603 // Emit a label associated with this metadata. 6604 MachineFunction &MF = DAG.getMachineFunction(); 6605 MCSymbol *Label = 6606 MF.getMMI().getContext().createTempSymbol("annotation", true); 6607 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6608 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6609 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6610 DAG.setRoot(Res); 6611 return; 6612 } 6613 6614 case Intrinsic::init_trampoline: { 6615 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6616 6617 SDValue Ops[6]; 6618 Ops[0] = getRoot(); 6619 Ops[1] = getValue(I.getArgOperand(0)); 6620 Ops[2] = getValue(I.getArgOperand(1)); 6621 Ops[3] = getValue(I.getArgOperand(2)); 6622 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6623 Ops[5] = DAG.getSrcValue(F); 6624 6625 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6626 6627 DAG.setRoot(Res); 6628 return; 6629 } 6630 case Intrinsic::adjust_trampoline: 6631 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6632 TLI.getPointerTy(DAG.getDataLayout()), 6633 getValue(I.getArgOperand(0)))); 6634 return; 6635 case Intrinsic::gcroot: { 6636 assert(DAG.getMachineFunction().getFunction().hasGC() && 6637 "only valid in functions with gc specified, enforced by Verifier"); 6638 assert(GFI && "implied by previous"); 6639 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6640 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6641 6642 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6643 GFI->addStackRoot(FI->getIndex(), TypeMap); 6644 return; 6645 } 6646 case Intrinsic::gcread: 6647 case Intrinsic::gcwrite: 6648 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6649 case Intrinsic::flt_rounds: 6650 Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot()); 6651 setValue(&I, Res); 6652 DAG.setRoot(Res.getValue(1)); 6653 return; 6654 6655 case Intrinsic::expect: 6656 // Just replace __builtin_expect(exp, c) with EXP. 6657 setValue(&I, getValue(I.getArgOperand(0))); 6658 return; 6659 6660 case Intrinsic::ubsantrap: 6661 case Intrinsic::debugtrap: 6662 case Intrinsic::trap: { 6663 StringRef TrapFuncName = 6664 I.getAttributes() 6665 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6666 .getValueAsString(); 6667 if (TrapFuncName.empty()) { 6668 switch (Intrinsic) { 6669 case Intrinsic::trap: 6670 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 6671 break; 6672 case Intrinsic::debugtrap: 6673 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 6674 break; 6675 case Intrinsic::ubsantrap: 6676 DAG.setRoot(DAG.getNode( 6677 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 6678 DAG.getTargetConstant( 6679 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 6680 MVT::i32))); 6681 break; 6682 default: llvm_unreachable("unknown trap intrinsic"); 6683 } 6684 return; 6685 } 6686 TargetLowering::ArgListTy Args; 6687 if (Intrinsic == Intrinsic::ubsantrap) { 6688 Args.push_back(TargetLoweringBase::ArgListEntry()); 6689 Args[0].Val = I.getArgOperand(0); 6690 Args[0].Node = getValue(Args[0].Val); 6691 Args[0].Ty = Args[0].Val->getType(); 6692 } 6693 6694 TargetLowering::CallLoweringInfo CLI(DAG); 6695 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6696 CallingConv::C, I.getType(), 6697 DAG.getExternalSymbol(TrapFuncName.data(), 6698 TLI.getPointerTy(DAG.getDataLayout())), 6699 std::move(Args)); 6700 6701 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6702 DAG.setRoot(Result.second); 6703 return; 6704 } 6705 6706 case Intrinsic::uadd_with_overflow: 6707 case Intrinsic::sadd_with_overflow: 6708 case Intrinsic::usub_with_overflow: 6709 case Intrinsic::ssub_with_overflow: 6710 case Intrinsic::umul_with_overflow: 6711 case Intrinsic::smul_with_overflow: { 6712 ISD::NodeType Op; 6713 switch (Intrinsic) { 6714 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6715 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6716 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6717 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6718 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6719 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6720 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6721 } 6722 SDValue Op1 = getValue(I.getArgOperand(0)); 6723 SDValue Op2 = getValue(I.getArgOperand(1)); 6724 6725 EVT ResultVT = Op1.getValueType(); 6726 EVT OverflowVT = MVT::i1; 6727 if (ResultVT.isVector()) 6728 OverflowVT = EVT::getVectorVT( 6729 *Context, OverflowVT, ResultVT.getVectorElementCount()); 6730 6731 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6732 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6733 return; 6734 } 6735 case Intrinsic::prefetch: { 6736 SDValue Ops[5]; 6737 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6738 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6739 Ops[0] = DAG.getRoot(); 6740 Ops[1] = getValue(I.getArgOperand(0)); 6741 Ops[2] = getValue(I.getArgOperand(1)); 6742 Ops[3] = getValue(I.getArgOperand(2)); 6743 Ops[4] = getValue(I.getArgOperand(3)); 6744 SDValue Result = DAG.getMemIntrinsicNode( 6745 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 6746 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 6747 /* align */ None, Flags); 6748 6749 // Chain the prefetch in parallell with any pending loads, to stay out of 6750 // the way of later optimizations. 6751 PendingLoads.push_back(Result); 6752 Result = getRoot(); 6753 DAG.setRoot(Result); 6754 return; 6755 } 6756 case Intrinsic::lifetime_start: 6757 case Intrinsic::lifetime_end: { 6758 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6759 // Stack coloring is not enabled in O0, discard region information. 6760 if (TM.getOptLevel() == CodeGenOpt::None) 6761 return; 6762 6763 const int64_t ObjectSize = 6764 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6765 Value *const ObjectPtr = I.getArgOperand(1); 6766 SmallVector<const Value *, 4> Allocas; 6767 getUnderlyingObjects(ObjectPtr, Allocas); 6768 6769 for (const Value *Alloca : Allocas) { 6770 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 6771 6772 // Could not find an Alloca. 6773 if (!LifetimeObject) 6774 continue; 6775 6776 // First check that the Alloca is static, otherwise it won't have a 6777 // valid frame index. 6778 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6779 if (SI == FuncInfo.StaticAllocaMap.end()) 6780 return; 6781 6782 const int FrameIndex = SI->second; 6783 int64_t Offset; 6784 if (GetPointerBaseWithConstantOffset( 6785 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6786 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6787 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6788 Offset); 6789 DAG.setRoot(Res); 6790 } 6791 return; 6792 } 6793 case Intrinsic::pseudoprobe: { 6794 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 6795 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6796 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 6797 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 6798 DAG.setRoot(Res); 6799 return; 6800 } 6801 case Intrinsic::invariant_start: 6802 // Discard region information. 6803 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6804 return; 6805 case Intrinsic::invariant_end: 6806 // Discard region information. 6807 return; 6808 case Intrinsic::clear_cache: 6809 /// FunctionName may be null. 6810 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6811 lowerCallToExternalSymbol(I, FunctionName); 6812 return; 6813 case Intrinsic::donothing: 6814 case Intrinsic::seh_try_begin: 6815 case Intrinsic::seh_scope_begin: 6816 case Intrinsic::seh_try_end: 6817 case Intrinsic::seh_scope_end: 6818 // ignore 6819 return; 6820 case Intrinsic::experimental_stackmap: 6821 visitStackmap(I); 6822 return; 6823 case Intrinsic::experimental_patchpoint_void: 6824 case Intrinsic::experimental_patchpoint_i64: 6825 visitPatchpoint(I); 6826 return; 6827 case Intrinsic::experimental_gc_statepoint: 6828 LowerStatepoint(cast<GCStatepointInst>(I)); 6829 return; 6830 case Intrinsic::experimental_gc_result: 6831 visitGCResult(cast<GCResultInst>(I)); 6832 return; 6833 case Intrinsic::experimental_gc_relocate: 6834 visitGCRelocate(cast<GCRelocateInst>(I)); 6835 return; 6836 case Intrinsic::instrprof_increment: 6837 llvm_unreachable("instrprof failed to lower an increment"); 6838 case Intrinsic::instrprof_value_profile: 6839 llvm_unreachable("instrprof failed to lower a value profiling call"); 6840 case Intrinsic::localescape: { 6841 MachineFunction &MF = DAG.getMachineFunction(); 6842 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6843 6844 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6845 // is the same on all targets. 6846 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6847 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6848 if (isa<ConstantPointerNull>(Arg)) 6849 continue; // Skip null pointers. They represent a hole in index space. 6850 AllocaInst *Slot = cast<AllocaInst>(Arg); 6851 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6852 "can only escape static allocas"); 6853 int FI = FuncInfo.StaticAllocaMap[Slot]; 6854 MCSymbol *FrameAllocSym = 6855 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6856 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6857 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6858 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6859 .addSym(FrameAllocSym) 6860 .addFrameIndex(FI); 6861 } 6862 6863 return; 6864 } 6865 6866 case Intrinsic::localrecover: { 6867 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6868 MachineFunction &MF = DAG.getMachineFunction(); 6869 6870 // Get the symbol that defines the frame offset. 6871 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6872 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6873 unsigned IdxVal = 6874 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6875 MCSymbol *FrameAllocSym = 6876 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6877 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6878 6879 Value *FP = I.getArgOperand(1); 6880 SDValue FPVal = getValue(FP); 6881 EVT PtrVT = FPVal.getValueType(); 6882 6883 // Create a MCSymbol for the label to avoid any target lowering 6884 // that would make this PC relative. 6885 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6886 SDValue OffsetVal = 6887 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6888 6889 // Add the offset to the FP. 6890 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 6891 setValue(&I, Add); 6892 6893 return; 6894 } 6895 6896 case Intrinsic::eh_exceptionpointer: 6897 case Intrinsic::eh_exceptioncode: { 6898 // Get the exception pointer vreg, copy from it, and resize it to fit. 6899 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6900 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6901 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6902 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6903 SDValue N = 6904 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6905 if (Intrinsic == Intrinsic::eh_exceptioncode) 6906 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6907 setValue(&I, N); 6908 return; 6909 } 6910 case Intrinsic::xray_customevent: { 6911 // Here we want to make sure that the intrinsic behaves as if it has a 6912 // specific calling convention, and only for x86_64. 6913 // FIXME: Support other platforms later. 6914 const auto &Triple = DAG.getTarget().getTargetTriple(); 6915 if (Triple.getArch() != Triple::x86_64) 6916 return; 6917 6918 SDLoc DL = getCurSDLoc(); 6919 SmallVector<SDValue, 8> Ops; 6920 6921 // We want to say that we always want the arguments in registers. 6922 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6923 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6924 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6925 SDValue Chain = getRoot(); 6926 Ops.push_back(LogEntryVal); 6927 Ops.push_back(StrSizeVal); 6928 Ops.push_back(Chain); 6929 6930 // We need to enforce the calling convention for the callsite, so that 6931 // argument ordering is enforced correctly, and that register allocation can 6932 // see that some registers may be assumed clobbered and have to preserve 6933 // them across calls to the intrinsic. 6934 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6935 DL, NodeTys, Ops); 6936 SDValue patchableNode = SDValue(MN, 0); 6937 DAG.setRoot(patchableNode); 6938 setValue(&I, patchableNode); 6939 return; 6940 } 6941 case Intrinsic::xray_typedevent: { 6942 // Here we want to make sure that the intrinsic behaves as if it has a 6943 // specific calling convention, and only for x86_64. 6944 // FIXME: Support other platforms later. 6945 const auto &Triple = DAG.getTarget().getTargetTriple(); 6946 if (Triple.getArch() != Triple::x86_64) 6947 return; 6948 6949 SDLoc DL = getCurSDLoc(); 6950 SmallVector<SDValue, 8> Ops; 6951 6952 // We want to say that we always want the arguments in registers. 6953 // It's unclear to me how manipulating the selection DAG here forces callers 6954 // to provide arguments in registers instead of on the stack. 6955 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6956 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6957 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6958 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6959 SDValue Chain = getRoot(); 6960 Ops.push_back(LogTypeId); 6961 Ops.push_back(LogEntryVal); 6962 Ops.push_back(StrSizeVal); 6963 Ops.push_back(Chain); 6964 6965 // We need to enforce the calling convention for the callsite, so that 6966 // argument ordering is enforced correctly, and that register allocation can 6967 // see that some registers may be assumed clobbered and have to preserve 6968 // them across calls to the intrinsic. 6969 MachineSDNode *MN = DAG.getMachineNode( 6970 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6971 SDValue patchableNode = SDValue(MN, 0); 6972 DAG.setRoot(patchableNode); 6973 setValue(&I, patchableNode); 6974 return; 6975 } 6976 case Intrinsic::experimental_deoptimize: 6977 LowerDeoptimizeCall(&I); 6978 return; 6979 case Intrinsic::experimental_stepvector: 6980 visitStepVector(I); 6981 return; 6982 case Intrinsic::vector_reduce_fadd: 6983 case Intrinsic::vector_reduce_fmul: 6984 case Intrinsic::vector_reduce_add: 6985 case Intrinsic::vector_reduce_mul: 6986 case Intrinsic::vector_reduce_and: 6987 case Intrinsic::vector_reduce_or: 6988 case Intrinsic::vector_reduce_xor: 6989 case Intrinsic::vector_reduce_smax: 6990 case Intrinsic::vector_reduce_smin: 6991 case Intrinsic::vector_reduce_umax: 6992 case Intrinsic::vector_reduce_umin: 6993 case Intrinsic::vector_reduce_fmax: 6994 case Intrinsic::vector_reduce_fmin: 6995 visitVectorReduce(I, Intrinsic); 6996 return; 6997 6998 case Intrinsic::icall_branch_funnel: { 6999 SmallVector<SDValue, 16> Ops; 7000 Ops.push_back(getValue(I.getArgOperand(0))); 7001 7002 int64_t Offset; 7003 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7004 I.getArgOperand(1), Offset, DAG.getDataLayout())); 7005 if (!Base) 7006 report_fatal_error( 7007 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7008 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 7009 7010 struct BranchFunnelTarget { 7011 int64_t Offset; 7012 SDValue Target; 7013 }; 7014 SmallVector<BranchFunnelTarget, 8> Targets; 7015 7016 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 7017 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7018 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7019 if (ElemBase != Base) 7020 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7021 "to the same GlobalValue"); 7022 7023 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7024 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7025 if (!GA) 7026 report_fatal_error( 7027 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7028 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7029 GA->getGlobal(), getCurSDLoc(), 7030 Val.getValueType(), GA->getOffset())}); 7031 } 7032 llvm::sort(Targets, 7033 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7034 return T1.Offset < T2.Offset; 7035 }); 7036 7037 for (auto &T : Targets) { 7038 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 7039 Ops.push_back(T.Target); 7040 } 7041 7042 Ops.push_back(DAG.getRoot()); // Chain 7043 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 7044 getCurSDLoc(), MVT::Other, Ops), 7045 0); 7046 DAG.setRoot(N); 7047 setValue(&I, N); 7048 HasTailCall = true; 7049 return; 7050 } 7051 7052 case Intrinsic::wasm_landingpad_index: 7053 // Information this intrinsic contained has been transferred to 7054 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7055 // delete it now. 7056 return; 7057 7058 case Intrinsic::aarch64_settag: 7059 case Intrinsic::aarch64_settag_zero: { 7060 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7061 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7062 SDValue Val = TSI.EmitTargetCodeForSetTag( 7063 DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)), 7064 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7065 ZeroMemory); 7066 DAG.setRoot(Val); 7067 setValue(&I, Val); 7068 return; 7069 } 7070 case Intrinsic::ptrmask: { 7071 SDValue Ptr = getValue(I.getOperand(0)); 7072 SDValue Const = getValue(I.getOperand(1)); 7073 7074 EVT PtrVT = Ptr.getValueType(); 7075 setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), PtrVT, Ptr, 7076 DAG.getZExtOrTrunc(Const, getCurSDLoc(), PtrVT))); 7077 return; 7078 } 7079 case Intrinsic::get_active_lane_mask: { 7080 auto DL = getCurSDLoc(); 7081 SDValue Index = getValue(I.getOperand(0)); 7082 SDValue TripCount = getValue(I.getOperand(1)); 7083 Type *ElementTy = I.getOperand(0)->getType(); 7084 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7085 unsigned VecWidth = VT.getVectorNumElements(); 7086 7087 SmallVector<SDValue, 16> OpsTripCount; 7088 SmallVector<SDValue, 16> OpsIndex; 7089 SmallVector<SDValue, 16> OpsStepConstants; 7090 for (unsigned i = 0; i < VecWidth; i++) { 7091 OpsTripCount.push_back(TripCount); 7092 OpsIndex.push_back(Index); 7093 OpsStepConstants.push_back( 7094 DAG.getConstant(i, DL, EVT::getEVT(ElementTy))); 7095 } 7096 7097 EVT CCVT = EVT::getVectorVT(I.getContext(), MVT::i1, VecWidth); 7098 7099 auto VecTy = EVT::getEVT(FixedVectorType::get(ElementTy, VecWidth)); 7100 SDValue VectorIndex = DAG.getBuildVector(VecTy, DL, OpsIndex); 7101 SDValue VectorStep = DAG.getBuildVector(VecTy, DL, OpsStepConstants); 7102 SDValue VectorInduction = DAG.getNode( 7103 ISD::UADDO, DL, DAG.getVTList(VecTy, CCVT), VectorIndex, VectorStep); 7104 SDValue VectorTripCount = DAG.getBuildVector(VecTy, DL, OpsTripCount); 7105 SDValue SetCC = DAG.getSetCC(DL, CCVT, VectorInduction.getValue(0), 7106 VectorTripCount, ISD::CondCode::SETULT); 7107 setValue(&I, DAG.getNode(ISD::AND, DL, CCVT, 7108 DAG.getNOT(DL, VectorInduction.getValue(1), CCVT), 7109 SetCC)); 7110 return; 7111 } 7112 case Intrinsic::experimental_vector_insert: { 7113 auto DL = getCurSDLoc(); 7114 7115 SDValue Vec = getValue(I.getOperand(0)); 7116 SDValue SubVec = getValue(I.getOperand(1)); 7117 SDValue Index = getValue(I.getOperand(2)); 7118 7119 // The intrinsic's index type is i64, but the SDNode requires an index type 7120 // suitable for the target. Convert the index as required. 7121 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7122 if (Index.getValueType() != VectorIdxTy) 7123 Index = DAG.getVectorIdxConstant( 7124 cast<ConstantSDNode>(Index)->getZExtValue(), DL); 7125 7126 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7127 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ResultVT, Vec, SubVec, 7128 Index)); 7129 return; 7130 } 7131 case Intrinsic::experimental_vector_extract: { 7132 auto DL = getCurSDLoc(); 7133 7134 SDValue Vec = getValue(I.getOperand(0)); 7135 SDValue Index = getValue(I.getOperand(1)); 7136 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7137 7138 // The intrinsic's index type is i64, but the SDNode requires an index type 7139 // suitable for the target. Convert the index as required. 7140 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7141 if (Index.getValueType() != VectorIdxTy) 7142 Index = DAG.getVectorIdxConstant( 7143 cast<ConstantSDNode>(Index)->getZExtValue(), DL); 7144 7145 setValue(&I, DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResultVT, Vec, Index)); 7146 return; 7147 } 7148 case Intrinsic::experimental_vector_reverse: 7149 visitVectorReverse(I); 7150 return; 7151 case Intrinsic::experimental_vector_splice: 7152 visitVectorSplice(I); 7153 return; 7154 } 7155 } 7156 7157 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7158 const ConstrainedFPIntrinsic &FPI) { 7159 SDLoc sdl = getCurSDLoc(); 7160 7161 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7162 SmallVector<EVT, 4> ValueVTs; 7163 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 7164 ValueVTs.push_back(MVT::Other); // Out chain 7165 7166 // We do not need to serialize constrained FP intrinsics against 7167 // each other or against (nonvolatile) loads, so they can be 7168 // chained like loads. 7169 SDValue Chain = DAG.getRoot(); 7170 SmallVector<SDValue, 4> Opers; 7171 Opers.push_back(Chain); 7172 if (FPI.isUnaryOp()) { 7173 Opers.push_back(getValue(FPI.getArgOperand(0))); 7174 } else if (FPI.isTernaryOp()) { 7175 Opers.push_back(getValue(FPI.getArgOperand(0))); 7176 Opers.push_back(getValue(FPI.getArgOperand(1))); 7177 Opers.push_back(getValue(FPI.getArgOperand(2))); 7178 } else { 7179 Opers.push_back(getValue(FPI.getArgOperand(0))); 7180 Opers.push_back(getValue(FPI.getArgOperand(1))); 7181 } 7182 7183 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7184 assert(Result.getNode()->getNumValues() == 2); 7185 7186 // Push node to the appropriate list so that future instructions can be 7187 // chained up correctly. 7188 SDValue OutChain = Result.getValue(1); 7189 switch (EB) { 7190 case fp::ExceptionBehavior::ebIgnore: 7191 // The only reason why ebIgnore nodes still need to be chained is that 7192 // they might depend on the current rounding mode, and therefore must 7193 // not be moved across instruction that may change that mode. 7194 LLVM_FALLTHROUGH; 7195 case fp::ExceptionBehavior::ebMayTrap: 7196 // These must not be moved across calls or instructions that may change 7197 // floating-point exception masks. 7198 PendingConstrainedFP.push_back(OutChain); 7199 break; 7200 case fp::ExceptionBehavior::ebStrict: 7201 // These must not be moved across calls or instructions that may change 7202 // floating-point exception masks or read floating-point exception flags. 7203 // In addition, they cannot be optimized out even if unused. 7204 PendingConstrainedFPStrict.push_back(OutChain); 7205 break; 7206 } 7207 }; 7208 7209 SDVTList VTs = DAG.getVTList(ValueVTs); 7210 fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue(); 7211 7212 SDNodeFlags Flags; 7213 if (EB == fp::ExceptionBehavior::ebIgnore) 7214 Flags.setNoFPExcept(true); 7215 7216 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7217 Flags.copyFMF(*FPOp); 7218 7219 unsigned Opcode; 7220 switch (FPI.getIntrinsicID()) { 7221 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7222 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7223 case Intrinsic::INTRINSIC: \ 7224 Opcode = ISD::STRICT_##DAGN; \ 7225 break; 7226 #include "llvm/IR/ConstrainedOps.def" 7227 case Intrinsic::experimental_constrained_fmuladd: { 7228 Opcode = ISD::STRICT_FMA; 7229 // Break fmuladd into fmul and fadd. 7230 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7231 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), 7232 ValueVTs[0])) { 7233 Opers.pop_back(); 7234 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7235 pushOutChain(Mul, EB); 7236 Opcode = ISD::STRICT_FADD; 7237 Opers.clear(); 7238 Opers.push_back(Mul.getValue(1)); 7239 Opers.push_back(Mul.getValue(0)); 7240 Opers.push_back(getValue(FPI.getArgOperand(2))); 7241 } 7242 break; 7243 } 7244 } 7245 7246 // A few strict DAG nodes carry additional operands that are not 7247 // set up by the default code above. 7248 switch (Opcode) { 7249 default: break; 7250 case ISD::STRICT_FP_ROUND: 7251 Opers.push_back( 7252 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7253 break; 7254 case ISD::STRICT_FSETCC: 7255 case ISD::STRICT_FSETCCS: { 7256 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7257 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 7258 if (TM.Options.NoNaNsFPMath) 7259 Condition = getFCmpCodeWithoutNaN(Condition); 7260 Opers.push_back(DAG.getCondCode(Condition)); 7261 break; 7262 } 7263 } 7264 7265 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7266 pushOutChain(Result, EB); 7267 7268 SDValue FPResult = Result.getValue(0); 7269 setValue(&FPI, FPResult); 7270 } 7271 7272 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 7273 Optional<unsigned> ResOPC; 7274 switch (VPIntrin.getIntrinsicID()) { 7275 #define BEGIN_REGISTER_VP_INTRINSIC(INTRIN, ...) case Intrinsic::INTRIN: 7276 #define BEGIN_REGISTER_VP_SDNODE(VPSDID, ...) ResOPC = ISD::VPSDID; 7277 #define END_REGISTER_VP_INTRINSIC(...) break; 7278 #include "llvm/IR/VPIntrinsics.def" 7279 } 7280 7281 if (!ResOPC.hasValue()) 7282 llvm_unreachable( 7283 "Inconsistency: no SDNode available for this VPIntrinsic!"); 7284 7285 return ResOPC.getValue(); 7286 } 7287 7288 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 7289 const VPIntrinsic &VPIntrin) { 7290 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 7291 7292 SmallVector<EVT, 4> ValueVTs; 7293 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7294 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 7295 SDVTList VTs = DAG.getVTList(ValueVTs); 7296 7297 // Request operands. 7298 SmallVector<SDValue, 7> OpValues; 7299 for (int i = 0; i < (int)VPIntrin.getNumArgOperands(); ++i) 7300 OpValues.push_back(getValue(VPIntrin.getArgOperand(i))); 7301 7302 SDLoc DL = getCurSDLoc(); 7303 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues); 7304 setValue(&VPIntrin, Result); 7305 } 7306 7307 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 7308 const BasicBlock *EHPadBB, 7309 MCSymbol *&BeginLabel) { 7310 MachineFunction &MF = DAG.getMachineFunction(); 7311 MachineModuleInfo &MMI = MF.getMMI(); 7312 7313 // Insert a label before the invoke call to mark the try range. This can be 7314 // used to detect deletion of the invoke via the MachineModuleInfo. 7315 BeginLabel = MMI.getContext().createTempSymbol(); 7316 7317 // For SjLj, keep track of which landing pads go with which invokes 7318 // so as to maintain the ordering of pads in the LSDA. 7319 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7320 if (CallSiteIndex) { 7321 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7322 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7323 7324 // Now that the call site is handled, stop tracking it. 7325 MMI.setCurrentCallSite(0); 7326 } 7327 7328 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 7329 } 7330 7331 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 7332 const BasicBlock *EHPadBB, 7333 MCSymbol *BeginLabel) { 7334 assert(BeginLabel && "BeginLabel should've been set"); 7335 7336 MachineFunction &MF = DAG.getMachineFunction(); 7337 MachineModuleInfo &MMI = MF.getMMI(); 7338 7339 // Insert a label at the end of the invoke call to mark the try range. This 7340 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7341 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7342 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 7343 7344 // Inform MachineModuleInfo of range. 7345 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7346 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7347 // actually use outlined funclets and their LSDA info style. 7348 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7349 assert(II && "II should've been set"); 7350 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 7351 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 7352 } else if (!isScopedEHPersonality(Pers)) { 7353 assert(EHPadBB); 7354 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7355 } 7356 7357 return Chain; 7358 } 7359 7360 std::pair<SDValue, SDValue> 7361 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7362 const BasicBlock *EHPadBB) { 7363 MCSymbol *BeginLabel = nullptr; 7364 7365 if (EHPadBB) { 7366 // Both PendingLoads and PendingExports must be flushed here; 7367 // this call might not return. 7368 (void)getRoot(); 7369 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 7370 CLI.setChain(getRoot()); 7371 } 7372 7373 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7374 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7375 7376 assert((CLI.IsTailCall || Result.second.getNode()) && 7377 "Non-null chain expected with non-tail call!"); 7378 assert((Result.second.getNode() || !Result.first.getNode()) && 7379 "Null value expected with tail call!"); 7380 7381 if (!Result.second.getNode()) { 7382 // As a special case, a null chain means that a tail call has been emitted 7383 // and the DAG root is already updated. 7384 HasTailCall = true; 7385 7386 // Since there's no actual continuation from this block, nothing can be 7387 // relying on us setting vregs for them. 7388 PendingExports.clear(); 7389 } else { 7390 DAG.setRoot(Result.second); 7391 } 7392 7393 if (EHPadBB) { 7394 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 7395 BeginLabel)); 7396 } 7397 7398 return Result; 7399 } 7400 7401 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 7402 bool isTailCall, 7403 const BasicBlock *EHPadBB) { 7404 auto &DL = DAG.getDataLayout(); 7405 FunctionType *FTy = CB.getFunctionType(); 7406 Type *RetTy = CB.getType(); 7407 7408 TargetLowering::ArgListTy Args; 7409 Args.reserve(CB.arg_size()); 7410 7411 const Value *SwiftErrorVal = nullptr; 7412 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7413 7414 if (isTailCall) { 7415 // Avoid emitting tail calls in functions with the disable-tail-calls 7416 // attribute. 7417 auto *Caller = CB.getParent()->getParent(); 7418 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7419 "true") 7420 isTailCall = false; 7421 7422 // We can't tail call inside a function with a swifterror argument. Lowering 7423 // does not support this yet. It would have to move into the swifterror 7424 // register before the call. 7425 if (TLI.supportSwiftError() && 7426 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7427 isTailCall = false; 7428 } 7429 7430 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 7431 TargetLowering::ArgListEntry Entry; 7432 const Value *V = *I; 7433 7434 // Skip empty types 7435 if (V->getType()->isEmptyTy()) 7436 continue; 7437 7438 SDValue ArgNode = getValue(V); 7439 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7440 7441 Entry.setAttributes(&CB, I - CB.arg_begin()); 7442 7443 // Use swifterror virtual register as input to the call. 7444 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7445 SwiftErrorVal = V; 7446 // We find the virtual register for the actual swifterror argument. 7447 // Instead of using the Value, we use the virtual register instead. 7448 Entry.Node = 7449 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 7450 EVT(TLI.getPointerTy(DL))); 7451 } 7452 7453 Args.push_back(Entry); 7454 7455 // If we have an explicit sret argument that is an Instruction, (i.e., it 7456 // might point to function-local memory), we can't meaningfully tail-call. 7457 if (Entry.IsSRet && isa<Instruction>(V)) 7458 isTailCall = false; 7459 } 7460 7461 // If call site has a cfguardtarget operand bundle, create and add an 7462 // additional ArgListEntry. 7463 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7464 TargetLowering::ArgListEntry Entry; 7465 Value *V = Bundle->Inputs[0]; 7466 SDValue ArgNode = getValue(V); 7467 Entry.Node = ArgNode; 7468 Entry.Ty = V->getType(); 7469 Entry.IsCFGuardTarget = true; 7470 Args.push_back(Entry); 7471 } 7472 7473 // Check if target-independent constraints permit a tail call here. 7474 // Target-dependent constraints are checked within TLI->LowerCallTo. 7475 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 7476 isTailCall = false; 7477 7478 // Disable tail calls if there is an swifterror argument. Targets have not 7479 // been updated to support tail calls. 7480 if (TLI.supportSwiftError() && SwiftErrorVal) 7481 isTailCall = false; 7482 7483 TargetLowering::CallLoweringInfo CLI(DAG); 7484 CLI.setDebugLoc(getCurSDLoc()) 7485 .setChain(getRoot()) 7486 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 7487 .setTailCall(isTailCall) 7488 .setConvergent(CB.isConvergent()) 7489 .setIsPreallocated( 7490 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 7491 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7492 7493 if (Result.first.getNode()) { 7494 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 7495 setValue(&CB, Result.first); 7496 } 7497 7498 // The last element of CLI.InVals has the SDValue for swifterror return. 7499 // Here we copy it to a virtual register and update SwiftErrorMap for 7500 // book-keeping. 7501 if (SwiftErrorVal && TLI.supportSwiftError()) { 7502 // Get the last element of InVals. 7503 SDValue Src = CLI.InVals.back(); 7504 Register VReg = 7505 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 7506 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7507 DAG.setRoot(CopyNode); 7508 } 7509 } 7510 7511 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7512 SelectionDAGBuilder &Builder) { 7513 // Check to see if this load can be trivially constant folded, e.g. if the 7514 // input is from a string literal. 7515 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7516 // Cast pointer to the type we really want to load. 7517 Type *LoadTy = 7518 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7519 if (LoadVT.isVector()) 7520 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7521 7522 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7523 PointerType::getUnqual(LoadTy)); 7524 7525 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 7526 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 7527 return Builder.getValue(LoadCst); 7528 } 7529 7530 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7531 // still constant memory, the input chain can be the entry node. 7532 SDValue Root; 7533 bool ConstantMemory = false; 7534 7535 // Do not serialize (non-volatile) loads of constant memory with anything. 7536 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7537 Root = Builder.DAG.getEntryNode(); 7538 ConstantMemory = true; 7539 } else { 7540 // Do not serialize non-volatile loads against each other. 7541 Root = Builder.DAG.getRoot(); 7542 } 7543 7544 SDValue Ptr = Builder.getValue(PtrVal); 7545 SDValue LoadVal = 7546 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 7547 MachinePointerInfo(PtrVal), Align(1)); 7548 7549 if (!ConstantMemory) 7550 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7551 return LoadVal; 7552 } 7553 7554 /// Record the value for an instruction that produces an integer result, 7555 /// converting the type where necessary. 7556 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7557 SDValue Value, 7558 bool IsSigned) { 7559 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7560 I.getType(), true); 7561 if (IsSigned) 7562 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7563 else 7564 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7565 setValue(&I, Value); 7566 } 7567 7568 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 7569 /// true and lower it. Otherwise return false, and it will be lowered like a 7570 /// normal call. 7571 /// The caller already checked that \p I calls the appropriate LibFunc with a 7572 /// correct prototype. 7573 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 7574 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 7575 const Value *Size = I.getArgOperand(2); 7576 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 7577 if (CSize && CSize->getZExtValue() == 0) { 7578 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7579 I.getType(), true); 7580 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 7581 return true; 7582 } 7583 7584 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7585 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 7586 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 7587 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 7588 if (Res.first.getNode()) { 7589 processIntegerCallValue(I, Res.first, true); 7590 PendingLoads.push_back(Res.second); 7591 return true; 7592 } 7593 7594 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 7595 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 7596 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 7597 return false; 7598 7599 // If the target has a fast compare for the given size, it will return a 7600 // preferred load type for that size. Require that the load VT is legal and 7601 // that the target supports unaligned loads of that type. Otherwise, return 7602 // INVALID. 7603 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 7604 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7605 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 7606 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 7607 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 7608 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 7609 // TODO: Check alignment of src and dest ptrs. 7610 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 7611 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 7612 if (!TLI.isTypeLegal(LVT) || 7613 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 7614 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 7615 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 7616 } 7617 7618 return LVT; 7619 }; 7620 7621 // This turns into unaligned loads. We only do this if the target natively 7622 // supports the MVT we'll be loading or if it is small enough (<= 4) that 7623 // we'll only produce a small number of byte loads. 7624 MVT LoadVT; 7625 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 7626 switch (NumBitsToCompare) { 7627 default: 7628 return false; 7629 case 16: 7630 LoadVT = MVT::i16; 7631 break; 7632 case 32: 7633 LoadVT = MVT::i32; 7634 break; 7635 case 64: 7636 case 128: 7637 case 256: 7638 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 7639 break; 7640 } 7641 7642 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 7643 return false; 7644 7645 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 7646 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 7647 7648 // Bitcast to a wide integer type if the loads are vectors. 7649 if (LoadVT.isVector()) { 7650 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 7651 LoadL = DAG.getBitcast(CmpVT, LoadL); 7652 LoadR = DAG.getBitcast(CmpVT, LoadR); 7653 } 7654 7655 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 7656 processIntegerCallValue(I, Cmp, false); 7657 return true; 7658 } 7659 7660 /// See if we can lower a memchr call into an optimized form. If so, return 7661 /// true and lower it. Otherwise return false, and it will be lowered like a 7662 /// normal call. 7663 /// The caller already checked that \p I calls the appropriate LibFunc with a 7664 /// correct prototype. 7665 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 7666 const Value *Src = I.getArgOperand(0); 7667 const Value *Char = I.getArgOperand(1); 7668 const Value *Length = I.getArgOperand(2); 7669 7670 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7671 std::pair<SDValue, SDValue> Res = 7672 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 7673 getValue(Src), getValue(Char), getValue(Length), 7674 MachinePointerInfo(Src)); 7675 if (Res.first.getNode()) { 7676 setValue(&I, Res.first); 7677 PendingLoads.push_back(Res.second); 7678 return true; 7679 } 7680 7681 return false; 7682 } 7683 7684 /// See if we can lower a mempcpy call into an optimized form. If so, return 7685 /// true and lower it. Otherwise return false, and it will be lowered like a 7686 /// normal call. 7687 /// The caller already checked that \p I calls the appropriate LibFunc with a 7688 /// correct prototype. 7689 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 7690 SDValue Dst = getValue(I.getArgOperand(0)); 7691 SDValue Src = getValue(I.getArgOperand(1)); 7692 SDValue Size = getValue(I.getArgOperand(2)); 7693 7694 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 7695 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 7696 // DAG::getMemcpy needs Alignment to be defined. 7697 Align Alignment = std::min(DstAlign, SrcAlign); 7698 7699 bool isVol = false; 7700 SDLoc sdl = getCurSDLoc(); 7701 7702 // In the mempcpy context we need to pass in a false value for isTailCall 7703 // because the return pointer needs to be adjusted by the size of 7704 // the copied memory. 7705 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 7706 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false, 7707 /*isTailCall=*/false, 7708 MachinePointerInfo(I.getArgOperand(0)), 7709 MachinePointerInfo(I.getArgOperand(1))); 7710 assert(MC.getNode() != nullptr && 7711 "** memcpy should not be lowered as TailCall in mempcpy context **"); 7712 DAG.setRoot(MC); 7713 7714 // Check if Size needs to be truncated or extended. 7715 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 7716 7717 // Adjust return pointer to point just past the last dst byte. 7718 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 7719 Dst, Size); 7720 setValue(&I, DstPlusSize); 7721 return true; 7722 } 7723 7724 /// See if we can lower a strcpy call into an optimized form. If so, return 7725 /// true and lower it, otherwise return false and it will be lowered like a 7726 /// normal call. 7727 /// The caller already checked that \p I calls the appropriate LibFunc with a 7728 /// correct prototype. 7729 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 7730 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7731 7732 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7733 std::pair<SDValue, SDValue> Res = 7734 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 7735 getValue(Arg0), getValue(Arg1), 7736 MachinePointerInfo(Arg0), 7737 MachinePointerInfo(Arg1), isStpcpy); 7738 if (Res.first.getNode()) { 7739 setValue(&I, Res.first); 7740 DAG.setRoot(Res.second); 7741 return true; 7742 } 7743 7744 return false; 7745 } 7746 7747 /// See if we can lower a strcmp call into an optimized form. If so, return 7748 /// true and lower it, otherwise return false and it will be lowered like a 7749 /// normal call. 7750 /// The caller already checked that \p I calls the appropriate LibFunc with a 7751 /// correct prototype. 7752 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 7753 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7754 7755 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7756 std::pair<SDValue, SDValue> Res = 7757 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 7758 getValue(Arg0), getValue(Arg1), 7759 MachinePointerInfo(Arg0), 7760 MachinePointerInfo(Arg1)); 7761 if (Res.first.getNode()) { 7762 processIntegerCallValue(I, Res.first, true); 7763 PendingLoads.push_back(Res.second); 7764 return true; 7765 } 7766 7767 return false; 7768 } 7769 7770 /// See if we can lower a strlen call into an optimized form. If so, return 7771 /// true and lower it, otherwise return false and it will be lowered like a 7772 /// normal call. 7773 /// The caller already checked that \p I calls the appropriate LibFunc with a 7774 /// correct prototype. 7775 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 7776 const Value *Arg0 = I.getArgOperand(0); 7777 7778 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7779 std::pair<SDValue, SDValue> Res = 7780 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 7781 getValue(Arg0), MachinePointerInfo(Arg0)); 7782 if (Res.first.getNode()) { 7783 processIntegerCallValue(I, Res.first, false); 7784 PendingLoads.push_back(Res.second); 7785 return true; 7786 } 7787 7788 return false; 7789 } 7790 7791 /// See if we can lower a strnlen call into an optimized form. If so, return 7792 /// true and lower it, otherwise return false and it will be lowered like a 7793 /// normal call. 7794 /// The caller already checked that \p I calls the appropriate LibFunc with a 7795 /// correct prototype. 7796 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 7797 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7798 7799 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7800 std::pair<SDValue, SDValue> Res = 7801 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 7802 getValue(Arg0), getValue(Arg1), 7803 MachinePointerInfo(Arg0)); 7804 if (Res.first.getNode()) { 7805 processIntegerCallValue(I, Res.first, false); 7806 PendingLoads.push_back(Res.second); 7807 return true; 7808 } 7809 7810 return false; 7811 } 7812 7813 /// See if we can lower a unary floating-point operation into an SDNode with 7814 /// the specified Opcode. If so, return true and lower it, otherwise return 7815 /// false and it will be lowered like a normal call. 7816 /// The caller already checked that \p I calls the appropriate LibFunc with a 7817 /// correct prototype. 7818 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 7819 unsigned Opcode) { 7820 // We already checked this call's prototype; verify it doesn't modify errno. 7821 if (!I.onlyReadsMemory()) 7822 return false; 7823 7824 SDNodeFlags Flags; 7825 Flags.copyFMF(cast<FPMathOperator>(I)); 7826 7827 SDValue Tmp = getValue(I.getArgOperand(0)); 7828 setValue(&I, 7829 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 7830 return true; 7831 } 7832 7833 /// See if we can lower a binary floating-point operation into an SDNode with 7834 /// the specified Opcode. If so, return true and lower it. Otherwise return 7835 /// false, and it will be lowered like a normal call. 7836 /// The caller already checked that \p I calls the appropriate LibFunc with a 7837 /// correct prototype. 7838 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 7839 unsigned Opcode) { 7840 // We already checked this call's prototype; verify it doesn't modify errno. 7841 if (!I.onlyReadsMemory()) 7842 return false; 7843 7844 SDNodeFlags Flags; 7845 Flags.copyFMF(cast<FPMathOperator>(I)); 7846 7847 SDValue Tmp0 = getValue(I.getArgOperand(0)); 7848 SDValue Tmp1 = getValue(I.getArgOperand(1)); 7849 EVT VT = Tmp0.getValueType(); 7850 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 7851 return true; 7852 } 7853 7854 void SelectionDAGBuilder::visitCall(const CallInst &I) { 7855 // Handle inline assembly differently. 7856 if (I.isInlineAsm()) { 7857 visitInlineAsm(I); 7858 return; 7859 } 7860 7861 if (Function *F = I.getCalledFunction()) { 7862 if (F->isDeclaration()) { 7863 // Is this an LLVM intrinsic or a target-specific intrinsic? 7864 unsigned IID = F->getIntrinsicID(); 7865 if (!IID) 7866 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7867 IID = II->getIntrinsicID(F); 7868 7869 if (IID) { 7870 visitIntrinsicCall(I, IID); 7871 return; 7872 } 7873 } 7874 7875 // Check for well-known libc/libm calls. If the function is internal, it 7876 // can't be a library call. Don't do the check if marked as nobuiltin for 7877 // some reason or the call site requires strict floating point semantics. 7878 LibFunc Func; 7879 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7880 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7881 LibInfo->hasOptimizedCodeGen(Func)) { 7882 switch (Func) { 7883 default: break; 7884 case LibFunc_bcmp: 7885 if (visitMemCmpBCmpCall(I)) 7886 return; 7887 break; 7888 case LibFunc_copysign: 7889 case LibFunc_copysignf: 7890 case LibFunc_copysignl: 7891 // We already checked this call's prototype; verify it doesn't modify 7892 // errno. 7893 if (I.onlyReadsMemory()) { 7894 SDValue LHS = getValue(I.getArgOperand(0)); 7895 SDValue RHS = getValue(I.getArgOperand(1)); 7896 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7897 LHS.getValueType(), LHS, RHS)); 7898 return; 7899 } 7900 break; 7901 case LibFunc_fabs: 7902 case LibFunc_fabsf: 7903 case LibFunc_fabsl: 7904 if (visitUnaryFloatCall(I, ISD::FABS)) 7905 return; 7906 break; 7907 case LibFunc_fmin: 7908 case LibFunc_fminf: 7909 case LibFunc_fminl: 7910 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7911 return; 7912 break; 7913 case LibFunc_fmax: 7914 case LibFunc_fmaxf: 7915 case LibFunc_fmaxl: 7916 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7917 return; 7918 break; 7919 case LibFunc_sin: 7920 case LibFunc_sinf: 7921 case LibFunc_sinl: 7922 if (visitUnaryFloatCall(I, ISD::FSIN)) 7923 return; 7924 break; 7925 case LibFunc_cos: 7926 case LibFunc_cosf: 7927 case LibFunc_cosl: 7928 if (visitUnaryFloatCall(I, ISD::FCOS)) 7929 return; 7930 break; 7931 case LibFunc_sqrt: 7932 case LibFunc_sqrtf: 7933 case LibFunc_sqrtl: 7934 case LibFunc_sqrt_finite: 7935 case LibFunc_sqrtf_finite: 7936 case LibFunc_sqrtl_finite: 7937 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7938 return; 7939 break; 7940 case LibFunc_floor: 7941 case LibFunc_floorf: 7942 case LibFunc_floorl: 7943 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7944 return; 7945 break; 7946 case LibFunc_nearbyint: 7947 case LibFunc_nearbyintf: 7948 case LibFunc_nearbyintl: 7949 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7950 return; 7951 break; 7952 case LibFunc_ceil: 7953 case LibFunc_ceilf: 7954 case LibFunc_ceill: 7955 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7956 return; 7957 break; 7958 case LibFunc_rint: 7959 case LibFunc_rintf: 7960 case LibFunc_rintl: 7961 if (visitUnaryFloatCall(I, ISD::FRINT)) 7962 return; 7963 break; 7964 case LibFunc_round: 7965 case LibFunc_roundf: 7966 case LibFunc_roundl: 7967 if (visitUnaryFloatCall(I, ISD::FROUND)) 7968 return; 7969 break; 7970 case LibFunc_trunc: 7971 case LibFunc_truncf: 7972 case LibFunc_truncl: 7973 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7974 return; 7975 break; 7976 case LibFunc_log2: 7977 case LibFunc_log2f: 7978 case LibFunc_log2l: 7979 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7980 return; 7981 break; 7982 case LibFunc_exp2: 7983 case LibFunc_exp2f: 7984 case LibFunc_exp2l: 7985 if (visitUnaryFloatCall(I, ISD::FEXP2)) 7986 return; 7987 break; 7988 case LibFunc_memcmp: 7989 if (visitMemCmpBCmpCall(I)) 7990 return; 7991 break; 7992 case LibFunc_mempcpy: 7993 if (visitMemPCpyCall(I)) 7994 return; 7995 break; 7996 case LibFunc_memchr: 7997 if (visitMemChrCall(I)) 7998 return; 7999 break; 8000 case LibFunc_strcpy: 8001 if (visitStrCpyCall(I, false)) 8002 return; 8003 break; 8004 case LibFunc_stpcpy: 8005 if (visitStrCpyCall(I, true)) 8006 return; 8007 break; 8008 case LibFunc_strcmp: 8009 if (visitStrCmpCall(I)) 8010 return; 8011 break; 8012 case LibFunc_strlen: 8013 if (visitStrLenCall(I)) 8014 return; 8015 break; 8016 case LibFunc_strnlen: 8017 if (visitStrNLenCall(I)) 8018 return; 8019 break; 8020 } 8021 } 8022 } 8023 8024 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 8025 // have to do anything here to lower funclet bundles. 8026 // CFGuardTarget bundles are lowered in LowerCallTo. 8027 assert(!I.hasOperandBundlesOtherThan( 8028 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 8029 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 8030 LLVMContext::OB_clang_arc_attachedcall}) && 8031 "Cannot lower calls with arbitrary operand bundles!"); 8032 8033 SDValue Callee = getValue(I.getCalledOperand()); 8034 8035 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 8036 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 8037 else 8038 // Check if we can potentially perform a tail call. More detailed checking 8039 // is be done within LowerCallTo, after more information about the call is 8040 // known. 8041 LowerCallTo(I, Callee, I.isTailCall()); 8042 } 8043 8044 namespace { 8045 8046 /// AsmOperandInfo - This contains information for each constraint that we are 8047 /// lowering. 8048 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 8049 public: 8050 /// CallOperand - If this is the result output operand or a clobber 8051 /// this is null, otherwise it is the incoming operand to the CallInst. 8052 /// This gets modified as the asm is processed. 8053 SDValue CallOperand; 8054 8055 /// AssignedRegs - If this is a register or register class operand, this 8056 /// contains the set of register corresponding to the operand. 8057 RegsForValue AssignedRegs; 8058 8059 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 8060 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 8061 } 8062 8063 /// Whether or not this operand accesses memory 8064 bool hasMemory(const TargetLowering &TLI) const { 8065 // Indirect operand accesses access memory. 8066 if (isIndirect) 8067 return true; 8068 8069 for (const auto &Code : Codes) 8070 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 8071 return true; 8072 8073 return false; 8074 } 8075 8076 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 8077 /// corresponds to. If there is no Value* for this operand, it returns 8078 /// MVT::Other. 8079 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 8080 const DataLayout &DL) const { 8081 if (!CallOperandVal) return MVT::Other; 8082 8083 if (isa<BasicBlock>(CallOperandVal)) 8084 return TLI.getProgramPointerTy(DL); 8085 8086 llvm::Type *OpTy = CallOperandVal->getType(); 8087 8088 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 8089 // If this is an indirect operand, the operand is a pointer to the 8090 // accessed type. 8091 if (isIndirect) { 8092 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 8093 if (!PtrTy) 8094 report_fatal_error("Indirect operand for inline asm not a pointer!"); 8095 OpTy = PtrTy->getElementType(); 8096 } 8097 8098 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 8099 if (StructType *STy = dyn_cast<StructType>(OpTy)) 8100 if (STy->getNumElements() == 1) 8101 OpTy = STy->getElementType(0); 8102 8103 // If OpTy is not a single value, it may be a struct/union that we 8104 // can tile with integers. 8105 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 8106 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 8107 switch (BitSize) { 8108 default: break; 8109 case 1: 8110 case 8: 8111 case 16: 8112 case 32: 8113 case 64: 8114 case 128: 8115 OpTy = IntegerType::get(Context, BitSize); 8116 break; 8117 } 8118 } 8119 8120 return TLI.getValueType(DL, OpTy, true); 8121 } 8122 }; 8123 8124 8125 } // end anonymous namespace 8126 8127 /// Make sure that the output operand \p OpInfo and its corresponding input 8128 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 8129 /// out). 8130 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 8131 SDISelAsmOperandInfo &MatchingOpInfo, 8132 SelectionDAG &DAG) { 8133 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 8134 return; 8135 8136 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 8137 const auto &TLI = DAG.getTargetLoweringInfo(); 8138 8139 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 8140 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 8141 OpInfo.ConstraintVT); 8142 std::pair<unsigned, const TargetRegisterClass *> InputRC = 8143 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 8144 MatchingOpInfo.ConstraintVT); 8145 if ((OpInfo.ConstraintVT.isInteger() != 8146 MatchingOpInfo.ConstraintVT.isInteger()) || 8147 (MatchRC.second != InputRC.second)) { 8148 // FIXME: error out in a more elegant fashion 8149 report_fatal_error("Unsupported asm: input constraint" 8150 " with a matching output constraint of" 8151 " incompatible type!"); 8152 } 8153 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 8154 } 8155 8156 /// Get a direct memory input to behave well as an indirect operand. 8157 /// This may introduce stores, hence the need for a \p Chain. 8158 /// \return The (possibly updated) chain. 8159 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 8160 SDISelAsmOperandInfo &OpInfo, 8161 SelectionDAG &DAG) { 8162 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8163 8164 // If we don't have an indirect input, put it in the constpool if we can, 8165 // otherwise spill it to a stack slot. 8166 // TODO: This isn't quite right. We need to handle these according to 8167 // the addressing mode that the constraint wants. Also, this may take 8168 // an additional register for the computation and we don't want that 8169 // either. 8170 8171 // If the operand is a float, integer, or vector constant, spill to a 8172 // constant pool entry to get its address. 8173 const Value *OpVal = OpInfo.CallOperandVal; 8174 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 8175 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 8176 OpInfo.CallOperand = DAG.getConstantPool( 8177 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 8178 return Chain; 8179 } 8180 8181 // Otherwise, create a stack slot and emit a store to it before the asm. 8182 Type *Ty = OpVal->getType(); 8183 auto &DL = DAG.getDataLayout(); 8184 uint64_t TySize = DL.getTypeAllocSize(Ty); 8185 MachineFunction &MF = DAG.getMachineFunction(); 8186 int SSFI = MF.getFrameInfo().CreateStackObject( 8187 TySize, DL.getPrefTypeAlign(Ty), false); 8188 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 8189 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 8190 MachinePointerInfo::getFixedStack(MF, SSFI), 8191 TLI.getMemValueType(DL, Ty)); 8192 OpInfo.CallOperand = StackSlot; 8193 8194 return Chain; 8195 } 8196 8197 /// GetRegistersForValue - Assign registers (virtual or physical) for the 8198 /// specified operand. We prefer to assign virtual registers, to allow the 8199 /// register allocator to handle the assignment process. However, if the asm 8200 /// uses features that we can't model on machineinstrs, we have SDISel do the 8201 /// allocation. This produces generally horrible, but correct, code. 8202 /// 8203 /// OpInfo describes the operand 8204 /// RefOpInfo describes the matching operand if any, the operand otherwise 8205 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 8206 SDISelAsmOperandInfo &OpInfo, 8207 SDISelAsmOperandInfo &RefOpInfo) { 8208 LLVMContext &Context = *DAG.getContext(); 8209 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8210 8211 MachineFunction &MF = DAG.getMachineFunction(); 8212 SmallVector<unsigned, 4> Regs; 8213 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8214 8215 // No work to do for memory operations. 8216 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 8217 return; 8218 8219 // If this is a constraint for a single physreg, or a constraint for a 8220 // register class, find it. 8221 unsigned AssignedReg; 8222 const TargetRegisterClass *RC; 8223 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 8224 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 8225 // RC is unset only on failure. Return immediately. 8226 if (!RC) 8227 return; 8228 8229 // Get the actual register value type. This is important, because the user 8230 // may have asked for (e.g.) the AX register in i32 type. We need to 8231 // remember that AX is actually i16 to get the right extension. 8232 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 8233 8234 if (OpInfo.ConstraintVT != MVT::Other) { 8235 // If this is an FP operand in an integer register (or visa versa), or more 8236 // generally if the operand value disagrees with the register class we plan 8237 // to stick it in, fix the operand type. 8238 // 8239 // If this is an input value, the bitcast to the new type is done now. 8240 // Bitcast for output value is done at the end of visitInlineAsm(). 8241 if ((OpInfo.Type == InlineAsm::isOutput || 8242 OpInfo.Type == InlineAsm::isInput) && 8243 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 8244 // Try to convert to the first EVT that the reg class contains. If the 8245 // types are identical size, use a bitcast to convert (e.g. two differing 8246 // vector types). Note: output bitcast is done at the end of 8247 // visitInlineAsm(). 8248 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 8249 // Exclude indirect inputs while they are unsupported because the code 8250 // to perform the load is missing and thus OpInfo.CallOperand still 8251 // refers to the input address rather than the pointed-to value. 8252 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 8253 OpInfo.CallOperand = 8254 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 8255 OpInfo.ConstraintVT = RegVT; 8256 // If the operand is an FP value and we want it in integer registers, 8257 // use the corresponding integer type. This turns an f64 value into 8258 // i64, which can be passed with two i32 values on a 32-bit machine. 8259 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 8260 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 8261 if (OpInfo.Type == InlineAsm::isInput) 8262 OpInfo.CallOperand = 8263 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 8264 OpInfo.ConstraintVT = VT; 8265 } 8266 } 8267 } 8268 8269 // No need to allocate a matching input constraint since the constraint it's 8270 // matching to has already been allocated. 8271 if (OpInfo.isMatchingInputConstraint()) 8272 return; 8273 8274 EVT ValueVT = OpInfo.ConstraintVT; 8275 if (OpInfo.ConstraintVT == MVT::Other) 8276 ValueVT = RegVT; 8277 8278 // Initialize NumRegs. 8279 unsigned NumRegs = 1; 8280 if (OpInfo.ConstraintVT != MVT::Other) 8281 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 8282 8283 // If this is a constraint for a specific physical register, like {r17}, 8284 // assign it now. 8285 8286 // If this associated to a specific register, initialize iterator to correct 8287 // place. If virtual, make sure we have enough registers 8288 8289 // Initialize iterator if necessary 8290 TargetRegisterClass::iterator I = RC->begin(); 8291 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8292 8293 // Do not check for single registers. 8294 if (AssignedReg) { 8295 for (; *I != AssignedReg; ++I) 8296 assert(I != RC->end() && "AssignedReg should be member of RC"); 8297 } 8298 8299 for (; NumRegs; --NumRegs, ++I) { 8300 assert(I != RC->end() && "Ran out of registers to allocate!"); 8301 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8302 Regs.push_back(R); 8303 } 8304 8305 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8306 } 8307 8308 static unsigned 8309 findMatchingInlineAsmOperand(unsigned OperandNo, 8310 const std::vector<SDValue> &AsmNodeOperands) { 8311 // Scan until we find the definition we already emitted of this operand. 8312 unsigned CurOp = InlineAsm::Op_FirstOperand; 8313 for (; OperandNo; --OperandNo) { 8314 // Advance to the next operand. 8315 unsigned OpFlag = 8316 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8317 assert((InlineAsm::isRegDefKind(OpFlag) || 8318 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8319 InlineAsm::isMemKind(OpFlag)) && 8320 "Skipped past definitions?"); 8321 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8322 } 8323 return CurOp; 8324 } 8325 8326 namespace { 8327 8328 class ExtraFlags { 8329 unsigned Flags = 0; 8330 8331 public: 8332 explicit ExtraFlags(const CallBase &Call) { 8333 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8334 if (IA->hasSideEffects()) 8335 Flags |= InlineAsm::Extra_HasSideEffects; 8336 if (IA->isAlignStack()) 8337 Flags |= InlineAsm::Extra_IsAlignStack; 8338 if (Call.isConvergent()) 8339 Flags |= InlineAsm::Extra_IsConvergent; 8340 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8341 } 8342 8343 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8344 // Ideally, we would only check against memory constraints. However, the 8345 // meaning of an Other constraint can be target-specific and we can't easily 8346 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8347 // for Other constraints as well. 8348 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8349 OpInfo.ConstraintType == TargetLowering::C_Other) { 8350 if (OpInfo.Type == InlineAsm::isInput) 8351 Flags |= InlineAsm::Extra_MayLoad; 8352 else if (OpInfo.Type == InlineAsm::isOutput) 8353 Flags |= InlineAsm::Extra_MayStore; 8354 else if (OpInfo.Type == InlineAsm::isClobber) 8355 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8356 } 8357 } 8358 8359 unsigned get() const { return Flags; } 8360 }; 8361 8362 } // end anonymous namespace 8363 8364 /// visitInlineAsm - Handle a call to an InlineAsm object. 8365 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 8366 const BasicBlock *EHPadBB) { 8367 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8368 8369 /// ConstraintOperands - Information about all of the constraints. 8370 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 8371 8372 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8373 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8374 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 8375 8376 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8377 // AsmDialect, MayLoad, MayStore). 8378 bool HasSideEffect = IA->hasSideEffects(); 8379 ExtraFlags ExtraInfo(Call); 8380 8381 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 8382 unsigned ResNo = 0; // ResNo - The result number of the next output. 8383 unsigned NumMatchingOps = 0; 8384 for (auto &T : TargetConstraints) { 8385 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8386 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8387 8388 // Compute the value type for each operand. 8389 if (OpInfo.Type == InlineAsm::isInput || 8390 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 8391 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++); 8392 8393 // Process the call argument. BasicBlocks are labels, currently appearing 8394 // only in asm's. 8395 if (isa<CallBrInst>(Call) && 8396 ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() - 8397 cast<CallBrInst>(&Call)->getNumIndirectDests() - 8398 NumMatchingOps) && 8399 (NumMatchingOps == 0 || 8400 ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() - 8401 NumMatchingOps))) { 8402 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal); 8403 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true); 8404 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT); 8405 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 8406 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 8407 } else { 8408 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8409 } 8410 8411 EVT VT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, 8412 DAG.getDataLayout()); 8413 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other; 8414 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 8415 // The return value of the call is this value. As such, there is no 8416 // corresponding argument. 8417 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8418 if (StructType *STy = dyn_cast<StructType>(Call.getType())) { 8419 OpInfo.ConstraintVT = TLI.getSimpleValueType( 8420 DAG.getDataLayout(), STy->getElementType(ResNo)); 8421 } else { 8422 assert(ResNo == 0 && "Asm only has one result!"); 8423 OpInfo.ConstraintVT = 8424 TLI.getSimpleValueType(DAG.getDataLayout(), Call.getType()); 8425 } 8426 ++ResNo; 8427 } else { 8428 OpInfo.ConstraintVT = MVT::Other; 8429 } 8430 8431 if (OpInfo.hasMatchingInput()) 8432 ++NumMatchingOps; 8433 8434 if (!HasSideEffect) 8435 HasSideEffect = OpInfo.hasMemory(TLI); 8436 8437 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8438 // FIXME: Could we compute this on OpInfo rather than T? 8439 8440 // Compute the constraint code and ConstraintType to use. 8441 TLI.ComputeConstraintToUse(T, SDValue()); 8442 8443 if (T.ConstraintType == TargetLowering::C_Immediate && 8444 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8445 // We've delayed emitting a diagnostic like the "n" constraint because 8446 // inlining could cause an integer showing up. 8447 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 8448 "' expects an integer constant " 8449 "expression"); 8450 8451 ExtraInfo.update(T); 8452 } 8453 8454 // We won't need to flush pending loads if this asm doesn't touch 8455 // memory and is nonvolatile. 8456 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8457 8458 bool EmitEHLabels = isa<InvokeInst>(Call) && IA->canThrow(); 8459 if (EmitEHLabels) { 8460 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 8461 } 8462 bool IsCallBr = isa<CallBrInst>(Call); 8463 8464 if (IsCallBr || EmitEHLabels) { 8465 // If this is a callbr or invoke we need to flush pending exports since 8466 // inlineasm_br and invoke are terminators. 8467 // We need to do this before nodes are glued to the inlineasm_br node. 8468 Chain = getControlRoot(); 8469 } 8470 8471 MCSymbol *BeginLabel = nullptr; 8472 if (EmitEHLabels) { 8473 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 8474 } 8475 8476 // Second pass over the constraints: compute which constraint option to use. 8477 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8478 // If this is an output operand with a matching input operand, look up the 8479 // matching input. If their types mismatch, e.g. one is an integer, the 8480 // other is floating point, or their sizes are different, flag it as an 8481 // error. 8482 if (OpInfo.hasMatchingInput()) { 8483 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8484 patchMatchingInput(OpInfo, Input, DAG); 8485 } 8486 8487 // Compute the constraint code and ConstraintType to use. 8488 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8489 8490 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8491 OpInfo.Type == InlineAsm::isClobber) 8492 continue; 8493 8494 // If this is a memory input, and if the operand is not indirect, do what we 8495 // need to provide an address for the memory input. 8496 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8497 !OpInfo.isIndirect) { 8498 assert((OpInfo.isMultipleAlternative || 8499 (OpInfo.Type == InlineAsm::isInput)) && 8500 "Can only indirectify direct input operands!"); 8501 8502 // Memory operands really want the address of the value. 8503 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8504 8505 // There is no longer a Value* corresponding to this operand. 8506 OpInfo.CallOperandVal = nullptr; 8507 8508 // It is now an indirect operand. 8509 OpInfo.isIndirect = true; 8510 } 8511 8512 } 8513 8514 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8515 std::vector<SDValue> AsmNodeOperands; 8516 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8517 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8518 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 8519 8520 // If we have a !srcloc metadata node associated with it, we want to attach 8521 // this to the ultimately generated inline asm machineinstr. To do this, we 8522 // pass in the third operand as this (potentially null) inline asm MDNode. 8523 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 8524 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8525 8526 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8527 // bits as operand 3. 8528 AsmNodeOperands.push_back(DAG.getTargetConstant( 8529 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8530 8531 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8532 // this, assign virtual and physical registers for inputs and otput. 8533 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8534 // Assign Registers. 8535 SDISelAsmOperandInfo &RefOpInfo = 8536 OpInfo.isMatchingInputConstraint() 8537 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8538 : OpInfo; 8539 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8540 8541 auto DetectWriteToReservedRegister = [&]() { 8542 const MachineFunction &MF = DAG.getMachineFunction(); 8543 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8544 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 8545 if (Register::isPhysicalRegister(Reg) && 8546 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 8547 const char *RegName = TRI.getName(Reg); 8548 emitInlineAsmError(Call, "write to reserved register '" + 8549 Twine(RegName) + "'"); 8550 return true; 8551 } 8552 } 8553 return false; 8554 }; 8555 8556 switch (OpInfo.Type) { 8557 case InlineAsm::isOutput: 8558 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8559 unsigned ConstraintID = 8560 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8561 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8562 "Failed to convert memory constraint code to constraint id."); 8563 8564 // Add information to the INLINEASM node to know about this output. 8565 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8566 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8567 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8568 MVT::i32)); 8569 AsmNodeOperands.push_back(OpInfo.CallOperand); 8570 } else { 8571 // Otherwise, this outputs to a register (directly for C_Register / 8572 // C_RegisterClass, and a target-defined fashion for 8573 // C_Immediate/C_Other). Find a register that we can use. 8574 if (OpInfo.AssignedRegs.Regs.empty()) { 8575 emitInlineAsmError( 8576 Call, "couldn't allocate output register for constraint '" + 8577 Twine(OpInfo.ConstraintCode) + "'"); 8578 return; 8579 } 8580 8581 if (DetectWriteToReservedRegister()) 8582 return; 8583 8584 // Add information to the INLINEASM node to know that this register is 8585 // set. 8586 OpInfo.AssignedRegs.AddInlineAsmOperands( 8587 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8588 : InlineAsm::Kind_RegDef, 8589 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8590 } 8591 break; 8592 8593 case InlineAsm::isInput: { 8594 SDValue InOperandVal = OpInfo.CallOperand; 8595 8596 if (OpInfo.isMatchingInputConstraint()) { 8597 // If this is required to match an output register we have already set, 8598 // just use its register. 8599 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8600 AsmNodeOperands); 8601 unsigned OpFlag = 8602 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8603 if (InlineAsm::isRegDefKind(OpFlag) || 8604 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8605 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8606 if (OpInfo.isIndirect) { 8607 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8608 emitInlineAsmError(Call, "inline asm not supported yet: " 8609 "don't know how to handle tied " 8610 "indirect register inputs"); 8611 return; 8612 } 8613 8614 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 8615 SmallVector<unsigned, 4> Regs; 8616 8617 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { 8618 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8619 MachineRegisterInfo &RegInfo = 8620 DAG.getMachineFunction().getRegInfo(); 8621 for (unsigned i = 0; i != NumRegs; ++i) 8622 Regs.push_back(RegInfo.createVirtualRegister(RC)); 8623 } else { 8624 emitInlineAsmError(Call, 8625 "inline asm error: This value type register " 8626 "class is not natively supported!"); 8627 return; 8628 } 8629 8630 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8631 8632 SDLoc dl = getCurSDLoc(); 8633 // Use the produced MatchedRegs object to 8634 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call); 8635 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8636 true, OpInfo.getMatchedOperand(), dl, 8637 DAG, AsmNodeOperands); 8638 break; 8639 } 8640 8641 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8642 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8643 "Unexpected number of operands"); 8644 // Add information to the INLINEASM node to know about this input. 8645 // See InlineAsm.h isUseOperandTiedToDef. 8646 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8647 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8648 OpInfo.getMatchedOperand()); 8649 AsmNodeOperands.push_back(DAG.getTargetConstant( 8650 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8651 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8652 break; 8653 } 8654 8655 // Treat indirect 'X' constraint as memory. 8656 if (OpInfo.ConstraintType == TargetLowering::C_Other && 8657 OpInfo.isIndirect) 8658 OpInfo.ConstraintType = TargetLowering::C_Memory; 8659 8660 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 8661 OpInfo.ConstraintType == TargetLowering::C_Other) { 8662 std::vector<SDValue> Ops; 8663 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 8664 Ops, DAG); 8665 if (Ops.empty()) { 8666 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 8667 if (isa<ConstantSDNode>(InOperandVal)) { 8668 emitInlineAsmError(Call, "value out of range for constraint '" + 8669 Twine(OpInfo.ConstraintCode) + "'"); 8670 return; 8671 } 8672 8673 emitInlineAsmError(Call, 8674 "invalid operand for inline asm constraint '" + 8675 Twine(OpInfo.ConstraintCode) + "'"); 8676 return; 8677 } 8678 8679 // Add information to the INLINEASM node to know about this input. 8680 unsigned ResOpType = 8681 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 8682 AsmNodeOperands.push_back(DAG.getTargetConstant( 8683 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8684 llvm::append_range(AsmNodeOperands, Ops); 8685 break; 8686 } 8687 8688 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8689 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 8690 assert(InOperandVal.getValueType() == 8691 TLI.getPointerTy(DAG.getDataLayout()) && 8692 "Memory operands expect pointer values"); 8693 8694 unsigned ConstraintID = 8695 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8696 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8697 "Failed to convert memory constraint code to constraint id."); 8698 8699 // Add information to the INLINEASM node to know about this input. 8700 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8701 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 8702 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 8703 getCurSDLoc(), 8704 MVT::i32)); 8705 AsmNodeOperands.push_back(InOperandVal); 8706 break; 8707 } 8708 8709 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 8710 OpInfo.ConstraintType == TargetLowering::C_Register) && 8711 "Unknown constraint type!"); 8712 8713 // TODO: Support this. 8714 if (OpInfo.isIndirect) { 8715 emitInlineAsmError( 8716 Call, "Don't know how to handle indirect register inputs yet " 8717 "for constraint '" + 8718 Twine(OpInfo.ConstraintCode) + "'"); 8719 return; 8720 } 8721 8722 // Copy the input into the appropriate registers. 8723 if (OpInfo.AssignedRegs.Regs.empty()) { 8724 emitInlineAsmError(Call, 8725 "couldn't allocate input reg for constraint '" + 8726 Twine(OpInfo.ConstraintCode) + "'"); 8727 return; 8728 } 8729 8730 if (DetectWriteToReservedRegister()) 8731 return; 8732 8733 SDLoc dl = getCurSDLoc(); 8734 8735 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 8736 &Call); 8737 8738 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 8739 dl, DAG, AsmNodeOperands); 8740 break; 8741 } 8742 case InlineAsm::isClobber: 8743 // Add the clobbered value to the operand list, so that the register 8744 // allocator is aware that the physreg got clobbered. 8745 if (!OpInfo.AssignedRegs.Regs.empty()) 8746 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 8747 false, 0, getCurSDLoc(), DAG, 8748 AsmNodeOperands); 8749 break; 8750 } 8751 } 8752 8753 // Finish up input operands. Set the input chain and add the flag last. 8754 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 8755 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 8756 8757 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 8758 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 8759 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 8760 Flag = Chain.getValue(1); 8761 8762 // Do additional work to generate outputs. 8763 8764 SmallVector<EVT, 1> ResultVTs; 8765 SmallVector<SDValue, 1> ResultValues; 8766 SmallVector<SDValue, 8> OutChains; 8767 8768 llvm::Type *CallResultType = Call.getType(); 8769 ArrayRef<Type *> ResultTypes; 8770 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 8771 ResultTypes = StructResult->elements(); 8772 else if (!CallResultType->isVoidTy()) 8773 ResultTypes = makeArrayRef(CallResultType); 8774 8775 auto CurResultType = ResultTypes.begin(); 8776 auto handleRegAssign = [&](SDValue V) { 8777 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 8778 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 8779 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 8780 ++CurResultType; 8781 // If the type of the inline asm call site return value is different but has 8782 // same size as the type of the asm output bitcast it. One example of this 8783 // is for vectors with different width / number of elements. This can 8784 // happen for register classes that can contain multiple different value 8785 // types. The preg or vreg allocated may not have the same VT as was 8786 // expected. 8787 // 8788 // This can also happen for a return value that disagrees with the register 8789 // class it is put in, eg. a double in a general-purpose register on a 8790 // 32-bit machine. 8791 if (ResultVT != V.getValueType() && 8792 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 8793 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 8794 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 8795 V.getValueType().isInteger()) { 8796 // If a result value was tied to an input value, the computed result 8797 // may have a wider width than the expected result. Extract the 8798 // relevant portion. 8799 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 8800 } 8801 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 8802 ResultVTs.push_back(ResultVT); 8803 ResultValues.push_back(V); 8804 }; 8805 8806 // Deal with output operands. 8807 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8808 if (OpInfo.Type == InlineAsm::isOutput) { 8809 SDValue Val; 8810 // Skip trivial output operands. 8811 if (OpInfo.AssignedRegs.Regs.empty()) 8812 continue; 8813 8814 switch (OpInfo.ConstraintType) { 8815 case TargetLowering::C_Register: 8816 case TargetLowering::C_RegisterClass: 8817 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 8818 Chain, &Flag, &Call); 8819 break; 8820 case TargetLowering::C_Immediate: 8821 case TargetLowering::C_Other: 8822 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 8823 OpInfo, DAG); 8824 break; 8825 case TargetLowering::C_Memory: 8826 break; // Already handled. 8827 case TargetLowering::C_Unknown: 8828 assert(false && "Unexpected unknown constraint"); 8829 } 8830 8831 // Indirect output manifest as stores. Record output chains. 8832 if (OpInfo.isIndirect) { 8833 const Value *Ptr = OpInfo.CallOperandVal; 8834 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 8835 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 8836 MachinePointerInfo(Ptr)); 8837 OutChains.push_back(Store); 8838 } else { 8839 // generate CopyFromRegs to associated registers. 8840 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8841 if (Val.getOpcode() == ISD::MERGE_VALUES) { 8842 for (const SDValue &V : Val->op_values()) 8843 handleRegAssign(V); 8844 } else 8845 handleRegAssign(Val); 8846 } 8847 } 8848 } 8849 8850 // Set results. 8851 if (!ResultValues.empty()) { 8852 assert(CurResultType == ResultTypes.end() && 8853 "Mismatch in number of ResultTypes"); 8854 assert(ResultValues.size() == ResultTypes.size() && 8855 "Mismatch in number of output operands in asm result"); 8856 8857 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 8858 DAG.getVTList(ResultVTs), ResultValues); 8859 setValue(&Call, V); 8860 } 8861 8862 // Collect store chains. 8863 if (!OutChains.empty()) 8864 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 8865 8866 if (EmitEHLabels) { 8867 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 8868 } 8869 8870 // Only Update Root if inline assembly has a memory effect. 8871 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 8872 EmitEHLabels) 8873 DAG.setRoot(Chain); 8874 } 8875 8876 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 8877 const Twine &Message) { 8878 LLVMContext &Ctx = *DAG.getContext(); 8879 Ctx.emitError(&Call, Message); 8880 8881 // Make sure we leave the DAG in a valid state 8882 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8883 SmallVector<EVT, 1> ValueVTs; 8884 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 8885 8886 if (ValueVTs.empty()) 8887 return; 8888 8889 SmallVector<SDValue, 1> Ops; 8890 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 8891 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 8892 8893 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 8894 } 8895 8896 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 8897 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 8898 MVT::Other, getRoot(), 8899 getValue(I.getArgOperand(0)), 8900 DAG.getSrcValue(I.getArgOperand(0)))); 8901 } 8902 8903 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 8904 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8905 const DataLayout &DL = DAG.getDataLayout(); 8906 SDValue V = DAG.getVAArg( 8907 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 8908 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 8909 DL.getABITypeAlign(I.getType()).value()); 8910 DAG.setRoot(V.getValue(1)); 8911 8912 if (I.getType()->isPointerTy()) 8913 V = DAG.getPtrExtOrTrunc( 8914 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 8915 setValue(&I, V); 8916 } 8917 8918 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 8919 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 8920 MVT::Other, getRoot(), 8921 getValue(I.getArgOperand(0)), 8922 DAG.getSrcValue(I.getArgOperand(0)))); 8923 } 8924 8925 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 8926 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 8927 MVT::Other, getRoot(), 8928 getValue(I.getArgOperand(0)), 8929 getValue(I.getArgOperand(1)), 8930 DAG.getSrcValue(I.getArgOperand(0)), 8931 DAG.getSrcValue(I.getArgOperand(1)))); 8932 } 8933 8934 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 8935 const Instruction &I, 8936 SDValue Op) { 8937 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 8938 if (!Range) 8939 return Op; 8940 8941 ConstantRange CR = getConstantRangeFromMetadata(*Range); 8942 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 8943 return Op; 8944 8945 APInt Lo = CR.getUnsignedMin(); 8946 if (!Lo.isMinValue()) 8947 return Op; 8948 8949 APInt Hi = CR.getUnsignedMax(); 8950 unsigned Bits = std::max(Hi.getActiveBits(), 8951 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 8952 8953 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8954 8955 SDLoc SL = getCurSDLoc(); 8956 8957 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8958 DAG.getValueType(SmallVT)); 8959 unsigned NumVals = Op.getNode()->getNumValues(); 8960 if (NumVals == 1) 8961 return ZExt; 8962 8963 SmallVector<SDValue, 4> Ops; 8964 8965 Ops.push_back(ZExt); 8966 for (unsigned I = 1; I != NumVals; ++I) 8967 Ops.push_back(Op.getValue(I)); 8968 8969 return DAG.getMergeValues(Ops, SL); 8970 } 8971 8972 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8973 /// the call being lowered. 8974 /// 8975 /// This is a helper for lowering intrinsics that follow a target calling 8976 /// convention or require stack pointer adjustment. Only a subset of the 8977 /// intrinsic's operands need to participate in the calling convention. 8978 void SelectionDAGBuilder::populateCallLoweringInfo( 8979 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 8980 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8981 bool IsPatchPoint) { 8982 TargetLowering::ArgListTy Args; 8983 Args.reserve(NumArgs); 8984 8985 // Populate the argument list. 8986 // Attributes for args start at offset 1, after the return attribute. 8987 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8988 ArgI != ArgE; ++ArgI) { 8989 const Value *V = Call->getOperand(ArgI); 8990 8991 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 8992 8993 TargetLowering::ArgListEntry Entry; 8994 Entry.Node = getValue(V); 8995 Entry.Ty = V->getType(); 8996 Entry.setAttributes(Call, ArgI); 8997 Args.push_back(Entry); 8998 } 8999 9000 CLI.setDebugLoc(getCurSDLoc()) 9001 .setChain(getRoot()) 9002 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 9003 .setDiscardResult(Call->use_empty()) 9004 .setIsPatchPoint(IsPatchPoint) 9005 .setIsPreallocated( 9006 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 9007 } 9008 9009 /// Add a stack map intrinsic call's live variable operands to a stackmap 9010 /// or patchpoint target node's operand list. 9011 /// 9012 /// Constants are converted to TargetConstants purely as an optimization to 9013 /// avoid constant materialization and register allocation. 9014 /// 9015 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 9016 /// generate addess computation nodes, and so FinalizeISel can convert the 9017 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 9018 /// address materialization and register allocation, but may also be required 9019 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 9020 /// alloca in the entry block, then the runtime may assume that the alloca's 9021 /// StackMap location can be read immediately after compilation and that the 9022 /// location is valid at any point during execution (this is similar to the 9023 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 9024 /// only available in a register, then the runtime would need to trap when 9025 /// execution reaches the StackMap in order to read the alloca's location. 9026 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 9027 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 9028 SelectionDAGBuilder &Builder) { 9029 for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) { 9030 SDValue OpVal = Builder.getValue(Call.getArgOperand(i)); 9031 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 9032 Ops.push_back( 9033 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 9034 Ops.push_back( 9035 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 9036 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 9037 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 9038 Ops.push_back(Builder.DAG.getTargetFrameIndex( 9039 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 9040 } else 9041 Ops.push_back(OpVal); 9042 } 9043 } 9044 9045 /// Lower llvm.experimental.stackmap directly to its target opcode. 9046 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 9047 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 9048 // [live variables...]) 9049 9050 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 9051 9052 SDValue Chain, InFlag, Callee, NullPtr; 9053 SmallVector<SDValue, 32> Ops; 9054 9055 SDLoc DL = getCurSDLoc(); 9056 Callee = getValue(CI.getCalledOperand()); 9057 NullPtr = DAG.getIntPtrConstant(0, DL, true); 9058 9059 // The stackmap intrinsic only records the live variables (the arguments 9060 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 9061 // intrinsic, this won't be lowered to a function call. This means we don't 9062 // have to worry about calling conventions and target specific lowering code. 9063 // Instead we perform the call lowering right here. 9064 // 9065 // chain, flag = CALLSEQ_START(chain, 0, 0) 9066 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 9067 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 9068 // 9069 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 9070 InFlag = Chain.getValue(1); 9071 9072 // Add the <id> and <numBytes> constants. 9073 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 9074 Ops.push_back(DAG.getTargetConstant( 9075 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 9076 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 9077 Ops.push_back(DAG.getTargetConstant( 9078 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 9079 MVT::i32)); 9080 9081 // Push live variables for the stack map. 9082 addStackMapLiveVars(CI, 2, DL, Ops, *this); 9083 9084 // We are not pushing any register mask info here on the operands list, 9085 // because the stackmap doesn't clobber anything. 9086 9087 // Push the chain and the glue flag. 9088 Ops.push_back(Chain); 9089 Ops.push_back(InFlag); 9090 9091 // Create the STACKMAP node. 9092 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9093 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 9094 Chain = SDValue(SM, 0); 9095 InFlag = Chain.getValue(1); 9096 9097 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 9098 9099 // Stackmaps don't generate values, so nothing goes into the NodeMap. 9100 9101 // Set the root to the target-lowered call chain. 9102 DAG.setRoot(Chain); 9103 9104 // Inform the Frame Information that we have a stackmap in this function. 9105 FuncInfo.MF->getFrameInfo().setHasStackMap(); 9106 } 9107 9108 /// Lower llvm.experimental.patchpoint directly to its target opcode. 9109 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 9110 const BasicBlock *EHPadBB) { 9111 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 9112 // i32 <numBytes>, 9113 // i8* <target>, 9114 // i32 <numArgs>, 9115 // [Args...], 9116 // [live variables...]) 9117 9118 CallingConv::ID CC = CB.getCallingConv(); 9119 bool IsAnyRegCC = CC == CallingConv::AnyReg; 9120 bool HasDef = !CB.getType()->isVoidTy(); 9121 SDLoc dl = getCurSDLoc(); 9122 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 9123 9124 // Handle immediate and symbolic callees. 9125 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 9126 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 9127 /*isTarget=*/true); 9128 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 9129 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 9130 SDLoc(SymbolicCallee), 9131 SymbolicCallee->getValueType(0)); 9132 9133 // Get the real number of arguments participating in the call <numArgs> 9134 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 9135 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 9136 9137 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 9138 // Intrinsics include all meta-operands up to but not including CC. 9139 unsigned NumMetaOpers = PatchPointOpers::CCPos; 9140 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 9141 "Not enough arguments provided to the patchpoint intrinsic"); 9142 9143 // For AnyRegCC the arguments are lowered later on manually. 9144 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 9145 Type *ReturnTy = 9146 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 9147 9148 TargetLowering::CallLoweringInfo CLI(DAG); 9149 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 9150 ReturnTy, true); 9151 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 9152 9153 SDNode *CallEnd = Result.second.getNode(); 9154 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 9155 CallEnd = CallEnd->getOperand(0).getNode(); 9156 9157 /// Get a call instruction from the call sequence chain. 9158 /// Tail calls are not allowed. 9159 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 9160 "Expected a callseq node."); 9161 SDNode *Call = CallEnd->getOperand(0).getNode(); 9162 bool HasGlue = Call->getGluedNode(); 9163 9164 // Replace the target specific call node with the patchable intrinsic. 9165 SmallVector<SDValue, 8> Ops; 9166 9167 // Add the <id> and <numBytes> constants. 9168 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 9169 Ops.push_back(DAG.getTargetConstant( 9170 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 9171 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 9172 Ops.push_back(DAG.getTargetConstant( 9173 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 9174 MVT::i32)); 9175 9176 // Add the callee. 9177 Ops.push_back(Callee); 9178 9179 // Adjust <numArgs> to account for any arguments that have been passed on the 9180 // stack instead. 9181 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 9182 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 9183 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 9184 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 9185 9186 // Add the calling convention 9187 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 9188 9189 // Add the arguments we omitted previously. The register allocator should 9190 // place these in any free register. 9191 if (IsAnyRegCC) 9192 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 9193 Ops.push_back(getValue(CB.getArgOperand(i))); 9194 9195 // Push the arguments from the call instruction up to the register mask. 9196 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 9197 Ops.append(Call->op_begin() + 2, e); 9198 9199 // Push live variables for the stack map. 9200 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 9201 9202 // Push the register mask info. 9203 if (HasGlue) 9204 Ops.push_back(*(Call->op_end()-2)); 9205 else 9206 Ops.push_back(*(Call->op_end()-1)); 9207 9208 // Push the chain (this is originally the first operand of the call, but 9209 // becomes now the last or second to last operand). 9210 Ops.push_back(*(Call->op_begin())); 9211 9212 // Push the glue flag (last operand). 9213 if (HasGlue) 9214 Ops.push_back(*(Call->op_end()-1)); 9215 9216 SDVTList NodeTys; 9217 if (IsAnyRegCC && HasDef) { 9218 // Create the return types based on the intrinsic definition 9219 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9220 SmallVector<EVT, 3> ValueVTs; 9221 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 9222 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 9223 9224 // There is always a chain and a glue type at the end 9225 ValueVTs.push_back(MVT::Other); 9226 ValueVTs.push_back(MVT::Glue); 9227 NodeTys = DAG.getVTList(ValueVTs); 9228 } else 9229 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9230 9231 // Replace the target specific call node with a PATCHPOINT node. 9232 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 9233 dl, NodeTys, Ops); 9234 9235 // Update the NodeMap. 9236 if (HasDef) { 9237 if (IsAnyRegCC) 9238 setValue(&CB, SDValue(MN, 0)); 9239 else 9240 setValue(&CB, Result.first); 9241 } 9242 9243 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 9244 // call sequence. Furthermore the location of the chain and glue can change 9245 // when the AnyReg calling convention is used and the intrinsic returns a 9246 // value. 9247 if (IsAnyRegCC && HasDef) { 9248 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 9249 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 9250 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 9251 } else 9252 DAG.ReplaceAllUsesWith(Call, MN); 9253 DAG.DeleteNode(Call); 9254 9255 // Inform the Frame Information that we have a patchpoint in this function. 9256 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 9257 } 9258 9259 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 9260 unsigned Intrinsic) { 9261 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9262 SDValue Op1 = getValue(I.getArgOperand(0)); 9263 SDValue Op2; 9264 if (I.getNumArgOperands() > 1) 9265 Op2 = getValue(I.getArgOperand(1)); 9266 SDLoc dl = getCurSDLoc(); 9267 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 9268 SDValue Res; 9269 SDNodeFlags SDFlags; 9270 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 9271 SDFlags.copyFMF(*FPMO); 9272 9273 switch (Intrinsic) { 9274 case Intrinsic::vector_reduce_fadd: 9275 if (SDFlags.hasAllowReassociation()) 9276 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 9277 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 9278 SDFlags); 9279 else 9280 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 9281 break; 9282 case Intrinsic::vector_reduce_fmul: 9283 if (SDFlags.hasAllowReassociation()) 9284 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 9285 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 9286 SDFlags); 9287 else 9288 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 9289 break; 9290 case Intrinsic::vector_reduce_add: 9291 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 9292 break; 9293 case Intrinsic::vector_reduce_mul: 9294 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 9295 break; 9296 case Intrinsic::vector_reduce_and: 9297 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 9298 break; 9299 case Intrinsic::vector_reduce_or: 9300 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 9301 break; 9302 case Intrinsic::vector_reduce_xor: 9303 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 9304 break; 9305 case Intrinsic::vector_reduce_smax: 9306 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 9307 break; 9308 case Intrinsic::vector_reduce_smin: 9309 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 9310 break; 9311 case Intrinsic::vector_reduce_umax: 9312 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 9313 break; 9314 case Intrinsic::vector_reduce_umin: 9315 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 9316 break; 9317 case Intrinsic::vector_reduce_fmax: 9318 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 9319 break; 9320 case Intrinsic::vector_reduce_fmin: 9321 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 9322 break; 9323 default: 9324 llvm_unreachable("Unhandled vector reduce intrinsic"); 9325 } 9326 setValue(&I, Res); 9327 } 9328 9329 /// Returns an AttributeList representing the attributes applied to the return 9330 /// value of the given call. 9331 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9332 SmallVector<Attribute::AttrKind, 2> Attrs; 9333 if (CLI.RetSExt) 9334 Attrs.push_back(Attribute::SExt); 9335 if (CLI.RetZExt) 9336 Attrs.push_back(Attribute::ZExt); 9337 if (CLI.IsInReg) 9338 Attrs.push_back(Attribute::InReg); 9339 9340 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9341 Attrs); 9342 } 9343 9344 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9345 /// implementation, which just calls LowerCall. 9346 /// FIXME: When all targets are 9347 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9348 std::pair<SDValue, SDValue> 9349 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9350 // Handle the incoming return values from the call. 9351 CLI.Ins.clear(); 9352 Type *OrigRetTy = CLI.RetTy; 9353 SmallVector<EVT, 4> RetTys; 9354 SmallVector<uint64_t, 4> Offsets; 9355 auto &DL = CLI.DAG.getDataLayout(); 9356 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 9357 9358 if (CLI.IsPostTypeLegalization) { 9359 // If we are lowering a libcall after legalization, split the return type. 9360 SmallVector<EVT, 4> OldRetTys; 9361 SmallVector<uint64_t, 4> OldOffsets; 9362 RetTys.swap(OldRetTys); 9363 Offsets.swap(OldOffsets); 9364 9365 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9366 EVT RetVT = OldRetTys[i]; 9367 uint64_t Offset = OldOffsets[i]; 9368 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9369 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9370 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9371 RetTys.append(NumRegs, RegisterVT); 9372 for (unsigned j = 0; j != NumRegs; ++j) 9373 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9374 } 9375 } 9376 9377 SmallVector<ISD::OutputArg, 4> Outs; 9378 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9379 9380 bool CanLowerReturn = 9381 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9382 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9383 9384 SDValue DemoteStackSlot; 9385 int DemoteStackIdx = -100; 9386 if (!CanLowerReturn) { 9387 // FIXME: equivalent assert? 9388 // assert(!CS.hasInAllocaArgument() && 9389 // "sret demotion is incompatible with inalloca"); 9390 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9391 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 9392 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9393 DemoteStackIdx = 9394 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 9395 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9396 DL.getAllocaAddrSpace()); 9397 9398 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9399 ArgListEntry Entry; 9400 Entry.Node = DemoteStackSlot; 9401 Entry.Ty = StackSlotPtrType; 9402 Entry.IsSExt = false; 9403 Entry.IsZExt = false; 9404 Entry.IsInReg = false; 9405 Entry.IsSRet = true; 9406 Entry.IsNest = false; 9407 Entry.IsByVal = false; 9408 Entry.IsByRef = false; 9409 Entry.IsReturned = false; 9410 Entry.IsSwiftSelf = false; 9411 Entry.IsSwiftAsync = false; 9412 Entry.IsSwiftError = false; 9413 Entry.IsCFGuardTarget = false; 9414 Entry.Alignment = Alignment; 9415 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9416 CLI.NumFixedArgs += 1; 9417 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9418 9419 // sret demotion isn't compatible with tail-calls, since the sret argument 9420 // points into the callers stack frame. 9421 CLI.IsTailCall = false; 9422 } else { 9423 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9424 CLI.RetTy, CLI.CallConv, CLI.IsVarArg); 9425 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9426 ISD::ArgFlagsTy Flags; 9427 if (NeedsRegBlock) { 9428 Flags.setInConsecutiveRegs(); 9429 if (I == RetTys.size() - 1) 9430 Flags.setInConsecutiveRegsLast(); 9431 } 9432 EVT VT = RetTys[I]; 9433 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9434 CLI.CallConv, VT); 9435 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9436 CLI.CallConv, VT); 9437 for (unsigned i = 0; i != NumRegs; ++i) { 9438 ISD::InputArg MyFlags; 9439 MyFlags.Flags = Flags; 9440 MyFlags.VT = RegisterVT; 9441 MyFlags.ArgVT = VT; 9442 MyFlags.Used = CLI.IsReturnValueUsed; 9443 if (CLI.RetTy->isPointerTy()) { 9444 MyFlags.Flags.setPointer(); 9445 MyFlags.Flags.setPointerAddrSpace( 9446 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9447 } 9448 if (CLI.RetSExt) 9449 MyFlags.Flags.setSExt(); 9450 if (CLI.RetZExt) 9451 MyFlags.Flags.setZExt(); 9452 if (CLI.IsInReg) 9453 MyFlags.Flags.setInReg(); 9454 CLI.Ins.push_back(MyFlags); 9455 } 9456 } 9457 } 9458 9459 // We push in swifterror return as the last element of CLI.Ins. 9460 ArgListTy &Args = CLI.getArgs(); 9461 if (supportSwiftError()) { 9462 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9463 if (Args[i].IsSwiftError) { 9464 ISD::InputArg MyFlags; 9465 MyFlags.VT = getPointerTy(DL); 9466 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9467 MyFlags.Flags.setSwiftError(); 9468 CLI.Ins.push_back(MyFlags); 9469 } 9470 } 9471 } 9472 9473 // Handle all of the outgoing arguments. 9474 CLI.Outs.clear(); 9475 CLI.OutVals.clear(); 9476 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9477 SmallVector<EVT, 4> ValueVTs; 9478 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9479 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9480 Type *FinalType = Args[i].Ty; 9481 if (Args[i].IsByVal) 9482 FinalType = Args[i].IndirectType; 9483 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9484 FinalType, CLI.CallConv, CLI.IsVarArg); 9485 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9486 ++Value) { 9487 EVT VT = ValueVTs[Value]; 9488 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9489 SDValue Op = SDValue(Args[i].Node.getNode(), 9490 Args[i].Node.getResNo() + Value); 9491 ISD::ArgFlagsTy Flags; 9492 9493 // Certain targets (such as MIPS), may have a different ABI alignment 9494 // for a type depending on the context. Give the target a chance to 9495 // specify the alignment it wants. 9496 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 9497 Flags.setOrigAlign(OriginalAlignment); 9498 9499 if (Args[i].Ty->isPointerTy()) { 9500 Flags.setPointer(); 9501 Flags.setPointerAddrSpace( 9502 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9503 } 9504 if (Args[i].IsZExt) 9505 Flags.setZExt(); 9506 if (Args[i].IsSExt) 9507 Flags.setSExt(); 9508 if (Args[i].IsInReg) { 9509 // If we are using vectorcall calling convention, a structure that is 9510 // passed InReg - is surely an HVA 9511 if (CLI.CallConv == CallingConv::X86_VectorCall && 9512 isa<StructType>(FinalType)) { 9513 // The first value of a structure is marked 9514 if (0 == Value) 9515 Flags.setHvaStart(); 9516 Flags.setHva(); 9517 } 9518 // Set InReg Flag 9519 Flags.setInReg(); 9520 } 9521 if (Args[i].IsSRet) 9522 Flags.setSRet(); 9523 if (Args[i].IsSwiftSelf) 9524 Flags.setSwiftSelf(); 9525 if (Args[i].IsSwiftAsync) 9526 Flags.setSwiftAsync(); 9527 if (Args[i].IsSwiftError) 9528 Flags.setSwiftError(); 9529 if (Args[i].IsCFGuardTarget) 9530 Flags.setCFGuardTarget(); 9531 if (Args[i].IsByVal) 9532 Flags.setByVal(); 9533 if (Args[i].IsByRef) 9534 Flags.setByRef(); 9535 if (Args[i].IsPreallocated) { 9536 Flags.setPreallocated(); 9537 // Set the byval flag for CCAssignFn callbacks that don't know about 9538 // preallocated. This way we can know how many bytes we should've 9539 // allocated and how many bytes a callee cleanup function will pop. If 9540 // we port preallocated to more targets, we'll have to add custom 9541 // preallocated handling in the various CC lowering callbacks. 9542 Flags.setByVal(); 9543 } 9544 if (Args[i].IsInAlloca) { 9545 Flags.setInAlloca(); 9546 // Set the byval flag for CCAssignFn callbacks that don't know about 9547 // inalloca. This way we can know how many bytes we should've allocated 9548 // and how many bytes a callee cleanup function will pop. If we port 9549 // inalloca to more targets, we'll have to add custom inalloca handling 9550 // in the various CC lowering callbacks. 9551 Flags.setByVal(); 9552 } 9553 Align MemAlign; 9554 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 9555 Type *ElementTy = Args[i].IndirectType; 9556 assert(ElementTy && "Indirect type not set in ArgListEntry"); 9557 9558 unsigned FrameSize = DL.getTypeAllocSize(ElementTy); 9559 Flags.setByValSize(FrameSize); 9560 9561 // info is not there but there are cases it cannot get right. 9562 if (auto MA = Args[i].Alignment) 9563 MemAlign = *MA; 9564 else 9565 MemAlign = Align(getByValTypeAlignment(ElementTy, DL)); 9566 } else if (auto MA = Args[i].Alignment) { 9567 MemAlign = *MA; 9568 } else { 9569 MemAlign = OriginalAlignment; 9570 } 9571 Flags.setMemAlign(MemAlign); 9572 if (Args[i].IsNest) 9573 Flags.setNest(); 9574 if (NeedsRegBlock) 9575 Flags.setInConsecutiveRegs(); 9576 9577 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9578 CLI.CallConv, VT); 9579 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9580 CLI.CallConv, VT); 9581 SmallVector<SDValue, 4> Parts(NumParts); 9582 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9583 9584 if (Args[i].IsSExt) 9585 ExtendKind = ISD::SIGN_EXTEND; 9586 else if (Args[i].IsZExt) 9587 ExtendKind = ISD::ZERO_EXTEND; 9588 9589 // Conservatively only handle 'returned' on non-vectors that can be lowered, 9590 // for now. 9591 if (Args[i].IsReturned && !Op.getValueType().isVector() && 9592 CanLowerReturn) { 9593 assert((CLI.RetTy == Args[i].Ty || 9594 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 9595 CLI.RetTy->getPointerAddressSpace() == 9596 Args[i].Ty->getPointerAddressSpace())) && 9597 RetTys.size() == NumValues && "unexpected use of 'returned'"); 9598 // Before passing 'returned' to the target lowering code, ensure that 9599 // either the register MVT and the actual EVT are the same size or that 9600 // the return value and argument are extended in the same way; in these 9601 // cases it's safe to pass the argument register value unchanged as the 9602 // return register value (although it's at the target's option whether 9603 // to do so) 9604 // TODO: allow code generation to take advantage of partially preserved 9605 // registers rather than clobbering the entire register when the 9606 // parameter extension method is not compatible with the return 9607 // extension method 9608 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9609 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9610 CLI.RetZExt == Args[i].IsZExt)) 9611 Flags.setReturned(); 9612 } 9613 9614 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 9615 CLI.CallConv, ExtendKind); 9616 9617 for (unsigned j = 0; j != NumParts; ++j) { 9618 // if it isn't first piece, alignment must be 1 9619 // For scalable vectors the scalable part is currently handled 9620 // by individual targets, so we just use the known minimum size here. 9621 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 9622 i < CLI.NumFixedArgs, i, 9623 j*Parts[j].getValueType().getStoreSize().getKnownMinSize()); 9624 if (NumParts > 1 && j == 0) 9625 MyFlags.Flags.setSplit(); 9626 else if (j != 0) { 9627 MyFlags.Flags.setOrigAlign(Align(1)); 9628 if (j == NumParts - 1) 9629 MyFlags.Flags.setSplitEnd(); 9630 } 9631 9632 CLI.Outs.push_back(MyFlags); 9633 CLI.OutVals.push_back(Parts[j]); 9634 } 9635 9636 if (NeedsRegBlock && Value == NumValues - 1) 9637 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 9638 } 9639 } 9640 9641 SmallVector<SDValue, 4> InVals; 9642 CLI.Chain = LowerCall(CLI, InVals); 9643 9644 // Update CLI.InVals to use outside of this function. 9645 CLI.InVals = InVals; 9646 9647 // Verify that the target's LowerCall behaved as expected. 9648 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 9649 "LowerCall didn't return a valid chain!"); 9650 assert((!CLI.IsTailCall || InVals.empty()) && 9651 "LowerCall emitted a return value for a tail call!"); 9652 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9653 "LowerCall didn't emit the correct number of values!"); 9654 9655 // For a tail call, the return value is merely live-out and there aren't 9656 // any nodes in the DAG representing it. Return a special value to 9657 // indicate that a tail call has been emitted and no more Instructions 9658 // should be processed in the current block. 9659 if (CLI.IsTailCall) { 9660 CLI.DAG.setRoot(CLI.Chain); 9661 return std::make_pair(SDValue(), SDValue()); 9662 } 9663 9664 #ifndef NDEBUG 9665 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 9666 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 9667 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 9668 "LowerCall emitted a value with the wrong type!"); 9669 } 9670 #endif 9671 9672 SmallVector<SDValue, 4> ReturnValues; 9673 if (!CanLowerReturn) { 9674 // The instruction result is the result of loading from the 9675 // hidden sret parameter. 9676 SmallVector<EVT, 1> PVTs; 9677 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 9678 9679 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 9680 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 9681 EVT PtrVT = PVTs[0]; 9682 9683 unsigned NumValues = RetTys.size(); 9684 ReturnValues.resize(NumValues); 9685 SmallVector<SDValue, 4> Chains(NumValues); 9686 9687 // An aggregate return value cannot wrap around the address space, so 9688 // offsets to its parts don't wrap either. 9689 SDNodeFlags Flags; 9690 Flags.setNoUnsignedWrap(true); 9691 9692 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9693 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 9694 for (unsigned i = 0; i < NumValues; ++i) { 9695 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 9696 CLI.DAG.getConstant(Offsets[i], CLI.DL, 9697 PtrVT), Flags); 9698 SDValue L = CLI.DAG.getLoad( 9699 RetTys[i], CLI.DL, CLI.Chain, Add, 9700 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 9701 DemoteStackIdx, Offsets[i]), 9702 HiddenSRetAlign); 9703 ReturnValues[i] = L; 9704 Chains[i] = L.getValue(1); 9705 } 9706 9707 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 9708 } else { 9709 // Collect the legal value parts into potentially illegal values 9710 // that correspond to the original function's return values. 9711 Optional<ISD::NodeType> AssertOp; 9712 if (CLI.RetSExt) 9713 AssertOp = ISD::AssertSext; 9714 else if (CLI.RetZExt) 9715 AssertOp = ISD::AssertZext; 9716 unsigned CurReg = 0; 9717 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9718 EVT VT = RetTys[I]; 9719 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9720 CLI.CallConv, VT); 9721 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9722 CLI.CallConv, VT); 9723 9724 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 9725 NumRegs, RegisterVT, VT, nullptr, 9726 CLI.CallConv, AssertOp)); 9727 CurReg += NumRegs; 9728 } 9729 9730 // For a function returning void, there is no return value. We can't create 9731 // such a node, so we just return a null return value in that case. In 9732 // that case, nothing will actually look at the value. 9733 if (ReturnValues.empty()) 9734 return std::make_pair(SDValue(), CLI.Chain); 9735 } 9736 9737 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 9738 CLI.DAG.getVTList(RetTys), ReturnValues); 9739 return std::make_pair(Res, CLI.Chain); 9740 } 9741 9742 /// Places new result values for the node in Results (their number 9743 /// and types must exactly match those of the original return values of 9744 /// the node), or leaves Results empty, which indicates that the node is not 9745 /// to be custom lowered after all. 9746 void TargetLowering::LowerOperationWrapper(SDNode *N, 9747 SmallVectorImpl<SDValue> &Results, 9748 SelectionDAG &DAG) const { 9749 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 9750 9751 if (!Res.getNode()) 9752 return; 9753 9754 // If the original node has one result, take the return value from 9755 // LowerOperation as is. It might not be result number 0. 9756 if (N->getNumValues() == 1) { 9757 Results.push_back(Res); 9758 return; 9759 } 9760 9761 // If the original node has multiple results, then the return node should 9762 // have the same number of results. 9763 assert((N->getNumValues() == Res->getNumValues()) && 9764 "Lowering returned the wrong number of results!"); 9765 9766 // Places new result values base on N result number. 9767 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 9768 Results.push_back(Res.getValue(I)); 9769 } 9770 9771 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9772 llvm_unreachable("LowerOperation not implemented for this target!"); 9773 } 9774 9775 void 9776 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 9777 SDValue Op = getNonRegisterValue(V); 9778 assert((Op.getOpcode() != ISD::CopyFromReg || 9779 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 9780 "Copy from a reg to the same reg!"); 9781 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 9782 9783 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9784 // If this is an InlineAsm we have to match the registers required, not the 9785 // notional registers required by the type. 9786 9787 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 9788 None); // This is not an ABI copy. 9789 SDValue Chain = DAG.getEntryNode(); 9790 9791 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 9792 FuncInfo.PreferredExtendType.end()) 9793 ? ISD::ANY_EXTEND 9794 : FuncInfo.PreferredExtendType[V]; 9795 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 9796 PendingExports.push_back(Chain); 9797 } 9798 9799 #include "llvm/CodeGen/SelectionDAGISel.h" 9800 9801 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 9802 /// entry block, return true. This includes arguments used by switches, since 9803 /// the switch may expand into multiple basic blocks. 9804 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 9805 // With FastISel active, we may be splitting blocks, so force creation 9806 // of virtual registers for all non-dead arguments. 9807 if (FastISel) 9808 return A->use_empty(); 9809 9810 const BasicBlock &Entry = A->getParent()->front(); 9811 for (const User *U : A->users()) 9812 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 9813 return false; // Use not in entry block. 9814 9815 return true; 9816 } 9817 9818 using ArgCopyElisionMapTy = 9819 DenseMap<const Argument *, 9820 std::pair<const AllocaInst *, const StoreInst *>>; 9821 9822 /// Scan the entry block of the function in FuncInfo for arguments that look 9823 /// like copies into a local alloca. Record any copied arguments in 9824 /// ArgCopyElisionCandidates. 9825 static void 9826 findArgumentCopyElisionCandidates(const DataLayout &DL, 9827 FunctionLoweringInfo *FuncInfo, 9828 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 9829 // Record the state of every static alloca used in the entry block. Argument 9830 // allocas are all used in the entry block, so we need approximately as many 9831 // entries as we have arguments. 9832 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 9833 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 9834 unsigned NumArgs = FuncInfo->Fn->arg_size(); 9835 StaticAllocas.reserve(NumArgs * 2); 9836 9837 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 9838 if (!V) 9839 return nullptr; 9840 V = V->stripPointerCasts(); 9841 const auto *AI = dyn_cast<AllocaInst>(V); 9842 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 9843 return nullptr; 9844 auto Iter = StaticAllocas.insert({AI, Unknown}); 9845 return &Iter.first->second; 9846 }; 9847 9848 // Look for stores of arguments to static allocas. Look through bitcasts and 9849 // GEPs to handle type coercions, as long as the alloca is fully initialized 9850 // by the store. Any non-store use of an alloca escapes it and any subsequent 9851 // unanalyzed store might write it. 9852 // FIXME: Handle structs initialized with multiple stores. 9853 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 9854 // Look for stores, and handle non-store uses conservatively. 9855 const auto *SI = dyn_cast<StoreInst>(&I); 9856 if (!SI) { 9857 // We will look through cast uses, so ignore them completely. 9858 if (I.isCast()) 9859 continue; 9860 // Ignore debug info and pseudo op intrinsics, they don't escape or store 9861 // to allocas. 9862 if (I.isDebugOrPseudoInst()) 9863 continue; 9864 // This is an unknown instruction. Assume it escapes or writes to all 9865 // static alloca operands. 9866 for (const Use &U : I.operands()) { 9867 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 9868 *Info = StaticAllocaInfo::Clobbered; 9869 } 9870 continue; 9871 } 9872 9873 // If the stored value is a static alloca, mark it as escaped. 9874 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 9875 *Info = StaticAllocaInfo::Clobbered; 9876 9877 // Check if the destination is a static alloca. 9878 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 9879 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 9880 if (!Info) 9881 continue; 9882 const AllocaInst *AI = cast<AllocaInst>(Dst); 9883 9884 // Skip allocas that have been initialized or clobbered. 9885 if (*Info != StaticAllocaInfo::Unknown) 9886 continue; 9887 9888 // Check if the stored value is an argument, and that this store fully 9889 // initializes the alloca. Don't elide copies from the same argument twice. 9890 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 9891 const auto *Arg = dyn_cast<Argument>(Val); 9892 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 9893 Arg->getType()->isEmptyTy() || 9894 DL.getTypeStoreSize(Arg->getType()) != 9895 DL.getTypeAllocSize(AI->getAllocatedType()) || 9896 ArgCopyElisionCandidates.count(Arg)) { 9897 *Info = StaticAllocaInfo::Clobbered; 9898 continue; 9899 } 9900 9901 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 9902 << '\n'); 9903 9904 // Mark this alloca and store for argument copy elision. 9905 *Info = StaticAllocaInfo::Elidable; 9906 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 9907 9908 // Stop scanning if we've seen all arguments. This will happen early in -O0 9909 // builds, which is useful, because -O0 builds have large entry blocks and 9910 // many allocas. 9911 if (ArgCopyElisionCandidates.size() == NumArgs) 9912 break; 9913 } 9914 } 9915 9916 /// Try to elide argument copies from memory into a local alloca. Succeeds if 9917 /// ArgVal is a load from a suitable fixed stack object. 9918 static void tryToElideArgumentCopy( 9919 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 9920 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 9921 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 9922 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 9923 SDValue ArgVal, bool &ArgHasUses) { 9924 // Check if this is a load from a fixed stack object. 9925 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 9926 if (!LNode) 9927 return; 9928 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 9929 if (!FINode) 9930 return; 9931 9932 // Check that the fixed stack object is the right size and alignment. 9933 // Look at the alignment that the user wrote on the alloca instead of looking 9934 // at the stack object. 9935 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 9936 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 9937 const AllocaInst *AI = ArgCopyIter->second.first; 9938 int FixedIndex = FINode->getIndex(); 9939 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 9940 int OldIndex = AllocaIndex; 9941 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 9942 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 9943 LLVM_DEBUG( 9944 dbgs() << " argument copy elision failed due to bad fixed stack " 9945 "object size\n"); 9946 return; 9947 } 9948 Align RequiredAlignment = AI->getAlign(); 9949 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 9950 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 9951 "greater than stack argument alignment (" 9952 << DebugStr(RequiredAlignment) << " vs " 9953 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 9954 return; 9955 } 9956 9957 // Perform the elision. Delete the old stack object and replace its only use 9958 // in the variable info map. Mark the stack object as mutable. 9959 LLVM_DEBUG({ 9960 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 9961 << " Replacing frame index " << OldIndex << " with " << FixedIndex 9962 << '\n'; 9963 }); 9964 MFI.RemoveStackObject(OldIndex); 9965 MFI.setIsImmutableObjectIndex(FixedIndex, false); 9966 AllocaIndex = FixedIndex; 9967 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 9968 Chains.push_back(ArgVal.getValue(1)); 9969 9970 // Avoid emitting code for the store implementing the copy. 9971 const StoreInst *SI = ArgCopyIter->second.second; 9972 ElidedArgCopyInstrs.insert(SI); 9973 9974 // Check for uses of the argument again so that we can avoid exporting ArgVal 9975 // if it is't used by anything other than the store. 9976 for (const Value *U : Arg.users()) { 9977 if (U != SI) { 9978 ArgHasUses = true; 9979 break; 9980 } 9981 } 9982 } 9983 9984 void SelectionDAGISel::LowerArguments(const Function &F) { 9985 SelectionDAG &DAG = SDB->DAG; 9986 SDLoc dl = SDB->getCurSDLoc(); 9987 const DataLayout &DL = DAG.getDataLayout(); 9988 SmallVector<ISD::InputArg, 16> Ins; 9989 9990 // In Naked functions we aren't going to save any registers. 9991 if (F.hasFnAttribute(Attribute::Naked)) 9992 return; 9993 9994 if (!FuncInfo->CanLowerReturn) { 9995 // Put in an sret pointer parameter before all the other parameters. 9996 SmallVector<EVT, 1> ValueVTs; 9997 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9998 F.getReturnType()->getPointerTo( 9999 DAG.getDataLayout().getAllocaAddrSpace()), 10000 ValueVTs); 10001 10002 // NOTE: Assuming that a pointer will never break down to more than one VT 10003 // or one register. 10004 ISD::ArgFlagsTy Flags; 10005 Flags.setSRet(); 10006 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 10007 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 10008 ISD::InputArg::NoArgIndex, 0); 10009 Ins.push_back(RetArg); 10010 } 10011 10012 // Look for stores of arguments to static allocas. Mark such arguments with a 10013 // flag to ask the target to give us the memory location of that argument if 10014 // available. 10015 ArgCopyElisionMapTy ArgCopyElisionCandidates; 10016 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 10017 ArgCopyElisionCandidates); 10018 10019 // Set up the incoming argument description vector. 10020 for (const Argument &Arg : F.args()) { 10021 unsigned ArgNo = Arg.getArgNo(); 10022 SmallVector<EVT, 4> ValueVTs; 10023 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10024 bool isArgValueUsed = !Arg.use_empty(); 10025 unsigned PartBase = 0; 10026 Type *FinalType = Arg.getType(); 10027 if (Arg.hasAttribute(Attribute::ByVal)) 10028 FinalType = Arg.getParamByValType(); 10029 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 10030 FinalType, F.getCallingConv(), F.isVarArg()); 10031 for (unsigned Value = 0, NumValues = ValueVTs.size(); 10032 Value != NumValues; ++Value) { 10033 EVT VT = ValueVTs[Value]; 10034 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 10035 ISD::ArgFlagsTy Flags; 10036 10037 10038 if (Arg.getType()->isPointerTy()) { 10039 Flags.setPointer(); 10040 Flags.setPointerAddrSpace( 10041 cast<PointerType>(Arg.getType())->getAddressSpace()); 10042 } 10043 if (Arg.hasAttribute(Attribute::ZExt)) 10044 Flags.setZExt(); 10045 if (Arg.hasAttribute(Attribute::SExt)) 10046 Flags.setSExt(); 10047 if (Arg.hasAttribute(Attribute::InReg)) { 10048 // If we are using vectorcall calling convention, a structure that is 10049 // passed InReg - is surely an HVA 10050 if (F.getCallingConv() == CallingConv::X86_VectorCall && 10051 isa<StructType>(Arg.getType())) { 10052 // The first value of a structure is marked 10053 if (0 == Value) 10054 Flags.setHvaStart(); 10055 Flags.setHva(); 10056 } 10057 // Set InReg Flag 10058 Flags.setInReg(); 10059 } 10060 if (Arg.hasAttribute(Attribute::StructRet)) 10061 Flags.setSRet(); 10062 if (Arg.hasAttribute(Attribute::SwiftSelf)) 10063 Flags.setSwiftSelf(); 10064 if (Arg.hasAttribute(Attribute::SwiftAsync)) 10065 Flags.setSwiftAsync(); 10066 if (Arg.hasAttribute(Attribute::SwiftError)) 10067 Flags.setSwiftError(); 10068 if (Arg.hasAttribute(Attribute::ByVal)) 10069 Flags.setByVal(); 10070 if (Arg.hasAttribute(Attribute::ByRef)) 10071 Flags.setByRef(); 10072 if (Arg.hasAttribute(Attribute::InAlloca)) { 10073 Flags.setInAlloca(); 10074 // Set the byval flag for CCAssignFn callbacks that don't know about 10075 // inalloca. This way we can know how many bytes we should've allocated 10076 // and how many bytes a callee cleanup function will pop. If we port 10077 // inalloca to more targets, we'll have to add custom inalloca handling 10078 // in the various CC lowering callbacks. 10079 Flags.setByVal(); 10080 } 10081 if (Arg.hasAttribute(Attribute::Preallocated)) { 10082 Flags.setPreallocated(); 10083 // Set the byval flag for CCAssignFn callbacks that don't know about 10084 // preallocated. This way we can know how many bytes we should've 10085 // allocated and how many bytes a callee cleanup function will pop. If 10086 // we port preallocated to more targets, we'll have to add custom 10087 // preallocated handling in the various CC lowering callbacks. 10088 Flags.setByVal(); 10089 } 10090 10091 // Certain targets (such as MIPS), may have a different ABI alignment 10092 // for a type depending on the context. Give the target a chance to 10093 // specify the alignment it wants. 10094 const Align OriginalAlignment( 10095 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 10096 Flags.setOrigAlign(OriginalAlignment); 10097 10098 Align MemAlign; 10099 Type *ArgMemTy = nullptr; 10100 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 10101 Flags.isByRef()) { 10102 if (!ArgMemTy) 10103 ArgMemTy = Arg.getPointeeInMemoryValueType(); 10104 10105 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 10106 10107 // For in-memory arguments, size and alignment should be passed from FE. 10108 // BE will guess if this info is not there but there are cases it cannot 10109 // get right. 10110 if (auto ParamAlign = Arg.getParamStackAlign()) 10111 MemAlign = *ParamAlign; 10112 else if ((ParamAlign = Arg.getParamAlign())) 10113 MemAlign = *ParamAlign; 10114 else 10115 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 10116 if (Flags.isByRef()) 10117 Flags.setByRefSize(MemSize); 10118 else 10119 Flags.setByValSize(MemSize); 10120 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 10121 MemAlign = *ParamAlign; 10122 } else { 10123 MemAlign = OriginalAlignment; 10124 } 10125 Flags.setMemAlign(MemAlign); 10126 10127 if (Arg.hasAttribute(Attribute::Nest)) 10128 Flags.setNest(); 10129 if (NeedsRegBlock) 10130 Flags.setInConsecutiveRegs(); 10131 if (ArgCopyElisionCandidates.count(&Arg)) 10132 Flags.setCopyElisionCandidate(); 10133 if (Arg.hasAttribute(Attribute::Returned)) 10134 Flags.setReturned(); 10135 10136 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 10137 *CurDAG->getContext(), F.getCallingConv(), VT); 10138 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 10139 *CurDAG->getContext(), F.getCallingConv(), VT); 10140 for (unsigned i = 0; i != NumRegs; ++i) { 10141 // For scalable vectors, use the minimum size; individual targets 10142 // are responsible for handling scalable vector arguments and 10143 // return values. 10144 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 10145 ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize()); 10146 if (NumRegs > 1 && i == 0) 10147 MyFlags.Flags.setSplit(); 10148 // if it isn't first piece, alignment must be 1 10149 else if (i > 0) { 10150 MyFlags.Flags.setOrigAlign(Align(1)); 10151 if (i == NumRegs - 1) 10152 MyFlags.Flags.setSplitEnd(); 10153 } 10154 Ins.push_back(MyFlags); 10155 } 10156 if (NeedsRegBlock && Value == NumValues - 1) 10157 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 10158 PartBase += VT.getStoreSize().getKnownMinSize(); 10159 } 10160 } 10161 10162 // Call the target to set up the argument values. 10163 SmallVector<SDValue, 8> InVals; 10164 SDValue NewRoot = TLI->LowerFormalArguments( 10165 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 10166 10167 // Verify that the target's LowerFormalArguments behaved as expected. 10168 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 10169 "LowerFormalArguments didn't return a valid chain!"); 10170 assert(InVals.size() == Ins.size() && 10171 "LowerFormalArguments didn't emit the correct number of values!"); 10172 LLVM_DEBUG({ 10173 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 10174 assert(InVals[i].getNode() && 10175 "LowerFormalArguments emitted a null value!"); 10176 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 10177 "LowerFormalArguments emitted a value with the wrong type!"); 10178 } 10179 }); 10180 10181 // Update the DAG with the new chain value resulting from argument lowering. 10182 DAG.setRoot(NewRoot); 10183 10184 // Set up the argument values. 10185 unsigned i = 0; 10186 if (!FuncInfo->CanLowerReturn) { 10187 // Create a virtual register for the sret pointer, and put in a copy 10188 // from the sret argument into it. 10189 SmallVector<EVT, 1> ValueVTs; 10190 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10191 F.getReturnType()->getPointerTo( 10192 DAG.getDataLayout().getAllocaAddrSpace()), 10193 ValueVTs); 10194 MVT VT = ValueVTs[0].getSimpleVT(); 10195 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 10196 Optional<ISD::NodeType> AssertOp = None; 10197 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 10198 nullptr, F.getCallingConv(), AssertOp); 10199 10200 MachineFunction& MF = SDB->DAG.getMachineFunction(); 10201 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 10202 Register SRetReg = 10203 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 10204 FuncInfo->DemoteRegister = SRetReg; 10205 NewRoot = 10206 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 10207 DAG.setRoot(NewRoot); 10208 10209 // i indexes lowered arguments. Bump it past the hidden sret argument. 10210 ++i; 10211 } 10212 10213 SmallVector<SDValue, 4> Chains; 10214 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 10215 for (const Argument &Arg : F.args()) { 10216 SmallVector<SDValue, 4> ArgValues; 10217 SmallVector<EVT, 4> ValueVTs; 10218 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10219 unsigned NumValues = ValueVTs.size(); 10220 if (NumValues == 0) 10221 continue; 10222 10223 bool ArgHasUses = !Arg.use_empty(); 10224 10225 // Elide the copying store if the target loaded this argument from a 10226 // suitable fixed stack object. 10227 if (Ins[i].Flags.isCopyElisionCandidate()) { 10228 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 10229 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 10230 InVals[i], ArgHasUses); 10231 } 10232 10233 // If this argument is unused then remember its value. It is used to generate 10234 // debugging information. 10235 bool isSwiftErrorArg = 10236 TLI->supportSwiftError() && 10237 Arg.hasAttribute(Attribute::SwiftError); 10238 if (!ArgHasUses && !isSwiftErrorArg) { 10239 SDB->setUnusedArgValue(&Arg, InVals[i]); 10240 10241 // Also remember any frame index for use in FastISel. 10242 if (FrameIndexSDNode *FI = 10243 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 10244 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10245 } 10246 10247 for (unsigned Val = 0; Val != NumValues; ++Val) { 10248 EVT VT = ValueVTs[Val]; 10249 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 10250 F.getCallingConv(), VT); 10251 unsigned NumParts = TLI->getNumRegistersForCallingConv( 10252 *CurDAG->getContext(), F.getCallingConv(), VT); 10253 10254 // Even an apparent 'unused' swifterror argument needs to be returned. So 10255 // we do generate a copy for it that can be used on return from the 10256 // function. 10257 if (ArgHasUses || isSwiftErrorArg) { 10258 Optional<ISD::NodeType> AssertOp; 10259 if (Arg.hasAttribute(Attribute::SExt)) 10260 AssertOp = ISD::AssertSext; 10261 else if (Arg.hasAttribute(Attribute::ZExt)) 10262 AssertOp = ISD::AssertZext; 10263 10264 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 10265 PartVT, VT, nullptr, 10266 F.getCallingConv(), AssertOp)); 10267 } 10268 10269 i += NumParts; 10270 } 10271 10272 // We don't need to do anything else for unused arguments. 10273 if (ArgValues.empty()) 10274 continue; 10275 10276 // Note down frame index. 10277 if (FrameIndexSDNode *FI = 10278 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 10279 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10280 10281 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 10282 SDB->getCurSDLoc()); 10283 10284 SDB->setValue(&Arg, Res); 10285 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 10286 // We want to associate the argument with the frame index, among 10287 // involved operands, that correspond to the lowest address. The 10288 // getCopyFromParts function, called earlier, is swapping the order of 10289 // the operands to BUILD_PAIR depending on endianness. The result of 10290 // that swapping is that the least significant bits of the argument will 10291 // be in the first operand of the BUILD_PAIR node, and the most 10292 // significant bits will be in the second operand. 10293 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 10294 if (LoadSDNode *LNode = 10295 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 10296 if (FrameIndexSDNode *FI = 10297 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 10298 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10299 } 10300 10301 // Analyses past this point are naive and don't expect an assertion. 10302 if (Res.getOpcode() == ISD::AssertZext) 10303 Res = Res.getOperand(0); 10304 10305 // Update the SwiftErrorVRegDefMap. 10306 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 10307 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10308 if (Register::isVirtualRegister(Reg)) 10309 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 10310 Reg); 10311 } 10312 10313 // If this argument is live outside of the entry block, insert a copy from 10314 // wherever we got it to the vreg that other BB's will reference it as. 10315 if (Res.getOpcode() == ISD::CopyFromReg) { 10316 // If we can, though, try to skip creating an unnecessary vreg. 10317 // FIXME: This isn't very clean... it would be nice to make this more 10318 // general. 10319 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10320 if (Register::isVirtualRegister(Reg)) { 10321 FuncInfo->ValueMap[&Arg] = Reg; 10322 continue; 10323 } 10324 } 10325 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 10326 FuncInfo->InitializeRegForValue(&Arg); 10327 SDB->CopyToExportRegsIfNeeded(&Arg); 10328 } 10329 } 10330 10331 if (!Chains.empty()) { 10332 Chains.push_back(NewRoot); 10333 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 10334 } 10335 10336 DAG.setRoot(NewRoot); 10337 10338 assert(i == InVals.size() && "Argument register count mismatch!"); 10339 10340 // If any argument copy elisions occurred and we have debug info, update the 10341 // stale frame indices used in the dbg.declare variable info table. 10342 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 10343 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 10344 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 10345 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 10346 if (I != ArgCopyElisionFrameIndexMap.end()) 10347 VI.Slot = I->second; 10348 } 10349 } 10350 10351 // Finally, if the target has anything special to do, allow it to do so. 10352 emitFunctionEntryCode(); 10353 } 10354 10355 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 10356 /// ensure constants are generated when needed. Remember the virtual registers 10357 /// that need to be added to the Machine PHI nodes as input. We cannot just 10358 /// directly add them, because expansion might result in multiple MBB's for one 10359 /// BB. As such, the start of the BB might correspond to a different MBB than 10360 /// the end. 10361 void 10362 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 10363 const Instruction *TI = LLVMBB->getTerminator(); 10364 10365 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 10366 10367 // Check PHI nodes in successors that expect a value to be available from this 10368 // block. 10369 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 10370 const BasicBlock *SuccBB = TI->getSuccessor(succ); 10371 if (!isa<PHINode>(SuccBB->begin())) continue; 10372 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 10373 10374 // If this terminator has multiple identical successors (common for 10375 // switches), only handle each succ once. 10376 if (!SuccsHandled.insert(SuccMBB).second) 10377 continue; 10378 10379 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 10380 10381 // At this point we know that there is a 1-1 correspondence between LLVM PHI 10382 // nodes and Machine PHI nodes, but the incoming operands have not been 10383 // emitted yet. 10384 for (const PHINode &PN : SuccBB->phis()) { 10385 // Ignore dead phi's. 10386 if (PN.use_empty()) 10387 continue; 10388 10389 // Skip empty types 10390 if (PN.getType()->isEmptyTy()) 10391 continue; 10392 10393 unsigned Reg; 10394 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 10395 10396 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 10397 unsigned &RegOut = ConstantsOut[C]; 10398 if (RegOut == 0) { 10399 RegOut = FuncInfo.CreateRegs(C); 10400 CopyValueToVirtualRegister(C, RegOut); 10401 } 10402 Reg = RegOut; 10403 } else { 10404 DenseMap<const Value *, Register>::iterator I = 10405 FuncInfo.ValueMap.find(PHIOp); 10406 if (I != FuncInfo.ValueMap.end()) 10407 Reg = I->second; 10408 else { 10409 assert(isa<AllocaInst>(PHIOp) && 10410 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 10411 "Didn't codegen value into a register!??"); 10412 Reg = FuncInfo.CreateRegs(PHIOp); 10413 CopyValueToVirtualRegister(PHIOp, Reg); 10414 } 10415 } 10416 10417 // Remember that this register needs to added to the machine PHI node as 10418 // the input for this MBB. 10419 SmallVector<EVT, 4> ValueVTs; 10420 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10421 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 10422 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 10423 EVT VT = ValueVTs[vti]; 10424 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 10425 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 10426 FuncInfo.PHINodesToUpdate.push_back( 10427 std::make_pair(&*MBBI++, Reg + i)); 10428 Reg += NumRegisters; 10429 } 10430 } 10431 } 10432 10433 ConstantsOut.clear(); 10434 } 10435 10436 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 10437 /// is 0. 10438 MachineBasicBlock * 10439 SelectionDAGBuilder::StackProtectorDescriptor:: 10440 AddSuccessorMBB(const BasicBlock *BB, 10441 MachineBasicBlock *ParentMBB, 10442 bool IsLikely, 10443 MachineBasicBlock *SuccMBB) { 10444 // If SuccBB has not been created yet, create it. 10445 if (!SuccMBB) { 10446 MachineFunction *MF = ParentMBB->getParent(); 10447 MachineFunction::iterator BBI(ParentMBB); 10448 SuccMBB = MF->CreateMachineBasicBlock(BB); 10449 MF->insert(++BBI, SuccMBB); 10450 } 10451 // Add it as a successor of ParentMBB. 10452 ParentMBB->addSuccessor( 10453 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 10454 return SuccMBB; 10455 } 10456 10457 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 10458 MachineFunction::iterator I(MBB); 10459 if (++I == FuncInfo.MF->end()) 10460 return nullptr; 10461 return &*I; 10462 } 10463 10464 /// During lowering new call nodes can be created (such as memset, etc.). 10465 /// Those will become new roots of the current DAG, but complications arise 10466 /// when they are tail calls. In such cases, the call lowering will update 10467 /// the root, but the builder still needs to know that a tail call has been 10468 /// lowered in order to avoid generating an additional return. 10469 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 10470 // If the node is null, we do have a tail call. 10471 if (MaybeTC.getNode() != nullptr) 10472 DAG.setRoot(MaybeTC); 10473 else 10474 HasTailCall = true; 10475 } 10476 10477 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10478 MachineBasicBlock *SwitchMBB, 10479 MachineBasicBlock *DefaultMBB) { 10480 MachineFunction *CurMF = FuncInfo.MF; 10481 MachineBasicBlock *NextMBB = nullptr; 10482 MachineFunction::iterator BBI(W.MBB); 10483 if (++BBI != FuncInfo.MF->end()) 10484 NextMBB = &*BBI; 10485 10486 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10487 10488 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10489 10490 if (Size == 2 && W.MBB == SwitchMBB) { 10491 // If any two of the cases has the same destination, and if one value 10492 // is the same as the other, but has one bit unset that the other has set, 10493 // use bit manipulation to do two compares at once. For example: 10494 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10495 // TODO: This could be extended to merge any 2 cases in switches with 3 10496 // cases. 10497 // TODO: Handle cases where W.CaseBB != SwitchBB. 10498 CaseCluster &Small = *W.FirstCluster; 10499 CaseCluster &Big = *W.LastCluster; 10500 10501 if (Small.Low == Small.High && Big.Low == Big.High && 10502 Small.MBB == Big.MBB) { 10503 const APInt &SmallValue = Small.Low->getValue(); 10504 const APInt &BigValue = Big.Low->getValue(); 10505 10506 // Check that there is only one bit different. 10507 APInt CommonBit = BigValue ^ SmallValue; 10508 if (CommonBit.isPowerOf2()) { 10509 SDValue CondLHS = getValue(Cond); 10510 EVT VT = CondLHS.getValueType(); 10511 SDLoc DL = getCurSDLoc(); 10512 10513 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10514 DAG.getConstant(CommonBit, DL, VT)); 10515 SDValue Cond = DAG.getSetCC( 10516 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10517 ISD::SETEQ); 10518 10519 // Update successor info. 10520 // Both Small and Big will jump to Small.BB, so we sum up the 10521 // probabilities. 10522 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10523 if (BPI) 10524 addSuccessorWithProb( 10525 SwitchMBB, DefaultMBB, 10526 // The default destination is the first successor in IR. 10527 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10528 else 10529 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10530 10531 // Insert the true branch. 10532 SDValue BrCond = 10533 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10534 DAG.getBasicBlock(Small.MBB)); 10535 // Insert the false branch. 10536 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10537 DAG.getBasicBlock(DefaultMBB)); 10538 10539 DAG.setRoot(BrCond); 10540 return; 10541 } 10542 } 10543 } 10544 10545 if (TM.getOptLevel() != CodeGenOpt::None) { 10546 // Here, we order cases by probability so the most likely case will be 10547 // checked first. However, two clusters can have the same probability in 10548 // which case their relative ordering is non-deterministic. So we use Low 10549 // as a tie-breaker as clusters are guaranteed to never overlap. 10550 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10551 [](const CaseCluster &a, const CaseCluster &b) { 10552 return a.Prob != b.Prob ? 10553 a.Prob > b.Prob : 10554 a.Low->getValue().slt(b.Low->getValue()); 10555 }); 10556 10557 // Rearrange the case blocks so that the last one falls through if possible 10558 // without changing the order of probabilities. 10559 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10560 --I; 10561 if (I->Prob > W.LastCluster->Prob) 10562 break; 10563 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10564 std::swap(*I, *W.LastCluster); 10565 break; 10566 } 10567 } 10568 } 10569 10570 // Compute total probability. 10571 BranchProbability DefaultProb = W.DefaultProb; 10572 BranchProbability UnhandledProbs = DefaultProb; 10573 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10574 UnhandledProbs += I->Prob; 10575 10576 MachineBasicBlock *CurMBB = W.MBB; 10577 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10578 bool FallthroughUnreachable = false; 10579 MachineBasicBlock *Fallthrough; 10580 if (I == W.LastCluster) { 10581 // For the last cluster, fall through to the default destination. 10582 Fallthrough = DefaultMBB; 10583 FallthroughUnreachable = isa<UnreachableInst>( 10584 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10585 } else { 10586 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10587 CurMF->insert(BBI, Fallthrough); 10588 // Put Cond in a virtual register to make it available from the new blocks. 10589 ExportFromCurrentBlock(Cond); 10590 } 10591 UnhandledProbs -= I->Prob; 10592 10593 switch (I->Kind) { 10594 case CC_JumpTable: { 10595 // FIXME: Optimize away range check based on pivot comparisons. 10596 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 10597 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 10598 10599 // The jump block hasn't been inserted yet; insert it here. 10600 MachineBasicBlock *JumpMBB = JT->MBB; 10601 CurMF->insert(BBI, JumpMBB); 10602 10603 auto JumpProb = I->Prob; 10604 auto FallthroughProb = UnhandledProbs; 10605 10606 // If the default statement is a target of the jump table, we evenly 10607 // distribute the default probability to successors of CurMBB. Also 10608 // update the probability on the edge from JumpMBB to Fallthrough. 10609 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10610 SE = JumpMBB->succ_end(); 10611 SI != SE; ++SI) { 10612 if (*SI == DefaultMBB) { 10613 JumpProb += DefaultProb / 2; 10614 FallthroughProb -= DefaultProb / 2; 10615 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10616 JumpMBB->normalizeSuccProbs(); 10617 break; 10618 } 10619 } 10620 10621 if (FallthroughUnreachable) { 10622 // Skip the range check if the fallthrough block is unreachable. 10623 JTH->OmitRangeCheck = true; 10624 } 10625 10626 if (!JTH->OmitRangeCheck) 10627 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10628 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10629 CurMBB->normalizeSuccProbs(); 10630 10631 // The jump table header will be inserted in our current block, do the 10632 // range check, and fall through to our fallthrough block. 10633 JTH->HeaderBB = CurMBB; 10634 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10635 10636 // If we're in the right place, emit the jump table header right now. 10637 if (CurMBB == SwitchMBB) { 10638 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10639 JTH->Emitted = true; 10640 } 10641 break; 10642 } 10643 case CC_BitTests: { 10644 // FIXME: Optimize away range check based on pivot comparisons. 10645 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 10646 10647 // The bit test blocks haven't been inserted yet; insert them here. 10648 for (BitTestCase &BTC : BTB->Cases) 10649 CurMF->insert(BBI, BTC.ThisBB); 10650 10651 // Fill in fields of the BitTestBlock. 10652 BTB->Parent = CurMBB; 10653 BTB->Default = Fallthrough; 10654 10655 BTB->DefaultProb = UnhandledProbs; 10656 // If the cases in bit test don't form a contiguous range, we evenly 10657 // distribute the probability on the edge to Fallthrough to two 10658 // successors of CurMBB. 10659 if (!BTB->ContiguousRange) { 10660 BTB->Prob += DefaultProb / 2; 10661 BTB->DefaultProb -= DefaultProb / 2; 10662 } 10663 10664 if (FallthroughUnreachable) { 10665 // Skip the range check if the fallthrough block is unreachable. 10666 BTB->OmitRangeCheck = true; 10667 } 10668 10669 // If we're in the right place, emit the bit test header right now. 10670 if (CurMBB == SwitchMBB) { 10671 visitBitTestHeader(*BTB, SwitchMBB); 10672 BTB->Emitted = true; 10673 } 10674 break; 10675 } 10676 case CC_Range: { 10677 const Value *RHS, *LHS, *MHS; 10678 ISD::CondCode CC; 10679 if (I->Low == I->High) { 10680 // Check Cond == I->Low. 10681 CC = ISD::SETEQ; 10682 LHS = Cond; 10683 RHS=I->Low; 10684 MHS = nullptr; 10685 } else { 10686 // Check I->Low <= Cond <= I->High. 10687 CC = ISD::SETLE; 10688 LHS = I->Low; 10689 MHS = Cond; 10690 RHS = I->High; 10691 } 10692 10693 // If Fallthrough is unreachable, fold away the comparison. 10694 if (FallthroughUnreachable) 10695 CC = ISD::SETTRUE; 10696 10697 // The false probability is the sum of all unhandled cases. 10698 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10699 getCurSDLoc(), I->Prob, UnhandledProbs); 10700 10701 if (CurMBB == SwitchMBB) 10702 visitSwitchCase(CB, SwitchMBB); 10703 else 10704 SL->SwitchCases.push_back(CB); 10705 10706 break; 10707 } 10708 } 10709 CurMBB = Fallthrough; 10710 } 10711 } 10712 10713 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10714 CaseClusterIt First, 10715 CaseClusterIt Last) { 10716 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10717 if (X.Prob != CC.Prob) 10718 return X.Prob > CC.Prob; 10719 10720 // Ties are broken by comparing the case value. 10721 return X.Low->getValue().slt(CC.Low->getValue()); 10722 }); 10723 } 10724 10725 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10726 const SwitchWorkListItem &W, 10727 Value *Cond, 10728 MachineBasicBlock *SwitchMBB) { 10729 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10730 "Clusters not sorted?"); 10731 10732 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10733 10734 // Balance the tree based on branch probabilities to create a near-optimal (in 10735 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10736 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10737 CaseClusterIt LastLeft = W.FirstCluster; 10738 CaseClusterIt FirstRight = W.LastCluster; 10739 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10740 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10741 10742 // Move LastLeft and FirstRight towards each other from opposite directions to 10743 // find a partitioning of the clusters which balances the probability on both 10744 // sides. If LeftProb and RightProb are equal, alternate which side is 10745 // taken to ensure 0-probability nodes are distributed evenly. 10746 unsigned I = 0; 10747 while (LastLeft + 1 < FirstRight) { 10748 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10749 LeftProb += (++LastLeft)->Prob; 10750 else 10751 RightProb += (--FirstRight)->Prob; 10752 I++; 10753 } 10754 10755 while (true) { 10756 // Our binary search tree differs from a typical BST in that ours can have up 10757 // to three values in each leaf. The pivot selection above doesn't take that 10758 // into account, which means the tree might require more nodes and be less 10759 // efficient. We compensate for this here. 10760 10761 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10762 unsigned NumRight = W.LastCluster - FirstRight + 1; 10763 10764 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10765 // If one side has less than 3 clusters, and the other has more than 3, 10766 // consider taking a cluster from the other side. 10767 10768 if (NumLeft < NumRight) { 10769 // Consider moving the first cluster on the right to the left side. 10770 CaseCluster &CC = *FirstRight; 10771 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10772 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10773 if (LeftSideRank <= RightSideRank) { 10774 // Moving the cluster to the left does not demote it. 10775 ++LastLeft; 10776 ++FirstRight; 10777 continue; 10778 } 10779 } else { 10780 assert(NumRight < NumLeft); 10781 // Consider moving the last element on the left to the right side. 10782 CaseCluster &CC = *LastLeft; 10783 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10784 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10785 if (RightSideRank <= LeftSideRank) { 10786 // Moving the cluster to the right does not demot it. 10787 --LastLeft; 10788 --FirstRight; 10789 continue; 10790 } 10791 } 10792 } 10793 break; 10794 } 10795 10796 assert(LastLeft + 1 == FirstRight); 10797 assert(LastLeft >= W.FirstCluster); 10798 assert(FirstRight <= W.LastCluster); 10799 10800 // Use the first element on the right as pivot since we will make less-than 10801 // comparisons against it. 10802 CaseClusterIt PivotCluster = FirstRight; 10803 assert(PivotCluster > W.FirstCluster); 10804 assert(PivotCluster <= W.LastCluster); 10805 10806 CaseClusterIt FirstLeft = W.FirstCluster; 10807 CaseClusterIt LastRight = W.LastCluster; 10808 10809 const ConstantInt *Pivot = PivotCluster->Low; 10810 10811 // New blocks will be inserted immediately after the current one. 10812 MachineFunction::iterator BBI(W.MBB); 10813 ++BBI; 10814 10815 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10816 // we can branch to its destination directly if it's squeezed exactly in 10817 // between the known lower bound and Pivot - 1. 10818 MachineBasicBlock *LeftMBB; 10819 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10820 FirstLeft->Low == W.GE && 10821 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10822 LeftMBB = FirstLeft->MBB; 10823 } else { 10824 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10825 FuncInfo.MF->insert(BBI, LeftMBB); 10826 WorkList.push_back( 10827 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10828 // Put Cond in a virtual register to make it available from the new blocks. 10829 ExportFromCurrentBlock(Cond); 10830 } 10831 10832 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10833 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10834 // directly if RHS.High equals the current upper bound. 10835 MachineBasicBlock *RightMBB; 10836 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10837 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10838 RightMBB = FirstRight->MBB; 10839 } else { 10840 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10841 FuncInfo.MF->insert(BBI, RightMBB); 10842 WorkList.push_back( 10843 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10844 // Put Cond in a virtual register to make it available from the new blocks. 10845 ExportFromCurrentBlock(Cond); 10846 } 10847 10848 // Create the CaseBlock record that will be used to lower the branch. 10849 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10850 getCurSDLoc(), LeftProb, RightProb); 10851 10852 if (W.MBB == SwitchMBB) 10853 visitSwitchCase(CB, SwitchMBB); 10854 else 10855 SL->SwitchCases.push_back(CB); 10856 } 10857 10858 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10859 // from the swith statement. 10860 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10861 BranchProbability PeeledCaseProb) { 10862 if (PeeledCaseProb == BranchProbability::getOne()) 10863 return BranchProbability::getZero(); 10864 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10865 10866 uint32_t Numerator = CaseProb.getNumerator(); 10867 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10868 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10869 } 10870 10871 // Try to peel the top probability case if it exceeds the threshold. 10872 // Return current MachineBasicBlock for the switch statement if the peeling 10873 // does not occur. 10874 // If the peeling is performed, return the newly created MachineBasicBlock 10875 // for the peeled switch statement. Also update Clusters to remove the peeled 10876 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10877 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10878 const SwitchInst &SI, CaseClusterVector &Clusters, 10879 BranchProbability &PeeledCaseProb) { 10880 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10881 // Don't perform if there is only one cluster or optimizing for size. 10882 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10883 TM.getOptLevel() == CodeGenOpt::None || 10884 SwitchMBB->getParent()->getFunction().hasMinSize()) 10885 return SwitchMBB; 10886 10887 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10888 unsigned PeeledCaseIndex = 0; 10889 bool SwitchPeeled = false; 10890 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10891 CaseCluster &CC = Clusters[Index]; 10892 if (CC.Prob < TopCaseProb) 10893 continue; 10894 TopCaseProb = CC.Prob; 10895 PeeledCaseIndex = Index; 10896 SwitchPeeled = true; 10897 } 10898 if (!SwitchPeeled) 10899 return SwitchMBB; 10900 10901 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10902 << TopCaseProb << "\n"); 10903 10904 // Record the MBB for the peeled switch statement. 10905 MachineFunction::iterator BBI(SwitchMBB); 10906 ++BBI; 10907 MachineBasicBlock *PeeledSwitchMBB = 10908 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10909 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10910 10911 ExportFromCurrentBlock(SI.getCondition()); 10912 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10913 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10914 nullptr, nullptr, TopCaseProb.getCompl()}; 10915 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10916 10917 Clusters.erase(PeeledCaseIt); 10918 for (CaseCluster &CC : Clusters) { 10919 LLVM_DEBUG( 10920 dbgs() << "Scale the probablity for one cluster, before scaling: " 10921 << CC.Prob << "\n"); 10922 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10923 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10924 } 10925 PeeledCaseProb = TopCaseProb; 10926 return PeeledSwitchMBB; 10927 } 10928 10929 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10930 // Extract cases from the switch. 10931 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10932 CaseClusterVector Clusters; 10933 Clusters.reserve(SI.getNumCases()); 10934 for (auto I : SI.cases()) { 10935 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10936 const ConstantInt *CaseVal = I.getCaseValue(); 10937 BranchProbability Prob = 10938 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10939 : BranchProbability(1, SI.getNumCases() + 1); 10940 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10941 } 10942 10943 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10944 10945 // Cluster adjacent cases with the same destination. We do this at all 10946 // optimization levels because it's cheap to do and will make codegen faster 10947 // if there are many clusters. 10948 sortAndRangeify(Clusters); 10949 10950 // The branch probablity of the peeled case. 10951 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10952 MachineBasicBlock *PeeledSwitchMBB = 10953 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10954 10955 // If there is only the default destination, jump there directly. 10956 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10957 if (Clusters.empty()) { 10958 assert(PeeledSwitchMBB == SwitchMBB); 10959 SwitchMBB->addSuccessor(DefaultMBB); 10960 if (DefaultMBB != NextBlock(SwitchMBB)) { 10961 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10962 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10963 } 10964 return; 10965 } 10966 10967 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 10968 SL->findBitTestClusters(Clusters, &SI); 10969 10970 LLVM_DEBUG({ 10971 dbgs() << "Case clusters: "; 10972 for (const CaseCluster &C : Clusters) { 10973 if (C.Kind == CC_JumpTable) 10974 dbgs() << "JT:"; 10975 if (C.Kind == CC_BitTests) 10976 dbgs() << "BT:"; 10977 10978 C.Low->getValue().print(dbgs(), true); 10979 if (C.Low != C.High) { 10980 dbgs() << '-'; 10981 C.High->getValue().print(dbgs(), true); 10982 } 10983 dbgs() << ' '; 10984 } 10985 dbgs() << '\n'; 10986 }); 10987 10988 assert(!Clusters.empty()); 10989 SwitchWorkList WorkList; 10990 CaseClusterIt First = Clusters.begin(); 10991 CaseClusterIt Last = Clusters.end() - 1; 10992 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10993 // Scale the branchprobability for DefaultMBB if the peel occurs and 10994 // DefaultMBB is not replaced. 10995 if (PeeledCaseProb != BranchProbability::getZero() && 10996 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10997 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10998 WorkList.push_back( 10999 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 11000 11001 while (!WorkList.empty()) { 11002 SwitchWorkListItem W = WorkList.pop_back_val(); 11003 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 11004 11005 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 11006 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 11007 // For optimized builds, lower large range as a balanced binary tree. 11008 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 11009 continue; 11010 } 11011 11012 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 11013 } 11014 } 11015 11016 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 11017 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11018 auto DL = getCurSDLoc(); 11019 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11020 EVT OpVT = 11021 TLI.getTypeToTransformTo(*DAG.getContext(), ResultVT.getScalarType()); 11022 SDValue Step = DAG.getConstant(1, DL, OpVT); 11023 setValue(&I, DAG.getStepVector(DL, ResultVT, Step)); 11024 } 11025 11026 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 11027 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11028 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11029 11030 SDLoc DL = getCurSDLoc(); 11031 SDValue V = getValue(I.getOperand(0)); 11032 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 11033 11034 if (VT.isScalableVector()) { 11035 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 11036 return; 11037 } 11038 11039 // Use VECTOR_SHUFFLE for the fixed-length vector 11040 // to maintain existing behavior. 11041 SmallVector<int, 8> Mask; 11042 unsigned NumElts = VT.getVectorMinNumElements(); 11043 for (unsigned i = 0; i != NumElts; ++i) 11044 Mask.push_back(NumElts - 1 - i); 11045 11046 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 11047 } 11048 11049 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 11050 SmallVector<EVT, 4> ValueVTs; 11051 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 11052 ValueVTs); 11053 unsigned NumValues = ValueVTs.size(); 11054 if (NumValues == 0) return; 11055 11056 SmallVector<SDValue, 4> Values(NumValues); 11057 SDValue Op = getValue(I.getOperand(0)); 11058 11059 for (unsigned i = 0; i != NumValues; ++i) 11060 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 11061 SDValue(Op.getNode(), Op.getResNo() + i)); 11062 11063 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 11064 DAG.getVTList(ValueVTs), Values)); 11065 } 11066 11067 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 11068 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11069 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11070 11071 SDLoc DL = getCurSDLoc(); 11072 SDValue V1 = getValue(I.getOperand(0)); 11073 SDValue V2 = getValue(I.getOperand(1)); 11074 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 11075 11076 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 11077 if (VT.isScalableVector()) { 11078 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 11079 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 11080 DAG.getConstant(Imm, DL, IdxVT))); 11081 return; 11082 } 11083 11084 unsigned NumElts = VT.getVectorNumElements(); 11085 11086 if ((-Imm > NumElts) || (Imm >= NumElts)) { 11087 // Result is undefined if immediate is out-of-bounds. 11088 setValue(&I, DAG.getUNDEF(VT)); 11089 return; 11090 } 11091 11092 uint64_t Idx = (NumElts + Imm) % NumElts; 11093 11094 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 11095 SmallVector<int, 8> Mask; 11096 for (unsigned i = 0; i < NumElts; ++i) 11097 Mask.push_back(Idx + i); 11098 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 11099 } 11100