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 MVT RegisterVT = RegVTs[Value]; 992 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value], 993 RegisterVT); 994 for (unsigned i = 0; i != NumRegs; ++i) { 995 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 996 unsigned TheReg = Regs[Reg++]; 997 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 998 } 999 } 1000 } 1001 1002 SmallVector<std::pair<unsigned, TypeSize>, 4> 1003 RegsForValue::getRegsAndSizes() const { 1004 SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec; 1005 unsigned I = 0; 1006 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1007 unsigned RegCount = std::get<0>(CountAndVT); 1008 MVT RegisterVT = std::get<1>(CountAndVT); 1009 TypeSize RegisterSize = RegisterVT.getSizeInBits(); 1010 for (unsigned E = I + RegCount; I != E; ++I) 1011 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1012 } 1013 return OutVec; 1014 } 1015 1016 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1017 const TargetLibraryInfo *li) { 1018 AA = aa; 1019 GFI = gfi; 1020 LibInfo = li; 1021 DL = &DAG.getDataLayout(); 1022 Context = DAG.getContext(); 1023 LPadToCallSiteMap.clear(); 1024 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1025 } 1026 1027 void SelectionDAGBuilder::clear() { 1028 NodeMap.clear(); 1029 UnusedArgNodeMap.clear(); 1030 PendingLoads.clear(); 1031 PendingExports.clear(); 1032 PendingConstrainedFP.clear(); 1033 PendingConstrainedFPStrict.clear(); 1034 CurInst = nullptr; 1035 HasTailCall = false; 1036 SDNodeOrder = LowestSDNodeOrder; 1037 StatepointLowering.clear(); 1038 } 1039 1040 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1041 DanglingDebugInfoMap.clear(); 1042 } 1043 1044 // Update DAG root to include dependencies on Pending chains. 1045 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1046 SDValue Root = DAG.getRoot(); 1047 1048 if (Pending.empty()) 1049 return Root; 1050 1051 // Add current root to PendingChains, unless we already indirectly 1052 // depend on it. 1053 if (Root.getOpcode() != ISD::EntryToken) { 1054 unsigned i = 0, e = Pending.size(); 1055 for (; i != e; ++i) { 1056 assert(Pending[i].getNode()->getNumOperands() > 1); 1057 if (Pending[i].getNode()->getOperand(0) == Root) 1058 break; // Don't add the root if we already indirectly depend on it. 1059 } 1060 1061 if (i == e) 1062 Pending.push_back(Root); 1063 } 1064 1065 if (Pending.size() == 1) 1066 Root = Pending[0]; 1067 else 1068 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1069 1070 DAG.setRoot(Root); 1071 Pending.clear(); 1072 return Root; 1073 } 1074 1075 SDValue SelectionDAGBuilder::getMemoryRoot() { 1076 return updateRoot(PendingLoads); 1077 } 1078 1079 SDValue SelectionDAGBuilder::getRoot() { 1080 // Chain up all pending constrained intrinsics together with all 1081 // pending loads, by simply appending them to PendingLoads and 1082 // then calling getMemoryRoot(). 1083 PendingLoads.reserve(PendingLoads.size() + 1084 PendingConstrainedFP.size() + 1085 PendingConstrainedFPStrict.size()); 1086 PendingLoads.append(PendingConstrainedFP.begin(), 1087 PendingConstrainedFP.end()); 1088 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1089 PendingConstrainedFPStrict.end()); 1090 PendingConstrainedFP.clear(); 1091 PendingConstrainedFPStrict.clear(); 1092 return getMemoryRoot(); 1093 } 1094 1095 SDValue SelectionDAGBuilder::getControlRoot() { 1096 // We need to emit pending fpexcept.strict constrained intrinsics, 1097 // so append them to the PendingExports list. 1098 PendingExports.append(PendingConstrainedFPStrict.begin(), 1099 PendingConstrainedFPStrict.end()); 1100 PendingConstrainedFPStrict.clear(); 1101 return updateRoot(PendingExports); 1102 } 1103 1104 void SelectionDAGBuilder::visit(const Instruction &I) { 1105 // Set up outgoing PHI node register values before emitting the terminator. 1106 if (I.isTerminator()) { 1107 HandlePHINodesInSuccessorBlocks(I.getParent()); 1108 } 1109 1110 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1111 if (!isa<DbgInfoIntrinsic>(I)) 1112 ++SDNodeOrder; 1113 1114 CurInst = &I; 1115 1116 visit(I.getOpcode(), I); 1117 1118 if (!I.isTerminator() && !HasTailCall && 1119 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1120 CopyToExportRegsIfNeeded(&I); 1121 1122 CurInst = nullptr; 1123 } 1124 1125 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1126 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1127 } 1128 1129 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1130 // Note: this doesn't use InstVisitor, because it has to work with 1131 // ConstantExpr's in addition to instructions. 1132 switch (Opcode) { 1133 default: llvm_unreachable("Unknown instruction type encountered!"); 1134 // Build the switch statement using the Instruction.def file. 1135 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1136 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1137 #include "llvm/IR/Instruction.def" 1138 } 1139 } 1140 1141 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI, 1142 DebugLoc DL, unsigned Order) { 1143 // We treat variadic dbg_values differently at this stage. 1144 if (DI->hasArgList()) { 1145 // For variadic dbg_values we will now insert an undef. 1146 // FIXME: We can potentially recover these! 1147 SmallVector<SDDbgOperand, 2> Locs; 1148 for (const Value *V : DI->getValues()) { 1149 auto Undef = UndefValue::get(V->getType()); 1150 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1151 } 1152 SDDbgValue *SDV = DAG.getDbgValueList( 1153 DI->getVariable(), DI->getExpression(), Locs, {}, 1154 /*IsIndirect=*/false, DL, Order, /*IsVariadic=*/true); 1155 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1156 } else { 1157 // TODO: Dangling debug info will eventually either be resolved or produce 1158 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1159 // between the original dbg.value location and its resolved DBG_VALUE, 1160 // which we should ideally fill with an extra Undef DBG_VALUE. 1161 assert(DI->getNumVariableLocationOps() == 1 && 1162 "DbgValueInst without an ArgList should have a single location " 1163 "operand."); 1164 DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, DL, Order); 1165 } 1166 } 1167 1168 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1169 const DIExpression *Expr) { 1170 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1171 const DbgValueInst *DI = DDI.getDI(); 1172 DIVariable *DanglingVariable = DI->getVariable(); 1173 DIExpression *DanglingExpr = DI->getExpression(); 1174 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1175 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1176 return true; 1177 } 1178 return false; 1179 }; 1180 1181 for (auto &DDIMI : DanglingDebugInfoMap) { 1182 DanglingDebugInfoVector &DDIV = DDIMI.second; 1183 1184 // If debug info is to be dropped, run it through final checks to see 1185 // whether it can be salvaged. 1186 for (auto &DDI : DDIV) 1187 if (isMatchingDbgValue(DDI)) 1188 salvageUnresolvedDbgValue(DDI); 1189 1190 erase_if(DDIV, isMatchingDbgValue); 1191 } 1192 } 1193 1194 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1195 // generate the debug data structures now that we've seen its definition. 1196 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1197 SDValue Val) { 1198 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1199 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1200 return; 1201 1202 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1203 for (auto &DDI : DDIV) { 1204 const DbgValueInst *DI = DDI.getDI(); 1205 assert(!DI->hasArgList() && "Not implemented for variadic dbg_values"); 1206 assert(DI && "Ill-formed DanglingDebugInfo"); 1207 DebugLoc dl = DDI.getdl(); 1208 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1209 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1210 DILocalVariable *Variable = DI->getVariable(); 1211 DIExpression *Expr = DI->getExpression(); 1212 assert(Variable->isValidLocationForIntrinsic(dl) && 1213 "Expected inlined-at fields to agree"); 1214 SDDbgValue *SDV; 1215 if (Val.getNode()) { 1216 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1217 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1218 // we couldn't resolve it directly when examining the DbgValue intrinsic 1219 // in the first place we should not be more successful here). Unless we 1220 // have some test case that prove this to be correct we should avoid 1221 // calling EmitFuncArgumentDbgValue here. 1222 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1223 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1224 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1225 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1226 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1227 // inserted after the definition of Val when emitting the instructions 1228 // after ISel. An alternative could be to teach 1229 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1230 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1231 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1232 << ValSDNodeOrder << "\n"); 1233 SDV = getDbgValue(Val, Variable, Expr, dl, 1234 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1235 DAG.AddDbgValue(SDV, false); 1236 } else 1237 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1238 << "in EmitFuncArgumentDbgValue\n"); 1239 } else { 1240 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1241 auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType()); 1242 auto SDV = 1243 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); 1244 DAG.AddDbgValue(SDV, false); 1245 } 1246 } 1247 DDIV.clear(); 1248 } 1249 1250 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1251 assert(!DDI.getDI()->hasArgList() && 1252 "Not implemented for variadic dbg_values"); 1253 Value *V = DDI.getDI()->getValue(0); 1254 DILocalVariable *Var = DDI.getDI()->getVariable(); 1255 DIExpression *Expr = DDI.getDI()->getExpression(); 1256 DebugLoc DL = DDI.getdl(); 1257 DebugLoc InstDL = DDI.getDI()->getDebugLoc(); 1258 unsigned SDOrder = DDI.getSDNodeOrder(); 1259 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1260 // that DW_OP_stack_value is desired. 1261 assert(isa<DbgValueInst>(DDI.getDI())); 1262 bool StackValue = true; 1263 1264 // Can this Value can be encoded without any further work? 1265 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, /*IsVariadic=*/false)) 1266 return; 1267 1268 // Attempt to salvage back through as many instructions as possible. Bail if 1269 // a non-instruction is seen, such as a constant expression or global 1270 // variable. FIXME: Further work could recover those too. 1271 while (isa<Instruction>(V)) { 1272 Instruction &VAsInst = *cast<Instruction>(V); 1273 // Temporary "0", awaiting real implementation. 1274 DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue, 0); 1275 1276 // If we cannot salvage any further, and haven't yet found a suitable debug 1277 // expression, bail out. 1278 if (!NewExpr) 1279 break; 1280 1281 // New value and expr now represent this debuginfo. 1282 V = VAsInst.getOperand(0); 1283 Expr = NewExpr; 1284 1285 // Some kind of simplification occurred: check whether the operand of the 1286 // salvaged debug expression can be encoded in this DAG. 1287 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, 1288 /*IsVariadic=*/false)) { 1289 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n " 1290 << DDI.getDI() << "\nBy stripping back to:\n " << V); 1291 return; 1292 } 1293 } 1294 1295 // This was the final opportunity to salvage this debug information, and it 1296 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1297 // any earlier variable location. 1298 auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType()); 1299 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1300 DAG.AddDbgValue(SDV, false); 1301 1302 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI() 1303 << "\n"); 1304 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0) 1305 << "\n"); 1306 } 1307 1308 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1309 DILocalVariable *Var, 1310 DIExpression *Expr, DebugLoc dl, 1311 DebugLoc InstDL, unsigned Order, 1312 bool IsVariadic) { 1313 if (Values.empty()) 1314 return true; 1315 SmallVector<SDDbgOperand> LocationOps; 1316 SmallVector<SDNode *> Dependencies; 1317 for (const Value *V : Values) { 1318 // Constant value. 1319 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1320 isa<ConstantPointerNull>(V)) { 1321 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1322 continue; 1323 } 1324 1325 // If the Value is a frame index, we can create a FrameIndex debug value 1326 // without relying on the DAG at all. 1327 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1328 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1329 if (SI != FuncInfo.StaticAllocaMap.end()) { 1330 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1331 continue; 1332 } 1333 } 1334 1335 // Do not use getValue() in here; we don't want to generate code at 1336 // this point if it hasn't been done yet. 1337 SDValue N = NodeMap[V]; 1338 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1339 N = UnusedArgNodeMap[V]; 1340 if (N.getNode()) { 1341 // Only emit func arg dbg value for non-variadic dbg.values for now. 1342 if (!IsVariadic && EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N)) 1343 return true; 1344 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1345 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1346 // describe stack slot locations. 1347 // 1348 // Consider "int x = 0; int *px = &x;". There are two kinds of 1349 // interesting debug values here after optimization: 1350 // 1351 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1352 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1353 // 1354 // Both describe the direct values of their associated variables. 1355 Dependencies.push_back(N.getNode()); 1356 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1357 continue; 1358 } 1359 LocationOps.emplace_back( 1360 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1361 continue; 1362 } 1363 1364 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1365 // Special rules apply for the first dbg.values of parameter variables in a 1366 // function. Identify them by the fact they reference Argument Values, that 1367 // they're parameters, and they are parameters of the current function. We 1368 // need to let them dangle until they get an SDNode. 1369 bool IsParamOfFunc = 1370 isa<Argument>(V) && Var->isParameter() && !InstDL.getInlinedAt(); 1371 if (IsParamOfFunc) 1372 return false; 1373 1374 // The value is not used in this block yet (or it would have an SDNode). 1375 // We still want the value to appear for the user if possible -- if it has 1376 // an associated VReg, we can refer to that instead. 1377 auto VMI = FuncInfo.ValueMap.find(V); 1378 if (VMI != FuncInfo.ValueMap.end()) { 1379 unsigned Reg = VMI->second; 1380 // If this is a PHI node, it may be split up into several MI PHI nodes 1381 // (in FunctionLoweringInfo::set). 1382 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1383 V->getType(), None); 1384 if (RFV.occupiesMultipleRegs()) { 1385 // FIXME: We could potentially support variadic dbg_values here. 1386 if (IsVariadic) 1387 return false; 1388 unsigned Offset = 0; 1389 unsigned BitsToDescribe = 0; 1390 if (auto VarSize = Var->getSizeInBits()) 1391 BitsToDescribe = *VarSize; 1392 if (auto Fragment = Expr->getFragmentInfo()) 1393 BitsToDescribe = Fragment->SizeInBits; 1394 for (auto RegAndSize : RFV.getRegsAndSizes()) { 1395 // Bail out if all bits are described already. 1396 if (Offset >= BitsToDescribe) 1397 break; 1398 // TODO: handle scalable vectors. 1399 unsigned RegisterSize = RegAndSize.second; 1400 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1401 ? BitsToDescribe - Offset 1402 : RegisterSize; 1403 auto FragmentExpr = DIExpression::createFragmentExpression( 1404 Expr, Offset, FragmentSize); 1405 if (!FragmentExpr) 1406 continue; 1407 SDDbgValue *SDV = DAG.getVRegDbgValue( 1408 Var, *FragmentExpr, RegAndSize.first, false, dl, SDNodeOrder); 1409 DAG.AddDbgValue(SDV, false); 1410 Offset += RegisterSize; 1411 } 1412 return true; 1413 } 1414 // We can use simple vreg locations for variadic dbg_values as well. 1415 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1416 continue; 1417 } 1418 // We failed to create a SDDbgOperand for V. 1419 return false; 1420 } 1421 1422 // We have created a SDDbgOperand for each Value in Values. 1423 // Should use Order instead of SDNodeOrder? 1424 assert(!LocationOps.empty()); 1425 SDDbgValue *SDV = 1426 DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1427 /*IsIndirect=*/false, dl, SDNodeOrder, IsVariadic); 1428 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1429 return true; 1430 } 1431 1432 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1433 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1434 for (auto &Pair : DanglingDebugInfoMap) 1435 for (auto &DDI : Pair.second) 1436 salvageUnresolvedDbgValue(DDI); 1437 clearDanglingDebugInfo(); 1438 } 1439 1440 /// getCopyFromRegs - If there was virtual register allocated for the value V 1441 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1442 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1443 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1444 SDValue Result; 1445 1446 if (It != FuncInfo.ValueMap.end()) { 1447 Register InReg = It->second; 1448 1449 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1450 DAG.getDataLayout(), InReg, Ty, 1451 None); // This is not an ABI copy. 1452 SDValue Chain = DAG.getEntryNode(); 1453 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1454 V); 1455 resolveDanglingDebugInfo(V, Result); 1456 } 1457 1458 return Result; 1459 } 1460 1461 /// getValue - Return an SDValue for the given Value. 1462 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1463 // If we already have an SDValue for this value, use it. It's important 1464 // to do this first, so that we don't create a CopyFromReg if we already 1465 // have a regular SDValue. 1466 SDValue &N = NodeMap[V]; 1467 if (N.getNode()) return N; 1468 1469 // If there's a virtual register allocated and initialized for this 1470 // value, use it. 1471 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1472 return copyFromReg; 1473 1474 // Otherwise create a new SDValue and remember it. 1475 SDValue Val = getValueImpl(V); 1476 NodeMap[V] = Val; 1477 resolveDanglingDebugInfo(V, Val); 1478 return Val; 1479 } 1480 1481 /// getNonRegisterValue - Return an SDValue for the given Value, but 1482 /// don't look in FuncInfo.ValueMap for a virtual register. 1483 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1484 // If we already have an SDValue for this value, use it. 1485 SDValue &N = NodeMap[V]; 1486 if (N.getNode()) { 1487 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1488 // Remove the debug location from the node as the node is about to be used 1489 // in a location which may differ from the original debug location. This 1490 // is relevant to Constant and ConstantFP nodes because they can appear 1491 // as constant expressions inside PHI nodes. 1492 N->setDebugLoc(DebugLoc()); 1493 } 1494 return N; 1495 } 1496 1497 // Otherwise create a new SDValue and remember it. 1498 SDValue Val = getValueImpl(V); 1499 NodeMap[V] = Val; 1500 resolveDanglingDebugInfo(V, Val); 1501 return Val; 1502 } 1503 1504 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1505 /// Create an SDValue for the given value. 1506 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1507 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1508 1509 if (const Constant *C = dyn_cast<Constant>(V)) { 1510 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1511 1512 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1513 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1514 1515 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1516 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1517 1518 if (isa<ConstantPointerNull>(C)) { 1519 unsigned AS = V->getType()->getPointerAddressSpace(); 1520 return DAG.getConstant(0, getCurSDLoc(), 1521 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1522 } 1523 1524 if (match(C, m_VScale(DAG.getDataLayout()))) 1525 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1526 1527 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1528 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1529 1530 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1531 return DAG.getUNDEF(VT); 1532 1533 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1534 visit(CE->getOpcode(), *CE); 1535 SDValue N1 = NodeMap[V]; 1536 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1537 return N1; 1538 } 1539 1540 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1541 SmallVector<SDValue, 4> Constants; 1542 for (const Use &U : C->operands()) { 1543 SDNode *Val = getValue(U).getNode(); 1544 // If the operand is an empty aggregate, there are no values. 1545 if (!Val) continue; 1546 // Add each leaf value from the operand to the Constants list 1547 // to form a flattened list of all the values. 1548 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1549 Constants.push_back(SDValue(Val, i)); 1550 } 1551 1552 return DAG.getMergeValues(Constants, getCurSDLoc()); 1553 } 1554 1555 if (const ConstantDataSequential *CDS = 1556 dyn_cast<ConstantDataSequential>(C)) { 1557 SmallVector<SDValue, 4> Ops; 1558 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1559 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1560 // Add each leaf value from the operand to the Constants list 1561 // to form a flattened list of all the values. 1562 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1563 Ops.push_back(SDValue(Val, i)); 1564 } 1565 1566 if (isa<ArrayType>(CDS->getType())) 1567 return DAG.getMergeValues(Ops, getCurSDLoc()); 1568 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1569 } 1570 1571 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1572 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1573 "Unknown struct or array constant!"); 1574 1575 SmallVector<EVT, 4> ValueVTs; 1576 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1577 unsigned NumElts = ValueVTs.size(); 1578 if (NumElts == 0) 1579 return SDValue(); // empty struct 1580 SmallVector<SDValue, 4> Constants(NumElts); 1581 for (unsigned i = 0; i != NumElts; ++i) { 1582 EVT EltVT = ValueVTs[i]; 1583 if (isa<UndefValue>(C)) 1584 Constants[i] = DAG.getUNDEF(EltVT); 1585 else if (EltVT.isFloatingPoint()) 1586 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1587 else 1588 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1589 } 1590 1591 return DAG.getMergeValues(Constants, getCurSDLoc()); 1592 } 1593 1594 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1595 return DAG.getBlockAddress(BA, VT); 1596 1597 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1598 return getValue(Equiv->getGlobalValue()); 1599 1600 VectorType *VecTy = cast<VectorType>(V->getType()); 1601 1602 // Now that we know the number and type of the elements, get that number of 1603 // elements into the Ops array based on what kind of constant it is. 1604 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1605 SmallVector<SDValue, 16> Ops; 1606 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1607 for (unsigned i = 0; i != NumElements; ++i) 1608 Ops.push_back(getValue(CV->getOperand(i))); 1609 1610 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1611 } else if (isa<ConstantAggregateZero>(C)) { 1612 EVT EltVT = 1613 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1614 1615 SDValue Op; 1616 if (EltVT.isFloatingPoint()) 1617 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1618 else 1619 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1620 1621 if (isa<ScalableVectorType>(VecTy)) 1622 return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op); 1623 else { 1624 SmallVector<SDValue, 16> Ops; 1625 Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op); 1626 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1627 } 1628 } 1629 llvm_unreachable("Unknown vector constant"); 1630 } 1631 1632 // If this is a static alloca, generate it as the frameindex instead of 1633 // computation. 1634 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1635 DenseMap<const AllocaInst*, int>::iterator SI = 1636 FuncInfo.StaticAllocaMap.find(AI); 1637 if (SI != FuncInfo.StaticAllocaMap.end()) 1638 return DAG.getFrameIndex(SI->second, 1639 TLI.getFrameIndexTy(DAG.getDataLayout())); 1640 } 1641 1642 // If this is an instruction which fast-isel has deferred, select it now. 1643 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1644 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1645 1646 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1647 Inst->getType(), None); 1648 SDValue Chain = DAG.getEntryNode(); 1649 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1650 } 1651 1652 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) { 1653 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1654 } 1655 llvm_unreachable("Can't get register for value!"); 1656 } 1657 1658 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1659 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1660 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1661 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1662 bool IsSEH = isAsynchronousEHPersonality(Pers); 1663 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1664 if (!IsSEH) 1665 CatchPadMBB->setIsEHScopeEntry(); 1666 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1667 if (IsMSVCCXX || IsCoreCLR) 1668 CatchPadMBB->setIsEHFuncletEntry(); 1669 } 1670 1671 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1672 // Update machine-CFG edge. 1673 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1674 FuncInfo.MBB->addSuccessor(TargetMBB); 1675 TargetMBB->setIsEHCatchretTarget(true); 1676 DAG.getMachineFunction().setHasEHCatchret(true); 1677 1678 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1679 bool IsSEH = isAsynchronousEHPersonality(Pers); 1680 if (IsSEH) { 1681 // If this is not a fall-through branch or optimizations are switched off, 1682 // emit the branch. 1683 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1684 TM.getOptLevel() == CodeGenOpt::None) 1685 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1686 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1687 return; 1688 } 1689 1690 // Figure out the funclet membership for the catchret's successor. 1691 // This will be used by the FuncletLayout pass to determine how to order the 1692 // BB's. 1693 // A 'catchret' returns to the outer scope's color. 1694 Value *ParentPad = I.getCatchSwitchParentPad(); 1695 const BasicBlock *SuccessorColor; 1696 if (isa<ConstantTokenNone>(ParentPad)) 1697 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1698 else 1699 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1700 assert(SuccessorColor && "No parent funclet for catchret!"); 1701 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1702 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1703 1704 // Create the terminator node. 1705 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1706 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1707 DAG.getBasicBlock(SuccessorColorMBB)); 1708 DAG.setRoot(Ret); 1709 } 1710 1711 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1712 // Don't emit any special code for the cleanuppad instruction. It just marks 1713 // the start of an EH scope/funclet. 1714 FuncInfo.MBB->setIsEHScopeEntry(); 1715 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1716 if (Pers != EHPersonality::Wasm_CXX) { 1717 FuncInfo.MBB->setIsEHFuncletEntry(); 1718 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1719 } 1720 } 1721 1722 // In wasm EH, even though a catchpad may not catch an exception if a tag does 1723 // not match, it is OK to add only the first unwind destination catchpad to the 1724 // successors, because there will be at least one invoke instruction within the 1725 // catch scope that points to the next unwind destination, if one exists, so 1726 // CFGSort cannot mess up with BB sorting order. 1727 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 1728 // call within them, and catchpads only consisting of 'catch (...)' have a 1729 // '__cxa_end_catch' call within them, both of which generate invokes in case 1730 // the next unwind destination exists, i.e., the next unwind destination is not 1731 // the caller.) 1732 // 1733 // Having at most one EH pad successor is also simpler and helps later 1734 // transformations. 1735 // 1736 // For example, 1737 // current: 1738 // invoke void @foo to ... unwind label %catch.dispatch 1739 // catch.dispatch: 1740 // %0 = catchswitch within ... [label %catch.start] unwind label %next 1741 // catch.start: 1742 // ... 1743 // ... in this BB or some other child BB dominated by this BB there will be an 1744 // invoke that points to 'next' BB as an unwind destination 1745 // 1746 // next: ; We don't need to add this to 'current' BB's successor 1747 // ... 1748 static void findWasmUnwindDestinations( 1749 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1750 BranchProbability Prob, 1751 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1752 &UnwindDests) { 1753 while (EHPadBB) { 1754 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1755 if (isa<CleanupPadInst>(Pad)) { 1756 // Stop on cleanup pads. 1757 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1758 UnwindDests.back().first->setIsEHScopeEntry(); 1759 break; 1760 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1761 // Add the catchpad handlers to the possible destinations. We don't 1762 // continue to the unwind destination of the catchswitch for wasm. 1763 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1764 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1765 UnwindDests.back().first->setIsEHScopeEntry(); 1766 } 1767 break; 1768 } else { 1769 continue; 1770 } 1771 } 1772 } 1773 1774 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1775 /// many places it could ultimately go. In the IR, we have a single unwind 1776 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1777 /// This function skips over imaginary basic blocks that hold catchswitch 1778 /// instructions, and finds all the "real" machine 1779 /// basic block destinations. As those destinations may not be successors of 1780 /// EHPadBB, here we also calculate the edge probability to those destinations. 1781 /// The passed-in Prob is the edge probability to EHPadBB. 1782 static void findUnwindDestinations( 1783 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1784 BranchProbability Prob, 1785 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1786 &UnwindDests) { 1787 EHPersonality Personality = 1788 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1789 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1790 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1791 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1792 bool IsSEH = isAsynchronousEHPersonality(Personality); 1793 1794 if (IsWasmCXX) { 1795 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1796 assert(UnwindDests.size() <= 1 && 1797 "There should be at most one unwind destination for wasm"); 1798 return; 1799 } 1800 1801 while (EHPadBB) { 1802 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1803 BasicBlock *NewEHPadBB = nullptr; 1804 if (isa<LandingPadInst>(Pad)) { 1805 // Stop on landingpads. They are not funclets. 1806 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1807 break; 1808 } else if (isa<CleanupPadInst>(Pad)) { 1809 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1810 // personalities. 1811 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1812 UnwindDests.back().first->setIsEHScopeEntry(); 1813 UnwindDests.back().first->setIsEHFuncletEntry(); 1814 break; 1815 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1816 // Add the catchpad handlers to the possible destinations. 1817 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1818 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1819 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1820 if (IsMSVCCXX || IsCoreCLR) 1821 UnwindDests.back().first->setIsEHFuncletEntry(); 1822 if (!IsSEH) 1823 UnwindDests.back().first->setIsEHScopeEntry(); 1824 } 1825 NewEHPadBB = CatchSwitch->getUnwindDest(); 1826 } else { 1827 continue; 1828 } 1829 1830 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1831 if (BPI && NewEHPadBB) 1832 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1833 EHPadBB = NewEHPadBB; 1834 } 1835 } 1836 1837 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1838 // Update successor info. 1839 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1840 auto UnwindDest = I.getUnwindDest(); 1841 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1842 BranchProbability UnwindDestProb = 1843 (BPI && UnwindDest) 1844 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1845 : BranchProbability::getZero(); 1846 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1847 for (auto &UnwindDest : UnwindDests) { 1848 UnwindDest.first->setIsEHPad(); 1849 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1850 } 1851 FuncInfo.MBB->normalizeSuccProbs(); 1852 1853 // Create the terminator node. 1854 SDValue Ret = 1855 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1856 DAG.setRoot(Ret); 1857 } 1858 1859 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1860 report_fatal_error("visitCatchSwitch not yet implemented!"); 1861 } 1862 1863 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1864 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1865 auto &DL = DAG.getDataLayout(); 1866 SDValue Chain = getControlRoot(); 1867 SmallVector<ISD::OutputArg, 8> Outs; 1868 SmallVector<SDValue, 8> OutVals; 1869 1870 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1871 // lower 1872 // 1873 // %val = call <ty> @llvm.experimental.deoptimize() 1874 // ret <ty> %val 1875 // 1876 // differently. 1877 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1878 LowerDeoptimizingReturn(); 1879 return; 1880 } 1881 1882 if (!FuncInfo.CanLowerReturn) { 1883 unsigned DemoteReg = FuncInfo.DemoteRegister; 1884 const Function *F = I.getParent()->getParent(); 1885 1886 // Emit a store of the return value through the virtual register. 1887 // Leave Outs empty so that LowerReturn won't try to load return 1888 // registers the usual way. 1889 SmallVector<EVT, 1> PtrValueVTs; 1890 ComputeValueVTs(TLI, DL, 1891 F->getReturnType()->getPointerTo( 1892 DAG.getDataLayout().getAllocaAddrSpace()), 1893 PtrValueVTs); 1894 1895 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1896 DemoteReg, PtrValueVTs[0]); 1897 SDValue RetOp = getValue(I.getOperand(0)); 1898 1899 SmallVector<EVT, 4> ValueVTs, MemVTs; 1900 SmallVector<uint64_t, 4> Offsets; 1901 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1902 &Offsets); 1903 unsigned NumValues = ValueVTs.size(); 1904 1905 SmallVector<SDValue, 4> Chains(NumValues); 1906 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 1907 for (unsigned i = 0; i != NumValues; ++i) { 1908 // An aggregate return value cannot wrap around the address space, so 1909 // offsets to its parts don't wrap either. 1910 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 1911 TypeSize::Fixed(Offsets[i])); 1912 1913 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 1914 if (MemVTs[i] != ValueVTs[i]) 1915 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 1916 Chains[i] = DAG.getStore( 1917 Chain, getCurSDLoc(), Val, 1918 // FIXME: better loc info would be nice. 1919 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 1920 commonAlignment(BaseAlign, Offsets[i])); 1921 } 1922 1923 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1924 MVT::Other, Chains); 1925 } else if (I.getNumOperands() != 0) { 1926 SmallVector<EVT, 4> ValueVTs; 1927 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1928 unsigned NumValues = ValueVTs.size(); 1929 if (NumValues) { 1930 SDValue RetOp = getValue(I.getOperand(0)); 1931 1932 const Function *F = I.getParent()->getParent(); 1933 1934 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 1935 I.getOperand(0)->getType(), F->getCallingConv(), 1936 /*IsVarArg*/ false); 1937 1938 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1939 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1940 Attribute::SExt)) 1941 ExtendKind = ISD::SIGN_EXTEND; 1942 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1943 Attribute::ZExt)) 1944 ExtendKind = ISD::ZERO_EXTEND; 1945 1946 LLVMContext &Context = F->getContext(); 1947 bool RetInReg = F->getAttributes().hasAttribute( 1948 AttributeList::ReturnIndex, Attribute::InReg); 1949 1950 for (unsigned j = 0; j != NumValues; ++j) { 1951 EVT VT = ValueVTs[j]; 1952 1953 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1954 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1955 1956 CallingConv::ID CC = F->getCallingConv(); 1957 1958 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1959 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1960 SmallVector<SDValue, 4> Parts(NumParts); 1961 getCopyToParts(DAG, getCurSDLoc(), 1962 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1963 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1964 1965 // 'inreg' on function refers to return value 1966 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1967 if (RetInReg) 1968 Flags.setInReg(); 1969 1970 if (I.getOperand(0)->getType()->isPointerTy()) { 1971 Flags.setPointer(); 1972 Flags.setPointerAddrSpace( 1973 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 1974 } 1975 1976 if (NeedsRegBlock) { 1977 Flags.setInConsecutiveRegs(); 1978 if (j == NumValues - 1) 1979 Flags.setInConsecutiveRegsLast(); 1980 } 1981 1982 // Propagate extension type if any 1983 if (ExtendKind == ISD::SIGN_EXTEND) 1984 Flags.setSExt(); 1985 else if (ExtendKind == ISD::ZERO_EXTEND) 1986 Flags.setZExt(); 1987 1988 for (unsigned i = 0; i < NumParts; ++i) { 1989 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1990 VT, /*isfixed=*/true, 0, 0)); 1991 OutVals.push_back(Parts[i]); 1992 } 1993 } 1994 } 1995 } 1996 1997 // Push in swifterror virtual register as the last element of Outs. This makes 1998 // sure swifterror virtual register will be returned in the swifterror 1999 // physical register. 2000 const Function *F = I.getParent()->getParent(); 2001 if (TLI.supportSwiftError() && 2002 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2003 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2004 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2005 Flags.setSwiftError(); 2006 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 2007 EVT(TLI.getPointerTy(DL)) /*argvt*/, 2008 true /*isfixed*/, 1 /*origidx*/, 2009 0 /*partOffs*/)); 2010 // Create SDNode for the swifterror virtual register. 2011 OutVals.push_back( 2012 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2013 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2014 EVT(TLI.getPointerTy(DL)))); 2015 } 2016 2017 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2018 CallingConv::ID CallConv = 2019 DAG.getMachineFunction().getFunction().getCallingConv(); 2020 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2021 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2022 2023 // Verify that the target's LowerReturn behaved as expected. 2024 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2025 "LowerReturn didn't return a valid chain!"); 2026 2027 // Update the DAG with the new chain value resulting from return lowering. 2028 DAG.setRoot(Chain); 2029 } 2030 2031 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2032 /// created for it, emit nodes to copy the value into the virtual 2033 /// registers. 2034 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2035 // Skip empty types 2036 if (V->getType()->isEmptyTy()) 2037 return; 2038 2039 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2040 if (VMI != FuncInfo.ValueMap.end()) { 2041 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 2042 CopyValueToVirtualRegister(V, VMI->second); 2043 } 2044 } 2045 2046 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2047 /// the current basic block, add it to ValueMap now so that we'll get a 2048 /// CopyTo/FromReg. 2049 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2050 // No need to export constants. 2051 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2052 2053 // Already exported? 2054 if (FuncInfo.isExportedInst(V)) return; 2055 2056 unsigned Reg = FuncInfo.InitializeRegForValue(V); 2057 CopyValueToVirtualRegister(V, Reg); 2058 } 2059 2060 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2061 const BasicBlock *FromBB) { 2062 // The operands of the setcc have to be in this block. We don't know 2063 // how to export them from some other block. 2064 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2065 // Can export from current BB. 2066 if (VI->getParent() == FromBB) 2067 return true; 2068 2069 // Is already exported, noop. 2070 return FuncInfo.isExportedInst(V); 2071 } 2072 2073 // If this is an argument, we can export it if the BB is the entry block or 2074 // if it is already exported. 2075 if (isa<Argument>(V)) { 2076 if (FromBB->isEntryBlock()) 2077 return true; 2078 2079 // Otherwise, can only export this if it is already exported. 2080 return FuncInfo.isExportedInst(V); 2081 } 2082 2083 // Otherwise, constants can always be exported. 2084 return true; 2085 } 2086 2087 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2088 BranchProbability 2089 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2090 const MachineBasicBlock *Dst) const { 2091 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2092 const BasicBlock *SrcBB = Src->getBasicBlock(); 2093 const BasicBlock *DstBB = Dst->getBasicBlock(); 2094 if (!BPI) { 2095 // If BPI is not available, set the default probability as 1 / N, where N is 2096 // the number of successors. 2097 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2098 return BranchProbability(1, SuccSize); 2099 } 2100 return BPI->getEdgeProbability(SrcBB, DstBB); 2101 } 2102 2103 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2104 MachineBasicBlock *Dst, 2105 BranchProbability Prob) { 2106 if (!FuncInfo.BPI) 2107 Src->addSuccessorWithoutProb(Dst); 2108 else { 2109 if (Prob.isUnknown()) 2110 Prob = getEdgeProbability(Src, Dst); 2111 Src->addSuccessor(Dst, Prob); 2112 } 2113 } 2114 2115 static bool InBlock(const Value *V, const BasicBlock *BB) { 2116 if (const Instruction *I = dyn_cast<Instruction>(V)) 2117 return I->getParent() == BB; 2118 return true; 2119 } 2120 2121 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2122 /// This function emits a branch and is used at the leaves of an OR or an 2123 /// AND operator tree. 2124 void 2125 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2126 MachineBasicBlock *TBB, 2127 MachineBasicBlock *FBB, 2128 MachineBasicBlock *CurBB, 2129 MachineBasicBlock *SwitchBB, 2130 BranchProbability TProb, 2131 BranchProbability FProb, 2132 bool InvertCond) { 2133 const BasicBlock *BB = CurBB->getBasicBlock(); 2134 2135 // If the leaf of the tree is a comparison, merge the condition into 2136 // the caseblock. 2137 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2138 // The operands of the cmp have to be in this block. We don't know 2139 // how to export them from some other block. If this is the first block 2140 // of the sequence, no exporting is needed. 2141 if (CurBB == SwitchBB || 2142 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2143 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2144 ISD::CondCode Condition; 2145 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2146 ICmpInst::Predicate Pred = 2147 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2148 Condition = getICmpCondCode(Pred); 2149 } else { 2150 const FCmpInst *FC = cast<FCmpInst>(Cond); 2151 FCmpInst::Predicate Pred = 2152 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2153 Condition = getFCmpCondCode(Pred); 2154 if (TM.Options.NoNaNsFPMath) 2155 Condition = getFCmpCodeWithoutNaN(Condition); 2156 } 2157 2158 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2159 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2160 SL->SwitchCases.push_back(CB); 2161 return; 2162 } 2163 } 2164 2165 // Create a CaseBlock record representing this branch. 2166 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2167 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2168 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2169 SL->SwitchCases.push_back(CB); 2170 } 2171 2172 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2173 MachineBasicBlock *TBB, 2174 MachineBasicBlock *FBB, 2175 MachineBasicBlock *CurBB, 2176 MachineBasicBlock *SwitchBB, 2177 Instruction::BinaryOps Opc, 2178 BranchProbability TProb, 2179 BranchProbability FProb, 2180 bool InvertCond) { 2181 // Skip over not part of the tree and remember to invert op and operands at 2182 // next level. 2183 Value *NotCond; 2184 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2185 InBlock(NotCond, CurBB->getBasicBlock())) { 2186 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2187 !InvertCond); 2188 return; 2189 } 2190 2191 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2192 const Value *BOpOp0, *BOpOp1; 2193 // Compute the effective opcode for Cond, taking into account whether it needs 2194 // to be inverted, e.g. 2195 // and (not (or A, B)), C 2196 // gets lowered as 2197 // and (and (not A, not B), C) 2198 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2199 if (BOp) { 2200 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2201 ? Instruction::And 2202 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2203 ? Instruction::Or 2204 : (Instruction::BinaryOps)0); 2205 if (InvertCond) { 2206 if (BOpc == Instruction::And) 2207 BOpc = Instruction::Or; 2208 else if (BOpc == Instruction::Or) 2209 BOpc = Instruction::And; 2210 } 2211 } 2212 2213 // If this node is not part of the or/and tree, emit it as a branch. 2214 // Note that all nodes in the tree should have same opcode. 2215 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2216 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2217 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2218 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2219 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2220 TProb, FProb, InvertCond); 2221 return; 2222 } 2223 2224 // Create TmpBB after CurBB. 2225 MachineFunction::iterator BBI(CurBB); 2226 MachineFunction &MF = DAG.getMachineFunction(); 2227 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2228 CurBB->getParent()->insert(++BBI, TmpBB); 2229 2230 if (Opc == Instruction::Or) { 2231 // Codegen X | Y as: 2232 // BB1: 2233 // jmp_if_X TBB 2234 // jmp TmpBB 2235 // TmpBB: 2236 // jmp_if_Y TBB 2237 // jmp FBB 2238 // 2239 2240 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2241 // The requirement is that 2242 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2243 // = TrueProb for original BB. 2244 // Assuming the original probabilities are A and B, one choice is to set 2245 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2246 // A/(1+B) and 2B/(1+B). This choice assumes that 2247 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2248 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2249 // TmpBB, but the math is more complicated. 2250 2251 auto NewTrueProb = TProb / 2; 2252 auto NewFalseProb = TProb / 2 + FProb; 2253 // Emit the LHS condition. 2254 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2255 NewFalseProb, InvertCond); 2256 2257 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2258 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2259 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2260 // Emit the RHS condition into TmpBB. 2261 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2262 Probs[1], InvertCond); 2263 } else { 2264 assert(Opc == Instruction::And && "Unknown merge op!"); 2265 // Codegen X & Y as: 2266 // BB1: 2267 // jmp_if_X TmpBB 2268 // jmp FBB 2269 // TmpBB: 2270 // jmp_if_Y TBB 2271 // jmp FBB 2272 // 2273 // This requires creation of TmpBB after CurBB. 2274 2275 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2276 // The requirement is that 2277 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2278 // = FalseProb for original BB. 2279 // Assuming the original probabilities are A and B, one choice is to set 2280 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2281 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2282 // TrueProb for BB1 * FalseProb for TmpBB. 2283 2284 auto NewTrueProb = TProb + FProb / 2; 2285 auto NewFalseProb = FProb / 2; 2286 // Emit the LHS condition. 2287 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2288 NewFalseProb, InvertCond); 2289 2290 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2291 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2292 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2293 // Emit the RHS condition into TmpBB. 2294 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2295 Probs[1], InvertCond); 2296 } 2297 } 2298 2299 /// If the set of cases should be emitted as a series of branches, return true. 2300 /// If we should emit this as a bunch of and/or'd together conditions, return 2301 /// false. 2302 bool 2303 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2304 if (Cases.size() != 2) return true; 2305 2306 // If this is two comparisons of the same values or'd or and'd together, they 2307 // will get folded into a single comparison, so don't emit two blocks. 2308 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2309 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2310 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2311 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2312 return false; 2313 } 2314 2315 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2316 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2317 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2318 Cases[0].CC == Cases[1].CC && 2319 isa<Constant>(Cases[0].CmpRHS) && 2320 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2321 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2322 return false; 2323 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2324 return false; 2325 } 2326 2327 return true; 2328 } 2329 2330 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2331 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2332 2333 // Update machine-CFG edges. 2334 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2335 2336 if (I.isUnconditional()) { 2337 // Update machine-CFG edges. 2338 BrMBB->addSuccessor(Succ0MBB); 2339 2340 // If this is not a fall-through branch or optimizations are switched off, 2341 // emit the branch. 2342 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2343 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2344 MVT::Other, getControlRoot(), 2345 DAG.getBasicBlock(Succ0MBB))); 2346 2347 return; 2348 } 2349 2350 // If this condition is one of the special cases we handle, do special stuff 2351 // now. 2352 const Value *CondVal = I.getCondition(); 2353 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2354 2355 // If this is a series of conditions that are or'd or and'd together, emit 2356 // this as a sequence of branches instead of setcc's with and/or operations. 2357 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2358 // unpredictable branches, and vector extracts because those jumps are likely 2359 // expensive for any target), this should improve performance. 2360 // For example, instead of something like: 2361 // cmp A, B 2362 // C = seteq 2363 // cmp D, E 2364 // F = setle 2365 // or C, F 2366 // jnz foo 2367 // Emit: 2368 // cmp A, B 2369 // je foo 2370 // cmp D, E 2371 // jle foo 2372 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2373 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2374 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2375 Value *Vec; 2376 const Value *BOp0, *BOp1; 2377 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2378 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2379 Opcode = Instruction::And; 2380 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2381 Opcode = Instruction::Or; 2382 2383 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2384 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2385 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2386 getEdgeProbability(BrMBB, Succ0MBB), 2387 getEdgeProbability(BrMBB, Succ1MBB), 2388 /*InvertCond=*/false); 2389 // If the compares in later blocks need to use values not currently 2390 // exported from this block, export them now. This block should always 2391 // be the first entry. 2392 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2393 2394 // Allow some cases to be rejected. 2395 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2396 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2397 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2398 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2399 } 2400 2401 // Emit the branch for this block. 2402 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2403 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2404 return; 2405 } 2406 2407 // Okay, we decided not to do this, remove any inserted MBB's and clear 2408 // SwitchCases. 2409 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2410 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2411 2412 SL->SwitchCases.clear(); 2413 } 2414 } 2415 2416 // Create a CaseBlock record representing this branch. 2417 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2418 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2419 2420 // Use visitSwitchCase to actually insert the fast branch sequence for this 2421 // cond branch. 2422 visitSwitchCase(CB, BrMBB); 2423 } 2424 2425 /// visitSwitchCase - Emits the necessary code to represent a single node in 2426 /// the binary search tree resulting from lowering a switch instruction. 2427 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2428 MachineBasicBlock *SwitchBB) { 2429 SDValue Cond; 2430 SDValue CondLHS = getValue(CB.CmpLHS); 2431 SDLoc dl = CB.DL; 2432 2433 if (CB.CC == ISD::SETTRUE) { 2434 // Branch or fall through to TrueBB. 2435 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2436 SwitchBB->normalizeSuccProbs(); 2437 if (CB.TrueBB != NextBlock(SwitchBB)) { 2438 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2439 DAG.getBasicBlock(CB.TrueBB))); 2440 } 2441 return; 2442 } 2443 2444 auto &TLI = DAG.getTargetLoweringInfo(); 2445 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2446 2447 // Build the setcc now. 2448 if (!CB.CmpMHS) { 2449 // Fold "(X == true)" to X and "(X == false)" to !X to 2450 // handle common cases produced by branch lowering. 2451 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2452 CB.CC == ISD::SETEQ) 2453 Cond = CondLHS; 2454 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2455 CB.CC == ISD::SETEQ) { 2456 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2457 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2458 } else { 2459 SDValue CondRHS = getValue(CB.CmpRHS); 2460 2461 // If a pointer's DAG type is larger than its memory type then the DAG 2462 // values are zero-extended. This breaks signed comparisons so truncate 2463 // back to the underlying type before doing the compare. 2464 if (CondLHS.getValueType() != MemVT) { 2465 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2466 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2467 } 2468 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2469 } 2470 } else { 2471 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2472 2473 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2474 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2475 2476 SDValue CmpOp = getValue(CB.CmpMHS); 2477 EVT VT = CmpOp.getValueType(); 2478 2479 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2480 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2481 ISD::SETLE); 2482 } else { 2483 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2484 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2485 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2486 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2487 } 2488 } 2489 2490 // Update successor info 2491 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2492 // TrueBB and FalseBB are always different unless the incoming IR is 2493 // degenerate. This only happens when running llc on weird IR. 2494 if (CB.TrueBB != CB.FalseBB) 2495 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2496 SwitchBB->normalizeSuccProbs(); 2497 2498 // If the lhs block is the next block, invert the condition so that we can 2499 // fall through to the lhs instead of the rhs block. 2500 if (CB.TrueBB == NextBlock(SwitchBB)) { 2501 std::swap(CB.TrueBB, CB.FalseBB); 2502 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2503 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2504 } 2505 2506 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2507 MVT::Other, getControlRoot(), Cond, 2508 DAG.getBasicBlock(CB.TrueBB)); 2509 2510 // Insert the false branch. Do this even if it's a fall through branch, 2511 // this makes it easier to do DAG optimizations which require inverting 2512 // the branch condition. 2513 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2514 DAG.getBasicBlock(CB.FalseBB)); 2515 2516 DAG.setRoot(BrCond); 2517 } 2518 2519 /// visitJumpTable - Emit JumpTable node in the current MBB 2520 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2521 // Emit the code for the jump table 2522 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2523 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2524 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2525 JT.Reg, PTy); 2526 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2527 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2528 MVT::Other, Index.getValue(1), 2529 Table, Index); 2530 DAG.setRoot(BrJumpTable); 2531 } 2532 2533 /// visitJumpTableHeader - This function emits necessary code to produce index 2534 /// in the JumpTable from switch case. 2535 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2536 JumpTableHeader &JTH, 2537 MachineBasicBlock *SwitchBB) { 2538 SDLoc dl = getCurSDLoc(); 2539 2540 // Subtract the lowest switch case value from the value being switched on. 2541 SDValue SwitchOp = getValue(JTH.SValue); 2542 EVT VT = SwitchOp.getValueType(); 2543 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2544 DAG.getConstant(JTH.First, dl, VT)); 2545 2546 // The SDNode we just created, which holds the value being switched on minus 2547 // the smallest case value, needs to be copied to a virtual register so it 2548 // can be used as an index into the jump table in a subsequent basic block. 2549 // This value may be smaller or larger than the target's pointer type, and 2550 // therefore require extension or truncating. 2551 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2552 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2553 2554 unsigned JumpTableReg = 2555 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2556 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2557 JumpTableReg, SwitchOp); 2558 JT.Reg = JumpTableReg; 2559 2560 if (!JTH.OmitRangeCheck) { 2561 // Emit the range check for the jump table, and branch to the default block 2562 // for the switch statement if the value being switched on exceeds the 2563 // largest case in the switch. 2564 SDValue CMP = DAG.getSetCC( 2565 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2566 Sub.getValueType()), 2567 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2568 2569 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2570 MVT::Other, CopyTo, CMP, 2571 DAG.getBasicBlock(JT.Default)); 2572 2573 // Avoid emitting unnecessary branches to the next block. 2574 if (JT.MBB != NextBlock(SwitchBB)) 2575 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2576 DAG.getBasicBlock(JT.MBB)); 2577 2578 DAG.setRoot(BrCond); 2579 } else { 2580 // Avoid emitting unnecessary branches to the next block. 2581 if (JT.MBB != NextBlock(SwitchBB)) 2582 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2583 DAG.getBasicBlock(JT.MBB))); 2584 else 2585 DAG.setRoot(CopyTo); 2586 } 2587 } 2588 2589 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2590 /// variable if there exists one. 2591 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2592 SDValue &Chain) { 2593 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2594 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2595 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2596 MachineFunction &MF = DAG.getMachineFunction(); 2597 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2598 MachineSDNode *Node = 2599 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2600 if (Global) { 2601 MachinePointerInfo MPInfo(Global); 2602 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2603 MachineMemOperand::MODereferenceable; 2604 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2605 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2606 DAG.setNodeMemRefs(Node, {MemRef}); 2607 } 2608 if (PtrTy != PtrMemTy) 2609 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2610 return SDValue(Node, 0); 2611 } 2612 2613 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2614 /// tail spliced into a stack protector check success bb. 2615 /// 2616 /// For a high level explanation of how this fits into the stack protector 2617 /// generation see the comment on the declaration of class 2618 /// StackProtectorDescriptor. 2619 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2620 MachineBasicBlock *ParentBB) { 2621 2622 // First create the loads to the guard/stack slot for the comparison. 2623 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2624 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2625 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2626 2627 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2628 int FI = MFI.getStackProtectorIndex(); 2629 2630 SDValue Guard; 2631 SDLoc dl = getCurSDLoc(); 2632 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2633 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2634 Align Align = DL->getPrefTypeAlign(Type::getInt8PtrTy(M.getContext())); 2635 2636 // Generate code to load the content of the guard slot. 2637 SDValue GuardVal = DAG.getLoad( 2638 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2639 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2640 MachineMemOperand::MOVolatile); 2641 2642 if (TLI.useStackGuardXorFP()) 2643 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2644 2645 // Retrieve guard check function, nullptr if instrumentation is inlined. 2646 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2647 // The target provides a guard check function to validate the guard value. 2648 // Generate a call to that function with the content of the guard slot as 2649 // argument. 2650 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2651 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2652 2653 TargetLowering::ArgListTy Args; 2654 TargetLowering::ArgListEntry Entry; 2655 Entry.Node = GuardVal; 2656 Entry.Ty = FnTy->getParamType(0); 2657 if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg)) 2658 Entry.IsInReg = true; 2659 Args.push_back(Entry); 2660 2661 TargetLowering::CallLoweringInfo CLI(DAG); 2662 CLI.setDebugLoc(getCurSDLoc()) 2663 .setChain(DAG.getEntryNode()) 2664 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2665 getValue(GuardCheckFn), std::move(Args)); 2666 2667 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2668 DAG.setRoot(Result.second); 2669 return; 2670 } 2671 2672 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2673 // Otherwise, emit a volatile load to retrieve the stack guard value. 2674 SDValue Chain = DAG.getEntryNode(); 2675 if (TLI.useLoadStackGuardNode()) { 2676 Guard = getLoadStackGuard(DAG, dl, Chain); 2677 } else { 2678 const Value *IRGuard = TLI.getSDagStackGuard(M); 2679 SDValue GuardPtr = getValue(IRGuard); 2680 2681 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2682 MachinePointerInfo(IRGuard, 0), Align, 2683 MachineMemOperand::MOVolatile); 2684 } 2685 2686 // Perform the comparison via a getsetcc. 2687 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2688 *DAG.getContext(), 2689 Guard.getValueType()), 2690 Guard, GuardVal, ISD::SETNE); 2691 2692 // If the guard/stackslot do not equal, branch to failure MBB. 2693 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2694 MVT::Other, GuardVal.getOperand(0), 2695 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2696 // Otherwise branch to success MBB. 2697 SDValue Br = DAG.getNode(ISD::BR, dl, 2698 MVT::Other, BrCond, 2699 DAG.getBasicBlock(SPD.getSuccessMBB())); 2700 2701 DAG.setRoot(Br); 2702 } 2703 2704 /// Codegen the failure basic block for a stack protector check. 2705 /// 2706 /// A failure stack protector machine basic block consists simply of a call to 2707 /// __stack_chk_fail(). 2708 /// 2709 /// For a high level explanation of how this fits into the stack protector 2710 /// generation see the comment on the declaration of class 2711 /// StackProtectorDescriptor. 2712 void 2713 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2714 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2715 TargetLowering::MakeLibCallOptions CallOptions; 2716 CallOptions.setDiscardResult(true); 2717 SDValue Chain = 2718 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2719 None, CallOptions, getCurSDLoc()).second; 2720 // On PS4, the "return address" must still be within the calling function, 2721 // even if it's at the very end, so emit an explicit TRAP here. 2722 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2723 if (TM.getTargetTriple().isPS4CPU()) 2724 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2725 // WebAssembly needs an unreachable instruction after a non-returning call, 2726 // because the function return type can be different from __stack_chk_fail's 2727 // return type (void). 2728 if (TM.getTargetTriple().isWasm()) 2729 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2730 2731 DAG.setRoot(Chain); 2732 } 2733 2734 /// visitBitTestHeader - This function emits necessary code to produce value 2735 /// suitable for "bit tests" 2736 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2737 MachineBasicBlock *SwitchBB) { 2738 SDLoc dl = getCurSDLoc(); 2739 2740 // Subtract the minimum value. 2741 SDValue SwitchOp = getValue(B.SValue); 2742 EVT VT = SwitchOp.getValueType(); 2743 SDValue RangeSub = 2744 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2745 2746 // Determine the type of the test operands. 2747 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2748 bool UsePtrType = false; 2749 if (!TLI.isTypeLegal(VT)) { 2750 UsePtrType = true; 2751 } else { 2752 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2753 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2754 // Switch table case range are encoded into series of masks. 2755 // Just use pointer type, it's guaranteed to fit. 2756 UsePtrType = true; 2757 break; 2758 } 2759 } 2760 SDValue Sub = RangeSub; 2761 if (UsePtrType) { 2762 VT = TLI.getPointerTy(DAG.getDataLayout()); 2763 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2764 } 2765 2766 B.RegVT = VT.getSimpleVT(); 2767 B.Reg = FuncInfo.CreateReg(B.RegVT); 2768 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2769 2770 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2771 2772 if (!B.OmitRangeCheck) 2773 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2774 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2775 SwitchBB->normalizeSuccProbs(); 2776 2777 SDValue Root = CopyTo; 2778 if (!B.OmitRangeCheck) { 2779 // Conditional branch to the default block. 2780 SDValue RangeCmp = DAG.getSetCC(dl, 2781 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2782 RangeSub.getValueType()), 2783 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2784 ISD::SETUGT); 2785 2786 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2787 DAG.getBasicBlock(B.Default)); 2788 } 2789 2790 // Avoid emitting unnecessary branches to the next block. 2791 if (MBB != NextBlock(SwitchBB)) 2792 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2793 2794 DAG.setRoot(Root); 2795 } 2796 2797 /// visitBitTestCase - this function produces one "bit test" 2798 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2799 MachineBasicBlock* NextMBB, 2800 BranchProbability BranchProbToNext, 2801 unsigned Reg, 2802 BitTestCase &B, 2803 MachineBasicBlock *SwitchBB) { 2804 SDLoc dl = getCurSDLoc(); 2805 MVT VT = BB.RegVT; 2806 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2807 SDValue Cmp; 2808 unsigned PopCount = countPopulation(B.Mask); 2809 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2810 if (PopCount == 1) { 2811 // Testing for a single bit; just compare the shift count with what it 2812 // would need to be to shift a 1 bit in that position. 2813 Cmp = DAG.getSetCC( 2814 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2815 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2816 ISD::SETEQ); 2817 } else if (PopCount == BB.Range) { 2818 // There is only one zero bit in the range, test for it directly. 2819 Cmp = DAG.getSetCC( 2820 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2821 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2822 ISD::SETNE); 2823 } else { 2824 // Make desired shift 2825 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2826 DAG.getConstant(1, dl, VT), ShiftOp); 2827 2828 // Emit bit tests and jumps 2829 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2830 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2831 Cmp = DAG.getSetCC( 2832 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2833 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2834 } 2835 2836 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2837 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2838 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2839 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2840 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2841 // one as they are relative probabilities (and thus work more like weights), 2842 // and hence we need to normalize them to let the sum of them become one. 2843 SwitchBB->normalizeSuccProbs(); 2844 2845 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2846 MVT::Other, getControlRoot(), 2847 Cmp, DAG.getBasicBlock(B.TargetBB)); 2848 2849 // Avoid emitting unnecessary branches to the next block. 2850 if (NextMBB != NextBlock(SwitchBB)) 2851 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2852 DAG.getBasicBlock(NextMBB)); 2853 2854 DAG.setRoot(BrAnd); 2855 } 2856 2857 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2858 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2859 2860 // Retrieve successors. Look through artificial IR level blocks like 2861 // catchswitch for successors. 2862 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2863 const BasicBlock *EHPadBB = I.getSuccessor(1); 2864 2865 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2866 // have to do anything here to lower funclet bundles. 2867 assert(!I.hasOperandBundlesOtherThan( 2868 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 2869 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 2870 LLVMContext::OB_cfguardtarget, 2871 LLVMContext::OB_clang_arc_attachedcall}) && 2872 "Cannot lower invokes with arbitrary operand bundles yet!"); 2873 2874 const Value *Callee(I.getCalledOperand()); 2875 const Function *Fn = dyn_cast<Function>(Callee); 2876 if (isa<InlineAsm>(Callee)) 2877 visitInlineAsm(I, EHPadBB); 2878 else if (Fn && Fn->isIntrinsic()) { 2879 switch (Fn->getIntrinsicID()) { 2880 default: 2881 llvm_unreachable("Cannot invoke this intrinsic"); 2882 case Intrinsic::donothing: 2883 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2884 case Intrinsic::seh_try_begin: 2885 case Intrinsic::seh_scope_begin: 2886 case Intrinsic::seh_try_end: 2887 case Intrinsic::seh_scope_end: 2888 break; 2889 case Intrinsic::experimental_patchpoint_void: 2890 case Intrinsic::experimental_patchpoint_i64: 2891 visitPatchpoint(I, EHPadBB); 2892 break; 2893 case Intrinsic::experimental_gc_statepoint: 2894 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 2895 break; 2896 case Intrinsic::wasm_rethrow: { 2897 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2898 // special because it can be invoked, so we manually lower it to a DAG 2899 // node here. 2900 SmallVector<SDValue, 8> Ops; 2901 Ops.push_back(getRoot()); // inchain 2902 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2903 Ops.push_back( 2904 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 2905 TLI.getPointerTy(DAG.getDataLayout()))); 2906 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2907 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2908 break; 2909 } 2910 } 2911 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2912 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2913 // Eventually we will support lowering the @llvm.experimental.deoptimize 2914 // intrinsic, and right now there are no plans to support other intrinsics 2915 // with deopt state. 2916 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2917 } else { 2918 LowerCallTo(I, getValue(Callee), false, false, EHPadBB); 2919 } 2920 2921 // If the value of the invoke is used outside of its defining block, make it 2922 // available as a virtual register. 2923 // We already took care of the exported value for the statepoint instruction 2924 // during call to the LowerStatepoint. 2925 if (!isa<GCStatepointInst>(I)) { 2926 CopyToExportRegsIfNeeded(&I); 2927 } 2928 2929 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2930 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2931 BranchProbability EHPadBBProb = 2932 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2933 : BranchProbability::getZero(); 2934 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2935 2936 // Update successor info. 2937 addSuccessorWithProb(InvokeMBB, Return); 2938 for (auto &UnwindDest : UnwindDests) { 2939 UnwindDest.first->setIsEHPad(); 2940 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2941 } 2942 InvokeMBB->normalizeSuccProbs(); 2943 2944 // Drop into normal successor. 2945 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 2946 DAG.getBasicBlock(Return))); 2947 } 2948 2949 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 2950 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 2951 2952 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2953 // have to do anything here to lower funclet bundles. 2954 assert(!I.hasOperandBundlesOtherThan( 2955 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2956 "Cannot lower callbrs with arbitrary operand bundles yet!"); 2957 2958 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 2959 visitInlineAsm(I); 2960 CopyToExportRegsIfNeeded(&I); 2961 2962 // Retrieve successors. 2963 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 2964 2965 // Update successor info. 2966 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 2967 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 2968 MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)]; 2969 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 2970 Target->setIsInlineAsmBrIndirectTarget(); 2971 } 2972 CallBrMBB->normalizeSuccProbs(); 2973 2974 // Drop into default successor. 2975 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2976 MVT::Other, getControlRoot(), 2977 DAG.getBasicBlock(Return))); 2978 } 2979 2980 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2981 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2982 } 2983 2984 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2985 assert(FuncInfo.MBB->isEHPad() && 2986 "Call to landingpad not in landing pad!"); 2987 2988 // If there aren't registers to copy the values into (e.g., during SjLj 2989 // exceptions), then don't bother to create these DAG nodes. 2990 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2991 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2992 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2993 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2994 return; 2995 2996 // If landingpad's return type is token type, we don't create DAG nodes 2997 // for its exception pointer and selector value. The extraction of exception 2998 // pointer or selector value from token type landingpads is not currently 2999 // supported. 3000 if (LP.getType()->isTokenTy()) 3001 return; 3002 3003 SmallVector<EVT, 2> ValueVTs; 3004 SDLoc dl = getCurSDLoc(); 3005 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3006 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3007 3008 // Get the two live-in registers as SDValues. The physregs have already been 3009 // copied into virtual registers. 3010 SDValue Ops[2]; 3011 if (FuncInfo.ExceptionPointerVirtReg) { 3012 Ops[0] = DAG.getZExtOrTrunc( 3013 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3014 FuncInfo.ExceptionPointerVirtReg, 3015 TLI.getPointerTy(DAG.getDataLayout())), 3016 dl, ValueVTs[0]); 3017 } else { 3018 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3019 } 3020 Ops[1] = DAG.getZExtOrTrunc( 3021 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3022 FuncInfo.ExceptionSelectorVirtReg, 3023 TLI.getPointerTy(DAG.getDataLayout())), 3024 dl, ValueVTs[1]); 3025 3026 // Merge into one. 3027 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3028 DAG.getVTList(ValueVTs), Ops); 3029 setValue(&LP, Res); 3030 } 3031 3032 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3033 MachineBasicBlock *Last) { 3034 // Update JTCases. 3035 for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i) 3036 if (SL->JTCases[i].first.HeaderBB == First) 3037 SL->JTCases[i].first.HeaderBB = Last; 3038 3039 // Update BitTestCases. 3040 for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i) 3041 if (SL->BitTestCases[i].Parent == First) 3042 SL->BitTestCases[i].Parent = Last; 3043 } 3044 3045 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3046 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3047 3048 // Update machine-CFG edges with unique successors. 3049 SmallSet<BasicBlock*, 32> Done; 3050 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3051 BasicBlock *BB = I.getSuccessor(i); 3052 bool Inserted = Done.insert(BB).second; 3053 if (!Inserted) 3054 continue; 3055 3056 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3057 addSuccessorWithProb(IndirectBrMBB, Succ); 3058 } 3059 IndirectBrMBB->normalizeSuccProbs(); 3060 3061 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3062 MVT::Other, getControlRoot(), 3063 getValue(I.getAddress()))); 3064 } 3065 3066 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3067 if (!DAG.getTarget().Options.TrapUnreachable) 3068 return; 3069 3070 // We may be able to ignore unreachable behind a noreturn call. 3071 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3072 const BasicBlock &BB = *I.getParent(); 3073 if (&I != &BB.front()) { 3074 BasicBlock::const_iterator PredI = 3075 std::prev(BasicBlock::const_iterator(&I)); 3076 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 3077 if (Call->doesNotReturn()) 3078 return; 3079 } 3080 } 3081 } 3082 3083 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3084 } 3085 3086 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3087 SDNodeFlags Flags; 3088 3089 SDValue Op = getValue(I.getOperand(0)); 3090 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3091 Op, Flags); 3092 setValue(&I, UnNodeValue); 3093 } 3094 3095 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3096 SDNodeFlags Flags; 3097 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3098 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3099 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3100 } 3101 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3102 Flags.setExact(ExactOp->isExact()); 3103 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3104 Flags.copyFMF(*FPOp); 3105 3106 SDValue Op1 = getValue(I.getOperand(0)); 3107 SDValue Op2 = getValue(I.getOperand(1)); 3108 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3109 Op1, Op2, Flags); 3110 setValue(&I, BinNodeValue); 3111 } 3112 3113 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3114 SDValue Op1 = getValue(I.getOperand(0)); 3115 SDValue Op2 = getValue(I.getOperand(1)); 3116 3117 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3118 Op1.getValueType(), DAG.getDataLayout()); 3119 3120 // Coerce the shift amount to the right type if we can. 3121 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3122 unsigned ShiftSize = ShiftTy.getSizeInBits(); 3123 unsigned Op2Size = Op2.getValueSizeInBits(); 3124 SDLoc DL = getCurSDLoc(); 3125 3126 // If the operand is smaller than the shift count type, promote it. 3127 if (ShiftSize > Op2Size) 3128 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 3129 3130 // If the operand is larger than the shift count type but the shift 3131 // count type has enough bits to represent any shift value, truncate 3132 // it now. This is a common case and it exposes the truncate to 3133 // optimization early. 3134 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 3135 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 3136 // Otherwise we'll need to temporarily settle for some other convenient 3137 // type. Type legalization will make adjustments once the shiftee is split. 3138 else 3139 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 3140 } 3141 3142 bool nuw = false; 3143 bool nsw = false; 3144 bool exact = false; 3145 3146 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3147 3148 if (const OverflowingBinaryOperator *OFBinOp = 3149 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3150 nuw = OFBinOp->hasNoUnsignedWrap(); 3151 nsw = OFBinOp->hasNoSignedWrap(); 3152 } 3153 if (const PossiblyExactOperator *ExactOp = 3154 dyn_cast<const PossiblyExactOperator>(&I)) 3155 exact = ExactOp->isExact(); 3156 } 3157 SDNodeFlags Flags; 3158 Flags.setExact(exact); 3159 Flags.setNoSignedWrap(nsw); 3160 Flags.setNoUnsignedWrap(nuw); 3161 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3162 Flags); 3163 setValue(&I, Res); 3164 } 3165 3166 void SelectionDAGBuilder::visitSDiv(const User &I) { 3167 SDValue Op1 = getValue(I.getOperand(0)); 3168 SDValue Op2 = getValue(I.getOperand(1)); 3169 3170 SDNodeFlags Flags; 3171 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3172 cast<PossiblyExactOperator>(&I)->isExact()); 3173 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3174 Op2, Flags)); 3175 } 3176 3177 void SelectionDAGBuilder::visitICmp(const User &I) { 3178 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3179 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3180 predicate = IC->getPredicate(); 3181 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3182 predicate = ICmpInst::Predicate(IC->getPredicate()); 3183 SDValue Op1 = getValue(I.getOperand(0)); 3184 SDValue Op2 = getValue(I.getOperand(1)); 3185 ISD::CondCode Opcode = getICmpCondCode(predicate); 3186 3187 auto &TLI = DAG.getTargetLoweringInfo(); 3188 EVT MemVT = 3189 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3190 3191 // If a pointer's DAG type is larger than its memory type then the DAG values 3192 // are zero-extended. This breaks signed comparisons so truncate back to the 3193 // underlying type before doing the compare. 3194 if (Op1.getValueType() != MemVT) { 3195 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3196 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3197 } 3198 3199 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3200 I.getType()); 3201 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3202 } 3203 3204 void SelectionDAGBuilder::visitFCmp(const User &I) { 3205 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3206 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3207 predicate = FC->getPredicate(); 3208 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3209 predicate = FCmpInst::Predicate(FC->getPredicate()); 3210 SDValue Op1 = getValue(I.getOperand(0)); 3211 SDValue Op2 = getValue(I.getOperand(1)); 3212 3213 ISD::CondCode Condition = getFCmpCondCode(predicate); 3214 auto *FPMO = cast<FPMathOperator>(&I); 3215 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3216 Condition = getFCmpCodeWithoutNaN(Condition); 3217 3218 SDNodeFlags Flags; 3219 Flags.copyFMF(*FPMO); 3220 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3221 3222 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3223 I.getType()); 3224 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3225 } 3226 3227 // Check if the condition of the select has one use or two users that are both 3228 // selects with the same condition. 3229 static bool hasOnlySelectUsers(const Value *Cond) { 3230 return llvm::all_of(Cond->users(), [](const Value *V) { 3231 return isa<SelectInst>(V); 3232 }); 3233 } 3234 3235 void SelectionDAGBuilder::visitSelect(const User &I) { 3236 SmallVector<EVT, 4> ValueVTs; 3237 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3238 ValueVTs); 3239 unsigned NumValues = ValueVTs.size(); 3240 if (NumValues == 0) return; 3241 3242 SmallVector<SDValue, 4> Values(NumValues); 3243 SDValue Cond = getValue(I.getOperand(0)); 3244 SDValue LHSVal = getValue(I.getOperand(1)); 3245 SDValue RHSVal = getValue(I.getOperand(2)); 3246 SmallVector<SDValue, 1> BaseOps(1, Cond); 3247 ISD::NodeType OpCode = 3248 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3249 3250 bool IsUnaryAbs = false; 3251 bool Negate = false; 3252 3253 SDNodeFlags Flags; 3254 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3255 Flags.copyFMF(*FPOp); 3256 3257 // Min/max matching is only viable if all output VTs are the same. 3258 if (is_splat(ValueVTs)) { 3259 EVT VT = ValueVTs[0]; 3260 LLVMContext &Ctx = *DAG.getContext(); 3261 auto &TLI = DAG.getTargetLoweringInfo(); 3262 3263 // We care about the legality of the operation after it has been type 3264 // legalized. 3265 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3266 VT = TLI.getTypeToTransformTo(Ctx, VT); 3267 3268 // If the vselect is legal, assume we want to leave this as a vector setcc + 3269 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3270 // min/max is legal on the scalar type. 3271 bool UseScalarMinMax = VT.isVector() && 3272 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3273 3274 Value *LHS, *RHS; 3275 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3276 ISD::NodeType Opc = ISD::DELETED_NODE; 3277 switch (SPR.Flavor) { 3278 case SPF_UMAX: Opc = ISD::UMAX; break; 3279 case SPF_UMIN: Opc = ISD::UMIN; break; 3280 case SPF_SMAX: Opc = ISD::SMAX; break; 3281 case SPF_SMIN: Opc = ISD::SMIN; break; 3282 case SPF_FMINNUM: 3283 switch (SPR.NaNBehavior) { 3284 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3285 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3286 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3287 case SPNB_RETURNS_ANY: { 3288 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3289 Opc = ISD::FMINNUM; 3290 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3291 Opc = ISD::FMINIMUM; 3292 else if (UseScalarMinMax) 3293 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3294 ISD::FMINNUM : ISD::FMINIMUM; 3295 break; 3296 } 3297 } 3298 break; 3299 case SPF_FMAXNUM: 3300 switch (SPR.NaNBehavior) { 3301 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3302 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3303 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3304 case SPNB_RETURNS_ANY: 3305 3306 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3307 Opc = ISD::FMAXNUM; 3308 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3309 Opc = ISD::FMAXIMUM; 3310 else if (UseScalarMinMax) 3311 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3312 ISD::FMAXNUM : ISD::FMAXIMUM; 3313 break; 3314 } 3315 break; 3316 case SPF_NABS: 3317 Negate = true; 3318 LLVM_FALLTHROUGH; 3319 case SPF_ABS: 3320 IsUnaryAbs = true; 3321 Opc = ISD::ABS; 3322 break; 3323 default: break; 3324 } 3325 3326 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3327 (TLI.isOperationLegalOrCustom(Opc, VT) || 3328 (UseScalarMinMax && 3329 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3330 // If the underlying comparison instruction is used by any other 3331 // instruction, the consumed instructions won't be destroyed, so it is 3332 // not profitable to convert to a min/max. 3333 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3334 OpCode = Opc; 3335 LHSVal = getValue(LHS); 3336 RHSVal = getValue(RHS); 3337 BaseOps.clear(); 3338 } 3339 3340 if (IsUnaryAbs) { 3341 OpCode = Opc; 3342 LHSVal = getValue(LHS); 3343 BaseOps.clear(); 3344 } 3345 } 3346 3347 if (IsUnaryAbs) { 3348 for (unsigned i = 0; i != NumValues; ++i) { 3349 SDLoc dl = getCurSDLoc(); 3350 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3351 Values[i] = 3352 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3353 if (Negate) 3354 Values[i] = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), 3355 Values[i]); 3356 } 3357 } else { 3358 for (unsigned i = 0; i != NumValues; ++i) { 3359 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3360 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3361 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3362 Values[i] = DAG.getNode( 3363 OpCode, getCurSDLoc(), 3364 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3365 } 3366 } 3367 3368 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3369 DAG.getVTList(ValueVTs), Values)); 3370 } 3371 3372 void SelectionDAGBuilder::visitTrunc(const User &I) { 3373 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3374 SDValue N = getValue(I.getOperand(0)); 3375 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3376 I.getType()); 3377 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3378 } 3379 3380 void SelectionDAGBuilder::visitZExt(const User &I) { 3381 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3382 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3383 SDValue N = getValue(I.getOperand(0)); 3384 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3385 I.getType()); 3386 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3387 } 3388 3389 void SelectionDAGBuilder::visitSExt(const User &I) { 3390 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3391 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3392 SDValue N = getValue(I.getOperand(0)); 3393 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3394 I.getType()); 3395 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3396 } 3397 3398 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3399 // FPTrunc is never a no-op cast, no need to check 3400 SDValue N = getValue(I.getOperand(0)); 3401 SDLoc dl = getCurSDLoc(); 3402 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3403 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3404 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3405 DAG.getTargetConstant( 3406 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3407 } 3408 3409 void SelectionDAGBuilder::visitFPExt(const User &I) { 3410 // FPExt is never a no-op cast, no need to check 3411 SDValue N = getValue(I.getOperand(0)); 3412 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3413 I.getType()); 3414 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3415 } 3416 3417 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3418 // FPToUI 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_TO_UINT, getCurSDLoc(), DestVT, N)); 3423 } 3424 3425 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3426 // FPToSI 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_SINT, getCurSDLoc(), DestVT, N)); 3431 } 3432 3433 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3434 // UIToFP 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::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3439 } 3440 3441 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3442 // SIToFP 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::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3447 } 3448 3449 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3450 // What to do depends on the size of the integer and the size of the pointer. 3451 // We can either truncate, zero extend, or no-op, accordingly. 3452 SDValue N = getValue(I.getOperand(0)); 3453 auto &TLI = DAG.getTargetLoweringInfo(); 3454 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3455 I.getType()); 3456 EVT PtrMemVT = 3457 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3458 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3459 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3460 setValue(&I, N); 3461 } 3462 3463 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3464 // What to do depends on the size of the integer and the size of the pointer. 3465 // We can either truncate, zero extend, or no-op, accordingly. 3466 SDValue N = getValue(I.getOperand(0)); 3467 auto &TLI = DAG.getTargetLoweringInfo(); 3468 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3469 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3470 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3471 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3472 setValue(&I, N); 3473 } 3474 3475 void SelectionDAGBuilder::visitBitCast(const User &I) { 3476 SDValue N = getValue(I.getOperand(0)); 3477 SDLoc dl = getCurSDLoc(); 3478 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3479 I.getType()); 3480 3481 // BitCast assures us that source and destination are the same size so this is 3482 // either a BITCAST or a no-op. 3483 if (DestVT != N.getValueType()) 3484 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3485 DestVT, N)); // convert types. 3486 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3487 // might fold any kind of constant expression to an integer constant and that 3488 // is not what we are looking for. Only recognize a bitcast of a genuine 3489 // constant integer as an opaque constant. 3490 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3491 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3492 /*isOpaque*/true)); 3493 else 3494 setValue(&I, N); // noop cast. 3495 } 3496 3497 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3498 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3499 const Value *SV = I.getOperand(0); 3500 SDValue N = getValue(SV); 3501 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3502 3503 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3504 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3505 3506 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3507 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3508 3509 setValue(&I, N); 3510 } 3511 3512 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3513 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3514 SDValue InVec = getValue(I.getOperand(0)); 3515 SDValue InVal = getValue(I.getOperand(1)); 3516 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3517 TLI.getVectorIdxTy(DAG.getDataLayout())); 3518 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3519 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3520 InVec, InVal, InIdx)); 3521 } 3522 3523 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3524 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3525 SDValue InVec = getValue(I.getOperand(0)); 3526 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3527 TLI.getVectorIdxTy(DAG.getDataLayout())); 3528 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3529 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3530 InVec, InIdx)); 3531 } 3532 3533 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3534 SDValue Src1 = getValue(I.getOperand(0)); 3535 SDValue Src2 = getValue(I.getOperand(1)); 3536 ArrayRef<int> Mask; 3537 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3538 Mask = SVI->getShuffleMask(); 3539 else 3540 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3541 SDLoc DL = getCurSDLoc(); 3542 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3543 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3544 EVT SrcVT = Src1.getValueType(); 3545 3546 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3547 VT.isScalableVector()) { 3548 // Canonical splat form of first element of first input vector. 3549 SDValue FirstElt = 3550 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3551 DAG.getVectorIdxConstant(0, DL)); 3552 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3553 return; 3554 } 3555 3556 // For now, we only handle splats for scalable vectors. 3557 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3558 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3559 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3560 3561 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3562 unsigned MaskNumElts = Mask.size(); 3563 3564 if (SrcNumElts == MaskNumElts) { 3565 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3566 return; 3567 } 3568 3569 // Normalize the shuffle vector since mask and vector length don't match. 3570 if (SrcNumElts < MaskNumElts) { 3571 // Mask is longer than the source vectors. We can use concatenate vector to 3572 // make the mask and vectors lengths match. 3573 3574 if (MaskNumElts % SrcNumElts == 0) { 3575 // Mask length is a multiple of the source vector length. 3576 // Check if the shuffle is some kind of concatenation of the input 3577 // vectors. 3578 unsigned NumConcat = MaskNumElts / SrcNumElts; 3579 bool IsConcat = true; 3580 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3581 for (unsigned i = 0; i != MaskNumElts; ++i) { 3582 int Idx = Mask[i]; 3583 if (Idx < 0) 3584 continue; 3585 // Ensure the indices in each SrcVT sized piece are sequential and that 3586 // the same source is used for the whole piece. 3587 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3588 (ConcatSrcs[i / SrcNumElts] >= 0 && 3589 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3590 IsConcat = false; 3591 break; 3592 } 3593 // Remember which source this index came from. 3594 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3595 } 3596 3597 // The shuffle is concatenating multiple vectors together. Just emit 3598 // a CONCAT_VECTORS operation. 3599 if (IsConcat) { 3600 SmallVector<SDValue, 8> ConcatOps; 3601 for (auto Src : ConcatSrcs) { 3602 if (Src < 0) 3603 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3604 else if (Src == 0) 3605 ConcatOps.push_back(Src1); 3606 else 3607 ConcatOps.push_back(Src2); 3608 } 3609 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3610 return; 3611 } 3612 } 3613 3614 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3615 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3616 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3617 PaddedMaskNumElts); 3618 3619 // Pad both vectors with undefs to make them the same length as the mask. 3620 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3621 3622 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3623 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3624 MOps1[0] = Src1; 3625 MOps2[0] = Src2; 3626 3627 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3628 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3629 3630 // Readjust mask for new input vector length. 3631 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3632 for (unsigned i = 0; i != MaskNumElts; ++i) { 3633 int Idx = Mask[i]; 3634 if (Idx >= (int)SrcNumElts) 3635 Idx -= SrcNumElts - PaddedMaskNumElts; 3636 MappedOps[i] = Idx; 3637 } 3638 3639 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3640 3641 // If the concatenated vector was padded, extract a subvector with the 3642 // correct number of elements. 3643 if (MaskNumElts != PaddedMaskNumElts) 3644 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3645 DAG.getVectorIdxConstant(0, DL)); 3646 3647 setValue(&I, Result); 3648 return; 3649 } 3650 3651 if (SrcNumElts > MaskNumElts) { 3652 // Analyze the access pattern of the vector to see if we can extract 3653 // two subvectors and do the shuffle. 3654 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3655 bool CanExtract = true; 3656 for (int Idx : Mask) { 3657 unsigned Input = 0; 3658 if (Idx < 0) 3659 continue; 3660 3661 if (Idx >= (int)SrcNumElts) { 3662 Input = 1; 3663 Idx -= SrcNumElts; 3664 } 3665 3666 // If all the indices come from the same MaskNumElts sized portion of 3667 // the sources we can use extract. Also make sure the extract wouldn't 3668 // extract past the end of the source. 3669 int NewStartIdx = alignDown(Idx, MaskNumElts); 3670 if (NewStartIdx + MaskNumElts > SrcNumElts || 3671 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3672 CanExtract = false; 3673 // Make sure we always update StartIdx as we use it to track if all 3674 // elements are undef. 3675 StartIdx[Input] = NewStartIdx; 3676 } 3677 3678 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3679 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3680 return; 3681 } 3682 if (CanExtract) { 3683 // Extract appropriate subvector and generate a vector shuffle 3684 for (unsigned Input = 0; Input < 2; ++Input) { 3685 SDValue &Src = Input == 0 ? Src1 : Src2; 3686 if (StartIdx[Input] < 0) 3687 Src = DAG.getUNDEF(VT); 3688 else { 3689 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3690 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3691 } 3692 } 3693 3694 // Calculate new mask. 3695 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3696 for (int &Idx : MappedOps) { 3697 if (Idx >= (int)SrcNumElts) 3698 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3699 else if (Idx >= 0) 3700 Idx -= StartIdx[0]; 3701 } 3702 3703 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3704 return; 3705 } 3706 } 3707 3708 // We can't use either concat vectors or extract subvectors so fall back to 3709 // replacing the shuffle with extract and build vector. 3710 // to insert and build vector. 3711 EVT EltVT = VT.getVectorElementType(); 3712 SmallVector<SDValue,8> Ops; 3713 for (int Idx : Mask) { 3714 SDValue Res; 3715 3716 if (Idx < 0) { 3717 Res = DAG.getUNDEF(EltVT); 3718 } else { 3719 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3720 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3721 3722 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3723 DAG.getVectorIdxConstant(Idx, DL)); 3724 } 3725 3726 Ops.push_back(Res); 3727 } 3728 3729 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3730 } 3731 3732 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3733 ArrayRef<unsigned> Indices; 3734 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3735 Indices = IV->getIndices(); 3736 else 3737 Indices = cast<ConstantExpr>(&I)->getIndices(); 3738 3739 const Value *Op0 = I.getOperand(0); 3740 const Value *Op1 = I.getOperand(1); 3741 Type *AggTy = I.getType(); 3742 Type *ValTy = Op1->getType(); 3743 bool IntoUndef = isa<UndefValue>(Op0); 3744 bool FromUndef = isa<UndefValue>(Op1); 3745 3746 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3747 3748 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3749 SmallVector<EVT, 4> AggValueVTs; 3750 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3751 SmallVector<EVT, 4> ValValueVTs; 3752 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3753 3754 unsigned NumAggValues = AggValueVTs.size(); 3755 unsigned NumValValues = ValValueVTs.size(); 3756 SmallVector<SDValue, 4> Values(NumAggValues); 3757 3758 // Ignore an insertvalue that produces an empty object 3759 if (!NumAggValues) { 3760 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3761 return; 3762 } 3763 3764 SDValue Agg = getValue(Op0); 3765 unsigned i = 0; 3766 // Copy the beginning value(s) from the original aggregate. 3767 for (; i != LinearIndex; ++i) 3768 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3769 SDValue(Agg.getNode(), Agg.getResNo() + i); 3770 // Copy values from the inserted value(s). 3771 if (NumValValues) { 3772 SDValue Val = getValue(Op1); 3773 for (; i != LinearIndex + NumValValues; ++i) 3774 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3775 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3776 } 3777 // Copy remaining value(s) from the original aggregate. 3778 for (; i != NumAggValues; ++i) 3779 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3780 SDValue(Agg.getNode(), Agg.getResNo() + i); 3781 3782 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3783 DAG.getVTList(AggValueVTs), Values)); 3784 } 3785 3786 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3787 ArrayRef<unsigned> Indices; 3788 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3789 Indices = EV->getIndices(); 3790 else 3791 Indices = cast<ConstantExpr>(&I)->getIndices(); 3792 3793 const Value *Op0 = I.getOperand(0); 3794 Type *AggTy = Op0->getType(); 3795 Type *ValTy = I.getType(); 3796 bool OutOfUndef = isa<UndefValue>(Op0); 3797 3798 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3799 3800 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3801 SmallVector<EVT, 4> ValValueVTs; 3802 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3803 3804 unsigned NumValValues = ValValueVTs.size(); 3805 3806 // Ignore a extractvalue that produces an empty object 3807 if (!NumValValues) { 3808 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3809 return; 3810 } 3811 3812 SmallVector<SDValue, 4> Values(NumValValues); 3813 3814 SDValue Agg = getValue(Op0); 3815 // Copy out the selected value(s). 3816 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3817 Values[i - LinearIndex] = 3818 OutOfUndef ? 3819 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3820 SDValue(Agg.getNode(), Agg.getResNo() + i); 3821 3822 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3823 DAG.getVTList(ValValueVTs), Values)); 3824 } 3825 3826 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3827 Value *Op0 = I.getOperand(0); 3828 // Note that the pointer operand may be a vector of pointers. Take the scalar 3829 // element which holds a pointer. 3830 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3831 SDValue N = getValue(Op0); 3832 SDLoc dl = getCurSDLoc(); 3833 auto &TLI = DAG.getTargetLoweringInfo(); 3834 3835 // Normalize Vector GEP - all scalar operands should be converted to the 3836 // splat vector. 3837 bool IsVectorGEP = I.getType()->isVectorTy(); 3838 ElementCount VectorElementCount = 3839 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3840 : ElementCount::getFixed(0); 3841 3842 if (IsVectorGEP && !N.getValueType().isVector()) { 3843 LLVMContext &Context = *DAG.getContext(); 3844 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3845 if (VectorElementCount.isScalable()) 3846 N = DAG.getSplatVector(VT, dl, N); 3847 else 3848 N = DAG.getSplatBuildVector(VT, dl, N); 3849 } 3850 3851 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3852 GTI != E; ++GTI) { 3853 const Value *Idx = GTI.getOperand(); 3854 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3855 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3856 if (Field) { 3857 // N = N + Offset 3858 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3859 3860 // In an inbounds GEP with an offset that is nonnegative even when 3861 // interpreted as signed, assume there is no unsigned overflow. 3862 SDNodeFlags Flags; 3863 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3864 Flags.setNoUnsignedWrap(true); 3865 3866 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3867 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3868 } 3869 } else { 3870 // IdxSize is the width of the arithmetic according to IR semantics. 3871 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3872 // (and fix up the result later). 3873 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3874 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3875 TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType()); 3876 // We intentionally mask away the high bits here; ElementSize may not 3877 // fit in IdxTy. 3878 APInt ElementMul(IdxSize, ElementSize.getKnownMinSize()); 3879 bool ElementScalable = ElementSize.isScalable(); 3880 3881 // If this is a scalar constant or a splat vector of constants, 3882 // handle it quickly. 3883 const auto *C = dyn_cast<Constant>(Idx); 3884 if (C && isa<VectorType>(C->getType())) 3885 C = C->getSplatValue(); 3886 3887 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 3888 if (CI && CI->isZero()) 3889 continue; 3890 if (CI && !ElementScalable) { 3891 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 3892 LLVMContext &Context = *DAG.getContext(); 3893 SDValue OffsVal; 3894 if (IsVectorGEP) 3895 OffsVal = DAG.getConstant( 3896 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 3897 else 3898 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 3899 3900 // In an inbounds GEP with an offset that is nonnegative even when 3901 // interpreted as signed, assume there is no unsigned overflow. 3902 SDNodeFlags Flags; 3903 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3904 Flags.setNoUnsignedWrap(true); 3905 3906 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3907 3908 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3909 continue; 3910 } 3911 3912 // N = N + Idx * ElementMul; 3913 SDValue IdxN = getValue(Idx); 3914 3915 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 3916 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 3917 VectorElementCount); 3918 if (VectorElementCount.isScalable()) 3919 IdxN = DAG.getSplatVector(VT, dl, IdxN); 3920 else 3921 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3922 } 3923 3924 // If the index is smaller or larger than intptr_t, truncate or extend 3925 // it. 3926 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3927 3928 if (ElementScalable) { 3929 EVT VScaleTy = N.getValueType().getScalarType(); 3930 SDValue VScale = DAG.getNode( 3931 ISD::VSCALE, dl, VScaleTy, 3932 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 3933 if (IsVectorGEP) 3934 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 3935 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 3936 } else { 3937 // If this is a multiply by a power of two, turn it into a shl 3938 // immediately. This is a very common case. 3939 if (ElementMul != 1) { 3940 if (ElementMul.isPowerOf2()) { 3941 unsigned Amt = ElementMul.logBase2(); 3942 IdxN = DAG.getNode(ISD::SHL, dl, 3943 N.getValueType(), IdxN, 3944 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3945 } else { 3946 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 3947 IdxN.getValueType()); 3948 IdxN = DAG.getNode(ISD::MUL, dl, 3949 N.getValueType(), IdxN, Scale); 3950 } 3951 } 3952 } 3953 3954 N = DAG.getNode(ISD::ADD, dl, 3955 N.getValueType(), N, IdxN); 3956 } 3957 } 3958 3959 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 3960 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 3961 if (IsVectorGEP) { 3962 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 3963 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 3964 } 3965 3966 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 3967 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 3968 3969 setValue(&I, N); 3970 } 3971 3972 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3973 // If this is a fixed sized alloca in the entry block of the function, 3974 // allocate it statically on the stack. 3975 if (FuncInfo.StaticAllocaMap.count(&I)) 3976 return; // getValue will auto-populate this. 3977 3978 SDLoc dl = getCurSDLoc(); 3979 Type *Ty = I.getAllocatedType(); 3980 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3981 auto &DL = DAG.getDataLayout(); 3982 uint64_t TySize = DL.getTypeAllocSize(Ty); 3983 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 3984 3985 SDValue AllocSize = getValue(I.getArraySize()); 3986 3987 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3988 if (AllocSize.getValueType() != IntPtr) 3989 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3990 3991 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3992 AllocSize, 3993 DAG.getConstant(TySize, dl, IntPtr)); 3994 3995 // Handle alignment. If the requested alignment is less than or equal to 3996 // the stack alignment, ignore it. If the size is greater than or equal to 3997 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3998 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 3999 if (*Alignment <= StackAlign) 4000 Alignment = None; 4001 4002 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4003 // Round the size of the allocation up to the stack alignment size 4004 // by add SA-1 to the size. This doesn't overflow because we're computing 4005 // an address inside an alloca. 4006 SDNodeFlags Flags; 4007 Flags.setNoUnsignedWrap(true); 4008 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4009 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4010 4011 // Mask out the low bits for alignment purposes. 4012 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4013 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 4014 4015 SDValue Ops[] = { 4016 getRoot(), AllocSize, 4017 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4018 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4019 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4020 setValue(&I, DSA); 4021 DAG.setRoot(DSA.getValue(1)); 4022 4023 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4024 } 4025 4026 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4027 if (I.isAtomic()) 4028 return visitAtomicLoad(I); 4029 4030 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4031 const Value *SV = I.getOperand(0); 4032 if (TLI.supportSwiftError()) { 4033 // Swifterror values can come from either a function parameter with 4034 // swifterror attribute or an alloca with swifterror attribute. 4035 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4036 if (Arg->hasSwiftErrorAttr()) 4037 return visitLoadFromSwiftError(I); 4038 } 4039 4040 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4041 if (Alloca->isSwiftError()) 4042 return visitLoadFromSwiftError(I); 4043 } 4044 } 4045 4046 SDValue Ptr = getValue(SV); 4047 4048 Type *Ty = I.getType(); 4049 Align Alignment = I.getAlign(); 4050 4051 AAMDNodes AAInfo; 4052 I.getAAMetadata(AAInfo); 4053 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4054 4055 SmallVector<EVT, 4> ValueVTs, MemVTs; 4056 SmallVector<uint64_t, 4> Offsets; 4057 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4058 unsigned NumValues = ValueVTs.size(); 4059 if (NumValues == 0) 4060 return; 4061 4062 bool isVolatile = I.isVolatile(); 4063 4064 SDValue Root; 4065 bool ConstantMemory = false; 4066 if (isVolatile) 4067 // Serialize volatile loads with other side effects. 4068 Root = getRoot(); 4069 else if (NumValues > MaxParallelChains) 4070 Root = getMemoryRoot(); 4071 else if (AA && 4072 AA->pointsToConstantMemory(MemoryLocation( 4073 SV, 4074 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4075 AAInfo))) { 4076 // Do not serialize (non-volatile) loads of constant memory with anything. 4077 Root = DAG.getEntryNode(); 4078 ConstantMemory = true; 4079 } else { 4080 // Do not serialize non-volatile loads against each other. 4081 Root = DAG.getRoot(); 4082 } 4083 4084 SDLoc dl = getCurSDLoc(); 4085 4086 if (isVolatile) 4087 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4088 4089 // An aggregate load cannot wrap around the address space, so offsets to its 4090 // parts don't wrap either. 4091 SDNodeFlags Flags; 4092 Flags.setNoUnsignedWrap(true); 4093 4094 SmallVector<SDValue, 4> Values(NumValues); 4095 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4096 EVT PtrVT = Ptr.getValueType(); 4097 4098 MachineMemOperand::Flags MMOFlags 4099 = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4100 4101 unsigned ChainI = 0; 4102 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4103 // Serializing loads here may result in excessive register pressure, and 4104 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4105 // could recover a bit by hoisting nodes upward in the chain by recognizing 4106 // they are side-effect free or do not alias. The optimizer should really 4107 // avoid this case by converting large object/array copies to llvm.memcpy 4108 // (MaxParallelChains should always remain as failsafe). 4109 if (ChainI == MaxParallelChains) { 4110 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4111 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4112 makeArrayRef(Chains.data(), ChainI)); 4113 Root = Chain; 4114 ChainI = 0; 4115 } 4116 SDValue A = DAG.getNode(ISD::ADD, dl, 4117 PtrVT, Ptr, 4118 DAG.getConstant(Offsets[i], dl, PtrVT), 4119 Flags); 4120 4121 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4122 MachinePointerInfo(SV, Offsets[i]), Alignment, 4123 MMOFlags, AAInfo, Ranges); 4124 Chains[ChainI] = L.getValue(1); 4125 4126 if (MemVTs[i] != ValueVTs[i]) 4127 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4128 4129 Values[i] = L; 4130 } 4131 4132 if (!ConstantMemory) { 4133 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4134 makeArrayRef(Chains.data(), ChainI)); 4135 if (isVolatile) 4136 DAG.setRoot(Chain); 4137 else 4138 PendingLoads.push_back(Chain); 4139 } 4140 4141 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4142 DAG.getVTList(ValueVTs), Values)); 4143 } 4144 4145 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4146 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4147 "call visitStoreToSwiftError when backend supports swifterror"); 4148 4149 SmallVector<EVT, 4> ValueVTs; 4150 SmallVector<uint64_t, 4> Offsets; 4151 const Value *SrcV = I.getOperand(0); 4152 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4153 SrcV->getType(), ValueVTs, &Offsets); 4154 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4155 "expect a single EVT for swifterror"); 4156 4157 SDValue Src = getValue(SrcV); 4158 // Create a virtual register, then update the virtual register. 4159 Register VReg = 4160 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4161 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4162 // Chain can be getRoot or getControlRoot. 4163 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4164 SDValue(Src.getNode(), Src.getResNo())); 4165 DAG.setRoot(CopyNode); 4166 } 4167 4168 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4169 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4170 "call visitLoadFromSwiftError when backend supports swifterror"); 4171 4172 assert(!I.isVolatile() && 4173 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4174 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4175 "Support volatile, non temporal, invariant for load_from_swift_error"); 4176 4177 const Value *SV = I.getOperand(0); 4178 Type *Ty = I.getType(); 4179 AAMDNodes AAInfo; 4180 I.getAAMetadata(AAInfo); 4181 assert( 4182 (!AA || 4183 !AA->pointsToConstantMemory(MemoryLocation( 4184 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4185 AAInfo))) && 4186 "load_from_swift_error should not be constant memory"); 4187 4188 SmallVector<EVT, 4> ValueVTs; 4189 SmallVector<uint64_t, 4> Offsets; 4190 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4191 ValueVTs, &Offsets); 4192 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4193 "expect a single EVT for swifterror"); 4194 4195 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4196 SDValue L = DAG.getCopyFromReg( 4197 getRoot(), getCurSDLoc(), 4198 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4199 4200 setValue(&I, L); 4201 } 4202 4203 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4204 if (I.isAtomic()) 4205 return visitAtomicStore(I); 4206 4207 const Value *SrcV = I.getOperand(0); 4208 const Value *PtrV = I.getOperand(1); 4209 4210 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4211 if (TLI.supportSwiftError()) { 4212 // Swifterror values can come from either a function parameter with 4213 // swifterror attribute or an alloca with swifterror attribute. 4214 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4215 if (Arg->hasSwiftErrorAttr()) 4216 return visitStoreToSwiftError(I); 4217 } 4218 4219 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4220 if (Alloca->isSwiftError()) 4221 return visitStoreToSwiftError(I); 4222 } 4223 } 4224 4225 SmallVector<EVT, 4> ValueVTs, MemVTs; 4226 SmallVector<uint64_t, 4> Offsets; 4227 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4228 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4229 unsigned NumValues = ValueVTs.size(); 4230 if (NumValues == 0) 4231 return; 4232 4233 // Get the lowered operands. Note that we do this after 4234 // checking if NumResults is zero, because with zero results 4235 // the operands won't have values in the map. 4236 SDValue Src = getValue(SrcV); 4237 SDValue Ptr = getValue(PtrV); 4238 4239 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4240 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4241 SDLoc dl = getCurSDLoc(); 4242 Align Alignment = I.getAlign(); 4243 AAMDNodes AAInfo; 4244 I.getAAMetadata(AAInfo); 4245 4246 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4247 4248 // An aggregate load cannot wrap around the address space, so offsets to its 4249 // parts don't wrap either. 4250 SDNodeFlags Flags; 4251 Flags.setNoUnsignedWrap(true); 4252 4253 unsigned ChainI = 0; 4254 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4255 // See visitLoad comments. 4256 if (ChainI == MaxParallelChains) { 4257 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4258 makeArrayRef(Chains.data(), ChainI)); 4259 Root = Chain; 4260 ChainI = 0; 4261 } 4262 SDValue Add = 4263 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags); 4264 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4265 if (MemVTs[i] != ValueVTs[i]) 4266 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4267 SDValue St = 4268 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4269 Alignment, MMOFlags, AAInfo); 4270 Chains[ChainI] = St; 4271 } 4272 4273 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4274 makeArrayRef(Chains.data(), ChainI)); 4275 DAG.setRoot(StoreNode); 4276 } 4277 4278 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4279 bool IsCompressing) { 4280 SDLoc sdl = getCurSDLoc(); 4281 4282 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4283 MaybeAlign &Alignment) { 4284 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4285 Src0 = I.getArgOperand(0); 4286 Ptr = I.getArgOperand(1); 4287 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4288 Mask = I.getArgOperand(3); 4289 }; 4290 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4291 MaybeAlign &Alignment) { 4292 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4293 Src0 = I.getArgOperand(0); 4294 Ptr = I.getArgOperand(1); 4295 Mask = I.getArgOperand(2); 4296 Alignment = None; 4297 }; 4298 4299 Value *PtrOperand, *MaskOperand, *Src0Operand; 4300 MaybeAlign Alignment; 4301 if (IsCompressing) 4302 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4303 else 4304 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4305 4306 SDValue Ptr = getValue(PtrOperand); 4307 SDValue Src0 = getValue(Src0Operand); 4308 SDValue Mask = getValue(MaskOperand); 4309 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4310 4311 EVT VT = Src0.getValueType(); 4312 if (!Alignment) 4313 Alignment = DAG.getEVTAlign(VT); 4314 4315 AAMDNodes AAInfo; 4316 I.getAAMetadata(AAInfo); 4317 4318 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4319 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4320 // TODO: Make MachineMemOperands aware of scalable 4321 // vectors. 4322 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo); 4323 SDValue StoreNode = 4324 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4325 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4326 DAG.setRoot(StoreNode); 4327 setValue(&I, StoreNode); 4328 } 4329 4330 // Get a uniform base for the Gather/Scatter intrinsic. 4331 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4332 // We try to represent it as a base pointer + vector of indices. 4333 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4334 // The first operand of the GEP may be a single pointer or a vector of pointers 4335 // Example: 4336 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4337 // or 4338 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4339 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4340 // 4341 // When the first GEP operand is a single pointer - it is the uniform base we 4342 // are looking for. If first operand of the GEP is a splat vector - we 4343 // extract the splat value and use it as a uniform base. 4344 // In all other cases the function returns 'false'. 4345 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4346 ISD::MemIndexType &IndexType, SDValue &Scale, 4347 SelectionDAGBuilder *SDB, const BasicBlock *CurBB) { 4348 SelectionDAG& DAG = SDB->DAG; 4349 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4350 const DataLayout &DL = DAG.getDataLayout(); 4351 4352 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 4353 4354 // Handle splat constant pointer. 4355 if (auto *C = dyn_cast<Constant>(Ptr)) { 4356 C = C->getSplatValue(); 4357 if (!C) 4358 return false; 4359 4360 Base = SDB->getValue(C); 4361 4362 unsigned NumElts = cast<FixedVectorType>(Ptr->getType())->getNumElements(); 4363 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4364 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4365 IndexType = ISD::SIGNED_SCALED; 4366 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4367 return true; 4368 } 4369 4370 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4371 if (!GEP || GEP->getParent() != CurBB) 4372 return false; 4373 4374 if (GEP->getNumOperands() != 2) 4375 return false; 4376 4377 const Value *BasePtr = GEP->getPointerOperand(); 4378 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4379 4380 // Make sure the base is scalar and the index is a vector. 4381 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4382 return false; 4383 4384 Base = SDB->getValue(BasePtr); 4385 Index = SDB->getValue(IndexVal); 4386 IndexType = ISD::SIGNED_SCALED; 4387 Scale = DAG.getTargetConstant( 4388 DL.getTypeAllocSize(GEP->getResultElementType()), 4389 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4390 return true; 4391 } 4392 4393 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4394 SDLoc sdl = getCurSDLoc(); 4395 4396 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4397 const Value *Ptr = I.getArgOperand(1); 4398 SDValue Src0 = getValue(I.getArgOperand(0)); 4399 SDValue Mask = getValue(I.getArgOperand(3)); 4400 EVT VT = Src0.getValueType(); 4401 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4402 ->getMaybeAlignValue() 4403 .getValueOr(DAG.getEVTAlign(VT)); 4404 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4405 4406 AAMDNodes AAInfo; 4407 I.getAAMetadata(AAInfo); 4408 4409 SDValue Base; 4410 SDValue Index; 4411 ISD::MemIndexType IndexType; 4412 SDValue Scale; 4413 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4414 I.getParent()); 4415 4416 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4417 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4418 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4419 // TODO: Make MachineMemOperands aware of scalable 4420 // vectors. 4421 MemoryLocation::UnknownSize, Alignment, AAInfo); 4422 if (!UniformBase) { 4423 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4424 Index = getValue(Ptr); 4425 IndexType = ISD::SIGNED_UNSCALED; 4426 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4427 } 4428 4429 EVT IdxVT = Index.getValueType(); 4430 EVT EltTy = IdxVT.getVectorElementType(); 4431 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4432 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4433 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4434 } 4435 4436 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4437 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4438 Ops, MMO, IndexType, false); 4439 DAG.setRoot(Scatter); 4440 setValue(&I, Scatter); 4441 } 4442 4443 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4444 SDLoc sdl = getCurSDLoc(); 4445 4446 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4447 MaybeAlign &Alignment) { 4448 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4449 Ptr = I.getArgOperand(0); 4450 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4451 Mask = I.getArgOperand(2); 4452 Src0 = I.getArgOperand(3); 4453 }; 4454 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4455 MaybeAlign &Alignment) { 4456 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4457 Ptr = I.getArgOperand(0); 4458 Alignment = None; 4459 Mask = I.getArgOperand(1); 4460 Src0 = I.getArgOperand(2); 4461 }; 4462 4463 Value *PtrOperand, *MaskOperand, *Src0Operand; 4464 MaybeAlign Alignment; 4465 if (IsExpanding) 4466 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4467 else 4468 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4469 4470 SDValue Ptr = getValue(PtrOperand); 4471 SDValue Src0 = getValue(Src0Operand); 4472 SDValue Mask = getValue(MaskOperand); 4473 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4474 4475 EVT VT = Src0.getValueType(); 4476 if (!Alignment) 4477 Alignment = DAG.getEVTAlign(VT); 4478 4479 AAMDNodes AAInfo; 4480 I.getAAMetadata(AAInfo); 4481 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4482 4483 // Do not serialize masked loads of constant memory with anything. 4484 MemoryLocation ML; 4485 if (VT.isScalableVector()) 4486 ML = MemoryLocation::getAfter(PtrOperand); 4487 else 4488 ML = MemoryLocation(PtrOperand, LocationSize::precise( 4489 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4490 AAInfo); 4491 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4492 4493 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4494 4495 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4496 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4497 // TODO: Make MachineMemOperands aware of scalable 4498 // vectors. 4499 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges); 4500 4501 SDValue Load = 4502 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4503 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4504 if (AddToChain) 4505 PendingLoads.push_back(Load.getValue(1)); 4506 setValue(&I, Load); 4507 } 4508 4509 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4510 SDLoc sdl = getCurSDLoc(); 4511 4512 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4513 const Value *Ptr = I.getArgOperand(0); 4514 SDValue Src0 = getValue(I.getArgOperand(3)); 4515 SDValue Mask = getValue(I.getArgOperand(2)); 4516 4517 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4518 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4519 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4520 ->getMaybeAlignValue() 4521 .getValueOr(DAG.getEVTAlign(VT)); 4522 4523 AAMDNodes AAInfo; 4524 I.getAAMetadata(AAInfo); 4525 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4526 4527 SDValue Root = DAG.getRoot(); 4528 SDValue Base; 4529 SDValue Index; 4530 ISD::MemIndexType IndexType; 4531 SDValue Scale; 4532 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4533 I.getParent()); 4534 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4535 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4536 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4537 // TODO: Make MachineMemOperands aware of scalable 4538 // vectors. 4539 MemoryLocation::UnknownSize, Alignment, AAInfo, Ranges); 4540 4541 if (!UniformBase) { 4542 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4543 Index = getValue(Ptr); 4544 IndexType = ISD::SIGNED_UNSCALED; 4545 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4546 } 4547 4548 EVT IdxVT = Index.getValueType(); 4549 EVT EltTy = IdxVT.getVectorElementType(); 4550 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4551 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4552 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4553 } 4554 4555 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4556 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4557 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4558 4559 PendingLoads.push_back(Gather.getValue(1)); 4560 setValue(&I, Gather); 4561 } 4562 4563 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4564 SDLoc dl = getCurSDLoc(); 4565 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4566 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4567 SyncScope::ID SSID = I.getSyncScopeID(); 4568 4569 SDValue InChain = getRoot(); 4570 4571 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4572 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4573 4574 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4575 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4576 4577 MachineFunction &MF = DAG.getMachineFunction(); 4578 MachineMemOperand *MMO = MF.getMachineMemOperand( 4579 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4580 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4581 FailureOrdering); 4582 4583 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4584 dl, MemVT, VTs, InChain, 4585 getValue(I.getPointerOperand()), 4586 getValue(I.getCompareOperand()), 4587 getValue(I.getNewValOperand()), MMO); 4588 4589 SDValue OutChain = L.getValue(2); 4590 4591 setValue(&I, L); 4592 DAG.setRoot(OutChain); 4593 } 4594 4595 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4596 SDLoc dl = getCurSDLoc(); 4597 ISD::NodeType NT; 4598 switch (I.getOperation()) { 4599 default: llvm_unreachable("Unknown atomicrmw operation"); 4600 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4601 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4602 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4603 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4604 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4605 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4606 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4607 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4608 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4609 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4610 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4611 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4612 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4613 } 4614 AtomicOrdering Ordering = I.getOrdering(); 4615 SyncScope::ID SSID = I.getSyncScopeID(); 4616 4617 SDValue InChain = getRoot(); 4618 4619 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4620 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4621 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4622 4623 MachineFunction &MF = DAG.getMachineFunction(); 4624 MachineMemOperand *MMO = MF.getMachineMemOperand( 4625 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4626 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4627 4628 SDValue L = 4629 DAG.getAtomic(NT, dl, MemVT, InChain, 4630 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4631 MMO); 4632 4633 SDValue OutChain = L.getValue(1); 4634 4635 setValue(&I, L); 4636 DAG.setRoot(OutChain); 4637 } 4638 4639 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4640 SDLoc dl = getCurSDLoc(); 4641 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4642 SDValue Ops[3]; 4643 Ops[0] = getRoot(); 4644 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4645 TLI.getFenceOperandTy(DAG.getDataLayout())); 4646 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4647 TLI.getFenceOperandTy(DAG.getDataLayout())); 4648 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4649 } 4650 4651 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4652 SDLoc dl = getCurSDLoc(); 4653 AtomicOrdering Order = I.getOrdering(); 4654 SyncScope::ID SSID = I.getSyncScopeID(); 4655 4656 SDValue InChain = getRoot(); 4657 4658 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4659 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4660 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4661 4662 if (!TLI.supportsUnalignedAtomics() && 4663 I.getAlignment() < MemVT.getSizeInBits() / 8) 4664 report_fatal_error("Cannot generate unaligned atomic load"); 4665 4666 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4667 4668 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4669 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4670 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4671 4672 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4673 4674 SDValue Ptr = getValue(I.getPointerOperand()); 4675 4676 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4677 // TODO: Once this is better exercised by tests, it should be merged with 4678 // the normal path for loads to prevent future divergence. 4679 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4680 if (MemVT != VT) 4681 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4682 4683 setValue(&I, L); 4684 SDValue OutChain = L.getValue(1); 4685 if (!I.isUnordered()) 4686 DAG.setRoot(OutChain); 4687 else 4688 PendingLoads.push_back(OutChain); 4689 return; 4690 } 4691 4692 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4693 Ptr, MMO); 4694 4695 SDValue OutChain = L.getValue(1); 4696 if (MemVT != VT) 4697 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4698 4699 setValue(&I, L); 4700 DAG.setRoot(OutChain); 4701 } 4702 4703 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4704 SDLoc dl = getCurSDLoc(); 4705 4706 AtomicOrdering Ordering = I.getOrdering(); 4707 SyncScope::ID SSID = I.getSyncScopeID(); 4708 4709 SDValue InChain = getRoot(); 4710 4711 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4712 EVT MemVT = 4713 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4714 4715 if (I.getAlignment() < MemVT.getSizeInBits() / 8) 4716 report_fatal_error("Cannot generate unaligned atomic store"); 4717 4718 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4719 4720 MachineFunction &MF = DAG.getMachineFunction(); 4721 MachineMemOperand *MMO = MF.getMachineMemOperand( 4722 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4723 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4724 4725 SDValue Val = getValue(I.getValueOperand()); 4726 if (Val.getValueType() != MemVT) 4727 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4728 SDValue Ptr = getValue(I.getPointerOperand()); 4729 4730 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4731 // TODO: Once this is better exercised by tests, it should be merged with 4732 // the normal path for stores to prevent future divergence. 4733 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4734 DAG.setRoot(S); 4735 return; 4736 } 4737 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4738 Ptr, Val, MMO); 4739 4740 4741 DAG.setRoot(OutChain); 4742 } 4743 4744 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4745 /// node. 4746 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4747 unsigned Intrinsic) { 4748 // Ignore the callsite's attributes. A specific call site may be marked with 4749 // readnone, but the lowering code will expect the chain based on the 4750 // definition. 4751 const Function *F = I.getCalledFunction(); 4752 bool HasChain = !F->doesNotAccessMemory(); 4753 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4754 4755 // Build the operand list. 4756 SmallVector<SDValue, 8> Ops; 4757 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4758 if (OnlyLoad) { 4759 // We don't need to serialize loads against other loads. 4760 Ops.push_back(DAG.getRoot()); 4761 } else { 4762 Ops.push_back(getRoot()); 4763 } 4764 } 4765 4766 // Info is set by getTgtMemInstrinsic 4767 TargetLowering::IntrinsicInfo Info; 4768 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4769 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4770 DAG.getMachineFunction(), 4771 Intrinsic); 4772 4773 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4774 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4775 Info.opc == ISD::INTRINSIC_W_CHAIN) 4776 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4777 TLI.getPointerTy(DAG.getDataLayout()))); 4778 4779 // Add all operands of the call to the operand list. 4780 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4781 const Value *Arg = I.getArgOperand(i); 4782 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4783 Ops.push_back(getValue(Arg)); 4784 continue; 4785 } 4786 4787 // Use TargetConstant instead of a regular constant for immarg. 4788 EVT VT = TLI.getValueType(*DL, Arg->getType(), true); 4789 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4790 assert(CI->getBitWidth() <= 64 && 4791 "large intrinsic immediates not handled"); 4792 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4793 } else { 4794 Ops.push_back( 4795 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4796 } 4797 } 4798 4799 SmallVector<EVT, 4> ValueVTs; 4800 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4801 4802 if (HasChain) 4803 ValueVTs.push_back(MVT::Other); 4804 4805 SDVTList VTs = DAG.getVTList(ValueVTs); 4806 4807 // Propagate fast-math-flags from IR to node(s). 4808 SDNodeFlags Flags; 4809 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 4810 Flags.copyFMF(*FPMO); 4811 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 4812 4813 // Create the node. 4814 SDValue Result; 4815 if (IsTgtIntrinsic) { 4816 // This is target intrinsic that touches memory 4817 AAMDNodes AAInfo; 4818 I.getAAMetadata(AAInfo); 4819 Result = 4820 DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT, 4821 MachinePointerInfo(Info.ptrVal, Info.offset), 4822 Info.align, Info.flags, Info.size, AAInfo); 4823 } else if (!HasChain) { 4824 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4825 } else if (!I.getType()->isVoidTy()) { 4826 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4827 } else { 4828 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4829 } 4830 4831 if (HasChain) { 4832 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4833 if (OnlyLoad) 4834 PendingLoads.push_back(Chain); 4835 else 4836 DAG.setRoot(Chain); 4837 } 4838 4839 if (!I.getType()->isVoidTy()) { 4840 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4841 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4842 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4843 } else 4844 Result = lowerRangeToAssertZExt(DAG, I, Result); 4845 4846 MaybeAlign Alignment = I.getRetAlign(); 4847 if (!Alignment) 4848 Alignment = F->getAttributes().getRetAlignment(); 4849 // Insert `assertalign` node if there's an alignment. 4850 if (InsertAssertAlign && Alignment) { 4851 Result = 4852 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 4853 } 4854 4855 setValue(&I, Result); 4856 } 4857 } 4858 4859 /// GetSignificand - Get the significand and build it into a floating-point 4860 /// number with exponent of 1: 4861 /// 4862 /// Op = (Op & 0x007fffff) | 0x3f800000; 4863 /// 4864 /// where Op is the hexadecimal representation of floating point value. 4865 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4866 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4867 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4868 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4869 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4870 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4871 } 4872 4873 /// GetExponent - Get the exponent: 4874 /// 4875 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4876 /// 4877 /// where Op is the hexadecimal representation of floating point value. 4878 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4879 const TargetLowering &TLI, const SDLoc &dl) { 4880 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4881 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4882 SDValue t1 = DAG.getNode( 4883 ISD::SRL, dl, MVT::i32, t0, 4884 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4885 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4886 DAG.getConstant(127, dl, MVT::i32)); 4887 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4888 } 4889 4890 /// getF32Constant - Get 32-bit floating point constant. 4891 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4892 const SDLoc &dl) { 4893 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4894 MVT::f32); 4895 } 4896 4897 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4898 SelectionDAG &DAG) { 4899 // TODO: What fast-math-flags should be set on the floating-point nodes? 4900 4901 // IntegerPartOfX = ((int32_t)(t0); 4902 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4903 4904 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4905 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4906 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4907 4908 // IntegerPartOfX <<= 23; 4909 IntegerPartOfX = DAG.getNode( 4910 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4911 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4912 DAG.getDataLayout()))); 4913 4914 SDValue TwoToFractionalPartOfX; 4915 if (LimitFloatPrecision <= 6) { 4916 // For floating-point precision of 6: 4917 // 4918 // TwoToFractionalPartOfX = 4919 // 0.997535578f + 4920 // (0.735607626f + 0.252464424f * x) * x; 4921 // 4922 // error 0.0144103317, which is 6 bits 4923 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4924 getF32Constant(DAG, 0x3e814304, dl)); 4925 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4926 getF32Constant(DAG, 0x3f3c50c8, dl)); 4927 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4928 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4929 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4930 } else if (LimitFloatPrecision <= 12) { 4931 // For floating-point precision of 12: 4932 // 4933 // TwoToFractionalPartOfX = 4934 // 0.999892986f + 4935 // (0.696457318f + 4936 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4937 // 4938 // error 0.000107046256, which is 13 to 14 bits 4939 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4940 getF32Constant(DAG, 0x3da235e3, dl)); 4941 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4942 getF32Constant(DAG, 0x3e65b8f3, dl)); 4943 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4944 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4945 getF32Constant(DAG, 0x3f324b07, dl)); 4946 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4947 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4948 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4949 } else { // LimitFloatPrecision <= 18 4950 // For floating-point precision of 18: 4951 // 4952 // TwoToFractionalPartOfX = 4953 // 0.999999982f + 4954 // (0.693148872f + 4955 // (0.240227044f + 4956 // (0.554906021e-1f + 4957 // (0.961591928e-2f + 4958 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4959 // error 2.47208000*10^(-7), which is better than 18 bits 4960 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4961 getF32Constant(DAG, 0x3924b03e, dl)); 4962 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4963 getF32Constant(DAG, 0x3ab24b87, dl)); 4964 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4965 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4966 getF32Constant(DAG, 0x3c1d8c17, dl)); 4967 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4968 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4969 getF32Constant(DAG, 0x3d634a1d, dl)); 4970 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4971 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4972 getF32Constant(DAG, 0x3e75fe14, dl)); 4973 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4974 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4975 getF32Constant(DAG, 0x3f317234, dl)); 4976 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4977 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4978 getF32Constant(DAG, 0x3f800000, dl)); 4979 } 4980 4981 // Add the exponent into the result in integer domain. 4982 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4983 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4984 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4985 } 4986 4987 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4988 /// limited-precision mode. 4989 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4990 const TargetLowering &TLI, SDNodeFlags Flags) { 4991 if (Op.getValueType() == MVT::f32 && 4992 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4993 4994 // Put the exponent in the right bit position for later addition to the 4995 // final result: 4996 // 4997 // t0 = Op * log2(e) 4998 4999 // TODO: What fast-math-flags should be set here? 5000 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5001 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5002 return getLimitedPrecisionExp2(t0, dl, DAG); 5003 } 5004 5005 // No special expansion. 5006 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5007 } 5008 5009 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5010 /// limited-precision mode. 5011 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5012 const TargetLowering &TLI, SDNodeFlags Flags) { 5013 // TODO: What fast-math-flags should be set on the floating-point nodes? 5014 5015 if (Op.getValueType() == MVT::f32 && 5016 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5017 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5018 5019 // Scale the exponent by log(2). 5020 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5021 SDValue LogOfExponent = 5022 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5023 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5024 5025 // Get the significand and build it into a floating-point number with 5026 // exponent of 1. 5027 SDValue X = GetSignificand(DAG, Op1, dl); 5028 5029 SDValue LogOfMantissa; 5030 if (LimitFloatPrecision <= 6) { 5031 // For floating-point precision of 6: 5032 // 5033 // LogofMantissa = 5034 // -1.1609546f + 5035 // (1.4034025f - 0.23903021f * x) * x; 5036 // 5037 // error 0.0034276066, which is better than 8 bits 5038 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5039 getF32Constant(DAG, 0xbe74c456, dl)); 5040 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5041 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5042 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5043 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5044 getF32Constant(DAG, 0x3f949a29, dl)); 5045 } else if (LimitFloatPrecision <= 12) { 5046 // For floating-point precision of 12: 5047 // 5048 // LogOfMantissa = 5049 // -1.7417939f + 5050 // (2.8212026f + 5051 // (-1.4699568f + 5052 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5053 // 5054 // error 0.000061011436, which is 14 bits 5055 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5056 getF32Constant(DAG, 0xbd67b6d6, dl)); 5057 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5058 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5059 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5060 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5061 getF32Constant(DAG, 0x3fbc278b, dl)); 5062 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5063 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5064 getF32Constant(DAG, 0x40348e95, dl)); 5065 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5066 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5067 getF32Constant(DAG, 0x3fdef31a, dl)); 5068 } else { // LimitFloatPrecision <= 18 5069 // For floating-point precision of 18: 5070 // 5071 // LogOfMantissa = 5072 // -2.1072184f + 5073 // (4.2372794f + 5074 // (-3.7029485f + 5075 // (2.2781945f + 5076 // (-0.87823314f + 5077 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5078 // 5079 // error 0.0000023660568, which is better than 18 bits 5080 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5081 getF32Constant(DAG, 0xbc91e5ac, dl)); 5082 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5083 getF32Constant(DAG, 0x3e4350aa, dl)); 5084 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5085 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5086 getF32Constant(DAG, 0x3f60d3e3, dl)); 5087 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5088 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5089 getF32Constant(DAG, 0x4011cdf0, dl)); 5090 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5091 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5092 getF32Constant(DAG, 0x406cfd1c, dl)); 5093 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5094 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5095 getF32Constant(DAG, 0x408797cb, dl)); 5096 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5097 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5098 getF32Constant(DAG, 0x4006dcab, dl)); 5099 } 5100 5101 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5102 } 5103 5104 // No special expansion. 5105 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5106 } 5107 5108 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5109 /// limited-precision mode. 5110 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5111 const TargetLowering &TLI, SDNodeFlags Flags) { 5112 // TODO: What fast-math-flags should be set on the floating-point nodes? 5113 5114 if (Op.getValueType() == MVT::f32 && 5115 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5116 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5117 5118 // Get the exponent. 5119 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5120 5121 // Get the significand and build it into a floating-point number with 5122 // exponent of 1. 5123 SDValue X = GetSignificand(DAG, Op1, dl); 5124 5125 // Different possible minimax approximations of significand in 5126 // floating-point for various degrees of accuracy over [1,2]. 5127 SDValue Log2ofMantissa; 5128 if (LimitFloatPrecision <= 6) { 5129 // For floating-point precision of 6: 5130 // 5131 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5132 // 5133 // error 0.0049451742, which is more than 7 bits 5134 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5135 getF32Constant(DAG, 0xbeb08fe0, dl)); 5136 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5137 getF32Constant(DAG, 0x40019463, dl)); 5138 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5139 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5140 getF32Constant(DAG, 0x3fd6633d, dl)); 5141 } else if (LimitFloatPrecision <= 12) { 5142 // For floating-point precision of 12: 5143 // 5144 // Log2ofMantissa = 5145 // -2.51285454f + 5146 // (4.07009056f + 5147 // (-2.12067489f + 5148 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5149 // 5150 // error 0.0000876136000, which is better than 13 bits 5151 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5152 getF32Constant(DAG, 0xbda7262e, dl)); 5153 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5154 getF32Constant(DAG, 0x3f25280b, dl)); 5155 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5156 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5157 getF32Constant(DAG, 0x4007b923, dl)); 5158 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5159 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5160 getF32Constant(DAG, 0x40823e2f, dl)); 5161 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5162 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5163 getF32Constant(DAG, 0x4020d29c, dl)); 5164 } else { // LimitFloatPrecision <= 18 5165 // For floating-point precision of 18: 5166 // 5167 // Log2ofMantissa = 5168 // -3.0400495f + 5169 // (6.1129976f + 5170 // (-5.3420409f + 5171 // (3.2865683f + 5172 // (-1.2669343f + 5173 // (0.27515199f - 5174 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5175 // 5176 // error 0.0000018516, which is better than 18 bits 5177 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5178 getF32Constant(DAG, 0xbcd2769e, dl)); 5179 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5180 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5181 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5182 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5183 getF32Constant(DAG, 0x3fa22ae7, dl)); 5184 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5185 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5186 getF32Constant(DAG, 0x40525723, dl)); 5187 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5188 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5189 getF32Constant(DAG, 0x40aaf200, dl)); 5190 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5191 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5192 getF32Constant(DAG, 0x40c39dad, dl)); 5193 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5194 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5195 getF32Constant(DAG, 0x4042902c, dl)); 5196 } 5197 5198 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5199 } 5200 5201 // No special expansion. 5202 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5203 } 5204 5205 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5206 /// limited-precision mode. 5207 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5208 const TargetLowering &TLI, SDNodeFlags Flags) { 5209 // TODO: What fast-math-flags should be set on the floating-point nodes? 5210 5211 if (Op.getValueType() == MVT::f32 && 5212 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5213 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5214 5215 // Scale the exponent by log10(2) [0.30102999f]. 5216 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5217 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5218 getF32Constant(DAG, 0x3e9a209a, dl)); 5219 5220 // Get the significand and build it into a floating-point number with 5221 // exponent of 1. 5222 SDValue X = GetSignificand(DAG, Op1, dl); 5223 5224 SDValue Log10ofMantissa; 5225 if (LimitFloatPrecision <= 6) { 5226 // For floating-point precision of 6: 5227 // 5228 // Log10ofMantissa = 5229 // -0.50419619f + 5230 // (0.60948995f - 0.10380950f * x) * x; 5231 // 5232 // error 0.0014886165, which is 6 bits 5233 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5234 getF32Constant(DAG, 0xbdd49a13, dl)); 5235 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5236 getF32Constant(DAG, 0x3f1c0789, dl)); 5237 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5238 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5239 getF32Constant(DAG, 0x3f011300, dl)); 5240 } else if (LimitFloatPrecision <= 12) { 5241 // For floating-point precision of 12: 5242 // 5243 // Log10ofMantissa = 5244 // -0.64831180f + 5245 // (0.91751397f + 5246 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5247 // 5248 // error 0.00019228036, which is better than 12 bits 5249 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5250 getF32Constant(DAG, 0x3d431f31, dl)); 5251 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5252 getF32Constant(DAG, 0x3ea21fb2, dl)); 5253 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5254 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5255 getF32Constant(DAG, 0x3f6ae232, dl)); 5256 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5257 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5258 getF32Constant(DAG, 0x3f25f7c3, dl)); 5259 } else { // LimitFloatPrecision <= 18 5260 // For floating-point precision of 18: 5261 // 5262 // Log10ofMantissa = 5263 // -0.84299375f + 5264 // (1.5327582f + 5265 // (-1.0688956f + 5266 // (0.49102474f + 5267 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5268 // 5269 // error 0.0000037995730, which is better than 18 bits 5270 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5271 getF32Constant(DAG, 0x3c5d51ce, dl)); 5272 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5273 getF32Constant(DAG, 0x3e00685a, dl)); 5274 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5275 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5276 getF32Constant(DAG, 0x3efb6798, dl)); 5277 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5278 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5279 getF32Constant(DAG, 0x3f88d192, dl)); 5280 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5281 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5282 getF32Constant(DAG, 0x3fc4316c, dl)); 5283 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5284 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5285 getF32Constant(DAG, 0x3f57ce70, dl)); 5286 } 5287 5288 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5289 } 5290 5291 // No special expansion. 5292 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5293 } 5294 5295 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5296 /// limited-precision mode. 5297 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5298 const TargetLowering &TLI, SDNodeFlags Flags) { 5299 if (Op.getValueType() == MVT::f32 && 5300 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5301 return getLimitedPrecisionExp2(Op, dl, DAG); 5302 5303 // No special expansion. 5304 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5305 } 5306 5307 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5308 /// limited-precision mode with x == 10.0f. 5309 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5310 SelectionDAG &DAG, const TargetLowering &TLI, 5311 SDNodeFlags Flags) { 5312 bool IsExp10 = false; 5313 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5314 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5315 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5316 APFloat Ten(10.0f); 5317 IsExp10 = LHSC->isExactlyValue(Ten); 5318 } 5319 } 5320 5321 // TODO: What fast-math-flags should be set on the FMUL node? 5322 if (IsExp10) { 5323 // Put the exponent in the right bit position for later addition to the 5324 // final result: 5325 // 5326 // #define LOG2OF10 3.3219281f 5327 // t0 = Op * LOG2OF10; 5328 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5329 getF32Constant(DAG, 0x40549a78, dl)); 5330 return getLimitedPrecisionExp2(t0, dl, DAG); 5331 } 5332 5333 // No special expansion. 5334 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5335 } 5336 5337 /// ExpandPowI - Expand a llvm.powi intrinsic. 5338 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5339 SelectionDAG &DAG) { 5340 // If RHS is a constant, we can expand this out to a multiplication tree, 5341 // otherwise we end up lowering to a call to __powidf2 (for example). When 5342 // optimizing for size, we only want to do this if the expansion would produce 5343 // a small number of multiplies, otherwise we do the full expansion. 5344 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5345 // Get the exponent as a positive value. 5346 unsigned Val = RHSC->getSExtValue(); 5347 if ((int)Val < 0) Val = -Val; 5348 5349 // powi(x, 0) -> 1.0 5350 if (Val == 0) 5351 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5352 5353 bool OptForSize = DAG.shouldOptForSize(); 5354 if (!OptForSize || 5355 // If optimizing for size, don't insert too many multiplies. 5356 // This inserts up to 5 multiplies. 5357 countPopulation(Val) + Log2_32(Val) < 7) { 5358 // We use the simple binary decomposition method to generate the multiply 5359 // sequence. There are more optimal ways to do this (for example, 5360 // powi(x,15) generates one more multiply than it should), but this has 5361 // the benefit of being both really simple and much better than a libcall. 5362 SDValue Res; // Logically starts equal to 1.0 5363 SDValue CurSquare = LHS; 5364 // TODO: Intrinsics should have fast-math-flags that propagate to these 5365 // nodes. 5366 while (Val) { 5367 if (Val & 1) { 5368 if (Res.getNode()) 5369 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 5370 else 5371 Res = CurSquare; // 1.0*CurSquare. 5372 } 5373 5374 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5375 CurSquare, CurSquare); 5376 Val >>= 1; 5377 } 5378 5379 // If the original was negative, invert the result, producing 1/(x*x*x). 5380 if (RHSC->getSExtValue() < 0) 5381 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5382 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5383 return Res; 5384 } 5385 } 5386 5387 // Otherwise, expand to a libcall. 5388 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5389 } 5390 5391 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5392 SDValue LHS, SDValue RHS, SDValue Scale, 5393 SelectionDAG &DAG, const TargetLowering &TLI) { 5394 EVT VT = LHS.getValueType(); 5395 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5396 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5397 LLVMContext &Ctx = *DAG.getContext(); 5398 5399 // If the type is legal but the operation isn't, this node might survive all 5400 // the way to operation legalization. If we end up there and we do not have 5401 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5402 // node. 5403 5404 // Coax the legalizer into expanding the node during type legalization instead 5405 // by bumping the size by one bit. This will force it to Promote, enabling the 5406 // early expansion and avoiding the need to expand later. 5407 5408 // We don't have to do this if Scale is 0; that can always be expanded, unless 5409 // it's a saturating signed operation. Those can experience true integer 5410 // division overflow, a case which we must avoid. 5411 5412 // FIXME: We wouldn't have to do this (or any of the early 5413 // expansion/promotion) if it was possible to expand a libcall of an 5414 // illegal type during operation legalization. But it's not, so things 5415 // get a bit hacky. 5416 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5417 if ((ScaleInt > 0 || (Saturating && Signed)) && 5418 (TLI.isTypeLegal(VT) || 5419 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5420 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5421 Opcode, VT, ScaleInt); 5422 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5423 EVT PromVT; 5424 if (VT.isScalarInteger()) 5425 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5426 else if (VT.isVector()) { 5427 PromVT = VT.getVectorElementType(); 5428 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5429 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5430 } else 5431 llvm_unreachable("Wrong VT for DIVFIX?"); 5432 if (Signed) { 5433 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5434 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5435 } else { 5436 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5437 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5438 } 5439 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5440 // For saturating operations, we need to shift up the LHS to get the 5441 // proper saturation width, and then shift down again afterwards. 5442 if (Saturating) 5443 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5444 DAG.getConstant(1, DL, ShiftTy)); 5445 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5446 if (Saturating) 5447 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5448 DAG.getConstant(1, DL, ShiftTy)); 5449 return DAG.getZExtOrTrunc(Res, DL, VT); 5450 } 5451 } 5452 5453 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5454 } 5455 5456 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5457 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5458 static void 5459 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5460 const SDValue &N) { 5461 switch (N.getOpcode()) { 5462 case ISD::CopyFromReg: { 5463 SDValue Op = N.getOperand(1); 5464 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5465 Op.getValueType().getSizeInBits()); 5466 return; 5467 } 5468 case ISD::BITCAST: 5469 case ISD::AssertZext: 5470 case ISD::AssertSext: 5471 case ISD::TRUNCATE: 5472 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5473 return; 5474 case ISD::BUILD_PAIR: 5475 case ISD::BUILD_VECTOR: 5476 case ISD::CONCAT_VECTORS: 5477 for (SDValue Op : N->op_values()) 5478 getUnderlyingArgRegs(Regs, Op); 5479 return; 5480 default: 5481 return; 5482 } 5483 } 5484 5485 /// If the DbgValueInst is a dbg_value of a function argument, create the 5486 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5487 /// instruction selection, they will be inserted to the entry BB. 5488 /// We don't currently support this for variadic dbg_values, as they shouldn't 5489 /// appear for function arguments or in the prologue. 5490 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5491 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5492 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 5493 const Argument *Arg = dyn_cast<Argument>(V); 5494 if (!Arg) 5495 return false; 5496 5497 if (!IsDbgDeclare) { 5498 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5499 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5500 // the entry block. 5501 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5502 if (!IsInEntryBlock) 5503 return false; 5504 5505 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5506 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5507 // variable that also is a param. 5508 // 5509 // Although, if we are at the top of the entry block already, we can still 5510 // emit using ArgDbgValue. This might catch some situations when the 5511 // dbg.value refers to an argument that isn't used in the entry block, so 5512 // any CopyToReg node would be optimized out and the only way to express 5513 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5514 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5515 // we should only emit as ArgDbgValue if the Variable is an argument to the 5516 // current function, and the dbg.value intrinsic is found in the entry 5517 // block. 5518 bool VariableIsFunctionInputArg = Variable->isParameter() && 5519 !DL->getInlinedAt(); 5520 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5521 if (!IsInPrologue && !VariableIsFunctionInputArg) 5522 return false; 5523 5524 // Here we assume that a function argument on IR level only can be used to 5525 // describe one input parameter on source level. If we for example have 5526 // source code like this 5527 // 5528 // struct A { long x, y; }; 5529 // void foo(struct A a, long b) { 5530 // ... 5531 // b = a.x; 5532 // ... 5533 // } 5534 // 5535 // and IR like this 5536 // 5537 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5538 // entry: 5539 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5540 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5541 // call void @llvm.dbg.value(metadata i32 %b, "b", 5542 // ... 5543 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5544 // ... 5545 // 5546 // then the last dbg.value is describing a parameter "b" using a value that 5547 // is an argument. But since we already has used %a1 to describe a parameter 5548 // we should not handle that last dbg.value here (that would result in an 5549 // incorrect hoisting of the DBG_VALUE to the function entry). 5550 // Notice that we allow one dbg.value per IR level argument, to accommodate 5551 // for the situation with fragments above. 5552 if (VariableIsFunctionInputArg) { 5553 unsigned ArgNo = Arg->getArgNo(); 5554 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5555 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5556 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5557 return false; 5558 FuncInfo.DescribedArgs.set(ArgNo); 5559 } 5560 } 5561 5562 MachineFunction &MF = DAG.getMachineFunction(); 5563 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5564 5565 bool IsIndirect = false; 5566 Optional<MachineOperand> Op; 5567 // Some arguments' frame index is recorded during argument lowering. 5568 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5569 if (FI != std::numeric_limits<int>::max()) 5570 Op = MachineOperand::CreateFI(FI); 5571 5572 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 5573 if (!Op && N.getNode()) { 5574 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5575 Register Reg; 5576 if (ArgRegsAndSizes.size() == 1) 5577 Reg = ArgRegsAndSizes.front().first; 5578 5579 if (Reg && Reg.isVirtual()) { 5580 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5581 Register PR = RegInfo.getLiveInPhysReg(Reg); 5582 if (PR) 5583 Reg = PR; 5584 } 5585 if (Reg) { 5586 Op = MachineOperand::CreateReg(Reg, false); 5587 IsIndirect = IsDbgDeclare; 5588 } 5589 } 5590 5591 if (!Op && N.getNode()) { 5592 // Check if frame index is available. 5593 SDValue LCandidate = peekThroughBitcasts(N); 5594 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5595 if (FrameIndexSDNode *FINode = 5596 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5597 Op = MachineOperand::CreateFI(FINode->getIndex()); 5598 } 5599 5600 if (!Op) { 5601 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5602 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 5603 SplitRegs) { 5604 unsigned Offset = 0; 5605 for (auto RegAndSize : SplitRegs) { 5606 // If the expression is already a fragment, the current register 5607 // offset+size might extend beyond the fragment. In this case, only 5608 // the register bits that are inside the fragment are relevant. 5609 int RegFragmentSizeInBits = RegAndSize.second; 5610 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5611 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5612 // The register is entirely outside the expression fragment, 5613 // so is irrelevant for debug info. 5614 if (Offset >= ExprFragmentSizeInBits) 5615 break; 5616 // The register is partially outside the expression fragment, only 5617 // the low bits within the fragment are relevant for debug info. 5618 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5619 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5620 } 5621 } 5622 5623 auto FragmentExpr = DIExpression::createFragmentExpression( 5624 Expr, Offset, RegFragmentSizeInBits); 5625 Offset += RegAndSize.second; 5626 // If a valid fragment expression cannot be created, the variable's 5627 // correct value cannot be determined and so it is set as Undef. 5628 if (!FragmentExpr) { 5629 SDDbgValue *SDV = DAG.getConstantDbgValue( 5630 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5631 DAG.AddDbgValue(SDV, false); 5632 continue; 5633 } 5634 FuncInfo.ArgDbgValues.push_back( 5635 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare, 5636 RegAndSize.first, Variable, *FragmentExpr)); 5637 } 5638 }; 5639 5640 // Check if ValueMap has reg number. 5641 DenseMap<const Value *, Register>::const_iterator 5642 VMI = FuncInfo.ValueMap.find(V); 5643 if (VMI != FuncInfo.ValueMap.end()) { 5644 const auto &TLI = DAG.getTargetLoweringInfo(); 5645 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5646 V->getType(), None); 5647 if (RFV.occupiesMultipleRegs()) { 5648 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5649 return true; 5650 } 5651 5652 Op = MachineOperand::CreateReg(VMI->second, false); 5653 IsIndirect = IsDbgDeclare; 5654 } else if (ArgRegsAndSizes.size() > 1) { 5655 // This was split due to the calling convention, and no virtual register 5656 // mapping exists for the value. 5657 splitMultiRegDbgValue(ArgRegsAndSizes); 5658 return true; 5659 } 5660 } 5661 5662 if (!Op) 5663 return false; 5664 5665 assert(Variable->isValidLocationForIntrinsic(DL) && 5666 "Expected inlined-at fields to agree"); 5667 IsIndirect = (Op->isReg()) ? IsIndirect : true; 5668 FuncInfo.ArgDbgValues.push_back( 5669 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 5670 *Op, Variable, Expr)); 5671 5672 return true; 5673 } 5674 5675 /// Return the appropriate SDDbgValue based on N. 5676 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5677 DILocalVariable *Variable, 5678 DIExpression *Expr, 5679 const DebugLoc &dl, 5680 unsigned DbgSDNodeOrder) { 5681 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5682 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5683 // stack slot locations. 5684 // 5685 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5686 // debug values here after optimization: 5687 // 5688 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5689 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5690 // 5691 // Both describe the direct values of their associated variables. 5692 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5693 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5694 } 5695 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5696 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5697 } 5698 5699 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5700 switch (Intrinsic) { 5701 case Intrinsic::smul_fix: 5702 return ISD::SMULFIX; 5703 case Intrinsic::umul_fix: 5704 return ISD::UMULFIX; 5705 case Intrinsic::smul_fix_sat: 5706 return ISD::SMULFIXSAT; 5707 case Intrinsic::umul_fix_sat: 5708 return ISD::UMULFIXSAT; 5709 case Intrinsic::sdiv_fix: 5710 return ISD::SDIVFIX; 5711 case Intrinsic::udiv_fix: 5712 return ISD::UDIVFIX; 5713 case Intrinsic::sdiv_fix_sat: 5714 return ISD::SDIVFIXSAT; 5715 case Intrinsic::udiv_fix_sat: 5716 return ISD::UDIVFIXSAT; 5717 default: 5718 llvm_unreachable("Unhandled fixed point intrinsic"); 5719 } 5720 } 5721 5722 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5723 const char *FunctionName) { 5724 assert(FunctionName && "FunctionName must not be nullptr"); 5725 SDValue Callee = DAG.getExternalSymbol( 5726 FunctionName, 5727 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5728 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 5729 } 5730 5731 /// Given a @llvm.call.preallocated.setup, return the corresponding 5732 /// preallocated call. 5733 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5734 assert(cast<CallBase>(PreallocatedSetup) 5735 ->getCalledFunction() 5736 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5737 "expected call_preallocated_setup Value"); 5738 for (auto *U : PreallocatedSetup->users()) { 5739 auto *UseCall = cast<CallBase>(U); 5740 const Function *Fn = UseCall->getCalledFunction(); 5741 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5742 return UseCall; 5743 } 5744 } 5745 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5746 } 5747 5748 /// Lower the call to the specified intrinsic function. 5749 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5750 unsigned Intrinsic) { 5751 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5752 SDLoc sdl = getCurSDLoc(); 5753 DebugLoc dl = getCurDebugLoc(); 5754 SDValue Res; 5755 5756 SDNodeFlags Flags; 5757 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 5758 Flags.copyFMF(*FPOp); 5759 5760 switch (Intrinsic) { 5761 default: 5762 // By default, turn this into a target intrinsic node. 5763 visitTargetIntrinsic(I, Intrinsic); 5764 return; 5765 case Intrinsic::vscale: { 5766 match(&I, m_VScale(DAG.getDataLayout())); 5767 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5768 setValue(&I, 5769 DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1))); 5770 return; 5771 } 5772 case Intrinsic::vastart: visitVAStart(I); return; 5773 case Intrinsic::vaend: visitVAEnd(I); return; 5774 case Intrinsic::vacopy: visitVACopy(I); return; 5775 case Intrinsic::returnaddress: 5776 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5777 TLI.getPointerTy(DAG.getDataLayout()), 5778 getValue(I.getArgOperand(0)))); 5779 return; 5780 case Intrinsic::addressofreturnaddress: 5781 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5782 TLI.getPointerTy(DAG.getDataLayout()))); 5783 return; 5784 case Intrinsic::sponentry: 5785 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5786 TLI.getFrameIndexTy(DAG.getDataLayout()))); 5787 return; 5788 case Intrinsic::frameaddress: 5789 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5790 TLI.getFrameIndexTy(DAG.getDataLayout()), 5791 getValue(I.getArgOperand(0)))); 5792 return; 5793 case Intrinsic::read_volatile_register: 5794 case Intrinsic::read_register: { 5795 Value *Reg = I.getArgOperand(0); 5796 SDValue Chain = getRoot(); 5797 SDValue RegName = 5798 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5799 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5800 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5801 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5802 setValue(&I, Res); 5803 DAG.setRoot(Res.getValue(1)); 5804 return; 5805 } 5806 case Intrinsic::write_register: { 5807 Value *Reg = I.getArgOperand(0); 5808 Value *RegValue = I.getArgOperand(1); 5809 SDValue Chain = getRoot(); 5810 SDValue RegName = 5811 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5812 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5813 RegName, getValue(RegValue))); 5814 return; 5815 } 5816 case Intrinsic::memcpy: { 5817 const auto &MCI = cast<MemCpyInst>(I); 5818 SDValue Op1 = getValue(I.getArgOperand(0)); 5819 SDValue Op2 = getValue(I.getArgOperand(1)); 5820 SDValue Op3 = getValue(I.getArgOperand(2)); 5821 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5822 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5823 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5824 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5825 bool isVol = MCI.isVolatile(); 5826 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5827 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5828 // node. 5829 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5830 AAMDNodes AAInfo; 5831 I.getAAMetadata(AAInfo); 5832 SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5833 /* AlwaysInline */ false, isTC, 5834 MachinePointerInfo(I.getArgOperand(0)), 5835 MachinePointerInfo(I.getArgOperand(1)), AAInfo); 5836 updateDAGForMaybeTailCall(MC); 5837 return; 5838 } 5839 case Intrinsic::memcpy_inline: { 5840 const auto &MCI = cast<MemCpyInlineInst>(I); 5841 SDValue Dst = getValue(I.getArgOperand(0)); 5842 SDValue Src = getValue(I.getArgOperand(1)); 5843 SDValue Size = getValue(I.getArgOperand(2)); 5844 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 5845 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 5846 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5847 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5848 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5849 bool isVol = MCI.isVolatile(); 5850 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5851 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5852 // node. 5853 AAMDNodes AAInfo; 5854 I.getAAMetadata(AAInfo); 5855 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 5856 /* AlwaysInline */ true, isTC, 5857 MachinePointerInfo(I.getArgOperand(0)), 5858 MachinePointerInfo(I.getArgOperand(1)), AAInfo); 5859 updateDAGForMaybeTailCall(MC); 5860 return; 5861 } 5862 case Intrinsic::memset: { 5863 const auto &MSI = cast<MemSetInst>(I); 5864 SDValue Op1 = getValue(I.getArgOperand(0)); 5865 SDValue Op2 = getValue(I.getArgOperand(1)); 5866 SDValue Op3 = getValue(I.getArgOperand(2)); 5867 // @llvm.memset defines 0 and 1 to both mean no alignment. 5868 Align Alignment = MSI.getDestAlign().valueOrOne(); 5869 bool isVol = MSI.isVolatile(); 5870 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5871 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5872 AAMDNodes AAInfo; 5873 I.getAAMetadata(AAInfo); 5874 SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC, 5875 MachinePointerInfo(I.getArgOperand(0)), AAInfo); 5876 updateDAGForMaybeTailCall(MS); 5877 return; 5878 } 5879 case Intrinsic::memmove: { 5880 const auto &MMI = cast<MemMoveInst>(I); 5881 SDValue Op1 = getValue(I.getArgOperand(0)); 5882 SDValue Op2 = getValue(I.getArgOperand(1)); 5883 SDValue Op3 = getValue(I.getArgOperand(2)); 5884 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5885 Align DstAlign = MMI.getDestAlign().valueOrOne(); 5886 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 5887 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5888 bool isVol = MMI.isVolatile(); 5889 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5890 // FIXME: Support passing different dest/src alignments to the memmove DAG 5891 // node. 5892 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5893 AAMDNodes AAInfo; 5894 I.getAAMetadata(AAInfo); 5895 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5896 isTC, MachinePointerInfo(I.getArgOperand(0)), 5897 MachinePointerInfo(I.getArgOperand(1)), AAInfo); 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 SDLoc DL = getCurSDLoc(); 7291 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 7292 7293 SmallVector<EVT, 4> ValueVTs; 7294 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7295 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 7296 SDVTList VTs = DAG.getVTList(ValueVTs); 7297 7298 auto EVLParamPos = 7299 VPIntrinsic::getVectorLengthParamPos(VPIntrin.getIntrinsicID()); 7300 7301 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7302 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7303 "Unexpected target EVL type"); 7304 7305 // Request operands. 7306 SmallVector<SDValue, 7> OpValues; 7307 for (unsigned I = 0; I < VPIntrin.getNumArgOperands(); ++I) { 7308 auto Op = getValue(VPIntrin.getArgOperand(I)); 7309 if (I == EVLParamPos) 7310 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op); 7311 OpValues.push_back(Op); 7312 } 7313 7314 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues); 7315 setValue(&VPIntrin, Result); 7316 } 7317 7318 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 7319 const BasicBlock *EHPadBB, 7320 MCSymbol *&BeginLabel) { 7321 MachineFunction &MF = DAG.getMachineFunction(); 7322 MachineModuleInfo &MMI = MF.getMMI(); 7323 7324 // Insert a label before the invoke call to mark the try range. This can be 7325 // used to detect deletion of the invoke via the MachineModuleInfo. 7326 BeginLabel = MMI.getContext().createTempSymbol(); 7327 7328 // For SjLj, keep track of which landing pads go with which invokes 7329 // so as to maintain the ordering of pads in the LSDA. 7330 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7331 if (CallSiteIndex) { 7332 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7333 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7334 7335 // Now that the call site is handled, stop tracking it. 7336 MMI.setCurrentCallSite(0); 7337 } 7338 7339 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 7340 } 7341 7342 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 7343 const BasicBlock *EHPadBB, 7344 MCSymbol *BeginLabel) { 7345 assert(BeginLabel && "BeginLabel should've been set"); 7346 7347 MachineFunction &MF = DAG.getMachineFunction(); 7348 MachineModuleInfo &MMI = MF.getMMI(); 7349 7350 // Insert a label at the end of the invoke call to mark the try range. This 7351 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7352 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7353 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 7354 7355 // Inform MachineModuleInfo of range. 7356 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7357 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7358 // actually use outlined funclets and their LSDA info style. 7359 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7360 assert(II && "II should've been set"); 7361 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 7362 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 7363 } else if (!isScopedEHPersonality(Pers)) { 7364 assert(EHPadBB); 7365 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7366 } 7367 7368 return Chain; 7369 } 7370 7371 std::pair<SDValue, SDValue> 7372 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7373 const BasicBlock *EHPadBB) { 7374 MCSymbol *BeginLabel = nullptr; 7375 7376 if (EHPadBB) { 7377 // Both PendingLoads and PendingExports must be flushed here; 7378 // this call might not return. 7379 (void)getRoot(); 7380 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 7381 CLI.setChain(getRoot()); 7382 } 7383 7384 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7385 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7386 7387 assert((CLI.IsTailCall || Result.second.getNode()) && 7388 "Non-null chain expected with non-tail call!"); 7389 assert((Result.second.getNode() || !Result.first.getNode()) && 7390 "Null value expected with tail call!"); 7391 7392 if (!Result.second.getNode()) { 7393 // As a special case, a null chain means that a tail call has been emitted 7394 // and the DAG root is already updated. 7395 HasTailCall = true; 7396 7397 // Since there's no actual continuation from this block, nothing can be 7398 // relying on us setting vregs for them. 7399 PendingExports.clear(); 7400 } else { 7401 DAG.setRoot(Result.second); 7402 } 7403 7404 if (EHPadBB) { 7405 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 7406 BeginLabel)); 7407 } 7408 7409 return Result; 7410 } 7411 7412 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 7413 bool isTailCall, 7414 bool isMustTailCall, 7415 const BasicBlock *EHPadBB) { 7416 auto &DL = DAG.getDataLayout(); 7417 FunctionType *FTy = CB.getFunctionType(); 7418 Type *RetTy = CB.getType(); 7419 7420 TargetLowering::ArgListTy Args; 7421 Args.reserve(CB.arg_size()); 7422 7423 const Value *SwiftErrorVal = nullptr; 7424 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7425 7426 if (isTailCall) { 7427 // Avoid emitting tail calls in functions with the disable-tail-calls 7428 // attribute. 7429 auto *Caller = CB.getParent()->getParent(); 7430 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7431 "true" && !isMustTailCall) 7432 isTailCall = false; 7433 7434 // We can't tail call inside a function with a swifterror argument. Lowering 7435 // does not support this yet. It would have to move into the swifterror 7436 // register before the call. 7437 if (TLI.supportSwiftError() && 7438 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7439 isTailCall = false; 7440 } 7441 7442 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 7443 TargetLowering::ArgListEntry Entry; 7444 const Value *V = *I; 7445 7446 // Skip empty types 7447 if (V->getType()->isEmptyTy()) 7448 continue; 7449 7450 SDValue ArgNode = getValue(V); 7451 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7452 7453 Entry.setAttributes(&CB, I - CB.arg_begin()); 7454 7455 // Use swifterror virtual register as input to the call. 7456 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7457 SwiftErrorVal = V; 7458 // We find the virtual register for the actual swifterror argument. 7459 // Instead of using the Value, we use the virtual register instead. 7460 Entry.Node = 7461 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 7462 EVT(TLI.getPointerTy(DL))); 7463 } 7464 7465 Args.push_back(Entry); 7466 7467 // If we have an explicit sret argument that is an Instruction, (i.e., it 7468 // might point to function-local memory), we can't meaningfully tail-call. 7469 if (Entry.IsSRet && isa<Instruction>(V)) 7470 isTailCall = false; 7471 } 7472 7473 // If call site has a cfguardtarget operand bundle, create and add an 7474 // additional ArgListEntry. 7475 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7476 TargetLowering::ArgListEntry Entry; 7477 Value *V = Bundle->Inputs[0]; 7478 SDValue ArgNode = getValue(V); 7479 Entry.Node = ArgNode; 7480 Entry.Ty = V->getType(); 7481 Entry.IsCFGuardTarget = true; 7482 Args.push_back(Entry); 7483 } 7484 7485 // Check if target-independent constraints permit a tail call here. 7486 // Target-dependent constraints are checked within TLI->LowerCallTo. 7487 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 7488 isTailCall = false; 7489 7490 // Disable tail calls if there is an swifterror argument. Targets have not 7491 // been updated to support tail calls. 7492 if (TLI.supportSwiftError() && SwiftErrorVal) 7493 isTailCall = false; 7494 7495 TargetLowering::CallLoweringInfo CLI(DAG); 7496 CLI.setDebugLoc(getCurSDLoc()) 7497 .setChain(getRoot()) 7498 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 7499 .setTailCall(isTailCall) 7500 .setConvergent(CB.isConvergent()) 7501 .setIsPreallocated( 7502 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 7503 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7504 7505 if (Result.first.getNode()) { 7506 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 7507 setValue(&CB, Result.first); 7508 } 7509 7510 // The last element of CLI.InVals has the SDValue for swifterror return. 7511 // Here we copy it to a virtual register and update SwiftErrorMap for 7512 // book-keeping. 7513 if (SwiftErrorVal && TLI.supportSwiftError()) { 7514 // Get the last element of InVals. 7515 SDValue Src = CLI.InVals.back(); 7516 Register VReg = 7517 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 7518 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7519 DAG.setRoot(CopyNode); 7520 } 7521 } 7522 7523 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7524 SelectionDAGBuilder &Builder) { 7525 // Check to see if this load can be trivially constant folded, e.g. if the 7526 // input is from a string literal. 7527 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7528 // Cast pointer to the type we really want to load. 7529 Type *LoadTy = 7530 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7531 if (LoadVT.isVector()) 7532 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7533 7534 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7535 PointerType::getUnqual(LoadTy)); 7536 7537 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 7538 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 7539 return Builder.getValue(LoadCst); 7540 } 7541 7542 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7543 // still constant memory, the input chain can be the entry node. 7544 SDValue Root; 7545 bool ConstantMemory = false; 7546 7547 // Do not serialize (non-volatile) loads of constant memory with anything. 7548 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7549 Root = Builder.DAG.getEntryNode(); 7550 ConstantMemory = true; 7551 } else { 7552 // Do not serialize non-volatile loads against each other. 7553 Root = Builder.DAG.getRoot(); 7554 } 7555 7556 SDValue Ptr = Builder.getValue(PtrVal); 7557 SDValue LoadVal = 7558 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 7559 MachinePointerInfo(PtrVal), Align(1)); 7560 7561 if (!ConstantMemory) 7562 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7563 return LoadVal; 7564 } 7565 7566 /// Record the value for an instruction that produces an integer result, 7567 /// converting the type where necessary. 7568 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7569 SDValue Value, 7570 bool IsSigned) { 7571 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7572 I.getType(), true); 7573 if (IsSigned) 7574 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7575 else 7576 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7577 setValue(&I, Value); 7578 } 7579 7580 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 7581 /// true and lower it. Otherwise return false, and it will be lowered like a 7582 /// normal call. 7583 /// The caller already checked that \p I calls the appropriate LibFunc with a 7584 /// correct prototype. 7585 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 7586 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 7587 const Value *Size = I.getArgOperand(2); 7588 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 7589 if (CSize && CSize->getZExtValue() == 0) { 7590 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7591 I.getType(), true); 7592 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 7593 return true; 7594 } 7595 7596 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7597 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 7598 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 7599 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 7600 if (Res.first.getNode()) { 7601 processIntegerCallValue(I, Res.first, true); 7602 PendingLoads.push_back(Res.second); 7603 return true; 7604 } 7605 7606 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 7607 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 7608 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 7609 return false; 7610 7611 // If the target has a fast compare for the given size, it will return a 7612 // preferred load type for that size. Require that the load VT is legal and 7613 // that the target supports unaligned loads of that type. Otherwise, return 7614 // INVALID. 7615 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 7616 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7617 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 7618 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 7619 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 7620 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 7621 // TODO: Check alignment of src and dest ptrs. 7622 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 7623 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 7624 if (!TLI.isTypeLegal(LVT) || 7625 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 7626 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 7627 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 7628 } 7629 7630 return LVT; 7631 }; 7632 7633 // This turns into unaligned loads. We only do this if the target natively 7634 // supports the MVT we'll be loading or if it is small enough (<= 4) that 7635 // we'll only produce a small number of byte loads. 7636 MVT LoadVT; 7637 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 7638 switch (NumBitsToCompare) { 7639 default: 7640 return false; 7641 case 16: 7642 LoadVT = MVT::i16; 7643 break; 7644 case 32: 7645 LoadVT = MVT::i32; 7646 break; 7647 case 64: 7648 case 128: 7649 case 256: 7650 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 7651 break; 7652 } 7653 7654 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 7655 return false; 7656 7657 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 7658 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 7659 7660 // Bitcast to a wide integer type if the loads are vectors. 7661 if (LoadVT.isVector()) { 7662 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 7663 LoadL = DAG.getBitcast(CmpVT, LoadL); 7664 LoadR = DAG.getBitcast(CmpVT, LoadR); 7665 } 7666 7667 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 7668 processIntegerCallValue(I, Cmp, false); 7669 return true; 7670 } 7671 7672 /// See if we can lower a memchr call into an optimized form. If so, return 7673 /// true and lower it. Otherwise return false, and it will be lowered like a 7674 /// normal call. 7675 /// The caller already checked that \p I calls the appropriate LibFunc with a 7676 /// correct prototype. 7677 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 7678 const Value *Src = I.getArgOperand(0); 7679 const Value *Char = I.getArgOperand(1); 7680 const Value *Length = I.getArgOperand(2); 7681 7682 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7683 std::pair<SDValue, SDValue> Res = 7684 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 7685 getValue(Src), getValue(Char), getValue(Length), 7686 MachinePointerInfo(Src)); 7687 if (Res.first.getNode()) { 7688 setValue(&I, Res.first); 7689 PendingLoads.push_back(Res.second); 7690 return true; 7691 } 7692 7693 return false; 7694 } 7695 7696 /// See if we can lower a mempcpy call into an optimized form. If so, return 7697 /// true and lower it. Otherwise return false, and it will be lowered like a 7698 /// normal call. 7699 /// The caller already checked that \p I calls the appropriate LibFunc with a 7700 /// correct prototype. 7701 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 7702 SDValue Dst = getValue(I.getArgOperand(0)); 7703 SDValue Src = getValue(I.getArgOperand(1)); 7704 SDValue Size = getValue(I.getArgOperand(2)); 7705 7706 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 7707 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 7708 // DAG::getMemcpy needs Alignment to be defined. 7709 Align Alignment = std::min(DstAlign, SrcAlign); 7710 7711 bool isVol = false; 7712 SDLoc sdl = getCurSDLoc(); 7713 7714 // In the mempcpy context we need to pass in a false value for isTailCall 7715 // because the return pointer needs to be adjusted by the size of 7716 // the copied memory. 7717 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 7718 AAMDNodes AAInfo; 7719 I.getAAMetadata(AAInfo); 7720 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false, 7721 /*isTailCall=*/false, 7722 MachinePointerInfo(I.getArgOperand(0)), 7723 MachinePointerInfo(I.getArgOperand(1)), AAInfo); 7724 assert(MC.getNode() != nullptr && 7725 "** memcpy should not be lowered as TailCall in mempcpy context **"); 7726 DAG.setRoot(MC); 7727 7728 // Check if Size needs to be truncated or extended. 7729 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 7730 7731 // Adjust return pointer to point just past the last dst byte. 7732 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 7733 Dst, Size); 7734 setValue(&I, DstPlusSize); 7735 return true; 7736 } 7737 7738 /// See if we can lower a strcpy call into an optimized form. If so, return 7739 /// true and lower it, otherwise return false and it will be lowered like a 7740 /// normal call. 7741 /// The caller already checked that \p I calls the appropriate LibFunc with a 7742 /// correct prototype. 7743 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 7744 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7745 7746 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7747 std::pair<SDValue, SDValue> Res = 7748 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 7749 getValue(Arg0), getValue(Arg1), 7750 MachinePointerInfo(Arg0), 7751 MachinePointerInfo(Arg1), isStpcpy); 7752 if (Res.first.getNode()) { 7753 setValue(&I, Res.first); 7754 DAG.setRoot(Res.second); 7755 return true; 7756 } 7757 7758 return false; 7759 } 7760 7761 /// See if we can lower a strcmp call into an optimized form. If so, return 7762 /// true and lower it, otherwise return false and it will be lowered like a 7763 /// normal call. 7764 /// The caller already checked that \p I calls the appropriate LibFunc with a 7765 /// correct prototype. 7766 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 7767 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7768 7769 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7770 std::pair<SDValue, SDValue> Res = 7771 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 7772 getValue(Arg0), getValue(Arg1), 7773 MachinePointerInfo(Arg0), 7774 MachinePointerInfo(Arg1)); 7775 if (Res.first.getNode()) { 7776 processIntegerCallValue(I, Res.first, true); 7777 PendingLoads.push_back(Res.second); 7778 return true; 7779 } 7780 7781 return false; 7782 } 7783 7784 /// See if we can lower a strlen call into an optimized form. If so, return 7785 /// true and lower it, otherwise return false and it will be lowered like a 7786 /// normal call. 7787 /// The caller already checked that \p I calls the appropriate LibFunc with a 7788 /// correct prototype. 7789 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 7790 const Value *Arg0 = I.getArgOperand(0); 7791 7792 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7793 std::pair<SDValue, SDValue> Res = 7794 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 7795 getValue(Arg0), MachinePointerInfo(Arg0)); 7796 if (Res.first.getNode()) { 7797 processIntegerCallValue(I, Res.first, false); 7798 PendingLoads.push_back(Res.second); 7799 return true; 7800 } 7801 7802 return false; 7803 } 7804 7805 /// See if we can lower a strnlen call into an optimized form. If so, return 7806 /// true and lower it, otherwise return false and it will be lowered like a 7807 /// normal call. 7808 /// The caller already checked that \p I calls the appropriate LibFunc with a 7809 /// correct prototype. 7810 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 7811 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7812 7813 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7814 std::pair<SDValue, SDValue> Res = 7815 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 7816 getValue(Arg0), getValue(Arg1), 7817 MachinePointerInfo(Arg0)); 7818 if (Res.first.getNode()) { 7819 processIntegerCallValue(I, Res.first, false); 7820 PendingLoads.push_back(Res.second); 7821 return true; 7822 } 7823 7824 return false; 7825 } 7826 7827 /// See if we can lower a unary floating-point operation into an SDNode with 7828 /// the specified Opcode. If so, return true and lower it, otherwise return 7829 /// false and it will be lowered like a normal call. 7830 /// The caller already checked that \p I calls the appropriate LibFunc with a 7831 /// correct prototype. 7832 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 7833 unsigned Opcode) { 7834 // We already checked this call's prototype; verify it doesn't modify errno. 7835 if (!I.onlyReadsMemory()) 7836 return false; 7837 7838 SDNodeFlags Flags; 7839 Flags.copyFMF(cast<FPMathOperator>(I)); 7840 7841 SDValue Tmp = getValue(I.getArgOperand(0)); 7842 setValue(&I, 7843 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 7844 return true; 7845 } 7846 7847 /// See if we can lower a binary floating-point operation into an SDNode with 7848 /// the specified Opcode. If so, return true and lower it. Otherwise return 7849 /// false, and it will be lowered like a normal call. 7850 /// The caller already checked that \p I calls the appropriate LibFunc with a 7851 /// correct prototype. 7852 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 7853 unsigned Opcode) { 7854 // We already checked this call's prototype; verify it doesn't modify errno. 7855 if (!I.onlyReadsMemory()) 7856 return false; 7857 7858 SDNodeFlags Flags; 7859 Flags.copyFMF(cast<FPMathOperator>(I)); 7860 7861 SDValue Tmp0 = getValue(I.getArgOperand(0)); 7862 SDValue Tmp1 = getValue(I.getArgOperand(1)); 7863 EVT VT = Tmp0.getValueType(); 7864 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 7865 return true; 7866 } 7867 7868 void SelectionDAGBuilder::visitCall(const CallInst &I) { 7869 // Handle inline assembly differently. 7870 if (I.isInlineAsm()) { 7871 visitInlineAsm(I); 7872 return; 7873 } 7874 7875 if (Function *F = I.getCalledFunction()) { 7876 if (F->isDeclaration()) { 7877 // Is this an LLVM intrinsic or a target-specific intrinsic? 7878 unsigned IID = F->getIntrinsicID(); 7879 if (!IID) 7880 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7881 IID = II->getIntrinsicID(F); 7882 7883 if (IID) { 7884 visitIntrinsicCall(I, IID); 7885 return; 7886 } 7887 } 7888 7889 // Check for well-known libc/libm calls. If the function is internal, it 7890 // can't be a library call. Don't do the check if marked as nobuiltin for 7891 // some reason or the call site requires strict floating point semantics. 7892 LibFunc Func; 7893 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7894 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7895 LibInfo->hasOptimizedCodeGen(Func)) { 7896 switch (Func) { 7897 default: break; 7898 case LibFunc_bcmp: 7899 if (visitMemCmpBCmpCall(I)) 7900 return; 7901 break; 7902 case LibFunc_copysign: 7903 case LibFunc_copysignf: 7904 case LibFunc_copysignl: 7905 // We already checked this call's prototype; verify it doesn't modify 7906 // errno. 7907 if (I.onlyReadsMemory()) { 7908 SDValue LHS = getValue(I.getArgOperand(0)); 7909 SDValue RHS = getValue(I.getArgOperand(1)); 7910 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7911 LHS.getValueType(), LHS, RHS)); 7912 return; 7913 } 7914 break; 7915 case LibFunc_fabs: 7916 case LibFunc_fabsf: 7917 case LibFunc_fabsl: 7918 if (visitUnaryFloatCall(I, ISD::FABS)) 7919 return; 7920 break; 7921 case LibFunc_fmin: 7922 case LibFunc_fminf: 7923 case LibFunc_fminl: 7924 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7925 return; 7926 break; 7927 case LibFunc_fmax: 7928 case LibFunc_fmaxf: 7929 case LibFunc_fmaxl: 7930 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7931 return; 7932 break; 7933 case LibFunc_sin: 7934 case LibFunc_sinf: 7935 case LibFunc_sinl: 7936 if (visitUnaryFloatCall(I, ISD::FSIN)) 7937 return; 7938 break; 7939 case LibFunc_cos: 7940 case LibFunc_cosf: 7941 case LibFunc_cosl: 7942 if (visitUnaryFloatCall(I, ISD::FCOS)) 7943 return; 7944 break; 7945 case LibFunc_sqrt: 7946 case LibFunc_sqrtf: 7947 case LibFunc_sqrtl: 7948 case LibFunc_sqrt_finite: 7949 case LibFunc_sqrtf_finite: 7950 case LibFunc_sqrtl_finite: 7951 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7952 return; 7953 break; 7954 case LibFunc_floor: 7955 case LibFunc_floorf: 7956 case LibFunc_floorl: 7957 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7958 return; 7959 break; 7960 case LibFunc_nearbyint: 7961 case LibFunc_nearbyintf: 7962 case LibFunc_nearbyintl: 7963 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7964 return; 7965 break; 7966 case LibFunc_ceil: 7967 case LibFunc_ceilf: 7968 case LibFunc_ceill: 7969 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7970 return; 7971 break; 7972 case LibFunc_rint: 7973 case LibFunc_rintf: 7974 case LibFunc_rintl: 7975 if (visitUnaryFloatCall(I, ISD::FRINT)) 7976 return; 7977 break; 7978 case LibFunc_round: 7979 case LibFunc_roundf: 7980 case LibFunc_roundl: 7981 if (visitUnaryFloatCall(I, ISD::FROUND)) 7982 return; 7983 break; 7984 case LibFunc_trunc: 7985 case LibFunc_truncf: 7986 case LibFunc_truncl: 7987 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7988 return; 7989 break; 7990 case LibFunc_log2: 7991 case LibFunc_log2f: 7992 case LibFunc_log2l: 7993 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7994 return; 7995 break; 7996 case LibFunc_exp2: 7997 case LibFunc_exp2f: 7998 case LibFunc_exp2l: 7999 if (visitUnaryFloatCall(I, ISD::FEXP2)) 8000 return; 8001 break; 8002 case LibFunc_memcmp: 8003 if (visitMemCmpBCmpCall(I)) 8004 return; 8005 break; 8006 case LibFunc_mempcpy: 8007 if (visitMemPCpyCall(I)) 8008 return; 8009 break; 8010 case LibFunc_memchr: 8011 if (visitMemChrCall(I)) 8012 return; 8013 break; 8014 case LibFunc_strcpy: 8015 if (visitStrCpyCall(I, false)) 8016 return; 8017 break; 8018 case LibFunc_stpcpy: 8019 if (visitStrCpyCall(I, true)) 8020 return; 8021 break; 8022 case LibFunc_strcmp: 8023 if (visitStrCmpCall(I)) 8024 return; 8025 break; 8026 case LibFunc_strlen: 8027 if (visitStrLenCall(I)) 8028 return; 8029 break; 8030 case LibFunc_strnlen: 8031 if (visitStrNLenCall(I)) 8032 return; 8033 break; 8034 } 8035 } 8036 } 8037 8038 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 8039 // have to do anything here to lower funclet bundles. 8040 // CFGuardTarget bundles are lowered in LowerCallTo. 8041 assert(!I.hasOperandBundlesOtherThan( 8042 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 8043 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 8044 LLVMContext::OB_clang_arc_attachedcall}) && 8045 "Cannot lower calls with arbitrary operand bundles!"); 8046 8047 SDValue Callee = getValue(I.getCalledOperand()); 8048 8049 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 8050 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 8051 else 8052 // Check if we can potentially perform a tail call. More detailed checking 8053 // is be done within LowerCallTo, after more information about the call is 8054 // known. 8055 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 8056 } 8057 8058 namespace { 8059 8060 /// AsmOperandInfo - This contains information for each constraint that we are 8061 /// lowering. 8062 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 8063 public: 8064 /// CallOperand - If this is the result output operand or a clobber 8065 /// this is null, otherwise it is the incoming operand to the CallInst. 8066 /// This gets modified as the asm is processed. 8067 SDValue CallOperand; 8068 8069 /// AssignedRegs - If this is a register or register class operand, this 8070 /// contains the set of register corresponding to the operand. 8071 RegsForValue AssignedRegs; 8072 8073 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 8074 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 8075 } 8076 8077 /// Whether or not this operand accesses memory 8078 bool hasMemory(const TargetLowering &TLI) const { 8079 // Indirect operand accesses access memory. 8080 if (isIndirect) 8081 return true; 8082 8083 for (const auto &Code : Codes) 8084 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 8085 return true; 8086 8087 return false; 8088 } 8089 8090 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 8091 /// corresponds to. If there is no Value* for this operand, it returns 8092 /// MVT::Other. 8093 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 8094 const DataLayout &DL) const { 8095 if (!CallOperandVal) return MVT::Other; 8096 8097 if (isa<BasicBlock>(CallOperandVal)) 8098 return TLI.getProgramPointerTy(DL); 8099 8100 llvm::Type *OpTy = CallOperandVal->getType(); 8101 8102 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 8103 // If this is an indirect operand, the operand is a pointer to the 8104 // accessed type. 8105 if (isIndirect) { 8106 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 8107 if (!PtrTy) 8108 report_fatal_error("Indirect operand for inline asm not a pointer!"); 8109 OpTy = PtrTy->getElementType(); 8110 } 8111 8112 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 8113 if (StructType *STy = dyn_cast<StructType>(OpTy)) 8114 if (STy->getNumElements() == 1) 8115 OpTy = STy->getElementType(0); 8116 8117 // If OpTy is not a single value, it may be a struct/union that we 8118 // can tile with integers. 8119 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 8120 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 8121 switch (BitSize) { 8122 default: break; 8123 case 1: 8124 case 8: 8125 case 16: 8126 case 32: 8127 case 64: 8128 case 128: 8129 OpTy = IntegerType::get(Context, BitSize); 8130 break; 8131 } 8132 } 8133 8134 return TLI.getValueType(DL, OpTy, true); 8135 } 8136 }; 8137 8138 8139 } // end anonymous namespace 8140 8141 /// Make sure that the output operand \p OpInfo and its corresponding input 8142 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 8143 /// out). 8144 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 8145 SDISelAsmOperandInfo &MatchingOpInfo, 8146 SelectionDAG &DAG) { 8147 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 8148 return; 8149 8150 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 8151 const auto &TLI = DAG.getTargetLoweringInfo(); 8152 8153 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 8154 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 8155 OpInfo.ConstraintVT); 8156 std::pair<unsigned, const TargetRegisterClass *> InputRC = 8157 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 8158 MatchingOpInfo.ConstraintVT); 8159 if ((OpInfo.ConstraintVT.isInteger() != 8160 MatchingOpInfo.ConstraintVT.isInteger()) || 8161 (MatchRC.second != InputRC.second)) { 8162 // FIXME: error out in a more elegant fashion 8163 report_fatal_error("Unsupported asm: input constraint" 8164 " with a matching output constraint of" 8165 " incompatible type!"); 8166 } 8167 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 8168 } 8169 8170 /// Get a direct memory input to behave well as an indirect operand. 8171 /// This may introduce stores, hence the need for a \p Chain. 8172 /// \return The (possibly updated) chain. 8173 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 8174 SDISelAsmOperandInfo &OpInfo, 8175 SelectionDAG &DAG) { 8176 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8177 8178 // If we don't have an indirect input, put it in the constpool if we can, 8179 // otherwise spill it to a stack slot. 8180 // TODO: This isn't quite right. We need to handle these according to 8181 // the addressing mode that the constraint wants. Also, this may take 8182 // an additional register for the computation and we don't want that 8183 // either. 8184 8185 // If the operand is a float, integer, or vector constant, spill to a 8186 // constant pool entry to get its address. 8187 const Value *OpVal = OpInfo.CallOperandVal; 8188 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 8189 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 8190 OpInfo.CallOperand = DAG.getConstantPool( 8191 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 8192 return Chain; 8193 } 8194 8195 // Otherwise, create a stack slot and emit a store to it before the asm. 8196 Type *Ty = OpVal->getType(); 8197 auto &DL = DAG.getDataLayout(); 8198 uint64_t TySize = DL.getTypeAllocSize(Ty); 8199 MachineFunction &MF = DAG.getMachineFunction(); 8200 int SSFI = MF.getFrameInfo().CreateStackObject( 8201 TySize, DL.getPrefTypeAlign(Ty), false); 8202 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 8203 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 8204 MachinePointerInfo::getFixedStack(MF, SSFI), 8205 TLI.getMemValueType(DL, Ty)); 8206 OpInfo.CallOperand = StackSlot; 8207 8208 return Chain; 8209 } 8210 8211 /// GetRegistersForValue - Assign registers (virtual or physical) for the 8212 /// specified operand. We prefer to assign virtual registers, to allow the 8213 /// register allocator to handle the assignment process. However, if the asm 8214 /// uses features that we can't model on machineinstrs, we have SDISel do the 8215 /// allocation. This produces generally horrible, but correct, code. 8216 /// 8217 /// OpInfo describes the operand 8218 /// RefOpInfo describes the matching operand if any, the operand otherwise 8219 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 8220 SDISelAsmOperandInfo &OpInfo, 8221 SDISelAsmOperandInfo &RefOpInfo) { 8222 LLVMContext &Context = *DAG.getContext(); 8223 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8224 8225 MachineFunction &MF = DAG.getMachineFunction(); 8226 SmallVector<unsigned, 4> Regs; 8227 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8228 8229 // No work to do for memory operations. 8230 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 8231 return; 8232 8233 // If this is a constraint for a single physreg, or a constraint for a 8234 // register class, find it. 8235 unsigned AssignedReg; 8236 const TargetRegisterClass *RC; 8237 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 8238 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 8239 // RC is unset only on failure. Return immediately. 8240 if (!RC) 8241 return; 8242 8243 // Get the actual register value type. This is important, because the user 8244 // may have asked for (e.g.) the AX register in i32 type. We need to 8245 // remember that AX is actually i16 to get the right extension. 8246 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 8247 8248 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) { 8249 // If this is an FP operand in an integer register (or visa versa), or more 8250 // generally if the operand value disagrees with the register class we plan 8251 // to stick it in, fix the operand type. 8252 // 8253 // If this is an input value, the bitcast to the new type is done now. 8254 // Bitcast for output value is done at the end of visitInlineAsm(). 8255 if ((OpInfo.Type == InlineAsm::isOutput || 8256 OpInfo.Type == InlineAsm::isInput) && 8257 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 8258 // Try to convert to the first EVT that the reg class contains. If the 8259 // types are identical size, use a bitcast to convert (e.g. two differing 8260 // vector types). Note: output bitcast is done at the end of 8261 // visitInlineAsm(). 8262 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 8263 // Exclude indirect inputs while they are unsupported because the code 8264 // to perform the load is missing and thus OpInfo.CallOperand still 8265 // refers to the input address rather than the pointed-to value. 8266 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 8267 OpInfo.CallOperand = 8268 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 8269 OpInfo.ConstraintVT = RegVT; 8270 // If the operand is an FP value and we want it in integer registers, 8271 // use the corresponding integer type. This turns an f64 value into 8272 // i64, which can be passed with two i32 values on a 32-bit machine. 8273 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 8274 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 8275 if (OpInfo.Type == InlineAsm::isInput) 8276 OpInfo.CallOperand = 8277 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 8278 OpInfo.ConstraintVT = VT; 8279 } 8280 } 8281 } 8282 8283 // No need to allocate a matching input constraint since the constraint it's 8284 // matching to has already been allocated. 8285 if (OpInfo.isMatchingInputConstraint()) 8286 return; 8287 8288 EVT ValueVT = OpInfo.ConstraintVT; 8289 if (OpInfo.ConstraintVT == MVT::Other) 8290 ValueVT = RegVT; 8291 8292 // Initialize NumRegs. 8293 unsigned NumRegs = 1; 8294 if (OpInfo.ConstraintVT != MVT::Other) 8295 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT); 8296 8297 // If this is a constraint for a specific physical register, like {r17}, 8298 // assign it now. 8299 8300 // If this associated to a specific register, initialize iterator to correct 8301 // place. If virtual, make sure we have enough registers 8302 8303 // Initialize iterator if necessary 8304 TargetRegisterClass::iterator I = RC->begin(); 8305 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8306 8307 // Do not check for single registers. 8308 if (AssignedReg) { 8309 for (; *I != AssignedReg; ++I) 8310 assert(I != RC->end() && "AssignedReg should be member of RC"); 8311 } 8312 8313 for (; NumRegs; --NumRegs, ++I) { 8314 assert(I != RC->end() && "Ran out of registers to allocate!"); 8315 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8316 Regs.push_back(R); 8317 } 8318 8319 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8320 } 8321 8322 static unsigned 8323 findMatchingInlineAsmOperand(unsigned OperandNo, 8324 const std::vector<SDValue> &AsmNodeOperands) { 8325 // Scan until we find the definition we already emitted of this operand. 8326 unsigned CurOp = InlineAsm::Op_FirstOperand; 8327 for (; OperandNo; --OperandNo) { 8328 // Advance to the next operand. 8329 unsigned OpFlag = 8330 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8331 assert((InlineAsm::isRegDefKind(OpFlag) || 8332 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8333 InlineAsm::isMemKind(OpFlag)) && 8334 "Skipped past definitions?"); 8335 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8336 } 8337 return CurOp; 8338 } 8339 8340 namespace { 8341 8342 class ExtraFlags { 8343 unsigned Flags = 0; 8344 8345 public: 8346 explicit ExtraFlags(const CallBase &Call) { 8347 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8348 if (IA->hasSideEffects()) 8349 Flags |= InlineAsm::Extra_HasSideEffects; 8350 if (IA->isAlignStack()) 8351 Flags |= InlineAsm::Extra_IsAlignStack; 8352 if (Call.isConvergent()) 8353 Flags |= InlineAsm::Extra_IsConvergent; 8354 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8355 } 8356 8357 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8358 // Ideally, we would only check against memory constraints. However, the 8359 // meaning of an Other constraint can be target-specific and we can't easily 8360 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8361 // for Other constraints as well. 8362 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8363 OpInfo.ConstraintType == TargetLowering::C_Other) { 8364 if (OpInfo.Type == InlineAsm::isInput) 8365 Flags |= InlineAsm::Extra_MayLoad; 8366 else if (OpInfo.Type == InlineAsm::isOutput) 8367 Flags |= InlineAsm::Extra_MayStore; 8368 else if (OpInfo.Type == InlineAsm::isClobber) 8369 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8370 } 8371 } 8372 8373 unsigned get() const { return Flags; } 8374 }; 8375 8376 } // end anonymous namespace 8377 8378 /// visitInlineAsm - Handle a call to an InlineAsm object. 8379 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 8380 const BasicBlock *EHPadBB) { 8381 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8382 8383 /// ConstraintOperands - Information about all of the constraints. 8384 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 8385 8386 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8387 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8388 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 8389 8390 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8391 // AsmDialect, MayLoad, MayStore). 8392 bool HasSideEffect = IA->hasSideEffects(); 8393 ExtraFlags ExtraInfo(Call); 8394 8395 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 8396 unsigned ResNo = 0; // ResNo - The result number of the next output. 8397 unsigned NumMatchingOps = 0; 8398 for (auto &T : TargetConstraints) { 8399 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8400 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8401 8402 // Compute the value type for each operand. 8403 if (OpInfo.Type == InlineAsm::isInput || 8404 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 8405 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++); 8406 8407 // Process the call argument. BasicBlocks are labels, currently appearing 8408 // only in asm's. 8409 if (isa<CallBrInst>(Call) && 8410 ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() - 8411 cast<CallBrInst>(&Call)->getNumIndirectDests() - 8412 NumMatchingOps) && 8413 (NumMatchingOps == 0 || 8414 ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() - 8415 NumMatchingOps))) { 8416 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal); 8417 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true); 8418 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT); 8419 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 8420 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 8421 } else { 8422 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8423 } 8424 8425 EVT VT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, 8426 DAG.getDataLayout()); 8427 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other; 8428 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 8429 // The return value of the call is this value. As such, there is no 8430 // corresponding argument. 8431 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8432 if (StructType *STy = dyn_cast<StructType>(Call.getType())) { 8433 OpInfo.ConstraintVT = TLI.getSimpleValueType( 8434 DAG.getDataLayout(), STy->getElementType(ResNo)); 8435 } else { 8436 assert(ResNo == 0 && "Asm only has one result!"); 8437 OpInfo.ConstraintVT = 8438 TLI.getSimpleValueType(DAG.getDataLayout(), Call.getType()); 8439 } 8440 ++ResNo; 8441 } else { 8442 OpInfo.ConstraintVT = MVT::Other; 8443 } 8444 8445 if (OpInfo.hasMatchingInput()) 8446 ++NumMatchingOps; 8447 8448 if (!HasSideEffect) 8449 HasSideEffect = OpInfo.hasMemory(TLI); 8450 8451 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8452 // FIXME: Could we compute this on OpInfo rather than T? 8453 8454 // Compute the constraint code and ConstraintType to use. 8455 TLI.ComputeConstraintToUse(T, SDValue()); 8456 8457 if (T.ConstraintType == TargetLowering::C_Immediate && 8458 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8459 // We've delayed emitting a diagnostic like the "n" constraint because 8460 // inlining could cause an integer showing up. 8461 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 8462 "' expects an integer constant " 8463 "expression"); 8464 8465 ExtraInfo.update(T); 8466 } 8467 8468 // We won't need to flush pending loads if this asm doesn't touch 8469 // memory and is nonvolatile. 8470 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8471 8472 bool EmitEHLabels = isa<InvokeInst>(Call) && IA->canThrow(); 8473 if (EmitEHLabels) { 8474 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 8475 } 8476 bool IsCallBr = isa<CallBrInst>(Call); 8477 8478 if (IsCallBr || EmitEHLabels) { 8479 // If this is a callbr or invoke we need to flush pending exports since 8480 // inlineasm_br and invoke are terminators. 8481 // We need to do this before nodes are glued to the inlineasm_br node. 8482 Chain = getControlRoot(); 8483 } 8484 8485 MCSymbol *BeginLabel = nullptr; 8486 if (EmitEHLabels) { 8487 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 8488 } 8489 8490 // Second pass over the constraints: compute which constraint option to use. 8491 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8492 // If this is an output operand with a matching input operand, look up the 8493 // matching input. If their types mismatch, e.g. one is an integer, the 8494 // other is floating point, or their sizes are different, flag it as an 8495 // error. 8496 if (OpInfo.hasMatchingInput()) { 8497 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8498 patchMatchingInput(OpInfo, Input, DAG); 8499 } 8500 8501 // Compute the constraint code and ConstraintType to use. 8502 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8503 8504 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8505 OpInfo.Type == InlineAsm::isClobber) 8506 continue; 8507 8508 // If this is a memory input, and if the operand is not indirect, do what we 8509 // need to provide an address for the memory input. 8510 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8511 !OpInfo.isIndirect) { 8512 assert((OpInfo.isMultipleAlternative || 8513 (OpInfo.Type == InlineAsm::isInput)) && 8514 "Can only indirectify direct input operands!"); 8515 8516 // Memory operands really want the address of the value. 8517 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8518 8519 // There is no longer a Value* corresponding to this operand. 8520 OpInfo.CallOperandVal = nullptr; 8521 8522 // It is now an indirect operand. 8523 OpInfo.isIndirect = true; 8524 } 8525 8526 } 8527 8528 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8529 std::vector<SDValue> AsmNodeOperands; 8530 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8531 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8532 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 8533 8534 // If we have a !srcloc metadata node associated with it, we want to attach 8535 // this to the ultimately generated inline asm machineinstr. To do this, we 8536 // pass in the third operand as this (potentially null) inline asm MDNode. 8537 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 8538 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8539 8540 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8541 // bits as operand 3. 8542 AsmNodeOperands.push_back(DAG.getTargetConstant( 8543 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8544 8545 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8546 // this, assign virtual and physical registers for inputs and otput. 8547 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8548 // Assign Registers. 8549 SDISelAsmOperandInfo &RefOpInfo = 8550 OpInfo.isMatchingInputConstraint() 8551 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8552 : OpInfo; 8553 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8554 8555 auto DetectWriteToReservedRegister = [&]() { 8556 const MachineFunction &MF = DAG.getMachineFunction(); 8557 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8558 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 8559 if (Register::isPhysicalRegister(Reg) && 8560 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 8561 const char *RegName = TRI.getName(Reg); 8562 emitInlineAsmError(Call, "write to reserved register '" + 8563 Twine(RegName) + "'"); 8564 return true; 8565 } 8566 } 8567 return false; 8568 }; 8569 8570 switch (OpInfo.Type) { 8571 case InlineAsm::isOutput: 8572 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8573 unsigned ConstraintID = 8574 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8575 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8576 "Failed to convert memory constraint code to constraint id."); 8577 8578 // Add information to the INLINEASM node to know about this output. 8579 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8580 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8581 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8582 MVT::i32)); 8583 AsmNodeOperands.push_back(OpInfo.CallOperand); 8584 } else { 8585 // Otherwise, this outputs to a register (directly for C_Register / 8586 // C_RegisterClass, and a target-defined fashion for 8587 // C_Immediate/C_Other). Find a register that we can use. 8588 if (OpInfo.AssignedRegs.Regs.empty()) { 8589 emitInlineAsmError( 8590 Call, "couldn't allocate output register for constraint '" + 8591 Twine(OpInfo.ConstraintCode) + "'"); 8592 return; 8593 } 8594 8595 if (DetectWriteToReservedRegister()) 8596 return; 8597 8598 // Add information to the INLINEASM node to know that this register is 8599 // set. 8600 OpInfo.AssignedRegs.AddInlineAsmOperands( 8601 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8602 : InlineAsm::Kind_RegDef, 8603 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8604 } 8605 break; 8606 8607 case InlineAsm::isInput: { 8608 SDValue InOperandVal = OpInfo.CallOperand; 8609 8610 if (OpInfo.isMatchingInputConstraint()) { 8611 // If this is required to match an output register we have already set, 8612 // just use its register. 8613 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8614 AsmNodeOperands); 8615 unsigned OpFlag = 8616 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8617 if (InlineAsm::isRegDefKind(OpFlag) || 8618 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8619 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8620 if (OpInfo.isIndirect) { 8621 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8622 emitInlineAsmError(Call, "inline asm not supported yet: " 8623 "don't know how to handle tied " 8624 "indirect register inputs"); 8625 return; 8626 } 8627 8628 SmallVector<unsigned, 4> Regs; 8629 MachineFunction &MF = DAG.getMachineFunction(); 8630 MachineRegisterInfo &MRI = MF.getRegInfo(); 8631 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8632 RegisterSDNode *R = dyn_cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]); 8633 Register TiedReg = R->getReg(); 8634 MVT RegVT = R->getSimpleValueType(0); 8635 const TargetRegisterClass *RC = TiedReg.isVirtual() ? 8636 MRI.getRegClass(TiedReg) : TRI.getMinimalPhysRegClass(TiedReg); 8637 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8638 for (unsigned i = 0; i != NumRegs; ++i) 8639 Regs.push_back(MRI.createVirtualRegister(RC)); 8640 8641 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8642 8643 SDLoc dl = getCurSDLoc(); 8644 // Use the produced MatchedRegs object to 8645 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call); 8646 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8647 true, OpInfo.getMatchedOperand(), dl, 8648 DAG, AsmNodeOperands); 8649 break; 8650 } 8651 8652 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8653 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8654 "Unexpected number of operands"); 8655 // Add information to the INLINEASM node to know about this input. 8656 // See InlineAsm.h isUseOperandTiedToDef. 8657 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8658 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8659 OpInfo.getMatchedOperand()); 8660 AsmNodeOperands.push_back(DAG.getTargetConstant( 8661 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8662 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8663 break; 8664 } 8665 8666 // Treat indirect 'X' constraint as memory. 8667 if (OpInfo.ConstraintType == TargetLowering::C_Other && 8668 OpInfo.isIndirect) 8669 OpInfo.ConstraintType = TargetLowering::C_Memory; 8670 8671 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 8672 OpInfo.ConstraintType == TargetLowering::C_Other) { 8673 std::vector<SDValue> Ops; 8674 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 8675 Ops, DAG); 8676 if (Ops.empty()) { 8677 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 8678 if (isa<ConstantSDNode>(InOperandVal)) { 8679 emitInlineAsmError(Call, "value out of range for constraint '" + 8680 Twine(OpInfo.ConstraintCode) + "'"); 8681 return; 8682 } 8683 8684 emitInlineAsmError(Call, 8685 "invalid operand for inline asm constraint '" + 8686 Twine(OpInfo.ConstraintCode) + "'"); 8687 return; 8688 } 8689 8690 // Add information to the INLINEASM node to know about this input. 8691 unsigned ResOpType = 8692 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 8693 AsmNodeOperands.push_back(DAG.getTargetConstant( 8694 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8695 llvm::append_range(AsmNodeOperands, Ops); 8696 break; 8697 } 8698 8699 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8700 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 8701 assert(InOperandVal.getValueType() == 8702 TLI.getPointerTy(DAG.getDataLayout()) && 8703 "Memory operands expect pointer values"); 8704 8705 unsigned ConstraintID = 8706 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8707 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8708 "Failed to convert memory constraint code to constraint id."); 8709 8710 // Add information to the INLINEASM node to know about this input. 8711 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8712 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 8713 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 8714 getCurSDLoc(), 8715 MVT::i32)); 8716 AsmNodeOperands.push_back(InOperandVal); 8717 break; 8718 } 8719 8720 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 8721 OpInfo.ConstraintType == TargetLowering::C_Register) && 8722 "Unknown constraint type!"); 8723 8724 // TODO: Support this. 8725 if (OpInfo.isIndirect) { 8726 emitInlineAsmError( 8727 Call, "Don't know how to handle indirect register inputs yet " 8728 "for constraint '" + 8729 Twine(OpInfo.ConstraintCode) + "'"); 8730 return; 8731 } 8732 8733 // Copy the input into the appropriate registers. 8734 if (OpInfo.AssignedRegs.Regs.empty()) { 8735 emitInlineAsmError(Call, 8736 "couldn't allocate input reg for constraint '" + 8737 Twine(OpInfo.ConstraintCode) + "'"); 8738 return; 8739 } 8740 8741 if (DetectWriteToReservedRegister()) 8742 return; 8743 8744 SDLoc dl = getCurSDLoc(); 8745 8746 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 8747 &Call); 8748 8749 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 8750 dl, DAG, AsmNodeOperands); 8751 break; 8752 } 8753 case InlineAsm::isClobber: 8754 // Add the clobbered value to the operand list, so that the register 8755 // allocator is aware that the physreg got clobbered. 8756 if (!OpInfo.AssignedRegs.Regs.empty()) 8757 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 8758 false, 0, getCurSDLoc(), DAG, 8759 AsmNodeOperands); 8760 break; 8761 } 8762 } 8763 8764 // Finish up input operands. Set the input chain and add the flag last. 8765 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 8766 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 8767 8768 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 8769 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 8770 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 8771 Flag = Chain.getValue(1); 8772 8773 // Do additional work to generate outputs. 8774 8775 SmallVector<EVT, 1> ResultVTs; 8776 SmallVector<SDValue, 1> ResultValues; 8777 SmallVector<SDValue, 8> OutChains; 8778 8779 llvm::Type *CallResultType = Call.getType(); 8780 ArrayRef<Type *> ResultTypes; 8781 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 8782 ResultTypes = StructResult->elements(); 8783 else if (!CallResultType->isVoidTy()) 8784 ResultTypes = makeArrayRef(CallResultType); 8785 8786 auto CurResultType = ResultTypes.begin(); 8787 auto handleRegAssign = [&](SDValue V) { 8788 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 8789 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 8790 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 8791 ++CurResultType; 8792 // If the type of the inline asm call site return value is different but has 8793 // same size as the type of the asm output bitcast it. One example of this 8794 // is for vectors with different width / number of elements. This can 8795 // happen for register classes that can contain multiple different value 8796 // types. The preg or vreg allocated may not have the same VT as was 8797 // expected. 8798 // 8799 // This can also happen for a return value that disagrees with the register 8800 // class it is put in, eg. a double in a general-purpose register on a 8801 // 32-bit machine. 8802 if (ResultVT != V.getValueType() && 8803 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 8804 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 8805 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 8806 V.getValueType().isInteger()) { 8807 // If a result value was tied to an input value, the computed result 8808 // may have a wider width than the expected result. Extract the 8809 // relevant portion. 8810 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 8811 } 8812 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 8813 ResultVTs.push_back(ResultVT); 8814 ResultValues.push_back(V); 8815 }; 8816 8817 // Deal with output operands. 8818 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8819 if (OpInfo.Type == InlineAsm::isOutput) { 8820 SDValue Val; 8821 // Skip trivial output operands. 8822 if (OpInfo.AssignedRegs.Regs.empty()) 8823 continue; 8824 8825 switch (OpInfo.ConstraintType) { 8826 case TargetLowering::C_Register: 8827 case TargetLowering::C_RegisterClass: 8828 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 8829 Chain, &Flag, &Call); 8830 break; 8831 case TargetLowering::C_Immediate: 8832 case TargetLowering::C_Other: 8833 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 8834 OpInfo, DAG); 8835 break; 8836 case TargetLowering::C_Memory: 8837 break; // Already handled. 8838 case TargetLowering::C_Unknown: 8839 assert(false && "Unexpected unknown constraint"); 8840 } 8841 8842 // Indirect output manifest as stores. Record output chains. 8843 if (OpInfo.isIndirect) { 8844 const Value *Ptr = OpInfo.CallOperandVal; 8845 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 8846 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 8847 MachinePointerInfo(Ptr)); 8848 OutChains.push_back(Store); 8849 } else { 8850 // generate CopyFromRegs to associated registers. 8851 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8852 if (Val.getOpcode() == ISD::MERGE_VALUES) { 8853 for (const SDValue &V : Val->op_values()) 8854 handleRegAssign(V); 8855 } else 8856 handleRegAssign(Val); 8857 } 8858 } 8859 } 8860 8861 // Set results. 8862 if (!ResultValues.empty()) { 8863 assert(CurResultType == ResultTypes.end() && 8864 "Mismatch in number of ResultTypes"); 8865 assert(ResultValues.size() == ResultTypes.size() && 8866 "Mismatch in number of output operands in asm result"); 8867 8868 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 8869 DAG.getVTList(ResultVTs), ResultValues); 8870 setValue(&Call, V); 8871 } 8872 8873 // Collect store chains. 8874 if (!OutChains.empty()) 8875 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 8876 8877 if (EmitEHLabels) { 8878 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 8879 } 8880 8881 // Only Update Root if inline assembly has a memory effect. 8882 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 8883 EmitEHLabels) 8884 DAG.setRoot(Chain); 8885 } 8886 8887 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 8888 const Twine &Message) { 8889 LLVMContext &Ctx = *DAG.getContext(); 8890 Ctx.emitError(&Call, Message); 8891 8892 // Make sure we leave the DAG in a valid state 8893 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8894 SmallVector<EVT, 1> ValueVTs; 8895 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 8896 8897 if (ValueVTs.empty()) 8898 return; 8899 8900 SmallVector<SDValue, 1> Ops; 8901 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 8902 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 8903 8904 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 8905 } 8906 8907 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 8908 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 8909 MVT::Other, getRoot(), 8910 getValue(I.getArgOperand(0)), 8911 DAG.getSrcValue(I.getArgOperand(0)))); 8912 } 8913 8914 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 8915 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8916 const DataLayout &DL = DAG.getDataLayout(); 8917 SDValue V = DAG.getVAArg( 8918 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 8919 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 8920 DL.getABITypeAlign(I.getType()).value()); 8921 DAG.setRoot(V.getValue(1)); 8922 8923 if (I.getType()->isPointerTy()) 8924 V = DAG.getPtrExtOrTrunc( 8925 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 8926 setValue(&I, V); 8927 } 8928 8929 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 8930 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 8931 MVT::Other, getRoot(), 8932 getValue(I.getArgOperand(0)), 8933 DAG.getSrcValue(I.getArgOperand(0)))); 8934 } 8935 8936 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 8937 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 8938 MVT::Other, getRoot(), 8939 getValue(I.getArgOperand(0)), 8940 getValue(I.getArgOperand(1)), 8941 DAG.getSrcValue(I.getArgOperand(0)), 8942 DAG.getSrcValue(I.getArgOperand(1)))); 8943 } 8944 8945 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 8946 const Instruction &I, 8947 SDValue Op) { 8948 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 8949 if (!Range) 8950 return Op; 8951 8952 ConstantRange CR = getConstantRangeFromMetadata(*Range); 8953 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 8954 return Op; 8955 8956 APInt Lo = CR.getUnsignedMin(); 8957 if (!Lo.isMinValue()) 8958 return Op; 8959 8960 APInt Hi = CR.getUnsignedMax(); 8961 unsigned Bits = std::max(Hi.getActiveBits(), 8962 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 8963 8964 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8965 8966 SDLoc SL = getCurSDLoc(); 8967 8968 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8969 DAG.getValueType(SmallVT)); 8970 unsigned NumVals = Op.getNode()->getNumValues(); 8971 if (NumVals == 1) 8972 return ZExt; 8973 8974 SmallVector<SDValue, 4> Ops; 8975 8976 Ops.push_back(ZExt); 8977 for (unsigned I = 1; I != NumVals; ++I) 8978 Ops.push_back(Op.getValue(I)); 8979 8980 return DAG.getMergeValues(Ops, SL); 8981 } 8982 8983 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8984 /// the call being lowered. 8985 /// 8986 /// This is a helper for lowering intrinsics that follow a target calling 8987 /// convention or require stack pointer adjustment. Only a subset of the 8988 /// intrinsic's operands need to participate in the calling convention. 8989 void SelectionDAGBuilder::populateCallLoweringInfo( 8990 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 8991 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8992 bool IsPatchPoint) { 8993 TargetLowering::ArgListTy Args; 8994 Args.reserve(NumArgs); 8995 8996 // Populate the argument list. 8997 // Attributes for args start at offset 1, after the return attribute. 8998 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8999 ArgI != ArgE; ++ArgI) { 9000 const Value *V = Call->getOperand(ArgI); 9001 9002 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 9003 9004 TargetLowering::ArgListEntry Entry; 9005 Entry.Node = getValue(V); 9006 Entry.Ty = V->getType(); 9007 Entry.setAttributes(Call, ArgI); 9008 Args.push_back(Entry); 9009 } 9010 9011 CLI.setDebugLoc(getCurSDLoc()) 9012 .setChain(getRoot()) 9013 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 9014 .setDiscardResult(Call->use_empty()) 9015 .setIsPatchPoint(IsPatchPoint) 9016 .setIsPreallocated( 9017 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 9018 } 9019 9020 /// Add a stack map intrinsic call's live variable operands to a stackmap 9021 /// or patchpoint target node's operand list. 9022 /// 9023 /// Constants are converted to TargetConstants purely as an optimization to 9024 /// avoid constant materialization and register allocation. 9025 /// 9026 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 9027 /// generate addess computation nodes, and so FinalizeISel can convert the 9028 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 9029 /// address materialization and register allocation, but may also be required 9030 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 9031 /// alloca in the entry block, then the runtime may assume that the alloca's 9032 /// StackMap location can be read immediately after compilation and that the 9033 /// location is valid at any point during execution (this is similar to the 9034 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 9035 /// only available in a register, then the runtime would need to trap when 9036 /// execution reaches the StackMap in order to read the alloca's location. 9037 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 9038 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 9039 SelectionDAGBuilder &Builder) { 9040 for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) { 9041 SDValue OpVal = Builder.getValue(Call.getArgOperand(i)); 9042 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 9043 Ops.push_back( 9044 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 9045 Ops.push_back( 9046 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 9047 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 9048 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 9049 Ops.push_back(Builder.DAG.getTargetFrameIndex( 9050 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 9051 } else 9052 Ops.push_back(OpVal); 9053 } 9054 } 9055 9056 /// Lower llvm.experimental.stackmap directly to its target opcode. 9057 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 9058 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 9059 // [live variables...]) 9060 9061 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 9062 9063 SDValue Chain, InFlag, Callee, NullPtr; 9064 SmallVector<SDValue, 32> Ops; 9065 9066 SDLoc DL = getCurSDLoc(); 9067 Callee = getValue(CI.getCalledOperand()); 9068 NullPtr = DAG.getIntPtrConstant(0, DL, true); 9069 9070 // The stackmap intrinsic only records the live variables (the arguments 9071 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 9072 // intrinsic, this won't be lowered to a function call. This means we don't 9073 // have to worry about calling conventions and target specific lowering code. 9074 // Instead we perform the call lowering right here. 9075 // 9076 // chain, flag = CALLSEQ_START(chain, 0, 0) 9077 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 9078 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 9079 // 9080 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 9081 InFlag = Chain.getValue(1); 9082 9083 // Add the <id> and <numBytes> constants. 9084 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 9085 Ops.push_back(DAG.getTargetConstant( 9086 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 9087 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 9088 Ops.push_back(DAG.getTargetConstant( 9089 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 9090 MVT::i32)); 9091 9092 // Push live variables for the stack map. 9093 addStackMapLiveVars(CI, 2, DL, Ops, *this); 9094 9095 // We are not pushing any register mask info here on the operands list, 9096 // because the stackmap doesn't clobber anything. 9097 9098 // Push the chain and the glue flag. 9099 Ops.push_back(Chain); 9100 Ops.push_back(InFlag); 9101 9102 // Create the STACKMAP node. 9103 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9104 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 9105 Chain = SDValue(SM, 0); 9106 InFlag = Chain.getValue(1); 9107 9108 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 9109 9110 // Stackmaps don't generate values, so nothing goes into the NodeMap. 9111 9112 // Set the root to the target-lowered call chain. 9113 DAG.setRoot(Chain); 9114 9115 // Inform the Frame Information that we have a stackmap in this function. 9116 FuncInfo.MF->getFrameInfo().setHasStackMap(); 9117 } 9118 9119 /// Lower llvm.experimental.patchpoint directly to its target opcode. 9120 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 9121 const BasicBlock *EHPadBB) { 9122 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 9123 // i32 <numBytes>, 9124 // i8* <target>, 9125 // i32 <numArgs>, 9126 // [Args...], 9127 // [live variables...]) 9128 9129 CallingConv::ID CC = CB.getCallingConv(); 9130 bool IsAnyRegCC = CC == CallingConv::AnyReg; 9131 bool HasDef = !CB.getType()->isVoidTy(); 9132 SDLoc dl = getCurSDLoc(); 9133 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 9134 9135 // Handle immediate and symbolic callees. 9136 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 9137 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 9138 /*isTarget=*/true); 9139 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 9140 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 9141 SDLoc(SymbolicCallee), 9142 SymbolicCallee->getValueType(0)); 9143 9144 // Get the real number of arguments participating in the call <numArgs> 9145 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 9146 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 9147 9148 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 9149 // Intrinsics include all meta-operands up to but not including CC. 9150 unsigned NumMetaOpers = PatchPointOpers::CCPos; 9151 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 9152 "Not enough arguments provided to the patchpoint intrinsic"); 9153 9154 // For AnyRegCC the arguments are lowered later on manually. 9155 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 9156 Type *ReturnTy = 9157 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 9158 9159 TargetLowering::CallLoweringInfo CLI(DAG); 9160 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 9161 ReturnTy, true); 9162 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 9163 9164 SDNode *CallEnd = Result.second.getNode(); 9165 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 9166 CallEnd = CallEnd->getOperand(0).getNode(); 9167 9168 /// Get a call instruction from the call sequence chain. 9169 /// Tail calls are not allowed. 9170 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 9171 "Expected a callseq node."); 9172 SDNode *Call = CallEnd->getOperand(0).getNode(); 9173 bool HasGlue = Call->getGluedNode(); 9174 9175 // Replace the target specific call node with the patchable intrinsic. 9176 SmallVector<SDValue, 8> Ops; 9177 9178 // Add the <id> and <numBytes> constants. 9179 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 9180 Ops.push_back(DAG.getTargetConstant( 9181 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 9182 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 9183 Ops.push_back(DAG.getTargetConstant( 9184 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 9185 MVT::i32)); 9186 9187 // Add the callee. 9188 Ops.push_back(Callee); 9189 9190 // Adjust <numArgs> to account for any arguments that have been passed on the 9191 // stack instead. 9192 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 9193 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 9194 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 9195 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 9196 9197 // Add the calling convention 9198 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 9199 9200 // Add the arguments we omitted previously. The register allocator should 9201 // place these in any free register. 9202 if (IsAnyRegCC) 9203 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 9204 Ops.push_back(getValue(CB.getArgOperand(i))); 9205 9206 // Push the arguments from the call instruction up to the register mask. 9207 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 9208 Ops.append(Call->op_begin() + 2, e); 9209 9210 // Push live variables for the stack map. 9211 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 9212 9213 // Push the register mask info. 9214 if (HasGlue) 9215 Ops.push_back(*(Call->op_end()-2)); 9216 else 9217 Ops.push_back(*(Call->op_end()-1)); 9218 9219 // Push the chain (this is originally the first operand of the call, but 9220 // becomes now the last or second to last operand). 9221 Ops.push_back(*(Call->op_begin())); 9222 9223 // Push the glue flag (last operand). 9224 if (HasGlue) 9225 Ops.push_back(*(Call->op_end()-1)); 9226 9227 SDVTList NodeTys; 9228 if (IsAnyRegCC && HasDef) { 9229 // Create the return types based on the intrinsic definition 9230 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9231 SmallVector<EVT, 3> ValueVTs; 9232 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 9233 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 9234 9235 // There is always a chain and a glue type at the end 9236 ValueVTs.push_back(MVT::Other); 9237 ValueVTs.push_back(MVT::Glue); 9238 NodeTys = DAG.getVTList(ValueVTs); 9239 } else 9240 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9241 9242 // Replace the target specific call node with a PATCHPOINT node. 9243 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 9244 dl, NodeTys, Ops); 9245 9246 // Update the NodeMap. 9247 if (HasDef) { 9248 if (IsAnyRegCC) 9249 setValue(&CB, SDValue(MN, 0)); 9250 else 9251 setValue(&CB, Result.first); 9252 } 9253 9254 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 9255 // call sequence. Furthermore the location of the chain and glue can change 9256 // when the AnyReg calling convention is used and the intrinsic returns a 9257 // value. 9258 if (IsAnyRegCC && HasDef) { 9259 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 9260 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 9261 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 9262 } else 9263 DAG.ReplaceAllUsesWith(Call, MN); 9264 DAG.DeleteNode(Call); 9265 9266 // Inform the Frame Information that we have a patchpoint in this function. 9267 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 9268 } 9269 9270 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 9271 unsigned Intrinsic) { 9272 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9273 SDValue Op1 = getValue(I.getArgOperand(0)); 9274 SDValue Op2; 9275 if (I.getNumArgOperands() > 1) 9276 Op2 = getValue(I.getArgOperand(1)); 9277 SDLoc dl = getCurSDLoc(); 9278 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 9279 SDValue Res; 9280 SDNodeFlags SDFlags; 9281 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 9282 SDFlags.copyFMF(*FPMO); 9283 9284 switch (Intrinsic) { 9285 case Intrinsic::vector_reduce_fadd: 9286 if (SDFlags.hasAllowReassociation()) 9287 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 9288 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 9289 SDFlags); 9290 else 9291 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 9292 break; 9293 case Intrinsic::vector_reduce_fmul: 9294 if (SDFlags.hasAllowReassociation()) 9295 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 9296 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 9297 SDFlags); 9298 else 9299 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 9300 break; 9301 case Intrinsic::vector_reduce_add: 9302 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 9303 break; 9304 case Intrinsic::vector_reduce_mul: 9305 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 9306 break; 9307 case Intrinsic::vector_reduce_and: 9308 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 9309 break; 9310 case Intrinsic::vector_reduce_or: 9311 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 9312 break; 9313 case Intrinsic::vector_reduce_xor: 9314 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 9315 break; 9316 case Intrinsic::vector_reduce_smax: 9317 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 9318 break; 9319 case Intrinsic::vector_reduce_smin: 9320 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 9321 break; 9322 case Intrinsic::vector_reduce_umax: 9323 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 9324 break; 9325 case Intrinsic::vector_reduce_umin: 9326 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 9327 break; 9328 case Intrinsic::vector_reduce_fmax: 9329 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 9330 break; 9331 case Intrinsic::vector_reduce_fmin: 9332 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 9333 break; 9334 default: 9335 llvm_unreachable("Unhandled vector reduce intrinsic"); 9336 } 9337 setValue(&I, Res); 9338 } 9339 9340 /// Returns an AttributeList representing the attributes applied to the return 9341 /// value of the given call. 9342 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9343 SmallVector<Attribute::AttrKind, 2> Attrs; 9344 if (CLI.RetSExt) 9345 Attrs.push_back(Attribute::SExt); 9346 if (CLI.RetZExt) 9347 Attrs.push_back(Attribute::ZExt); 9348 if (CLI.IsInReg) 9349 Attrs.push_back(Attribute::InReg); 9350 9351 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9352 Attrs); 9353 } 9354 9355 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9356 /// implementation, which just calls LowerCall. 9357 /// FIXME: When all targets are 9358 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9359 std::pair<SDValue, SDValue> 9360 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9361 // Handle the incoming return values from the call. 9362 CLI.Ins.clear(); 9363 Type *OrigRetTy = CLI.RetTy; 9364 SmallVector<EVT, 4> RetTys; 9365 SmallVector<uint64_t, 4> Offsets; 9366 auto &DL = CLI.DAG.getDataLayout(); 9367 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 9368 9369 if (CLI.IsPostTypeLegalization) { 9370 // If we are lowering a libcall after legalization, split the return type. 9371 SmallVector<EVT, 4> OldRetTys; 9372 SmallVector<uint64_t, 4> OldOffsets; 9373 RetTys.swap(OldRetTys); 9374 Offsets.swap(OldOffsets); 9375 9376 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9377 EVT RetVT = OldRetTys[i]; 9378 uint64_t Offset = OldOffsets[i]; 9379 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9380 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9381 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9382 RetTys.append(NumRegs, RegisterVT); 9383 for (unsigned j = 0; j != NumRegs; ++j) 9384 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9385 } 9386 } 9387 9388 SmallVector<ISD::OutputArg, 4> Outs; 9389 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9390 9391 bool CanLowerReturn = 9392 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9393 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9394 9395 SDValue DemoteStackSlot; 9396 int DemoteStackIdx = -100; 9397 if (!CanLowerReturn) { 9398 // FIXME: equivalent assert? 9399 // assert(!CS.hasInAllocaArgument() && 9400 // "sret demotion is incompatible with inalloca"); 9401 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9402 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 9403 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9404 DemoteStackIdx = 9405 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 9406 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9407 DL.getAllocaAddrSpace()); 9408 9409 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9410 ArgListEntry Entry; 9411 Entry.Node = DemoteStackSlot; 9412 Entry.Ty = StackSlotPtrType; 9413 Entry.IsSExt = false; 9414 Entry.IsZExt = false; 9415 Entry.IsInReg = false; 9416 Entry.IsSRet = true; 9417 Entry.IsNest = false; 9418 Entry.IsByVal = false; 9419 Entry.IsByRef = false; 9420 Entry.IsReturned = false; 9421 Entry.IsSwiftSelf = false; 9422 Entry.IsSwiftAsync = false; 9423 Entry.IsSwiftError = false; 9424 Entry.IsCFGuardTarget = false; 9425 Entry.Alignment = Alignment; 9426 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9427 CLI.NumFixedArgs += 1; 9428 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9429 9430 // sret demotion isn't compatible with tail-calls, since the sret argument 9431 // points into the callers stack frame. 9432 CLI.IsTailCall = false; 9433 } else { 9434 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9435 CLI.RetTy, CLI.CallConv, CLI.IsVarArg); 9436 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9437 ISD::ArgFlagsTy Flags; 9438 if (NeedsRegBlock) { 9439 Flags.setInConsecutiveRegs(); 9440 if (I == RetTys.size() - 1) 9441 Flags.setInConsecutiveRegsLast(); 9442 } 9443 EVT VT = RetTys[I]; 9444 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9445 CLI.CallConv, VT); 9446 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9447 CLI.CallConv, VT); 9448 for (unsigned i = 0; i != NumRegs; ++i) { 9449 ISD::InputArg MyFlags; 9450 MyFlags.Flags = Flags; 9451 MyFlags.VT = RegisterVT; 9452 MyFlags.ArgVT = VT; 9453 MyFlags.Used = CLI.IsReturnValueUsed; 9454 if (CLI.RetTy->isPointerTy()) { 9455 MyFlags.Flags.setPointer(); 9456 MyFlags.Flags.setPointerAddrSpace( 9457 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9458 } 9459 if (CLI.RetSExt) 9460 MyFlags.Flags.setSExt(); 9461 if (CLI.RetZExt) 9462 MyFlags.Flags.setZExt(); 9463 if (CLI.IsInReg) 9464 MyFlags.Flags.setInReg(); 9465 CLI.Ins.push_back(MyFlags); 9466 } 9467 } 9468 } 9469 9470 // We push in swifterror return as the last element of CLI.Ins. 9471 ArgListTy &Args = CLI.getArgs(); 9472 if (supportSwiftError()) { 9473 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9474 if (Args[i].IsSwiftError) { 9475 ISD::InputArg MyFlags; 9476 MyFlags.VT = getPointerTy(DL); 9477 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9478 MyFlags.Flags.setSwiftError(); 9479 CLI.Ins.push_back(MyFlags); 9480 } 9481 } 9482 } 9483 9484 // Handle all of the outgoing arguments. 9485 CLI.Outs.clear(); 9486 CLI.OutVals.clear(); 9487 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9488 SmallVector<EVT, 4> ValueVTs; 9489 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9490 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9491 Type *FinalType = Args[i].Ty; 9492 if (Args[i].IsByVal) 9493 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 9494 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9495 FinalType, CLI.CallConv, CLI.IsVarArg); 9496 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9497 ++Value) { 9498 EVT VT = ValueVTs[Value]; 9499 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9500 SDValue Op = SDValue(Args[i].Node.getNode(), 9501 Args[i].Node.getResNo() + Value); 9502 ISD::ArgFlagsTy Flags; 9503 9504 // Certain targets (such as MIPS), may have a different ABI alignment 9505 // for a type depending on the context. Give the target a chance to 9506 // specify the alignment it wants. 9507 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 9508 Flags.setOrigAlign(OriginalAlignment); 9509 9510 if (Args[i].Ty->isPointerTy()) { 9511 Flags.setPointer(); 9512 Flags.setPointerAddrSpace( 9513 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9514 } 9515 if (Args[i].IsZExt) 9516 Flags.setZExt(); 9517 if (Args[i].IsSExt) 9518 Flags.setSExt(); 9519 if (Args[i].IsInReg) { 9520 // If we are using vectorcall calling convention, a structure that is 9521 // passed InReg - is surely an HVA 9522 if (CLI.CallConv == CallingConv::X86_VectorCall && 9523 isa<StructType>(FinalType)) { 9524 // The first value of a structure is marked 9525 if (0 == Value) 9526 Flags.setHvaStart(); 9527 Flags.setHva(); 9528 } 9529 // Set InReg Flag 9530 Flags.setInReg(); 9531 } 9532 if (Args[i].IsSRet) 9533 Flags.setSRet(); 9534 if (Args[i].IsSwiftSelf) 9535 Flags.setSwiftSelf(); 9536 if (Args[i].IsSwiftAsync) 9537 Flags.setSwiftAsync(); 9538 if (Args[i].IsSwiftError) 9539 Flags.setSwiftError(); 9540 if (Args[i].IsCFGuardTarget) 9541 Flags.setCFGuardTarget(); 9542 if (Args[i].IsByVal) 9543 Flags.setByVal(); 9544 if (Args[i].IsByRef) 9545 Flags.setByRef(); 9546 if (Args[i].IsPreallocated) { 9547 Flags.setPreallocated(); 9548 // Set the byval flag for CCAssignFn callbacks that don't know about 9549 // preallocated. This way we can know how many bytes we should've 9550 // allocated and how many bytes a callee cleanup function will pop. If 9551 // we port preallocated to more targets, we'll have to add custom 9552 // preallocated handling in the various CC lowering callbacks. 9553 Flags.setByVal(); 9554 } 9555 if (Args[i].IsInAlloca) { 9556 Flags.setInAlloca(); 9557 // Set the byval flag for CCAssignFn callbacks that don't know about 9558 // inalloca. This way we can know how many bytes we should've allocated 9559 // and how many bytes a callee cleanup function will pop. If we port 9560 // inalloca to more targets, we'll have to add custom inalloca handling 9561 // in the various CC lowering callbacks. 9562 Flags.setByVal(); 9563 } 9564 Align MemAlign; 9565 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 9566 PointerType *Ty = cast<PointerType>(Args[i].Ty); 9567 Type *ElementTy = Ty->getElementType(); 9568 9569 unsigned FrameSize = DL.getTypeAllocSize( 9570 Args[i].ByValType ? Args[i].ByValType : ElementTy); 9571 Flags.setByValSize(FrameSize); 9572 9573 // info is not there but there are cases it cannot get right. 9574 if (auto MA = Args[i].Alignment) 9575 MemAlign = *MA; 9576 else 9577 MemAlign = Align(getByValTypeAlignment(ElementTy, DL)); 9578 } else if (auto MA = Args[i].Alignment) { 9579 MemAlign = *MA; 9580 } else { 9581 MemAlign = OriginalAlignment; 9582 } 9583 Flags.setMemAlign(MemAlign); 9584 if (Args[i].IsNest) 9585 Flags.setNest(); 9586 if (NeedsRegBlock) 9587 Flags.setInConsecutiveRegs(); 9588 9589 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9590 CLI.CallConv, VT); 9591 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9592 CLI.CallConv, VT); 9593 SmallVector<SDValue, 4> Parts(NumParts); 9594 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9595 9596 if (Args[i].IsSExt) 9597 ExtendKind = ISD::SIGN_EXTEND; 9598 else if (Args[i].IsZExt) 9599 ExtendKind = ISD::ZERO_EXTEND; 9600 9601 // Conservatively only handle 'returned' on non-vectors that can be lowered, 9602 // for now. 9603 if (Args[i].IsReturned && !Op.getValueType().isVector() && 9604 CanLowerReturn) { 9605 assert((CLI.RetTy == Args[i].Ty || 9606 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 9607 CLI.RetTy->getPointerAddressSpace() == 9608 Args[i].Ty->getPointerAddressSpace())) && 9609 RetTys.size() == NumValues && "unexpected use of 'returned'"); 9610 // Before passing 'returned' to the target lowering code, ensure that 9611 // either the register MVT and the actual EVT are the same size or that 9612 // the return value and argument are extended in the same way; in these 9613 // cases it's safe to pass the argument register value unchanged as the 9614 // return register value (although it's at the target's option whether 9615 // to do so) 9616 // TODO: allow code generation to take advantage of partially preserved 9617 // registers rather than clobbering the entire register when the 9618 // parameter extension method is not compatible with the return 9619 // extension method 9620 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9621 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9622 CLI.RetZExt == Args[i].IsZExt)) 9623 Flags.setReturned(); 9624 } 9625 9626 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 9627 CLI.CallConv, ExtendKind); 9628 9629 for (unsigned j = 0; j != NumParts; ++j) { 9630 // if it isn't first piece, alignment must be 1 9631 // For scalable vectors the scalable part is currently handled 9632 // by individual targets, so we just use the known minimum size here. 9633 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 9634 i < CLI.NumFixedArgs, i, 9635 j*Parts[j].getValueType().getStoreSize().getKnownMinSize()); 9636 if (NumParts > 1 && j == 0) 9637 MyFlags.Flags.setSplit(); 9638 else if (j != 0) { 9639 MyFlags.Flags.setOrigAlign(Align(1)); 9640 if (j == NumParts - 1) 9641 MyFlags.Flags.setSplitEnd(); 9642 } 9643 9644 CLI.Outs.push_back(MyFlags); 9645 CLI.OutVals.push_back(Parts[j]); 9646 } 9647 9648 if (NeedsRegBlock && Value == NumValues - 1) 9649 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 9650 } 9651 } 9652 9653 SmallVector<SDValue, 4> InVals; 9654 CLI.Chain = LowerCall(CLI, InVals); 9655 9656 // Update CLI.InVals to use outside of this function. 9657 CLI.InVals = InVals; 9658 9659 // Verify that the target's LowerCall behaved as expected. 9660 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 9661 "LowerCall didn't return a valid chain!"); 9662 assert((!CLI.IsTailCall || InVals.empty()) && 9663 "LowerCall emitted a return value for a tail call!"); 9664 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9665 "LowerCall didn't emit the correct number of values!"); 9666 9667 // For a tail call, the return value is merely live-out and there aren't 9668 // any nodes in the DAG representing it. Return a special value to 9669 // indicate that a tail call has been emitted and no more Instructions 9670 // should be processed in the current block. 9671 if (CLI.IsTailCall) { 9672 CLI.DAG.setRoot(CLI.Chain); 9673 return std::make_pair(SDValue(), SDValue()); 9674 } 9675 9676 #ifndef NDEBUG 9677 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 9678 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 9679 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 9680 "LowerCall emitted a value with the wrong type!"); 9681 } 9682 #endif 9683 9684 SmallVector<SDValue, 4> ReturnValues; 9685 if (!CanLowerReturn) { 9686 // The instruction result is the result of loading from the 9687 // hidden sret parameter. 9688 SmallVector<EVT, 1> PVTs; 9689 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 9690 9691 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 9692 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 9693 EVT PtrVT = PVTs[0]; 9694 9695 unsigned NumValues = RetTys.size(); 9696 ReturnValues.resize(NumValues); 9697 SmallVector<SDValue, 4> Chains(NumValues); 9698 9699 // An aggregate return value cannot wrap around the address space, so 9700 // offsets to its parts don't wrap either. 9701 SDNodeFlags Flags; 9702 Flags.setNoUnsignedWrap(true); 9703 9704 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9705 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 9706 for (unsigned i = 0; i < NumValues; ++i) { 9707 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 9708 CLI.DAG.getConstant(Offsets[i], CLI.DL, 9709 PtrVT), Flags); 9710 SDValue L = CLI.DAG.getLoad( 9711 RetTys[i], CLI.DL, CLI.Chain, Add, 9712 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 9713 DemoteStackIdx, Offsets[i]), 9714 HiddenSRetAlign); 9715 ReturnValues[i] = L; 9716 Chains[i] = L.getValue(1); 9717 } 9718 9719 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 9720 } else { 9721 // Collect the legal value parts into potentially illegal values 9722 // that correspond to the original function's return values. 9723 Optional<ISD::NodeType> AssertOp; 9724 if (CLI.RetSExt) 9725 AssertOp = ISD::AssertSext; 9726 else if (CLI.RetZExt) 9727 AssertOp = ISD::AssertZext; 9728 unsigned CurReg = 0; 9729 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9730 EVT VT = RetTys[I]; 9731 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9732 CLI.CallConv, VT); 9733 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9734 CLI.CallConv, VT); 9735 9736 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 9737 NumRegs, RegisterVT, VT, nullptr, 9738 CLI.CallConv, AssertOp)); 9739 CurReg += NumRegs; 9740 } 9741 9742 // For a function returning void, there is no return value. We can't create 9743 // such a node, so we just return a null return value in that case. In 9744 // that case, nothing will actually look at the value. 9745 if (ReturnValues.empty()) 9746 return std::make_pair(SDValue(), CLI.Chain); 9747 } 9748 9749 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 9750 CLI.DAG.getVTList(RetTys), ReturnValues); 9751 return std::make_pair(Res, CLI.Chain); 9752 } 9753 9754 /// Places new result values for the node in Results (their number 9755 /// and types must exactly match those of the original return values of 9756 /// the node), or leaves Results empty, which indicates that the node is not 9757 /// to be custom lowered after all. 9758 void TargetLowering::LowerOperationWrapper(SDNode *N, 9759 SmallVectorImpl<SDValue> &Results, 9760 SelectionDAG &DAG) const { 9761 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 9762 9763 if (!Res.getNode()) 9764 return; 9765 9766 // If the original node has one result, take the return value from 9767 // LowerOperation as is. It might not be result number 0. 9768 if (N->getNumValues() == 1) { 9769 Results.push_back(Res); 9770 return; 9771 } 9772 9773 // If the original node has multiple results, then the return node should 9774 // have the same number of results. 9775 assert((N->getNumValues() == Res->getNumValues()) && 9776 "Lowering returned the wrong number of results!"); 9777 9778 // Places new result values base on N result number. 9779 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 9780 Results.push_back(Res.getValue(I)); 9781 } 9782 9783 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9784 llvm_unreachable("LowerOperation not implemented for this target!"); 9785 } 9786 9787 void 9788 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 9789 SDValue Op = getNonRegisterValue(V); 9790 assert((Op.getOpcode() != ISD::CopyFromReg || 9791 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 9792 "Copy from a reg to the same reg!"); 9793 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 9794 9795 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9796 // If this is an InlineAsm we have to match the registers required, not the 9797 // notional registers required by the type. 9798 9799 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 9800 None); // This is not an ABI copy. 9801 SDValue Chain = DAG.getEntryNode(); 9802 9803 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 9804 FuncInfo.PreferredExtendType.end()) 9805 ? ISD::ANY_EXTEND 9806 : FuncInfo.PreferredExtendType[V]; 9807 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 9808 PendingExports.push_back(Chain); 9809 } 9810 9811 #include "llvm/CodeGen/SelectionDAGISel.h" 9812 9813 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 9814 /// entry block, return true. This includes arguments used by switches, since 9815 /// the switch may expand into multiple basic blocks. 9816 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 9817 // With FastISel active, we may be splitting blocks, so force creation 9818 // of virtual registers for all non-dead arguments. 9819 if (FastISel) 9820 return A->use_empty(); 9821 9822 const BasicBlock &Entry = A->getParent()->front(); 9823 for (const User *U : A->users()) 9824 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 9825 return false; // Use not in entry block. 9826 9827 return true; 9828 } 9829 9830 using ArgCopyElisionMapTy = 9831 DenseMap<const Argument *, 9832 std::pair<const AllocaInst *, const StoreInst *>>; 9833 9834 /// Scan the entry block of the function in FuncInfo for arguments that look 9835 /// like copies into a local alloca. Record any copied arguments in 9836 /// ArgCopyElisionCandidates. 9837 static void 9838 findArgumentCopyElisionCandidates(const DataLayout &DL, 9839 FunctionLoweringInfo *FuncInfo, 9840 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 9841 // Record the state of every static alloca used in the entry block. Argument 9842 // allocas are all used in the entry block, so we need approximately as many 9843 // entries as we have arguments. 9844 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 9845 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 9846 unsigned NumArgs = FuncInfo->Fn->arg_size(); 9847 StaticAllocas.reserve(NumArgs * 2); 9848 9849 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 9850 if (!V) 9851 return nullptr; 9852 V = V->stripPointerCasts(); 9853 const auto *AI = dyn_cast<AllocaInst>(V); 9854 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 9855 return nullptr; 9856 auto Iter = StaticAllocas.insert({AI, Unknown}); 9857 return &Iter.first->second; 9858 }; 9859 9860 // Look for stores of arguments to static allocas. Look through bitcasts and 9861 // GEPs to handle type coercions, as long as the alloca is fully initialized 9862 // by the store. Any non-store use of an alloca escapes it and any subsequent 9863 // unanalyzed store might write it. 9864 // FIXME: Handle structs initialized with multiple stores. 9865 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 9866 // Look for stores, and handle non-store uses conservatively. 9867 const auto *SI = dyn_cast<StoreInst>(&I); 9868 if (!SI) { 9869 // We will look through cast uses, so ignore them completely. 9870 if (I.isCast()) 9871 continue; 9872 // Ignore debug info and pseudo op intrinsics, they don't escape or store 9873 // to allocas. 9874 if (I.isDebugOrPseudoInst()) 9875 continue; 9876 // This is an unknown instruction. Assume it escapes or writes to all 9877 // static alloca operands. 9878 for (const Use &U : I.operands()) { 9879 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 9880 *Info = StaticAllocaInfo::Clobbered; 9881 } 9882 continue; 9883 } 9884 9885 // If the stored value is a static alloca, mark it as escaped. 9886 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 9887 *Info = StaticAllocaInfo::Clobbered; 9888 9889 // Check if the destination is a static alloca. 9890 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 9891 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 9892 if (!Info) 9893 continue; 9894 const AllocaInst *AI = cast<AllocaInst>(Dst); 9895 9896 // Skip allocas that have been initialized or clobbered. 9897 if (*Info != StaticAllocaInfo::Unknown) 9898 continue; 9899 9900 // Check if the stored value is an argument, and that this store fully 9901 // initializes the alloca. 9902 // If the argument type has padding bits we can't directly forward a pointer 9903 // as the upper bits may contain garbage. 9904 // Don't elide copies from the same argument twice. 9905 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 9906 const auto *Arg = dyn_cast<Argument>(Val); 9907 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 9908 Arg->getType()->isEmptyTy() || 9909 DL.getTypeStoreSize(Arg->getType()) != 9910 DL.getTypeAllocSize(AI->getAllocatedType()) || 9911 !DL.typeSizeEqualsStoreSize(Arg->getType()) || 9912 ArgCopyElisionCandidates.count(Arg)) { 9913 *Info = StaticAllocaInfo::Clobbered; 9914 continue; 9915 } 9916 9917 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 9918 << '\n'); 9919 9920 // Mark this alloca and store for argument copy elision. 9921 *Info = StaticAllocaInfo::Elidable; 9922 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 9923 9924 // Stop scanning if we've seen all arguments. This will happen early in -O0 9925 // builds, which is useful, because -O0 builds have large entry blocks and 9926 // many allocas. 9927 if (ArgCopyElisionCandidates.size() == NumArgs) 9928 break; 9929 } 9930 } 9931 9932 /// Try to elide argument copies from memory into a local alloca. Succeeds if 9933 /// ArgVal is a load from a suitable fixed stack object. 9934 static void tryToElideArgumentCopy( 9935 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 9936 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 9937 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 9938 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 9939 SDValue ArgVal, bool &ArgHasUses) { 9940 // Check if this is a load from a fixed stack object. 9941 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 9942 if (!LNode) 9943 return; 9944 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 9945 if (!FINode) 9946 return; 9947 9948 // Check that the fixed stack object is the right size and alignment. 9949 // Look at the alignment that the user wrote on the alloca instead of looking 9950 // at the stack object. 9951 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 9952 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 9953 const AllocaInst *AI = ArgCopyIter->second.first; 9954 int FixedIndex = FINode->getIndex(); 9955 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 9956 int OldIndex = AllocaIndex; 9957 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 9958 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 9959 LLVM_DEBUG( 9960 dbgs() << " argument copy elision failed due to bad fixed stack " 9961 "object size\n"); 9962 return; 9963 } 9964 Align RequiredAlignment = AI->getAlign(); 9965 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 9966 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 9967 "greater than stack argument alignment (" 9968 << DebugStr(RequiredAlignment) << " vs " 9969 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 9970 return; 9971 } 9972 9973 // Perform the elision. Delete the old stack object and replace its only use 9974 // in the variable info map. Mark the stack object as mutable. 9975 LLVM_DEBUG({ 9976 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 9977 << " Replacing frame index " << OldIndex << " with " << FixedIndex 9978 << '\n'; 9979 }); 9980 MFI.RemoveStackObject(OldIndex); 9981 MFI.setIsImmutableObjectIndex(FixedIndex, false); 9982 AllocaIndex = FixedIndex; 9983 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 9984 Chains.push_back(ArgVal.getValue(1)); 9985 9986 // Avoid emitting code for the store implementing the copy. 9987 const StoreInst *SI = ArgCopyIter->second.second; 9988 ElidedArgCopyInstrs.insert(SI); 9989 9990 // Check for uses of the argument again so that we can avoid exporting ArgVal 9991 // if it is't used by anything other than the store. 9992 for (const Value *U : Arg.users()) { 9993 if (U != SI) { 9994 ArgHasUses = true; 9995 break; 9996 } 9997 } 9998 } 9999 10000 void SelectionDAGISel::LowerArguments(const Function &F) { 10001 SelectionDAG &DAG = SDB->DAG; 10002 SDLoc dl = SDB->getCurSDLoc(); 10003 const DataLayout &DL = DAG.getDataLayout(); 10004 SmallVector<ISD::InputArg, 16> Ins; 10005 10006 // In Naked functions we aren't going to save any registers. 10007 if (F.hasFnAttribute(Attribute::Naked)) 10008 return; 10009 10010 if (!FuncInfo->CanLowerReturn) { 10011 // Put in an sret pointer parameter before all the other parameters. 10012 SmallVector<EVT, 1> ValueVTs; 10013 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10014 F.getReturnType()->getPointerTo( 10015 DAG.getDataLayout().getAllocaAddrSpace()), 10016 ValueVTs); 10017 10018 // NOTE: Assuming that a pointer will never break down to more than one VT 10019 // or one register. 10020 ISD::ArgFlagsTy Flags; 10021 Flags.setSRet(); 10022 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 10023 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 10024 ISD::InputArg::NoArgIndex, 0); 10025 Ins.push_back(RetArg); 10026 } 10027 10028 // Look for stores of arguments to static allocas. Mark such arguments with a 10029 // flag to ask the target to give us the memory location of that argument if 10030 // available. 10031 ArgCopyElisionMapTy ArgCopyElisionCandidates; 10032 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 10033 ArgCopyElisionCandidates); 10034 10035 // Set up the incoming argument description vector. 10036 for (const Argument &Arg : F.args()) { 10037 unsigned ArgNo = Arg.getArgNo(); 10038 SmallVector<EVT, 4> ValueVTs; 10039 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10040 bool isArgValueUsed = !Arg.use_empty(); 10041 unsigned PartBase = 0; 10042 Type *FinalType = Arg.getType(); 10043 if (Arg.hasAttribute(Attribute::ByVal)) 10044 FinalType = Arg.getParamByValType(); 10045 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 10046 FinalType, F.getCallingConv(), F.isVarArg()); 10047 for (unsigned Value = 0, NumValues = ValueVTs.size(); 10048 Value != NumValues; ++Value) { 10049 EVT VT = ValueVTs[Value]; 10050 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 10051 ISD::ArgFlagsTy Flags; 10052 10053 10054 if (Arg.getType()->isPointerTy()) { 10055 Flags.setPointer(); 10056 Flags.setPointerAddrSpace( 10057 cast<PointerType>(Arg.getType())->getAddressSpace()); 10058 } 10059 if (Arg.hasAttribute(Attribute::ZExt)) 10060 Flags.setZExt(); 10061 if (Arg.hasAttribute(Attribute::SExt)) 10062 Flags.setSExt(); 10063 if (Arg.hasAttribute(Attribute::InReg)) { 10064 // If we are using vectorcall calling convention, a structure that is 10065 // passed InReg - is surely an HVA 10066 if (F.getCallingConv() == CallingConv::X86_VectorCall && 10067 isa<StructType>(Arg.getType())) { 10068 // The first value of a structure is marked 10069 if (0 == Value) 10070 Flags.setHvaStart(); 10071 Flags.setHva(); 10072 } 10073 // Set InReg Flag 10074 Flags.setInReg(); 10075 } 10076 if (Arg.hasAttribute(Attribute::StructRet)) 10077 Flags.setSRet(); 10078 if (Arg.hasAttribute(Attribute::SwiftSelf)) 10079 Flags.setSwiftSelf(); 10080 if (Arg.hasAttribute(Attribute::SwiftAsync)) 10081 Flags.setSwiftAsync(); 10082 if (Arg.hasAttribute(Attribute::SwiftError)) 10083 Flags.setSwiftError(); 10084 if (Arg.hasAttribute(Attribute::ByVal)) 10085 Flags.setByVal(); 10086 if (Arg.hasAttribute(Attribute::ByRef)) 10087 Flags.setByRef(); 10088 if (Arg.hasAttribute(Attribute::InAlloca)) { 10089 Flags.setInAlloca(); 10090 // Set the byval flag for CCAssignFn callbacks that don't know about 10091 // inalloca. This way we can know how many bytes we should've allocated 10092 // and how many bytes a callee cleanup function will pop. If we port 10093 // inalloca to more targets, we'll have to add custom inalloca handling 10094 // in the various CC lowering callbacks. 10095 Flags.setByVal(); 10096 } 10097 if (Arg.hasAttribute(Attribute::Preallocated)) { 10098 Flags.setPreallocated(); 10099 // Set the byval flag for CCAssignFn callbacks that don't know about 10100 // preallocated. This way we can know how many bytes we should've 10101 // allocated and how many bytes a callee cleanup function will pop. If 10102 // we port preallocated to more targets, we'll have to add custom 10103 // preallocated handling in the various CC lowering callbacks. 10104 Flags.setByVal(); 10105 } 10106 10107 // Certain targets (such as MIPS), may have a different ABI alignment 10108 // for a type depending on the context. Give the target a chance to 10109 // specify the alignment it wants. 10110 const Align OriginalAlignment( 10111 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 10112 Flags.setOrigAlign(OriginalAlignment); 10113 10114 Align MemAlign; 10115 Type *ArgMemTy = nullptr; 10116 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 10117 Flags.isByRef()) { 10118 if (!ArgMemTy) 10119 ArgMemTy = Arg.getPointeeInMemoryValueType(); 10120 10121 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 10122 10123 // For in-memory arguments, size and alignment should be passed from FE. 10124 // BE will guess if this info is not there but there are cases it cannot 10125 // get right. 10126 if (auto ParamAlign = Arg.getParamStackAlign()) 10127 MemAlign = *ParamAlign; 10128 else if ((ParamAlign = Arg.getParamAlign())) 10129 MemAlign = *ParamAlign; 10130 else 10131 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 10132 if (Flags.isByRef()) 10133 Flags.setByRefSize(MemSize); 10134 else 10135 Flags.setByValSize(MemSize); 10136 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 10137 MemAlign = *ParamAlign; 10138 } else { 10139 MemAlign = OriginalAlignment; 10140 } 10141 Flags.setMemAlign(MemAlign); 10142 10143 if (Arg.hasAttribute(Attribute::Nest)) 10144 Flags.setNest(); 10145 if (NeedsRegBlock) 10146 Flags.setInConsecutiveRegs(); 10147 if (ArgCopyElisionCandidates.count(&Arg)) 10148 Flags.setCopyElisionCandidate(); 10149 if (Arg.hasAttribute(Attribute::Returned)) 10150 Flags.setReturned(); 10151 10152 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 10153 *CurDAG->getContext(), F.getCallingConv(), VT); 10154 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 10155 *CurDAG->getContext(), F.getCallingConv(), VT); 10156 for (unsigned i = 0; i != NumRegs; ++i) { 10157 // For scalable vectors, use the minimum size; individual targets 10158 // are responsible for handling scalable vector arguments and 10159 // return values. 10160 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 10161 ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize()); 10162 if (NumRegs > 1 && i == 0) 10163 MyFlags.Flags.setSplit(); 10164 // if it isn't first piece, alignment must be 1 10165 else if (i > 0) { 10166 MyFlags.Flags.setOrigAlign(Align(1)); 10167 if (i == NumRegs - 1) 10168 MyFlags.Flags.setSplitEnd(); 10169 } 10170 Ins.push_back(MyFlags); 10171 } 10172 if (NeedsRegBlock && Value == NumValues - 1) 10173 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 10174 PartBase += VT.getStoreSize().getKnownMinSize(); 10175 } 10176 } 10177 10178 // Call the target to set up the argument values. 10179 SmallVector<SDValue, 8> InVals; 10180 SDValue NewRoot = TLI->LowerFormalArguments( 10181 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 10182 10183 // Verify that the target's LowerFormalArguments behaved as expected. 10184 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 10185 "LowerFormalArguments didn't return a valid chain!"); 10186 assert(InVals.size() == Ins.size() && 10187 "LowerFormalArguments didn't emit the correct number of values!"); 10188 LLVM_DEBUG({ 10189 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 10190 assert(InVals[i].getNode() && 10191 "LowerFormalArguments emitted a null value!"); 10192 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 10193 "LowerFormalArguments emitted a value with the wrong type!"); 10194 } 10195 }); 10196 10197 // Update the DAG with the new chain value resulting from argument lowering. 10198 DAG.setRoot(NewRoot); 10199 10200 // Set up the argument values. 10201 unsigned i = 0; 10202 if (!FuncInfo->CanLowerReturn) { 10203 // Create a virtual register for the sret pointer, and put in a copy 10204 // from the sret argument into it. 10205 SmallVector<EVT, 1> ValueVTs; 10206 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10207 F.getReturnType()->getPointerTo( 10208 DAG.getDataLayout().getAllocaAddrSpace()), 10209 ValueVTs); 10210 MVT VT = ValueVTs[0].getSimpleVT(); 10211 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 10212 Optional<ISD::NodeType> AssertOp = None; 10213 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 10214 nullptr, F.getCallingConv(), AssertOp); 10215 10216 MachineFunction& MF = SDB->DAG.getMachineFunction(); 10217 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 10218 Register SRetReg = 10219 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 10220 FuncInfo->DemoteRegister = SRetReg; 10221 NewRoot = 10222 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 10223 DAG.setRoot(NewRoot); 10224 10225 // i indexes lowered arguments. Bump it past the hidden sret argument. 10226 ++i; 10227 } 10228 10229 SmallVector<SDValue, 4> Chains; 10230 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 10231 for (const Argument &Arg : F.args()) { 10232 SmallVector<SDValue, 4> ArgValues; 10233 SmallVector<EVT, 4> ValueVTs; 10234 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10235 unsigned NumValues = ValueVTs.size(); 10236 if (NumValues == 0) 10237 continue; 10238 10239 bool ArgHasUses = !Arg.use_empty(); 10240 10241 // Elide the copying store if the target loaded this argument from a 10242 // suitable fixed stack object. 10243 if (Ins[i].Flags.isCopyElisionCandidate()) { 10244 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 10245 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 10246 InVals[i], ArgHasUses); 10247 } 10248 10249 // If this argument is unused then remember its value. It is used to generate 10250 // debugging information. 10251 bool isSwiftErrorArg = 10252 TLI->supportSwiftError() && 10253 Arg.hasAttribute(Attribute::SwiftError); 10254 if (!ArgHasUses && !isSwiftErrorArg) { 10255 SDB->setUnusedArgValue(&Arg, InVals[i]); 10256 10257 // Also remember any frame index for use in FastISel. 10258 if (FrameIndexSDNode *FI = 10259 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 10260 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10261 } 10262 10263 for (unsigned Val = 0; Val != NumValues; ++Val) { 10264 EVT VT = ValueVTs[Val]; 10265 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 10266 F.getCallingConv(), VT); 10267 unsigned NumParts = TLI->getNumRegistersForCallingConv( 10268 *CurDAG->getContext(), F.getCallingConv(), VT); 10269 10270 // Even an apparent 'unused' swifterror argument needs to be returned. So 10271 // we do generate a copy for it that can be used on return from the 10272 // function. 10273 if (ArgHasUses || isSwiftErrorArg) { 10274 Optional<ISD::NodeType> AssertOp; 10275 if (Arg.hasAttribute(Attribute::SExt)) 10276 AssertOp = ISD::AssertSext; 10277 else if (Arg.hasAttribute(Attribute::ZExt)) 10278 AssertOp = ISD::AssertZext; 10279 10280 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 10281 PartVT, VT, nullptr, 10282 F.getCallingConv(), AssertOp)); 10283 } 10284 10285 i += NumParts; 10286 } 10287 10288 // We don't need to do anything else for unused arguments. 10289 if (ArgValues.empty()) 10290 continue; 10291 10292 // Note down frame index. 10293 if (FrameIndexSDNode *FI = 10294 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 10295 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10296 10297 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 10298 SDB->getCurSDLoc()); 10299 10300 SDB->setValue(&Arg, Res); 10301 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 10302 // We want to associate the argument with the frame index, among 10303 // involved operands, that correspond to the lowest address. The 10304 // getCopyFromParts function, called earlier, is swapping the order of 10305 // the operands to BUILD_PAIR depending on endianness. The result of 10306 // that swapping is that the least significant bits of the argument will 10307 // be in the first operand of the BUILD_PAIR node, and the most 10308 // significant bits will be in the second operand. 10309 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 10310 if (LoadSDNode *LNode = 10311 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 10312 if (FrameIndexSDNode *FI = 10313 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 10314 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10315 } 10316 10317 // Analyses past this point are naive and don't expect an assertion. 10318 if (Res.getOpcode() == ISD::AssertZext) 10319 Res = Res.getOperand(0); 10320 10321 // Update the SwiftErrorVRegDefMap. 10322 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 10323 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10324 if (Register::isVirtualRegister(Reg)) 10325 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 10326 Reg); 10327 } 10328 10329 // If this argument is live outside of the entry block, insert a copy from 10330 // wherever we got it to the vreg that other BB's will reference it as. 10331 if (Res.getOpcode() == ISD::CopyFromReg) { 10332 // If we can, though, try to skip creating an unnecessary vreg. 10333 // FIXME: This isn't very clean... it would be nice to make this more 10334 // general. 10335 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10336 if (Register::isVirtualRegister(Reg)) { 10337 FuncInfo->ValueMap[&Arg] = Reg; 10338 continue; 10339 } 10340 } 10341 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 10342 FuncInfo->InitializeRegForValue(&Arg); 10343 SDB->CopyToExportRegsIfNeeded(&Arg); 10344 } 10345 } 10346 10347 if (!Chains.empty()) { 10348 Chains.push_back(NewRoot); 10349 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 10350 } 10351 10352 DAG.setRoot(NewRoot); 10353 10354 assert(i == InVals.size() && "Argument register count mismatch!"); 10355 10356 // If any argument copy elisions occurred and we have debug info, update the 10357 // stale frame indices used in the dbg.declare variable info table. 10358 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 10359 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 10360 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 10361 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 10362 if (I != ArgCopyElisionFrameIndexMap.end()) 10363 VI.Slot = I->second; 10364 } 10365 } 10366 10367 // Finally, if the target has anything special to do, allow it to do so. 10368 emitFunctionEntryCode(); 10369 } 10370 10371 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 10372 /// ensure constants are generated when needed. Remember the virtual registers 10373 /// that need to be added to the Machine PHI nodes as input. We cannot just 10374 /// directly add them, because expansion might result in multiple MBB's for one 10375 /// BB. As such, the start of the BB might correspond to a different MBB than 10376 /// the end. 10377 void 10378 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 10379 const Instruction *TI = LLVMBB->getTerminator(); 10380 10381 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 10382 10383 // Check PHI nodes in successors that expect a value to be available from this 10384 // block. 10385 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 10386 const BasicBlock *SuccBB = TI->getSuccessor(succ); 10387 if (!isa<PHINode>(SuccBB->begin())) continue; 10388 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 10389 10390 // If this terminator has multiple identical successors (common for 10391 // switches), only handle each succ once. 10392 if (!SuccsHandled.insert(SuccMBB).second) 10393 continue; 10394 10395 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 10396 10397 // At this point we know that there is a 1-1 correspondence between LLVM PHI 10398 // nodes and Machine PHI nodes, but the incoming operands have not been 10399 // emitted yet. 10400 for (const PHINode &PN : SuccBB->phis()) { 10401 // Ignore dead phi's. 10402 if (PN.use_empty()) 10403 continue; 10404 10405 // Skip empty types 10406 if (PN.getType()->isEmptyTy()) 10407 continue; 10408 10409 unsigned Reg; 10410 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 10411 10412 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 10413 unsigned &RegOut = ConstantsOut[C]; 10414 if (RegOut == 0) { 10415 RegOut = FuncInfo.CreateRegs(C); 10416 CopyValueToVirtualRegister(C, RegOut); 10417 } 10418 Reg = RegOut; 10419 } else { 10420 DenseMap<const Value *, Register>::iterator I = 10421 FuncInfo.ValueMap.find(PHIOp); 10422 if (I != FuncInfo.ValueMap.end()) 10423 Reg = I->second; 10424 else { 10425 assert(isa<AllocaInst>(PHIOp) && 10426 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 10427 "Didn't codegen value into a register!??"); 10428 Reg = FuncInfo.CreateRegs(PHIOp); 10429 CopyValueToVirtualRegister(PHIOp, Reg); 10430 } 10431 } 10432 10433 // Remember that this register needs to added to the machine PHI node as 10434 // the input for this MBB. 10435 SmallVector<EVT, 4> ValueVTs; 10436 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10437 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 10438 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 10439 EVT VT = ValueVTs[vti]; 10440 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 10441 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 10442 FuncInfo.PHINodesToUpdate.push_back( 10443 std::make_pair(&*MBBI++, Reg + i)); 10444 Reg += NumRegisters; 10445 } 10446 } 10447 } 10448 10449 ConstantsOut.clear(); 10450 } 10451 10452 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 10453 /// is 0. 10454 MachineBasicBlock * 10455 SelectionDAGBuilder::StackProtectorDescriptor:: 10456 AddSuccessorMBB(const BasicBlock *BB, 10457 MachineBasicBlock *ParentMBB, 10458 bool IsLikely, 10459 MachineBasicBlock *SuccMBB) { 10460 // If SuccBB has not been created yet, create it. 10461 if (!SuccMBB) { 10462 MachineFunction *MF = ParentMBB->getParent(); 10463 MachineFunction::iterator BBI(ParentMBB); 10464 SuccMBB = MF->CreateMachineBasicBlock(BB); 10465 MF->insert(++BBI, SuccMBB); 10466 } 10467 // Add it as a successor of ParentMBB. 10468 ParentMBB->addSuccessor( 10469 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 10470 return SuccMBB; 10471 } 10472 10473 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 10474 MachineFunction::iterator I(MBB); 10475 if (++I == FuncInfo.MF->end()) 10476 return nullptr; 10477 return &*I; 10478 } 10479 10480 /// During lowering new call nodes can be created (such as memset, etc.). 10481 /// Those will become new roots of the current DAG, but complications arise 10482 /// when they are tail calls. In such cases, the call lowering will update 10483 /// the root, but the builder still needs to know that a tail call has been 10484 /// lowered in order to avoid generating an additional return. 10485 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 10486 // If the node is null, we do have a tail call. 10487 if (MaybeTC.getNode() != nullptr) 10488 DAG.setRoot(MaybeTC); 10489 else 10490 HasTailCall = true; 10491 } 10492 10493 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10494 MachineBasicBlock *SwitchMBB, 10495 MachineBasicBlock *DefaultMBB) { 10496 MachineFunction *CurMF = FuncInfo.MF; 10497 MachineBasicBlock *NextMBB = nullptr; 10498 MachineFunction::iterator BBI(W.MBB); 10499 if (++BBI != FuncInfo.MF->end()) 10500 NextMBB = &*BBI; 10501 10502 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10503 10504 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10505 10506 if (Size == 2 && W.MBB == SwitchMBB) { 10507 // If any two of the cases has the same destination, and if one value 10508 // is the same as the other, but has one bit unset that the other has set, 10509 // use bit manipulation to do two compares at once. For example: 10510 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10511 // TODO: This could be extended to merge any 2 cases in switches with 3 10512 // cases. 10513 // TODO: Handle cases where W.CaseBB != SwitchBB. 10514 CaseCluster &Small = *W.FirstCluster; 10515 CaseCluster &Big = *W.LastCluster; 10516 10517 if (Small.Low == Small.High && Big.Low == Big.High && 10518 Small.MBB == Big.MBB) { 10519 const APInt &SmallValue = Small.Low->getValue(); 10520 const APInt &BigValue = Big.Low->getValue(); 10521 10522 // Check that there is only one bit different. 10523 APInt CommonBit = BigValue ^ SmallValue; 10524 if (CommonBit.isPowerOf2()) { 10525 SDValue CondLHS = getValue(Cond); 10526 EVT VT = CondLHS.getValueType(); 10527 SDLoc DL = getCurSDLoc(); 10528 10529 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10530 DAG.getConstant(CommonBit, DL, VT)); 10531 SDValue Cond = DAG.getSetCC( 10532 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10533 ISD::SETEQ); 10534 10535 // Update successor info. 10536 // Both Small and Big will jump to Small.BB, so we sum up the 10537 // probabilities. 10538 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10539 if (BPI) 10540 addSuccessorWithProb( 10541 SwitchMBB, DefaultMBB, 10542 // The default destination is the first successor in IR. 10543 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10544 else 10545 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10546 10547 // Insert the true branch. 10548 SDValue BrCond = 10549 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10550 DAG.getBasicBlock(Small.MBB)); 10551 // Insert the false branch. 10552 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10553 DAG.getBasicBlock(DefaultMBB)); 10554 10555 DAG.setRoot(BrCond); 10556 return; 10557 } 10558 } 10559 } 10560 10561 if (TM.getOptLevel() != CodeGenOpt::None) { 10562 // Here, we order cases by probability so the most likely case will be 10563 // checked first. However, two clusters can have the same probability in 10564 // which case their relative ordering is non-deterministic. So we use Low 10565 // as a tie-breaker as clusters are guaranteed to never overlap. 10566 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10567 [](const CaseCluster &a, const CaseCluster &b) { 10568 return a.Prob != b.Prob ? 10569 a.Prob > b.Prob : 10570 a.Low->getValue().slt(b.Low->getValue()); 10571 }); 10572 10573 // Rearrange the case blocks so that the last one falls through if possible 10574 // without changing the order of probabilities. 10575 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10576 --I; 10577 if (I->Prob > W.LastCluster->Prob) 10578 break; 10579 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10580 std::swap(*I, *W.LastCluster); 10581 break; 10582 } 10583 } 10584 } 10585 10586 // Compute total probability. 10587 BranchProbability DefaultProb = W.DefaultProb; 10588 BranchProbability UnhandledProbs = DefaultProb; 10589 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10590 UnhandledProbs += I->Prob; 10591 10592 MachineBasicBlock *CurMBB = W.MBB; 10593 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10594 bool FallthroughUnreachable = false; 10595 MachineBasicBlock *Fallthrough; 10596 if (I == W.LastCluster) { 10597 // For the last cluster, fall through to the default destination. 10598 Fallthrough = DefaultMBB; 10599 FallthroughUnreachable = isa<UnreachableInst>( 10600 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10601 } else { 10602 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10603 CurMF->insert(BBI, Fallthrough); 10604 // Put Cond in a virtual register to make it available from the new blocks. 10605 ExportFromCurrentBlock(Cond); 10606 } 10607 UnhandledProbs -= I->Prob; 10608 10609 switch (I->Kind) { 10610 case CC_JumpTable: { 10611 // FIXME: Optimize away range check based on pivot comparisons. 10612 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 10613 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 10614 10615 // The jump block hasn't been inserted yet; insert it here. 10616 MachineBasicBlock *JumpMBB = JT->MBB; 10617 CurMF->insert(BBI, JumpMBB); 10618 10619 auto JumpProb = I->Prob; 10620 auto FallthroughProb = UnhandledProbs; 10621 10622 // If the default statement is a target of the jump table, we evenly 10623 // distribute the default probability to successors of CurMBB. Also 10624 // update the probability on the edge from JumpMBB to Fallthrough. 10625 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10626 SE = JumpMBB->succ_end(); 10627 SI != SE; ++SI) { 10628 if (*SI == DefaultMBB) { 10629 JumpProb += DefaultProb / 2; 10630 FallthroughProb -= DefaultProb / 2; 10631 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10632 JumpMBB->normalizeSuccProbs(); 10633 break; 10634 } 10635 } 10636 10637 if (FallthroughUnreachable) { 10638 // Skip the range check if the fallthrough block is unreachable. 10639 JTH->OmitRangeCheck = true; 10640 } 10641 10642 if (!JTH->OmitRangeCheck) 10643 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10644 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10645 CurMBB->normalizeSuccProbs(); 10646 10647 // The jump table header will be inserted in our current block, do the 10648 // range check, and fall through to our fallthrough block. 10649 JTH->HeaderBB = CurMBB; 10650 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10651 10652 // If we're in the right place, emit the jump table header right now. 10653 if (CurMBB == SwitchMBB) { 10654 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10655 JTH->Emitted = true; 10656 } 10657 break; 10658 } 10659 case CC_BitTests: { 10660 // FIXME: Optimize away range check based on pivot comparisons. 10661 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 10662 10663 // The bit test blocks haven't been inserted yet; insert them here. 10664 for (BitTestCase &BTC : BTB->Cases) 10665 CurMF->insert(BBI, BTC.ThisBB); 10666 10667 // Fill in fields of the BitTestBlock. 10668 BTB->Parent = CurMBB; 10669 BTB->Default = Fallthrough; 10670 10671 BTB->DefaultProb = UnhandledProbs; 10672 // If the cases in bit test don't form a contiguous range, we evenly 10673 // distribute the probability on the edge to Fallthrough to two 10674 // successors of CurMBB. 10675 if (!BTB->ContiguousRange) { 10676 BTB->Prob += DefaultProb / 2; 10677 BTB->DefaultProb -= DefaultProb / 2; 10678 } 10679 10680 if (FallthroughUnreachable) { 10681 // Skip the range check if the fallthrough block is unreachable. 10682 BTB->OmitRangeCheck = true; 10683 } 10684 10685 // If we're in the right place, emit the bit test header right now. 10686 if (CurMBB == SwitchMBB) { 10687 visitBitTestHeader(*BTB, SwitchMBB); 10688 BTB->Emitted = true; 10689 } 10690 break; 10691 } 10692 case CC_Range: { 10693 const Value *RHS, *LHS, *MHS; 10694 ISD::CondCode CC; 10695 if (I->Low == I->High) { 10696 // Check Cond == I->Low. 10697 CC = ISD::SETEQ; 10698 LHS = Cond; 10699 RHS=I->Low; 10700 MHS = nullptr; 10701 } else { 10702 // Check I->Low <= Cond <= I->High. 10703 CC = ISD::SETLE; 10704 LHS = I->Low; 10705 MHS = Cond; 10706 RHS = I->High; 10707 } 10708 10709 // If Fallthrough is unreachable, fold away the comparison. 10710 if (FallthroughUnreachable) 10711 CC = ISD::SETTRUE; 10712 10713 // The false probability is the sum of all unhandled cases. 10714 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10715 getCurSDLoc(), I->Prob, UnhandledProbs); 10716 10717 if (CurMBB == SwitchMBB) 10718 visitSwitchCase(CB, SwitchMBB); 10719 else 10720 SL->SwitchCases.push_back(CB); 10721 10722 break; 10723 } 10724 } 10725 CurMBB = Fallthrough; 10726 } 10727 } 10728 10729 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10730 CaseClusterIt First, 10731 CaseClusterIt Last) { 10732 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10733 if (X.Prob != CC.Prob) 10734 return X.Prob > CC.Prob; 10735 10736 // Ties are broken by comparing the case value. 10737 return X.Low->getValue().slt(CC.Low->getValue()); 10738 }); 10739 } 10740 10741 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10742 const SwitchWorkListItem &W, 10743 Value *Cond, 10744 MachineBasicBlock *SwitchMBB) { 10745 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10746 "Clusters not sorted?"); 10747 10748 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10749 10750 // Balance the tree based on branch probabilities to create a near-optimal (in 10751 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10752 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10753 CaseClusterIt LastLeft = W.FirstCluster; 10754 CaseClusterIt FirstRight = W.LastCluster; 10755 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10756 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10757 10758 // Move LastLeft and FirstRight towards each other from opposite directions to 10759 // find a partitioning of the clusters which balances the probability on both 10760 // sides. If LeftProb and RightProb are equal, alternate which side is 10761 // taken to ensure 0-probability nodes are distributed evenly. 10762 unsigned I = 0; 10763 while (LastLeft + 1 < FirstRight) { 10764 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10765 LeftProb += (++LastLeft)->Prob; 10766 else 10767 RightProb += (--FirstRight)->Prob; 10768 I++; 10769 } 10770 10771 while (true) { 10772 // Our binary search tree differs from a typical BST in that ours can have up 10773 // to three values in each leaf. The pivot selection above doesn't take that 10774 // into account, which means the tree might require more nodes and be less 10775 // efficient. We compensate for this here. 10776 10777 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10778 unsigned NumRight = W.LastCluster - FirstRight + 1; 10779 10780 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10781 // If one side has less than 3 clusters, and the other has more than 3, 10782 // consider taking a cluster from the other side. 10783 10784 if (NumLeft < NumRight) { 10785 // Consider moving the first cluster on the right to the left side. 10786 CaseCluster &CC = *FirstRight; 10787 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10788 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10789 if (LeftSideRank <= RightSideRank) { 10790 // Moving the cluster to the left does not demote it. 10791 ++LastLeft; 10792 ++FirstRight; 10793 continue; 10794 } 10795 } else { 10796 assert(NumRight < NumLeft); 10797 // Consider moving the last element on the left to the right side. 10798 CaseCluster &CC = *LastLeft; 10799 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10800 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10801 if (RightSideRank <= LeftSideRank) { 10802 // Moving the cluster to the right does not demot it. 10803 --LastLeft; 10804 --FirstRight; 10805 continue; 10806 } 10807 } 10808 } 10809 break; 10810 } 10811 10812 assert(LastLeft + 1 == FirstRight); 10813 assert(LastLeft >= W.FirstCluster); 10814 assert(FirstRight <= W.LastCluster); 10815 10816 // Use the first element on the right as pivot since we will make less-than 10817 // comparisons against it. 10818 CaseClusterIt PivotCluster = FirstRight; 10819 assert(PivotCluster > W.FirstCluster); 10820 assert(PivotCluster <= W.LastCluster); 10821 10822 CaseClusterIt FirstLeft = W.FirstCluster; 10823 CaseClusterIt LastRight = W.LastCluster; 10824 10825 const ConstantInt *Pivot = PivotCluster->Low; 10826 10827 // New blocks will be inserted immediately after the current one. 10828 MachineFunction::iterator BBI(W.MBB); 10829 ++BBI; 10830 10831 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10832 // we can branch to its destination directly if it's squeezed exactly in 10833 // between the known lower bound and Pivot - 1. 10834 MachineBasicBlock *LeftMBB; 10835 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10836 FirstLeft->Low == W.GE && 10837 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10838 LeftMBB = FirstLeft->MBB; 10839 } else { 10840 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10841 FuncInfo.MF->insert(BBI, LeftMBB); 10842 WorkList.push_back( 10843 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10844 // Put Cond in a virtual register to make it available from the new blocks. 10845 ExportFromCurrentBlock(Cond); 10846 } 10847 10848 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10849 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10850 // directly if RHS.High equals the current upper bound. 10851 MachineBasicBlock *RightMBB; 10852 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10853 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10854 RightMBB = FirstRight->MBB; 10855 } else { 10856 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10857 FuncInfo.MF->insert(BBI, RightMBB); 10858 WorkList.push_back( 10859 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10860 // Put Cond in a virtual register to make it available from the new blocks. 10861 ExportFromCurrentBlock(Cond); 10862 } 10863 10864 // Create the CaseBlock record that will be used to lower the branch. 10865 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10866 getCurSDLoc(), LeftProb, RightProb); 10867 10868 if (W.MBB == SwitchMBB) 10869 visitSwitchCase(CB, SwitchMBB); 10870 else 10871 SL->SwitchCases.push_back(CB); 10872 } 10873 10874 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10875 // from the swith statement. 10876 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10877 BranchProbability PeeledCaseProb) { 10878 if (PeeledCaseProb == BranchProbability::getOne()) 10879 return BranchProbability::getZero(); 10880 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10881 10882 uint32_t Numerator = CaseProb.getNumerator(); 10883 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10884 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10885 } 10886 10887 // Try to peel the top probability case if it exceeds the threshold. 10888 // Return current MachineBasicBlock for the switch statement if the peeling 10889 // does not occur. 10890 // If the peeling is performed, return the newly created MachineBasicBlock 10891 // for the peeled switch statement. Also update Clusters to remove the peeled 10892 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10893 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10894 const SwitchInst &SI, CaseClusterVector &Clusters, 10895 BranchProbability &PeeledCaseProb) { 10896 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10897 // Don't perform if there is only one cluster or optimizing for size. 10898 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10899 TM.getOptLevel() == CodeGenOpt::None || 10900 SwitchMBB->getParent()->getFunction().hasMinSize()) 10901 return SwitchMBB; 10902 10903 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10904 unsigned PeeledCaseIndex = 0; 10905 bool SwitchPeeled = false; 10906 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10907 CaseCluster &CC = Clusters[Index]; 10908 if (CC.Prob < TopCaseProb) 10909 continue; 10910 TopCaseProb = CC.Prob; 10911 PeeledCaseIndex = Index; 10912 SwitchPeeled = true; 10913 } 10914 if (!SwitchPeeled) 10915 return SwitchMBB; 10916 10917 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10918 << TopCaseProb << "\n"); 10919 10920 // Record the MBB for the peeled switch statement. 10921 MachineFunction::iterator BBI(SwitchMBB); 10922 ++BBI; 10923 MachineBasicBlock *PeeledSwitchMBB = 10924 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10925 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10926 10927 ExportFromCurrentBlock(SI.getCondition()); 10928 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10929 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10930 nullptr, nullptr, TopCaseProb.getCompl()}; 10931 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10932 10933 Clusters.erase(PeeledCaseIt); 10934 for (CaseCluster &CC : Clusters) { 10935 LLVM_DEBUG( 10936 dbgs() << "Scale the probablity for one cluster, before scaling: " 10937 << CC.Prob << "\n"); 10938 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10939 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10940 } 10941 PeeledCaseProb = TopCaseProb; 10942 return PeeledSwitchMBB; 10943 } 10944 10945 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10946 // Extract cases from the switch. 10947 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10948 CaseClusterVector Clusters; 10949 Clusters.reserve(SI.getNumCases()); 10950 for (auto I : SI.cases()) { 10951 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10952 const ConstantInt *CaseVal = I.getCaseValue(); 10953 BranchProbability Prob = 10954 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10955 : BranchProbability(1, SI.getNumCases() + 1); 10956 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10957 } 10958 10959 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10960 10961 // Cluster adjacent cases with the same destination. We do this at all 10962 // optimization levels because it's cheap to do and will make codegen faster 10963 // if there are many clusters. 10964 sortAndRangeify(Clusters); 10965 10966 // The branch probablity of the peeled case. 10967 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10968 MachineBasicBlock *PeeledSwitchMBB = 10969 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10970 10971 // If there is only the default destination, jump there directly. 10972 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10973 if (Clusters.empty()) { 10974 assert(PeeledSwitchMBB == SwitchMBB); 10975 SwitchMBB->addSuccessor(DefaultMBB); 10976 if (DefaultMBB != NextBlock(SwitchMBB)) { 10977 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10978 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10979 } 10980 return; 10981 } 10982 10983 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 10984 SL->findBitTestClusters(Clusters, &SI); 10985 10986 LLVM_DEBUG({ 10987 dbgs() << "Case clusters: "; 10988 for (const CaseCluster &C : Clusters) { 10989 if (C.Kind == CC_JumpTable) 10990 dbgs() << "JT:"; 10991 if (C.Kind == CC_BitTests) 10992 dbgs() << "BT:"; 10993 10994 C.Low->getValue().print(dbgs(), true); 10995 if (C.Low != C.High) { 10996 dbgs() << '-'; 10997 C.High->getValue().print(dbgs(), true); 10998 } 10999 dbgs() << ' '; 11000 } 11001 dbgs() << '\n'; 11002 }); 11003 11004 assert(!Clusters.empty()); 11005 SwitchWorkList WorkList; 11006 CaseClusterIt First = Clusters.begin(); 11007 CaseClusterIt Last = Clusters.end() - 1; 11008 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 11009 // Scale the branchprobability for DefaultMBB if the peel occurs and 11010 // DefaultMBB is not replaced. 11011 if (PeeledCaseProb != BranchProbability::getZero() && 11012 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 11013 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 11014 WorkList.push_back( 11015 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 11016 11017 while (!WorkList.empty()) { 11018 SwitchWorkListItem W = WorkList.pop_back_val(); 11019 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 11020 11021 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 11022 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 11023 // For optimized builds, lower large range as a balanced binary tree. 11024 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 11025 continue; 11026 } 11027 11028 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 11029 } 11030 } 11031 11032 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 11033 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11034 auto DL = getCurSDLoc(); 11035 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11036 EVT OpVT = 11037 TLI.getTypeToTransformTo(*DAG.getContext(), ResultVT.getScalarType()); 11038 SDValue Step = DAG.getConstant(1, DL, OpVT); 11039 setValue(&I, DAG.getStepVector(DL, ResultVT, Step)); 11040 } 11041 11042 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 11043 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11044 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11045 11046 SDLoc DL = getCurSDLoc(); 11047 SDValue V = getValue(I.getOperand(0)); 11048 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 11049 11050 if (VT.isScalableVector()) { 11051 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 11052 return; 11053 } 11054 11055 // Use VECTOR_SHUFFLE for the fixed-length vector 11056 // to maintain existing behavior. 11057 SmallVector<int, 8> Mask; 11058 unsigned NumElts = VT.getVectorMinNumElements(); 11059 for (unsigned i = 0; i != NumElts; ++i) 11060 Mask.push_back(NumElts - 1 - i); 11061 11062 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 11063 } 11064 11065 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 11066 SmallVector<EVT, 4> ValueVTs; 11067 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 11068 ValueVTs); 11069 unsigned NumValues = ValueVTs.size(); 11070 if (NumValues == 0) return; 11071 11072 SmallVector<SDValue, 4> Values(NumValues); 11073 SDValue Op = getValue(I.getOperand(0)); 11074 11075 for (unsigned i = 0; i != NumValues; ++i) 11076 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 11077 SDValue(Op.getNode(), Op.getResNo() + i)); 11078 11079 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 11080 DAG.getVTList(ValueVTs), Values)); 11081 } 11082 11083 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 11084 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11085 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11086 11087 SDLoc DL = getCurSDLoc(); 11088 SDValue V1 = getValue(I.getOperand(0)); 11089 SDValue V2 = getValue(I.getOperand(1)); 11090 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 11091 11092 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 11093 if (VT.isScalableVector()) { 11094 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 11095 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 11096 DAG.getConstant(Imm, DL, IdxVT))); 11097 return; 11098 } 11099 11100 unsigned NumElts = VT.getVectorNumElements(); 11101 11102 if ((-Imm > NumElts) || (Imm >= NumElts)) { 11103 // Result is undefined if immediate is out-of-bounds. 11104 setValue(&I, DAG.getUNDEF(VT)); 11105 return; 11106 } 11107 11108 uint64_t Idx = (NumElts + Imm) % NumElts; 11109 11110 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 11111 SmallVector<int, 8> Mask; 11112 for (unsigned i = 0; i < NumElts; ++i) 11113 Mask.push_back(Idx + i); 11114 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 11115 } 11116