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 // Bitcast Val back the original type and extract the corresponding 440 // vector we want. 441 unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits(); 442 EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(), 443 ValueVT.getVectorElementType(), Elts); 444 Val = DAG.getBitcast(WiderVecType, Val); 445 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 446 DAG.getVectorIdxConstant(0, DL)); 447 } 448 449 diagnosePossiblyInvalidConstraint( 450 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 451 return DAG.getUNDEF(ValueVT); 452 } 453 454 // Handle cases such as i8 -> <1 x i1> 455 EVT ValueSVT = ValueVT.getVectorElementType(); 456 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 457 if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits()) 458 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 459 else 460 Val = ValueVT.isFloatingPoint() 461 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 462 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 463 } 464 465 return DAG.getBuildVector(ValueVT, DL, Val); 466 } 467 468 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 469 SDValue Val, SDValue *Parts, unsigned NumParts, 470 MVT PartVT, const Value *V, 471 Optional<CallingConv::ID> CallConv); 472 473 /// getCopyToParts - Create a series of nodes that contain the specified value 474 /// split into legal parts. If the parts contain more bits than Val, then, for 475 /// integers, ExtendKind can be used to specify how to generate the extra bits. 476 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 477 SDValue *Parts, unsigned NumParts, MVT PartVT, 478 const Value *V, 479 Optional<CallingConv::ID> CallConv = None, 480 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 481 // Let the target split the parts if it wants to 482 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 483 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 484 CallConv)) 485 return; 486 EVT ValueVT = Val.getValueType(); 487 488 // Handle the vector case separately. 489 if (ValueVT.isVector()) 490 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 491 CallConv); 492 493 unsigned PartBits = PartVT.getSizeInBits(); 494 unsigned OrigNumParts = NumParts; 495 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 496 "Copying to an illegal type!"); 497 498 if (NumParts == 0) 499 return; 500 501 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 502 EVT PartEVT = PartVT; 503 if (PartEVT == ValueVT) { 504 assert(NumParts == 1 && "No-op copy with multiple parts!"); 505 Parts[0] = Val; 506 return; 507 } 508 509 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 510 // If the parts cover more bits than the value has, promote the value. 511 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 512 assert(NumParts == 1 && "Do not know what to promote to!"); 513 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 514 } else { 515 if (ValueVT.isFloatingPoint()) { 516 // FP values need to be bitcast, then extended if they are being put 517 // into a larger container. 518 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 519 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 520 } 521 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 522 ValueVT.isInteger() && 523 "Unknown mismatch!"); 524 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 525 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 526 if (PartVT == MVT::x86mmx) 527 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 528 } 529 } else if (PartBits == ValueVT.getSizeInBits()) { 530 // Different types of the same size. 531 assert(NumParts == 1 && PartEVT != ValueVT); 532 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 533 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 534 // If the parts cover less bits than value has, truncate the value. 535 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 536 ValueVT.isInteger() && 537 "Unknown mismatch!"); 538 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 539 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 540 if (PartVT == MVT::x86mmx) 541 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 542 } 543 544 // The value may have changed - recompute ValueVT. 545 ValueVT = Val.getValueType(); 546 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 547 "Failed to tile the value with PartVT!"); 548 549 if (NumParts == 1) { 550 if (PartEVT != ValueVT) { 551 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 552 "scalar-to-vector conversion failed"); 553 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 554 } 555 556 Parts[0] = Val; 557 return; 558 } 559 560 // Expand the value into multiple parts. 561 if (NumParts & (NumParts - 1)) { 562 // The number of parts is not a power of 2. Split off and copy the tail. 563 assert(PartVT.isInteger() && ValueVT.isInteger() && 564 "Do not know what to expand to!"); 565 unsigned RoundParts = 1 << Log2_32(NumParts); 566 unsigned RoundBits = RoundParts * PartBits; 567 unsigned OddParts = NumParts - RoundParts; 568 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 569 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false)); 570 571 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 572 CallConv); 573 574 if (DAG.getDataLayout().isBigEndian()) 575 // The odd parts were reversed by getCopyToParts - unreverse them. 576 std::reverse(Parts + RoundParts, Parts + NumParts); 577 578 NumParts = RoundParts; 579 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 580 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 581 } 582 583 // The number of parts is a power of 2. Repeatedly bisect the value using 584 // EXTRACT_ELEMENT. 585 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 586 EVT::getIntegerVT(*DAG.getContext(), 587 ValueVT.getSizeInBits()), 588 Val); 589 590 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 591 for (unsigned i = 0; i < NumParts; i += StepSize) { 592 unsigned ThisBits = StepSize * PartBits / 2; 593 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 594 SDValue &Part0 = Parts[i]; 595 SDValue &Part1 = Parts[i+StepSize/2]; 596 597 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 598 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 599 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 600 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 601 602 if (ThisBits == PartBits && ThisVT != PartVT) { 603 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 604 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 605 } 606 } 607 } 608 609 if (DAG.getDataLayout().isBigEndian()) 610 std::reverse(Parts, Parts + OrigNumParts); 611 } 612 613 static SDValue widenVectorToPartType(SelectionDAG &DAG, 614 SDValue Val, const SDLoc &DL, EVT PartVT) { 615 if (!PartVT.isFixedLengthVector()) 616 return SDValue(); 617 618 EVT ValueVT = Val.getValueType(); 619 unsigned PartNumElts = PartVT.getVectorNumElements(); 620 unsigned ValueNumElts = ValueVT.getVectorNumElements(); 621 if (PartNumElts > ValueNumElts && 622 PartVT.getVectorElementType() == ValueVT.getVectorElementType()) { 623 EVT ElementVT = PartVT.getVectorElementType(); 624 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 625 // undef elements. 626 SmallVector<SDValue, 16> Ops; 627 DAG.ExtractVectorElements(Val, Ops); 628 SDValue EltUndef = DAG.getUNDEF(ElementVT); 629 for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i) 630 Ops.push_back(EltUndef); 631 632 // FIXME: Use CONCAT for 2x -> 4x. 633 return DAG.getBuildVector(PartVT, DL, Ops); 634 } 635 636 return SDValue(); 637 } 638 639 /// getCopyToPartsVector - Create a series of nodes that contain the specified 640 /// value split into legal parts. 641 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 642 SDValue Val, SDValue *Parts, unsigned NumParts, 643 MVT PartVT, const Value *V, 644 Optional<CallingConv::ID> CallConv) { 645 EVT ValueVT = Val.getValueType(); 646 assert(ValueVT.isVector() && "Not a vector"); 647 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 648 const bool IsABIRegCopy = CallConv.hasValue(); 649 650 if (NumParts == 1) { 651 EVT PartEVT = PartVT; 652 if (PartEVT == ValueVT) { 653 // Nothing to do. 654 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 655 // Bitconvert vector->vector case. 656 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 657 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 658 Val = Widened; 659 } else if (PartVT.isVector() && 660 PartEVT.getVectorElementType().bitsGE( 661 ValueVT.getVectorElementType()) && 662 PartEVT.getVectorElementCount() == 663 ValueVT.getVectorElementCount()) { 664 665 // Promoted vector extract 666 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 667 } else { 668 if (ValueVT.getVectorElementCount().isScalar()) { 669 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 670 DAG.getVectorIdxConstant(0, DL)); 671 } else { 672 uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 673 assert(PartVT.getFixedSizeInBits() > ValueSize && 674 "lossy conversion of vector to scalar type"); 675 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 676 Val = DAG.getBitcast(IntermediateType, Val); 677 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 678 } 679 } 680 681 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 682 Parts[0] = Val; 683 return; 684 } 685 686 // Handle a multi-element vector. 687 EVT IntermediateVT; 688 MVT RegisterVT; 689 unsigned NumIntermediates; 690 unsigned NumRegs; 691 if (IsABIRegCopy) { 692 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 693 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 694 NumIntermediates, RegisterVT); 695 } else { 696 NumRegs = 697 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 698 NumIntermediates, RegisterVT); 699 } 700 701 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 702 NumParts = NumRegs; // Silence a compiler warning. 703 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 704 705 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 706 "Mixing scalable and fixed vectors when copying in parts"); 707 708 Optional<ElementCount> DestEltCnt; 709 710 if (IntermediateVT.isVector()) 711 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 712 else 713 DestEltCnt = ElementCount::getFixed(NumIntermediates); 714 715 EVT BuiltVectorTy = EVT::getVectorVT( 716 *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt.getValue()); 717 if (ValueVT != BuiltVectorTy) { 718 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) 719 Val = Widened; 720 721 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 722 } 723 724 // Split the vector into intermediate operands. 725 SmallVector<SDValue, 8> Ops(NumIntermediates); 726 for (unsigned i = 0; i != NumIntermediates; ++i) { 727 if (IntermediateVT.isVector()) { 728 // This does something sensible for scalable vectors - see the 729 // definition of EXTRACT_SUBVECTOR for further details. 730 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 731 Ops[i] = 732 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 733 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 734 } else { 735 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 736 DAG.getVectorIdxConstant(i, DL)); 737 } 738 } 739 740 // Split the intermediate operands into legal parts. 741 if (NumParts == NumIntermediates) { 742 // If the register was not expanded, promote or copy the value, 743 // as appropriate. 744 for (unsigned i = 0; i != NumParts; ++i) 745 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 746 } else if (NumParts > 0) { 747 // If the intermediate type was expanded, split each the value into 748 // legal parts. 749 assert(NumIntermediates != 0 && "division by zero"); 750 assert(NumParts % NumIntermediates == 0 && 751 "Must expand into a divisible number of parts!"); 752 unsigned Factor = NumParts / NumIntermediates; 753 for (unsigned i = 0; i != NumIntermediates; ++i) 754 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 755 CallConv); 756 } 757 } 758 759 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 760 EVT valuevt, Optional<CallingConv::ID> CC) 761 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 762 RegCount(1, regs.size()), CallConv(CC) {} 763 764 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 765 const DataLayout &DL, unsigned Reg, Type *Ty, 766 Optional<CallingConv::ID> CC) { 767 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 768 769 CallConv = CC; 770 771 for (EVT ValueVT : ValueVTs) { 772 unsigned NumRegs = 773 isABIMangled() 774 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) 775 : TLI.getNumRegisters(Context, ValueVT); 776 MVT RegisterVT = 777 isABIMangled() 778 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) 779 : TLI.getRegisterType(Context, ValueVT); 780 for (unsigned i = 0; i != NumRegs; ++i) 781 Regs.push_back(Reg + i); 782 RegVTs.push_back(RegisterVT); 783 RegCount.push_back(NumRegs); 784 Reg += NumRegs; 785 } 786 } 787 788 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 789 FunctionLoweringInfo &FuncInfo, 790 const SDLoc &dl, SDValue &Chain, 791 SDValue *Flag, const Value *V) const { 792 // A Value with type {} or [0 x %t] needs no registers. 793 if (ValueVTs.empty()) 794 return SDValue(); 795 796 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 797 798 // Assemble the legal parts into the final values. 799 SmallVector<SDValue, 4> Values(ValueVTs.size()); 800 SmallVector<SDValue, 8> Parts; 801 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 802 // Copy the legal parts from the registers. 803 EVT ValueVT = ValueVTs[Value]; 804 unsigned NumRegs = RegCount[Value]; 805 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 806 *DAG.getContext(), 807 CallConv.getValue(), RegVTs[Value]) 808 : RegVTs[Value]; 809 810 Parts.resize(NumRegs); 811 for (unsigned i = 0; i != NumRegs; ++i) { 812 SDValue P; 813 if (!Flag) { 814 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 815 } else { 816 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 817 *Flag = P.getValue(2); 818 } 819 820 Chain = P.getValue(1); 821 Parts[i] = P; 822 823 // If the source register was virtual and if we know something about it, 824 // add an assert node. 825 if (!Register::isVirtualRegister(Regs[Part + i]) || 826 !RegisterVT.isInteger()) 827 continue; 828 829 const FunctionLoweringInfo::LiveOutInfo *LOI = 830 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 831 if (!LOI) 832 continue; 833 834 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 835 unsigned NumSignBits = LOI->NumSignBits; 836 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 837 838 if (NumZeroBits == RegSize) { 839 // The current value is a zero. 840 // Explicitly express that as it would be easier for 841 // optimizations to kick in. 842 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 843 continue; 844 } 845 846 // FIXME: We capture more information than the dag can represent. For 847 // now, just use the tightest assertzext/assertsext possible. 848 bool isSExt; 849 EVT FromVT(MVT::Other); 850 if (NumZeroBits) { 851 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 852 isSExt = false; 853 } else if (NumSignBits > 1) { 854 FromVT = 855 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 856 isSExt = true; 857 } else { 858 continue; 859 } 860 // Add an assertion node. 861 assert(FromVT != MVT::Other); 862 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 863 RegisterVT, P, DAG.getValueType(FromVT)); 864 } 865 866 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 867 RegisterVT, ValueVT, V, CallConv); 868 Part += NumRegs; 869 Parts.clear(); 870 } 871 872 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 873 } 874 875 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 876 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 877 const Value *V, 878 ISD::NodeType PreferredExtendType) const { 879 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 880 ISD::NodeType ExtendKind = PreferredExtendType; 881 882 // Get the list of the values's legal parts. 883 unsigned NumRegs = Regs.size(); 884 SmallVector<SDValue, 8> Parts(NumRegs); 885 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 886 unsigned NumParts = RegCount[Value]; 887 888 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 889 *DAG.getContext(), 890 CallConv.getValue(), RegVTs[Value]) 891 : RegVTs[Value]; 892 893 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 894 ExtendKind = ISD::ZERO_EXTEND; 895 896 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 897 NumParts, RegisterVT, V, CallConv, ExtendKind); 898 Part += NumParts; 899 } 900 901 // Copy the parts into the registers. 902 SmallVector<SDValue, 8> Chains(NumRegs); 903 for (unsigned i = 0; i != NumRegs; ++i) { 904 SDValue Part; 905 if (!Flag) { 906 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 907 } else { 908 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 909 *Flag = Part.getValue(1); 910 } 911 912 Chains[i] = Part.getValue(0); 913 } 914 915 if (NumRegs == 1 || Flag) 916 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 917 // flagged to it. That is the CopyToReg nodes and the user are considered 918 // a single scheduling unit. If we create a TokenFactor and return it as 919 // chain, then the TokenFactor is both a predecessor (operand) of the 920 // user as well as a successor (the TF operands are flagged to the user). 921 // c1, f1 = CopyToReg 922 // c2, f2 = CopyToReg 923 // c3 = TokenFactor c1, c2 924 // ... 925 // = op c3, ..., f2 926 Chain = Chains[NumRegs-1]; 927 else 928 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 929 } 930 931 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 932 unsigned MatchingIdx, const SDLoc &dl, 933 SelectionDAG &DAG, 934 std::vector<SDValue> &Ops) const { 935 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 936 937 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 938 if (HasMatching) 939 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 940 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 941 // Put the register class of the virtual registers in the flag word. That 942 // way, later passes can recompute register class constraints for inline 943 // assembly as well as normal instructions. 944 // Don't do this for tied operands that can use the regclass information 945 // from the def. 946 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 947 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 948 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 949 } 950 951 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 952 Ops.push_back(Res); 953 954 if (Code == InlineAsm::Kind_Clobber) { 955 // Clobbers should always have a 1:1 mapping with registers, and may 956 // reference registers that have illegal (e.g. vector) types. Hence, we 957 // shouldn't try to apply any sort of splitting logic to them. 958 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 959 "No 1:1 mapping from clobbers to regs?"); 960 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 961 (void)SP; 962 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 963 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 964 assert( 965 (Regs[I] != SP || 966 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 967 "If we clobbered the stack pointer, MFI should know about it."); 968 } 969 return; 970 } 971 972 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 973 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 974 MVT RegisterVT = RegVTs[Value]; 975 for (unsigned i = 0; i != NumRegs; ++i) { 976 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 977 unsigned TheReg = Regs[Reg++]; 978 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 979 } 980 } 981 } 982 983 SmallVector<std::pair<unsigned, TypeSize>, 4> 984 RegsForValue::getRegsAndSizes() const { 985 SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec; 986 unsigned I = 0; 987 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 988 unsigned RegCount = std::get<0>(CountAndVT); 989 MVT RegisterVT = std::get<1>(CountAndVT); 990 TypeSize RegisterSize = RegisterVT.getSizeInBits(); 991 for (unsigned E = I + RegCount; I != E; ++I) 992 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 993 } 994 return OutVec; 995 } 996 997 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 998 const TargetLibraryInfo *li) { 999 AA = aa; 1000 GFI = gfi; 1001 LibInfo = li; 1002 DL = &DAG.getDataLayout(); 1003 Context = DAG.getContext(); 1004 LPadToCallSiteMap.clear(); 1005 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1006 } 1007 1008 void SelectionDAGBuilder::clear() { 1009 NodeMap.clear(); 1010 UnusedArgNodeMap.clear(); 1011 PendingLoads.clear(); 1012 PendingExports.clear(); 1013 PendingConstrainedFP.clear(); 1014 PendingConstrainedFPStrict.clear(); 1015 CurInst = nullptr; 1016 HasTailCall = false; 1017 SDNodeOrder = LowestSDNodeOrder; 1018 StatepointLowering.clear(); 1019 } 1020 1021 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1022 DanglingDebugInfoMap.clear(); 1023 } 1024 1025 // Update DAG root to include dependencies on Pending chains. 1026 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1027 SDValue Root = DAG.getRoot(); 1028 1029 if (Pending.empty()) 1030 return Root; 1031 1032 // Add current root to PendingChains, unless we already indirectly 1033 // depend on it. 1034 if (Root.getOpcode() != ISD::EntryToken) { 1035 unsigned i = 0, e = Pending.size(); 1036 for (; i != e; ++i) { 1037 assert(Pending[i].getNode()->getNumOperands() > 1); 1038 if (Pending[i].getNode()->getOperand(0) == Root) 1039 break; // Don't add the root if we already indirectly depend on it. 1040 } 1041 1042 if (i == e) 1043 Pending.push_back(Root); 1044 } 1045 1046 if (Pending.size() == 1) 1047 Root = Pending[0]; 1048 else 1049 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1050 1051 DAG.setRoot(Root); 1052 Pending.clear(); 1053 return Root; 1054 } 1055 1056 SDValue SelectionDAGBuilder::getMemoryRoot() { 1057 return updateRoot(PendingLoads); 1058 } 1059 1060 SDValue SelectionDAGBuilder::getRoot() { 1061 // Chain up all pending constrained intrinsics together with all 1062 // pending loads, by simply appending them to PendingLoads and 1063 // then calling getMemoryRoot(). 1064 PendingLoads.reserve(PendingLoads.size() + 1065 PendingConstrainedFP.size() + 1066 PendingConstrainedFPStrict.size()); 1067 PendingLoads.append(PendingConstrainedFP.begin(), 1068 PendingConstrainedFP.end()); 1069 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1070 PendingConstrainedFPStrict.end()); 1071 PendingConstrainedFP.clear(); 1072 PendingConstrainedFPStrict.clear(); 1073 return getMemoryRoot(); 1074 } 1075 1076 SDValue SelectionDAGBuilder::getControlRoot() { 1077 // We need to emit pending fpexcept.strict constrained intrinsics, 1078 // so append them to the PendingExports list. 1079 PendingExports.append(PendingConstrainedFPStrict.begin(), 1080 PendingConstrainedFPStrict.end()); 1081 PendingConstrainedFPStrict.clear(); 1082 return updateRoot(PendingExports); 1083 } 1084 1085 void SelectionDAGBuilder::visit(const Instruction &I) { 1086 // Set up outgoing PHI node register values before emitting the terminator. 1087 if (I.isTerminator()) { 1088 HandlePHINodesInSuccessorBlocks(I.getParent()); 1089 } 1090 1091 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1092 if (!isa<DbgInfoIntrinsic>(I)) 1093 ++SDNodeOrder; 1094 1095 CurInst = &I; 1096 1097 visit(I.getOpcode(), I); 1098 1099 if (!I.isTerminator() && !HasTailCall && 1100 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1101 CopyToExportRegsIfNeeded(&I); 1102 1103 CurInst = nullptr; 1104 } 1105 1106 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1107 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1108 } 1109 1110 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1111 // Note: this doesn't use InstVisitor, because it has to work with 1112 // ConstantExpr's in addition to instructions. 1113 switch (Opcode) { 1114 default: llvm_unreachable("Unknown instruction type encountered!"); 1115 // Build the switch statement using the Instruction.def file. 1116 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1117 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1118 #include "llvm/IR/Instruction.def" 1119 } 1120 } 1121 1122 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI, 1123 DebugLoc DL, unsigned Order) { 1124 // We treat variadic dbg_values differently at this stage. 1125 if (DI->hasArgList()) { 1126 // For variadic dbg_values we will now insert an undef. 1127 // FIXME: We can potentially recover these! 1128 SmallVector<SDDbgOperand, 2> Locs; 1129 for (const Value *V : DI->getValues()) { 1130 auto Undef = UndefValue::get(V->getType()); 1131 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1132 } 1133 SDDbgValue *SDV = DAG.getDbgValueList( 1134 DI->getVariable(), DI->getExpression(), Locs, {}, 1135 /*IsIndirect=*/false, DL, Order, /*IsVariadic=*/true); 1136 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1137 } else { 1138 // TODO: Dangling debug info will eventually either be resolved or produce 1139 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1140 // between the original dbg.value location and its resolved DBG_VALUE, 1141 // which we should ideally fill with an extra Undef DBG_VALUE. 1142 assert(DI->getNumVariableLocationOps() == 1 && 1143 "DbgValueInst without an ArgList should have a single location " 1144 "operand."); 1145 DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, DL, Order); 1146 } 1147 } 1148 1149 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1150 const DIExpression *Expr) { 1151 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1152 const DbgValueInst *DI = DDI.getDI(); 1153 DIVariable *DanglingVariable = DI->getVariable(); 1154 DIExpression *DanglingExpr = DI->getExpression(); 1155 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1156 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1157 return true; 1158 } 1159 return false; 1160 }; 1161 1162 for (auto &DDIMI : DanglingDebugInfoMap) { 1163 DanglingDebugInfoVector &DDIV = DDIMI.second; 1164 1165 // If debug info is to be dropped, run it through final checks to see 1166 // whether it can be salvaged. 1167 for (auto &DDI : DDIV) 1168 if (isMatchingDbgValue(DDI)) 1169 salvageUnresolvedDbgValue(DDI); 1170 1171 erase_if(DDIV, isMatchingDbgValue); 1172 } 1173 } 1174 1175 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1176 // generate the debug data structures now that we've seen its definition. 1177 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1178 SDValue Val) { 1179 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1180 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1181 return; 1182 1183 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1184 for (auto &DDI : DDIV) { 1185 const DbgValueInst *DI = DDI.getDI(); 1186 assert(!DI->hasArgList() && "Not implemented for variadic dbg_values"); 1187 assert(DI && "Ill-formed DanglingDebugInfo"); 1188 DebugLoc dl = DDI.getdl(); 1189 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1190 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1191 DILocalVariable *Variable = DI->getVariable(); 1192 DIExpression *Expr = DI->getExpression(); 1193 assert(Variable->isValidLocationForIntrinsic(dl) && 1194 "Expected inlined-at fields to agree"); 1195 SDDbgValue *SDV; 1196 if (Val.getNode()) { 1197 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1198 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1199 // we couldn't resolve it directly when examining the DbgValue intrinsic 1200 // in the first place we should not be more successful here). Unless we 1201 // have some test case that prove this to be correct we should avoid 1202 // calling EmitFuncArgumentDbgValue here. 1203 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1204 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1205 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1206 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1207 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1208 // inserted after the definition of Val when emitting the instructions 1209 // after ISel. An alternative could be to teach 1210 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1211 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1212 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1213 << ValSDNodeOrder << "\n"); 1214 SDV = getDbgValue(Val, Variable, Expr, dl, 1215 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1216 DAG.AddDbgValue(SDV, false); 1217 } else 1218 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1219 << "in EmitFuncArgumentDbgValue\n"); 1220 } else { 1221 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1222 auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType()); 1223 auto SDV = 1224 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); 1225 DAG.AddDbgValue(SDV, false); 1226 } 1227 } 1228 DDIV.clear(); 1229 } 1230 1231 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1232 assert(!DDI.getDI()->hasArgList() && 1233 "Not implemented for variadic dbg_values"); 1234 Value *V = DDI.getDI()->getValue(0); 1235 DILocalVariable *Var = DDI.getDI()->getVariable(); 1236 DIExpression *Expr = DDI.getDI()->getExpression(); 1237 DebugLoc DL = DDI.getdl(); 1238 DebugLoc InstDL = DDI.getDI()->getDebugLoc(); 1239 unsigned SDOrder = DDI.getSDNodeOrder(); 1240 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1241 // that DW_OP_stack_value is desired. 1242 assert(isa<DbgValueInst>(DDI.getDI())); 1243 bool StackValue = true; 1244 1245 // Can this Value can be encoded without any further work? 1246 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, /*IsVariadic=*/false)) 1247 return; 1248 1249 // Attempt to salvage back through as many instructions as possible. Bail if 1250 // a non-instruction is seen, such as a constant expression or global 1251 // variable. FIXME: Further work could recover those too. 1252 while (isa<Instruction>(V)) { 1253 Instruction &VAsInst = *cast<Instruction>(V); 1254 DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue); 1255 1256 // If we cannot salvage any further, and haven't yet found a suitable debug 1257 // expression, bail out. 1258 if (!NewExpr) 1259 break; 1260 1261 // New value and expr now represent this debuginfo. 1262 V = VAsInst.getOperand(0); 1263 Expr = NewExpr; 1264 1265 // Some kind of simplification occurred: check whether the operand of the 1266 // salvaged debug expression can be encoded in this DAG. 1267 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, 1268 /*IsVariadic=*/false)) { 1269 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n " 1270 << DDI.getDI() << "\nBy stripping back to:\n " << V); 1271 return; 1272 } 1273 } 1274 1275 // This was the final opportunity to salvage this debug information, and it 1276 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1277 // any earlier variable location. 1278 auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType()); 1279 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1280 DAG.AddDbgValue(SDV, false); 1281 1282 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI() 1283 << "\n"); 1284 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0) 1285 << "\n"); 1286 } 1287 1288 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1289 DILocalVariable *Var, 1290 DIExpression *Expr, DebugLoc dl, 1291 DebugLoc InstDL, unsigned Order, 1292 bool IsVariadic) { 1293 if (Values.empty()) 1294 return true; 1295 SDDbgValue::LocOpVector LocationOps; 1296 SDDbgValue::SDNodeVector Dependencies; 1297 for (const Value *V : Values) { 1298 // Constant value. 1299 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1300 isa<ConstantPointerNull>(V)) { 1301 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1302 continue; 1303 } 1304 1305 // If the Value is a frame index, we can create a FrameIndex debug value 1306 // without relying on the DAG at all. 1307 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1308 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1309 if (SI != FuncInfo.StaticAllocaMap.end()) { 1310 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1311 continue; 1312 } 1313 } 1314 1315 // Do not use getValue() in here; we don't want to generate code at 1316 // this point if it hasn't been done yet. 1317 SDValue N = NodeMap[V]; 1318 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1319 N = UnusedArgNodeMap[V]; 1320 if (N.getNode()) { 1321 // Only emit func arg dbg value for non-variadic dbg.values for now. 1322 if (!IsVariadic && EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N)) 1323 return true; 1324 Dependencies.push_back(N.getNode()); 1325 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1326 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1327 // describe stack slot locations. 1328 // 1329 // Consider "int x = 0; int *px = &x;". There are two kinds of 1330 // interesting debug values here after optimization: 1331 // 1332 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1333 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1334 // 1335 // Both describe the direct values of their associated variables. 1336 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1337 continue; 1338 } 1339 LocationOps.emplace_back( 1340 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1341 continue; 1342 } 1343 1344 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1345 // Special rules apply for the first dbg.values of parameter variables in a 1346 // function. Identify them by the fact they reference Argument Values, that 1347 // they're parameters, and they are parameters of the current function. We 1348 // need to let them dangle until they get an SDNode. 1349 bool IsParamOfFunc = 1350 isa<Argument>(V) && Var->isParameter() && !InstDL.getInlinedAt(); 1351 if (IsParamOfFunc) 1352 return false; 1353 1354 // The value is not used in this block yet (or it would have an SDNode). 1355 // We still want the value to appear for the user if possible -- if it has 1356 // an associated VReg, we can refer to that instead. 1357 auto VMI = FuncInfo.ValueMap.find(V); 1358 if (VMI != FuncInfo.ValueMap.end()) { 1359 unsigned Reg = VMI->second; 1360 // If this is a PHI node, it may be split up into several MI PHI nodes 1361 // (in FunctionLoweringInfo::set). 1362 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1363 V->getType(), None); 1364 if (RFV.occupiesMultipleRegs()) { 1365 // FIXME: We could potentially support variadic dbg_values here. 1366 if (IsVariadic) 1367 return false; 1368 unsigned Offset = 0; 1369 unsigned BitsToDescribe = 0; 1370 if (auto VarSize = Var->getSizeInBits()) 1371 BitsToDescribe = *VarSize; 1372 if (auto Fragment = Expr->getFragmentInfo()) 1373 BitsToDescribe = Fragment->SizeInBits; 1374 for (auto RegAndSize : RFV.getRegsAndSizes()) { 1375 // Bail out if all bits are described already. 1376 if (Offset >= BitsToDescribe) 1377 break; 1378 // TODO: handle scalable vectors. 1379 unsigned RegisterSize = RegAndSize.second; 1380 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1381 ? BitsToDescribe - Offset 1382 : RegisterSize; 1383 auto FragmentExpr = DIExpression::createFragmentExpression( 1384 Expr, Offset, FragmentSize); 1385 if (!FragmentExpr) 1386 continue; 1387 SDDbgValue *SDV = DAG.getVRegDbgValue( 1388 Var, *FragmentExpr, RegAndSize.first, false, dl, SDNodeOrder); 1389 DAG.AddDbgValue(SDV, false); 1390 Offset += RegisterSize; 1391 } 1392 return true; 1393 } 1394 // We can use simple vreg locations for variadic dbg_values as well. 1395 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1396 continue; 1397 } 1398 // We failed to create a SDDbgOperand for V. 1399 return false; 1400 } 1401 1402 // We have created a SDDbgOperand for each Value in Values. 1403 // Should use Order instead of SDNodeOrder? 1404 assert(!LocationOps.empty()); 1405 SDDbgValue *SDV = 1406 DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1407 /*IsIndirect=*/false, dl, SDNodeOrder, IsVariadic); 1408 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1409 return true; 1410 } 1411 1412 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1413 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1414 for (auto &Pair : DanglingDebugInfoMap) 1415 for (auto &DDI : Pair.second) 1416 salvageUnresolvedDbgValue(DDI); 1417 clearDanglingDebugInfo(); 1418 } 1419 1420 /// getCopyFromRegs - If there was virtual register allocated for the value V 1421 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1422 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1423 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1424 SDValue Result; 1425 1426 if (It != FuncInfo.ValueMap.end()) { 1427 Register InReg = It->second; 1428 1429 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1430 DAG.getDataLayout(), InReg, Ty, 1431 None); // This is not an ABI copy. 1432 SDValue Chain = DAG.getEntryNode(); 1433 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1434 V); 1435 resolveDanglingDebugInfo(V, Result); 1436 } 1437 1438 return Result; 1439 } 1440 1441 /// getValue - Return an SDValue for the given Value. 1442 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1443 // If we already have an SDValue for this value, use it. It's important 1444 // to do this first, so that we don't create a CopyFromReg if we already 1445 // have a regular SDValue. 1446 SDValue &N = NodeMap[V]; 1447 if (N.getNode()) return N; 1448 1449 // If there's a virtual register allocated and initialized for this 1450 // value, use it. 1451 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1452 return copyFromReg; 1453 1454 // Otherwise create a new SDValue and remember it. 1455 SDValue Val = getValueImpl(V); 1456 NodeMap[V] = Val; 1457 resolveDanglingDebugInfo(V, Val); 1458 return Val; 1459 } 1460 1461 /// getNonRegisterValue - Return an SDValue for the given Value, but 1462 /// don't look in FuncInfo.ValueMap for a virtual register. 1463 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1464 // If we already have an SDValue for this value, use it. 1465 SDValue &N = NodeMap[V]; 1466 if (N.getNode()) { 1467 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1468 // Remove the debug location from the node as the node is about to be used 1469 // in a location which may differ from the original debug location. This 1470 // is relevant to Constant and ConstantFP nodes because they can appear 1471 // as constant expressions inside PHI nodes. 1472 N->setDebugLoc(DebugLoc()); 1473 } 1474 return N; 1475 } 1476 1477 // Otherwise create a new SDValue and remember it. 1478 SDValue Val = getValueImpl(V); 1479 NodeMap[V] = Val; 1480 resolveDanglingDebugInfo(V, Val); 1481 return Val; 1482 } 1483 1484 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1485 /// Create an SDValue for the given value. 1486 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1487 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1488 1489 if (const Constant *C = dyn_cast<Constant>(V)) { 1490 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1491 1492 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1493 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1494 1495 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1496 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1497 1498 if (isa<ConstantPointerNull>(C)) { 1499 unsigned AS = V->getType()->getPointerAddressSpace(); 1500 return DAG.getConstant(0, getCurSDLoc(), 1501 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1502 } 1503 1504 if (match(C, m_VScale(DAG.getDataLayout()))) 1505 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1506 1507 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1508 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1509 1510 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1511 return DAG.getUNDEF(VT); 1512 1513 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1514 visit(CE->getOpcode(), *CE); 1515 SDValue N1 = NodeMap[V]; 1516 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1517 return N1; 1518 } 1519 1520 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1521 SmallVector<SDValue, 4> Constants; 1522 for (const Use &U : C->operands()) { 1523 SDNode *Val = getValue(U).getNode(); 1524 // If the operand is an empty aggregate, there are no values. 1525 if (!Val) continue; 1526 // Add each leaf value from the operand to the Constants list 1527 // to form a flattened list of all the values. 1528 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1529 Constants.push_back(SDValue(Val, i)); 1530 } 1531 1532 return DAG.getMergeValues(Constants, getCurSDLoc()); 1533 } 1534 1535 if (const ConstantDataSequential *CDS = 1536 dyn_cast<ConstantDataSequential>(C)) { 1537 SmallVector<SDValue, 4> Ops; 1538 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1539 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1540 // Add each leaf value from the operand to the Constants list 1541 // to form a flattened list of all the values. 1542 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1543 Ops.push_back(SDValue(Val, i)); 1544 } 1545 1546 if (isa<ArrayType>(CDS->getType())) 1547 return DAG.getMergeValues(Ops, getCurSDLoc()); 1548 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1549 } 1550 1551 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1552 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1553 "Unknown struct or array constant!"); 1554 1555 SmallVector<EVT, 4> ValueVTs; 1556 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1557 unsigned NumElts = ValueVTs.size(); 1558 if (NumElts == 0) 1559 return SDValue(); // empty struct 1560 SmallVector<SDValue, 4> Constants(NumElts); 1561 for (unsigned i = 0; i != NumElts; ++i) { 1562 EVT EltVT = ValueVTs[i]; 1563 if (isa<UndefValue>(C)) 1564 Constants[i] = DAG.getUNDEF(EltVT); 1565 else if (EltVT.isFloatingPoint()) 1566 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1567 else 1568 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1569 } 1570 1571 return DAG.getMergeValues(Constants, getCurSDLoc()); 1572 } 1573 1574 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1575 return DAG.getBlockAddress(BA, VT); 1576 1577 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1578 return getValue(Equiv->getGlobalValue()); 1579 1580 VectorType *VecTy = cast<VectorType>(V->getType()); 1581 1582 // Now that we know the number and type of the elements, get that number of 1583 // elements into the Ops array based on what kind of constant it is. 1584 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1585 SmallVector<SDValue, 16> Ops; 1586 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1587 for (unsigned i = 0; i != NumElements; ++i) 1588 Ops.push_back(getValue(CV->getOperand(i))); 1589 1590 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1591 } else if (isa<ConstantAggregateZero>(C)) { 1592 EVT EltVT = 1593 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1594 1595 SDValue Op; 1596 if (EltVT.isFloatingPoint()) 1597 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1598 else 1599 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1600 1601 if (isa<ScalableVectorType>(VecTy)) 1602 return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op); 1603 else { 1604 SmallVector<SDValue, 16> Ops; 1605 Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op); 1606 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1607 } 1608 } 1609 llvm_unreachable("Unknown vector constant"); 1610 } 1611 1612 // If this is a static alloca, generate it as the frameindex instead of 1613 // computation. 1614 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1615 DenseMap<const AllocaInst*, int>::iterator SI = 1616 FuncInfo.StaticAllocaMap.find(AI); 1617 if (SI != FuncInfo.StaticAllocaMap.end()) 1618 return DAG.getFrameIndex(SI->second, 1619 TLI.getFrameIndexTy(DAG.getDataLayout())); 1620 } 1621 1622 // If this is an instruction which fast-isel has deferred, select it now. 1623 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1624 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1625 1626 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1627 Inst->getType(), None); 1628 SDValue Chain = DAG.getEntryNode(); 1629 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1630 } 1631 1632 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) { 1633 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1634 } 1635 llvm_unreachable("Can't get register for value!"); 1636 } 1637 1638 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1639 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1640 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1641 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1642 bool IsSEH = isAsynchronousEHPersonality(Pers); 1643 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1644 if (!IsSEH) 1645 CatchPadMBB->setIsEHScopeEntry(); 1646 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1647 if (IsMSVCCXX || IsCoreCLR) 1648 CatchPadMBB->setIsEHFuncletEntry(); 1649 } 1650 1651 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1652 // Update machine-CFG edge. 1653 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1654 FuncInfo.MBB->addSuccessor(TargetMBB); 1655 TargetMBB->setIsEHCatchretTarget(true); 1656 DAG.getMachineFunction().setHasEHCatchret(true); 1657 1658 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1659 bool IsSEH = isAsynchronousEHPersonality(Pers); 1660 if (IsSEH) { 1661 // If this is not a fall-through branch or optimizations are switched off, 1662 // emit the branch. 1663 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1664 TM.getOptLevel() == CodeGenOpt::None) 1665 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1666 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1667 return; 1668 } 1669 1670 // Figure out the funclet membership for the catchret's successor. 1671 // This will be used by the FuncletLayout pass to determine how to order the 1672 // BB's. 1673 // A 'catchret' returns to the outer scope's color. 1674 Value *ParentPad = I.getCatchSwitchParentPad(); 1675 const BasicBlock *SuccessorColor; 1676 if (isa<ConstantTokenNone>(ParentPad)) 1677 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1678 else 1679 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1680 assert(SuccessorColor && "No parent funclet for catchret!"); 1681 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1682 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1683 1684 // Create the terminator node. 1685 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1686 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1687 DAG.getBasicBlock(SuccessorColorMBB)); 1688 DAG.setRoot(Ret); 1689 } 1690 1691 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1692 // Don't emit any special code for the cleanuppad instruction. It just marks 1693 // the start of an EH scope/funclet. 1694 FuncInfo.MBB->setIsEHScopeEntry(); 1695 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1696 if (Pers != EHPersonality::Wasm_CXX) { 1697 FuncInfo.MBB->setIsEHFuncletEntry(); 1698 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1699 } 1700 } 1701 1702 // In wasm EH, even though a catchpad may not catch an exception if a tag does 1703 // not match, it is OK to add only the first unwind destination catchpad to the 1704 // successors, because there will be at least one invoke instruction within the 1705 // catch scope that points to the next unwind destination, if one exists, so 1706 // CFGSort cannot mess up with BB sorting order. 1707 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 1708 // call within them, and catchpads only consisting of 'catch (...)' have a 1709 // '__cxa_end_catch' call within them, both of which generate invokes in case 1710 // the next unwind destination exists, i.e., the next unwind destination is not 1711 // the caller.) 1712 // 1713 // Having at most one EH pad successor is also simpler and helps later 1714 // transformations. 1715 // 1716 // For example, 1717 // current: 1718 // invoke void @foo to ... unwind label %catch.dispatch 1719 // catch.dispatch: 1720 // %0 = catchswitch within ... [label %catch.start] unwind label %next 1721 // catch.start: 1722 // ... 1723 // ... in this BB or some other child BB dominated by this BB there will be an 1724 // invoke that points to 'next' BB as an unwind destination 1725 // 1726 // next: ; We don't need to add this to 'current' BB's successor 1727 // ... 1728 static void findWasmUnwindDestinations( 1729 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1730 BranchProbability Prob, 1731 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1732 &UnwindDests) { 1733 while (EHPadBB) { 1734 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1735 if (isa<CleanupPadInst>(Pad)) { 1736 // Stop on cleanup pads. 1737 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1738 UnwindDests.back().first->setIsEHScopeEntry(); 1739 break; 1740 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1741 // Add the catchpad handlers to the possible destinations. We don't 1742 // continue to the unwind destination of the catchswitch for wasm. 1743 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1744 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1745 UnwindDests.back().first->setIsEHScopeEntry(); 1746 } 1747 break; 1748 } else { 1749 continue; 1750 } 1751 } 1752 } 1753 1754 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1755 /// many places it could ultimately go. In the IR, we have a single unwind 1756 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1757 /// This function skips over imaginary basic blocks that hold catchswitch 1758 /// instructions, and finds all the "real" machine 1759 /// basic block destinations. As those destinations may not be successors of 1760 /// EHPadBB, here we also calculate the edge probability to those destinations. 1761 /// The passed-in Prob is the edge probability to EHPadBB. 1762 static void findUnwindDestinations( 1763 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1764 BranchProbability Prob, 1765 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1766 &UnwindDests) { 1767 EHPersonality Personality = 1768 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1769 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1770 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1771 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1772 bool IsSEH = isAsynchronousEHPersonality(Personality); 1773 1774 if (IsWasmCXX) { 1775 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1776 assert(UnwindDests.size() <= 1 && 1777 "There should be at most one unwind destination for wasm"); 1778 return; 1779 } 1780 1781 while (EHPadBB) { 1782 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1783 BasicBlock *NewEHPadBB = nullptr; 1784 if (isa<LandingPadInst>(Pad)) { 1785 // Stop on landingpads. They are not funclets. 1786 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1787 break; 1788 } else if (isa<CleanupPadInst>(Pad)) { 1789 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1790 // personalities. 1791 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1792 UnwindDests.back().first->setIsEHScopeEntry(); 1793 UnwindDests.back().first->setIsEHFuncletEntry(); 1794 break; 1795 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1796 // Add the catchpad handlers to the possible destinations. 1797 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1798 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1799 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1800 if (IsMSVCCXX || IsCoreCLR) 1801 UnwindDests.back().first->setIsEHFuncletEntry(); 1802 if (!IsSEH) 1803 UnwindDests.back().first->setIsEHScopeEntry(); 1804 } 1805 NewEHPadBB = CatchSwitch->getUnwindDest(); 1806 } else { 1807 continue; 1808 } 1809 1810 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1811 if (BPI && NewEHPadBB) 1812 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1813 EHPadBB = NewEHPadBB; 1814 } 1815 } 1816 1817 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1818 // Update successor info. 1819 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1820 auto UnwindDest = I.getUnwindDest(); 1821 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1822 BranchProbability UnwindDestProb = 1823 (BPI && UnwindDest) 1824 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1825 : BranchProbability::getZero(); 1826 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1827 for (auto &UnwindDest : UnwindDests) { 1828 UnwindDest.first->setIsEHPad(); 1829 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1830 } 1831 FuncInfo.MBB->normalizeSuccProbs(); 1832 1833 // Create the terminator node. 1834 SDValue Ret = 1835 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1836 DAG.setRoot(Ret); 1837 } 1838 1839 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1840 report_fatal_error("visitCatchSwitch not yet implemented!"); 1841 } 1842 1843 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1844 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1845 auto &DL = DAG.getDataLayout(); 1846 SDValue Chain = getControlRoot(); 1847 SmallVector<ISD::OutputArg, 8> Outs; 1848 SmallVector<SDValue, 8> OutVals; 1849 1850 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1851 // lower 1852 // 1853 // %val = call <ty> @llvm.experimental.deoptimize() 1854 // ret <ty> %val 1855 // 1856 // differently. 1857 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1858 LowerDeoptimizingReturn(); 1859 return; 1860 } 1861 1862 if (!FuncInfo.CanLowerReturn) { 1863 unsigned DemoteReg = FuncInfo.DemoteRegister; 1864 const Function *F = I.getParent()->getParent(); 1865 1866 // Emit a store of the return value through the virtual register. 1867 // Leave Outs empty so that LowerReturn won't try to load return 1868 // registers the usual way. 1869 SmallVector<EVT, 1> PtrValueVTs; 1870 ComputeValueVTs(TLI, DL, 1871 F->getReturnType()->getPointerTo( 1872 DAG.getDataLayout().getAllocaAddrSpace()), 1873 PtrValueVTs); 1874 1875 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1876 DemoteReg, PtrValueVTs[0]); 1877 SDValue RetOp = getValue(I.getOperand(0)); 1878 1879 SmallVector<EVT, 4> ValueVTs, MemVTs; 1880 SmallVector<uint64_t, 4> Offsets; 1881 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1882 &Offsets); 1883 unsigned NumValues = ValueVTs.size(); 1884 1885 SmallVector<SDValue, 4> Chains(NumValues); 1886 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 1887 for (unsigned i = 0; i != NumValues; ++i) { 1888 // An aggregate return value cannot wrap around the address space, so 1889 // offsets to its parts don't wrap either. 1890 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 1891 TypeSize::Fixed(Offsets[i])); 1892 1893 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 1894 if (MemVTs[i] != ValueVTs[i]) 1895 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 1896 Chains[i] = DAG.getStore( 1897 Chain, getCurSDLoc(), Val, 1898 // FIXME: better loc info would be nice. 1899 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 1900 commonAlignment(BaseAlign, Offsets[i])); 1901 } 1902 1903 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1904 MVT::Other, Chains); 1905 } else if (I.getNumOperands() != 0) { 1906 SmallVector<EVT, 4> ValueVTs; 1907 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1908 unsigned NumValues = ValueVTs.size(); 1909 if (NumValues) { 1910 SDValue RetOp = getValue(I.getOperand(0)); 1911 1912 const Function *F = I.getParent()->getParent(); 1913 1914 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 1915 I.getOperand(0)->getType(), F->getCallingConv(), 1916 /*IsVarArg*/ false); 1917 1918 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1919 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1920 Attribute::SExt)) 1921 ExtendKind = ISD::SIGN_EXTEND; 1922 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1923 Attribute::ZExt)) 1924 ExtendKind = ISD::ZERO_EXTEND; 1925 1926 LLVMContext &Context = F->getContext(); 1927 bool RetInReg = F->getAttributes().hasAttribute( 1928 AttributeList::ReturnIndex, Attribute::InReg); 1929 1930 for (unsigned j = 0; j != NumValues; ++j) { 1931 EVT VT = ValueVTs[j]; 1932 1933 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1934 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1935 1936 CallingConv::ID CC = F->getCallingConv(); 1937 1938 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1939 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1940 SmallVector<SDValue, 4> Parts(NumParts); 1941 getCopyToParts(DAG, getCurSDLoc(), 1942 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1943 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1944 1945 // 'inreg' on function refers to return value 1946 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1947 if (RetInReg) 1948 Flags.setInReg(); 1949 1950 if (I.getOperand(0)->getType()->isPointerTy()) { 1951 Flags.setPointer(); 1952 Flags.setPointerAddrSpace( 1953 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 1954 } 1955 1956 if (NeedsRegBlock) { 1957 Flags.setInConsecutiveRegs(); 1958 if (j == NumValues - 1) 1959 Flags.setInConsecutiveRegsLast(); 1960 } 1961 1962 // Propagate extension type if any 1963 if (ExtendKind == ISD::SIGN_EXTEND) 1964 Flags.setSExt(); 1965 else if (ExtendKind == ISD::ZERO_EXTEND) 1966 Flags.setZExt(); 1967 1968 for (unsigned i = 0; i < NumParts; ++i) { 1969 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1970 VT, /*isfixed=*/true, 0, 0)); 1971 OutVals.push_back(Parts[i]); 1972 } 1973 } 1974 } 1975 } 1976 1977 // Push in swifterror virtual register as the last element of Outs. This makes 1978 // sure swifterror virtual register will be returned in the swifterror 1979 // physical register. 1980 const Function *F = I.getParent()->getParent(); 1981 if (TLI.supportSwiftError() && 1982 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 1983 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 1984 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1985 Flags.setSwiftError(); 1986 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 1987 EVT(TLI.getPointerTy(DL)) /*argvt*/, 1988 true /*isfixed*/, 1 /*origidx*/, 1989 0 /*partOffs*/)); 1990 // Create SDNode for the swifterror virtual register. 1991 OutVals.push_back( 1992 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 1993 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 1994 EVT(TLI.getPointerTy(DL)))); 1995 } 1996 1997 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 1998 CallingConv::ID CallConv = 1999 DAG.getMachineFunction().getFunction().getCallingConv(); 2000 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2001 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2002 2003 // Verify that the target's LowerReturn behaved as expected. 2004 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2005 "LowerReturn didn't return a valid chain!"); 2006 2007 // Update the DAG with the new chain value resulting from return lowering. 2008 DAG.setRoot(Chain); 2009 } 2010 2011 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2012 /// created for it, emit nodes to copy the value into the virtual 2013 /// registers. 2014 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2015 // Skip empty types 2016 if (V->getType()->isEmptyTy()) 2017 return; 2018 2019 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2020 if (VMI != FuncInfo.ValueMap.end()) { 2021 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 2022 CopyValueToVirtualRegister(V, VMI->second); 2023 } 2024 } 2025 2026 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2027 /// the current basic block, add it to ValueMap now so that we'll get a 2028 /// CopyTo/FromReg. 2029 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2030 // No need to export constants. 2031 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2032 2033 // Already exported? 2034 if (FuncInfo.isExportedInst(V)) return; 2035 2036 unsigned Reg = FuncInfo.InitializeRegForValue(V); 2037 CopyValueToVirtualRegister(V, Reg); 2038 } 2039 2040 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2041 const BasicBlock *FromBB) { 2042 // The operands of the setcc have to be in this block. We don't know 2043 // how to export them from some other block. 2044 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2045 // Can export from current BB. 2046 if (VI->getParent() == FromBB) 2047 return true; 2048 2049 // Is already exported, noop. 2050 return FuncInfo.isExportedInst(V); 2051 } 2052 2053 // If this is an argument, we can export it if the BB is the entry block or 2054 // if it is already exported. 2055 if (isa<Argument>(V)) { 2056 if (FromBB == &FromBB->getParent()->getEntryBlock()) 2057 return true; 2058 2059 // Otherwise, can only export this if it is already exported. 2060 return FuncInfo.isExportedInst(V); 2061 } 2062 2063 // Otherwise, constants can always be exported. 2064 return true; 2065 } 2066 2067 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2068 BranchProbability 2069 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2070 const MachineBasicBlock *Dst) const { 2071 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2072 const BasicBlock *SrcBB = Src->getBasicBlock(); 2073 const BasicBlock *DstBB = Dst->getBasicBlock(); 2074 if (!BPI) { 2075 // If BPI is not available, set the default probability as 1 / N, where N is 2076 // the number of successors. 2077 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2078 return BranchProbability(1, SuccSize); 2079 } 2080 return BPI->getEdgeProbability(SrcBB, DstBB); 2081 } 2082 2083 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2084 MachineBasicBlock *Dst, 2085 BranchProbability Prob) { 2086 if (!FuncInfo.BPI) 2087 Src->addSuccessorWithoutProb(Dst); 2088 else { 2089 if (Prob.isUnknown()) 2090 Prob = getEdgeProbability(Src, Dst); 2091 Src->addSuccessor(Dst, Prob); 2092 } 2093 } 2094 2095 static bool InBlock(const Value *V, const BasicBlock *BB) { 2096 if (const Instruction *I = dyn_cast<Instruction>(V)) 2097 return I->getParent() == BB; 2098 return true; 2099 } 2100 2101 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2102 /// This function emits a branch and is used at the leaves of an OR or an 2103 /// AND operator tree. 2104 void 2105 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2106 MachineBasicBlock *TBB, 2107 MachineBasicBlock *FBB, 2108 MachineBasicBlock *CurBB, 2109 MachineBasicBlock *SwitchBB, 2110 BranchProbability TProb, 2111 BranchProbability FProb, 2112 bool InvertCond) { 2113 const BasicBlock *BB = CurBB->getBasicBlock(); 2114 2115 // If the leaf of the tree is a comparison, merge the condition into 2116 // the caseblock. 2117 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2118 // The operands of the cmp have to be in this block. We don't know 2119 // how to export them from some other block. If this is the first block 2120 // of the sequence, no exporting is needed. 2121 if (CurBB == SwitchBB || 2122 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2123 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2124 ISD::CondCode Condition; 2125 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2126 ICmpInst::Predicate Pred = 2127 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2128 Condition = getICmpCondCode(Pred); 2129 } else { 2130 const FCmpInst *FC = cast<FCmpInst>(Cond); 2131 FCmpInst::Predicate Pred = 2132 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2133 Condition = getFCmpCondCode(Pred); 2134 if (TM.Options.NoNaNsFPMath) 2135 Condition = getFCmpCodeWithoutNaN(Condition); 2136 } 2137 2138 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2139 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2140 SL->SwitchCases.push_back(CB); 2141 return; 2142 } 2143 } 2144 2145 // Create a CaseBlock record representing this branch. 2146 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2147 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2148 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2149 SL->SwitchCases.push_back(CB); 2150 } 2151 2152 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2153 MachineBasicBlock *TBB, 2154 MachineBasicBlock *FBB, 2155 MachineBasicBlock *CurBB, 2156 MachineBasicBlock *SwitchBB, 2157 Instruction::BinaryOps Opc, 2158 BranchProbability TProb, 2159 BranchProbability FProb, 2160 bool InvertCond) { 2161 // Skip over not part of the tree and remember to invert op and operands at 2162 // next level. 2163 Value *NotCond; 2164 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2165 InBlock(NotCond, CurBB->getBasicBlock())) { 2166 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2167 !InvertCond); 2168 return; 2169 } 2170 2171 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2172 const Value *BOpOp0, *BOpOp1; 2173 // Compute the effective opcode for Cond, taking into account whether it needs 2174 // to be inverted, e.g. 2175 // and (not (or A, B)), C 2176 // gets lowered as 2177 // and (and (not A, not B), C) 2178 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2179 if (BOp) { 2180 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2181 ? Instruction::And 2182 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2183 ? Instruction::Or 2184 : (Instruction::BinaryOps)0); 2185 if (InvertCond) { 2186 if (BOpc == Instruction::And) 2187 BOpc = Instruction::Or; 2188 else if (BOpc == Instruction::Or) 2189 BOpc = Instruction::And; 2190 } 2191 } 2192 2193 // If this node is not part of the or/and tree, emit it as a branch. 2194 // Note that all nodes in the tree should have same opcode. 2195 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2196 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2197 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2198 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2199 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2200 TProb, FProb, InvertCond); 2201 return; 2202 } 2203 2204 // Create TmpBB after CurBB. 2205 MachineFunction::iterator BBI(CurBB); 2206 MachineFunction &MF = DAG.getMachineFunction(); 2207 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2208 CurBB->getParent()->insert(++BBI, TmpBB); 2209 2210 if (Opc == Instruction::Or) { 2211 // Codegen X | Y as: 2212 // BB1: 2213 // jmp_if_X TBB 2214 // jmp TmpBB 2215 // TmpBB: 2216 // jmp_if_Y TBB 2217 // jmp FBB 2218 // 2219 2220 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2221 // The requirement is that 2222 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2223 // = TrueProb for original BB. 2224 // Assuming the original probabilities are A and B, one choice is to set 2225 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2226 // A/(1+B) and 2B/(1+B). This choice assumes that 2227 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2228 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2229 // TmpBB, but the math is more complicated. 2230 2231 auto NewTrueProb = TProb / 2; 2232 auto NewFalseProb = TProb / 2 + FProb; 2233 // Emit the LHS condition. 2234 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2235 NewFalseProb, InvertCond); 2236 2237 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2238 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2239 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2240 // Emit the RHS condition into TmpBB. 2241 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2242 Probs[1], InvertCond); 2243 } else { 2244 assert(Opc == Instruction::And && "Unknown merge op!"); 2245 // Codegen X & Y as: 2246 // BB1: 2247 // jmp_if_X TmpBB 2248 // jmp FBB 2249 // TmpBB: 2250 // jmp_if_Y TBB 2251 // jmp FBB 2252 // 2253 // This requires creation of TmpBB after CurBB. 2254 2255 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2256 // The requirement is that 2257 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2258 // = FalseProb for original BB. 2259 // Assuming the original probabilities are A and B, one choice is to set 2260 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2261 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2262 // TrueProb for BB1 * FalseProb for TmpBB. 2263 2264 auto NewTrueProb = TProb + FProb / 2; 2265 auto NewFalseProb = FProb / 2; 2266 // Emit the LHS condition. 2267 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2268 NewFalseProb, InvertCond); 2269 2270 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2271 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2272 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2273 // Emit the RHS condition into TmpBB. 2274 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2275 Probs[1], InvertCond); 2276 } 2277 } 2278 2279 /// If the set of cases should be emitted as a series of branches, return true. 2280 /// If we should emit this as a bunch of and/or'd together conditions, return 2281 /// false. 2282 bool 2283 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2284 if (Cases.size() != 2) return true; 2285 2286 // If this is two comparisons of the same values or'd or and'd together, they 2287 // will get folded into a single comparison, so don't emit two blocks. 2288 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2289 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2290 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2291 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2292 return false; 2293 } 2294 2295 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2296 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2297 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2298 Cases[0].CC == Cases[1].CC && 2299 isa<Constant>(Cases[0].CmpRHS) && 2300 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2301 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2302 return false; 2303 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2304 return false; 2305 } 2306 2307 return true; 2308 } 2309 2310 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2311 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2312 2313 // Update machine-CFG edges. 2314 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2315 2316 if (I.isUnconditional()) { 2317 // Update machine-CFG edges. 2318 BrMBB->addSuccessor(Succ0MBB); 2319 2320 // If this is not a fall-through branch or optimizations are switched off, 2321 // emit the branch. 2322 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2323 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2324 MVT::Other, getControlRoot(), 2325 DAG.getBasicBlock(Succ0MBB))); 2326 2327 return; 2328 } 2329 2330 // If this condition is one of the special cases we handle, do special stuff 2331 // now. 2332 const Value *CondVal = I.getCondition(); 2333 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2334 2335 // If this is a series of conditions that are or'd or and'd together, emit 2336 // this as a sequence of branches instead of setcc's with and/or operations. 2337 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2338 // unpredictable branches, and vector extracts because those jumps are likely 2339 // expensive for any target), this should improve performance. 2340 // For example, instead of something like: 2341 // cmp A, B 2342 // C = seteq 2343 // cmp D, E 2344 // F = setle 2345 // or C, F 2346 // jnz foo 2347 // Emit: 2348 // cmp A, B 2349 // je foo 2350 // cmp D, E 2351 // jle foo 2352 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2353 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2354 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2355 Value *Vec; 2356 const Value *BOp0, *BOp1; 2357 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2358 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2359 Opcode = Instruction::And; 2360 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2361 Opcode = Instruction::Or; 2362 2363 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2364 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2365 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2366 getEdgeProbability(BrMBB, Succ0MBB), 2367 getEdgeProbability(BrMBB, Succ1MBB), 2368 /*InvertCond=*/false); 2369 // If the compares in later blocks need to use values not currently 2370 // exported from this block, export them now. This block should always 2371 // be the first entry. 2372 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2373 2374 // Allow some cases to be rejected. 2375 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2376 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2377 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2378 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2379 } 2380 2381 // Emit the branch for this block. 2382 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2383 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2384 return; 2385 } 2386 2387 // Okay, we decided not to do this, remove any inserted MBB's and clear 2388 // SwitchCases. 2389 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2390 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2391 2392 SL->SwitchCases.clear(); 2393 } 2394 } 2395 2396 // Create a CaseBlock record representing this branch. 2397 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2398 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2399 2400 // Use visitSwitchCase to actually insert the fast branch sequence for this 2401 // cond branch. 2402 visitSwitchCase(CB, BrMBB); 2403 } 2404 2405 /// visitSwitchCase - Emits the necessary code to represent a single node in 2406 /// the binary search tree resulting from lowering a switch instruction. 2407 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2408 MachineBasicBlock *SwitchBB) { 2409 SDValue Cond; 2410 SDValue CondLHS = getValue(CB.CmpLHS); 2411 SDLoc dl = CB.DL; 2412 2413 if (CB.CC == ISD::SETTRUE) { 2414 // Branch or fall through to TrueBB. 2415 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2416 SwitchBB->normalizeSuccProbs(); 2417 if (CB.TrueBB != NextBlock(SwitchBB)) { 2418 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2419 DAG.getBasicBlock(CB.TrueBB))); 2420 } 2421 return; 2422 } 2423 2424 auto &TLI = DAG.getTargetLoweringInfo(); 2425 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2426 2427 // Build the setcc now. 2428 if (!CB.CmpMHS) { 2429 // Fold "(X == true)" to X and "(X == false)" to !X to 2430 // handle common cases produced by branch lowering. 2431 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2432 CB.CC == ISD::SETEQ) 2433 Cond = CondLHS; 2434 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2435 CB.CC == ISD::SETEQ) { 2436 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2437 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2438 } else { 2439 SDValue CondRHS = getValue(CB.CmpRHS); 2440 2441 // If a pointer's DAG type is larger than its memory type then the DAG 2442 // values are zero-extended. This breaks signed comparisons so truncate 2443 // back to the underlying type before doing the compare. 2444 if (CondLHS.getValueType() != MemVT) { 2445 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2446 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2447 } 2448 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2449 } 2450 } else { 2451 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2452 2453 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2454 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2455 2456 SDValue CmpOp = getValue(CB.CmpMHS); 2457 EVT VT = CmpOp.getValueType(); 2458 2459 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2460 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2461 ISD::SETLE); 2462 } else { 2463 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2464 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2465 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2466 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2467 } 2468 } 2469 2470 // Update successor info 2471 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2472 // TrueBB and FalseBB are always different unless the incoming IR is 2473 // degenerate. This only happens when running llc on weird IR. 2474 if (CB.TrueBB != CB.FalseBB) 2475 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2476 SwitchBB->normalizeSuccProbs(); 2477 2478 // If the lhs block is the next block, invert the condition so that we can 2479 // fall through to the lhs instead of the rhs block. 2480 if (CB.TrueBB == NextBlock(SwitchBB)) { 2481 std::swap(CB.TrueBB, CB.FalseBB); 2482 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2483 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2484 } 2485 2486 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2487 MVT::Other, getControlRoot(), Cond, 2488 DAG.getBasicBlock(CB.TrueBB)); 2489 2490 // Insert the false branch. Do this even if it's a fall through branch, 2491 // this makes it easier to do DAG optimizations which require inverting 2492 // the branch condition. 2493 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2494 DAG.getBasicBlock(CB.FalseBB)); 2495 2496 DAG.setRoot(BrCond); 2497 } 2498 2499 /// visitJumpTable - Emit JumpTable node in the current MBB 2500 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2501 // Emit the code for the jump table 2502 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2503 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2504 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2505 JT.Reg, PTy); 2506 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2507 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2508 MVT::Other, Index.getValue(1), 2509 Table, Index); 2510 DAG.setRoot(BrJumpTable); 2511 } 2512 2513 /// visitJumpTableHeader - This function emits necessary code to produce index 2514 /// in the JumpTable from switch case. 2515 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2516 JumpTableHeader &JTH, 2517 MachineBasicBlock *SwitchBB) { 2518 SDLoc dl = getCurSDLoc(); 2519 2520 // Subtract the lowest switch case value from the value being switched on. 2521 SDValue SwitchOp = getValue(JTH.SValue); 2522 EVT VT = SwitchOp.getValueType(); 2523 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2524 DAG.getConstant(JTH.First, dl, VT)); 2525 2526 // The SDNode we just created, which holds the value being switched on minus 2527 // the smallest case value, needs to be copied to a virtual register so it 2528 // can be used as an index into the jump table in a subsequent basic block. 2529 // This value may be smaller or larger than the target's pointer type, and 2530 // therefore require extension or truncating. 2531 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2532 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2533 2534 unsigned JumpTableReg = 2535 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2536 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2537 JumpTableReg, SwitchOp); 2538 JT.Reg = JumpTableReg; 2539 2540 if (!JTH.OmitRangeCheck) { 2541 // Emit the range check for the jump table, and branch to the default block 2542 // for the switch statement if the value being switched on exceeds the 2543 // largest case in the switch. 2544 SDValue CMP = DAG.getSetCC( 2545 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2546 Sub.getValueType()), 2547 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2548 2549 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2550 MVT::Other, CopyTo, CMP, 2551 DAG.getBasicBlock(JT.Default)); 2552 2553 // Avoid emitting unnecessary branches to the next block. 2554 if (JT.MBB != NextBlock(SwitchBB)) 2555 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2556 DAG.getBasicBlock(JT.MBB)); 2557 2558 DAG.setRoot(BrCond); 2559 } else { 2560 // Avoid emitting unnecessary branches to the next block. 2561 if (JT.MBB != NextBlock(SwitchBB)) 2562 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2563 DAG.getBasicBlock(JT.MBB))); 2564 else 2565 DAG.setRoot(CopyTo); 2566 } 2567 } 2568 2569 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2570 /// variable if there exists one. 2571 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2572 SDValue &Chain) { 2573 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2574 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2575 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2576 MachineFunction &MF = DAG.getMachineFunction(); 2577 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2578 MachineSDNode *Node = 2579 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2580 if (Global) { 2581 MachinePointerInfo MPInfo(Global); 2582 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2583 MachineMemOperand::MODereferenceable; 2584 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2585 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2586 DAG.setNodeMemRefs(Node, {MemRef}); 2587 } 2588 if (PtrTy != PtrMemTy) 2589 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2590 return SDValue(Node, 0); 2591 } 2592 2593 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2594 /// tail spliced into a stack protector check success bb. 2595 /// 2596 /// For a high level explanation of how this fits into the stack protector 2597 /// generation see the comment on the declaration of class 2598 /// StackProtectorDescriptor. 2599 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2600 MachineBasicBlock *ParentBB) { 2601 2602 // First create the loads to the guard/stack slot for the comparison. 2603 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2604 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2605 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2606 2607 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2608 int FI = MFI.getStackProtectorIndex(); 2609 2610 SDValue Guard; 2611 SDLoc dl = getCurSDLoc(); 2612 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2613 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2614 Align Align = DL->getPrefTypeAlign(Type::getInt8PtrTy(M.getContext())); 2615 2616 // Generate code to load the content of the guard slot. 2617 SDValue GuardVal = DAG.getLoad( 2618 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2619 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2620 MachineMemOperand::MOVolatile); 2621 2622 if (TLI.useStackGuardXorFP()) 2623 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2624 2625 // Retrieve guard check function, nullptr if instrumentation is inlined. 2626 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2627 // The target provides a guard check function to validate the guard value. 2628 // Generate a call to that function with the content of the guard slot as 2629 // argument. 2630 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2631 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2632 2633 TargetLowering::ArgListTy Args; 2634 TargetLowering::ArgListEntry Entry; 2635 Entry.Node = GuardVal; 2636 Entry.Ty = FnTy->getParamType(0); 2637 if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg)) 2638 Entry.IsInReg = true; 2639 Args.push_back(Entry); 2640 2641 TargetLowering::CallLoweringInfo CLI(DAG); 2642 CLI.setDebugLoc(getCurSDLoc()) 2643 .setChain(DAG.getEntryNode()) 2644 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2645 getValue(GuardCheckFn), std::move(Args)); 2646 2647 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2648 DAG.setRoot(Result.second); 2649 return; 2650 } 2651 2652 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2653 // Otherwise, emit a volatile load to retrieve the stack guard value. 2654 SDValue Chain = DAG.getEntryNode(); 2655 if (TLI.useLoadStackGuardNode()) { 2656 Guard = getLoadStackGuard(DAG, dl, Chain); 2657 } else { 2658 const Value *IRGuard = TLI.getSDagStackGuard(M); 2659 SDValue GuardPtr = getValue(IRGuard); 2660 2661 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2662 MachinePointerInfo(IRGuard, 0), Align, 2663 MachineMemOperand::MOVolatile); 2664 } 2665 2666 // Perform the comparison via a getsetcc. 2667 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2668 *DAG.getContext(), 2669 Guard.getValueType()), 2670 Guard, GuardVal, ISD::SETNE); 2671 2672 // If the guard/stackslot do not equal, branch to failure MBB. 2673 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2674 MVT::Other, GuardVal.getOperand(0), 2675 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2676 // Otherwise branch to success MBB. 2677 SDValue Br = DAG.getNode(ISD::BR, dl, 2678 MVT::Other, BrCond, 2679 DAG.getBasicBlock(SPD.getSuccessMBB())); 2680 2681 DAG.setRoot(Br); 2682 } 2683 2684 /// Codegen the failure basic block for a stack protector check. 2685 /// 2686 /// A failure stack protector machine basic block consists simply of a call to 2687 /// __stack_chk_fail(). 2688 /// 2689 /// For a high level explanation of how this fits into the stack protector 2690 /// generation see the comment on the declaration of class 2691 /// StackProtectorDescriptor. 2692 void 2693 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2694 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2695 TargetLowering::MakeLibCallOptions CallOptions; 2696 CallOptions.setDiscardResult(true); 2697 SDValue Chain = 2698 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2699 None, CallOptions, getCurSDLoc()).second; 2700 // On PS4, the "return address" must still be within the calling function, 2701 // even if it's at the very end, so emit an explicit TRAP here. 2702 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2703 if (TM.getTargetTriple().isPS4CPU()) 2704 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2705 // WebAssembly needs an unreachable instruction after a non-returning call, 2706 // because the function return type can be different from __stack_chk_fail's 2707 // return type (void). 2708 if (TM.getTargetTriple().isWasm()) 2709 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2710 2711 DAG.setRoot(Chain); 2712 } 2713 2714 /// visitBitTestHeader - This function emits necessary code to produce value 2715 /// suitable for "bit tests" 2716 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2717 MachineBasicBlock *SwitchBB) { 2718 SDLoc dl = getCurSDLoc(); 2719 2720 // Subtract the minimum value. 2721 SDValue SwitchOp = getValue(B.SValue); 2722 EVT VT = SwitchOp.getValueType(); 2723 SDValue RangeSub = 2724 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2725 2726 // Determine the type of the test operands. 2727 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2728 bool UsePtrType = false; 2729 if (!TLI.isTypeLegal(VT)) { 2730 UsePtrType = true; 2731 } else { 2732 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2733 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2734 // Switch table case range are encoded into series of masks. 2735 // Just use pointer type, it's guaranteed to fit. 2736 UsePtrType = true; 2737 break; 2738 } 2739 } 2740 SDValue Sub = RangeSub; 2741 if (UsePtrType) { 2742 VT = TLI.getPointerTy(DAG.getDataLayout()); 2743 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2744 } 2745 2746 B.RegVT = VT.getSimpleVT(); 2747 B.Reg = FuncInfo.CreateReg(B.RegVT); 2748 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2749 2750 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2751 2752 if (!B.OmitRangeCheck) 2753 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2754 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2755 SwitchBB->normalizeSuccProbs(); 2756 2757 SDValue Root = CopyTo; 2758 if (!B.OmitRangeCheck) { 2759 // Conditional branch to the default block. 2760 SDValue RangeCmp = DAG.getSetCC(dl, 2761 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2762 RangeSub.getValueType()), 2763 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2764 ISD::SETUGT); 2765 2766 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2767 DAG.getBasicBlock(B.Default)); 2768 } 2769 2770 // Avoid emitting unnecessary branches to the next block. 2771 if (MBB != NextBlock(SwitchBB)) 2772 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2773 2774 DAG.setRoot(Root); 2775 } 2776 2777 /// visitBitTestCase - this function produces one "bit test" 2778 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2779 MachineBasicBlock* NextMBB, 2780 BranchProbability BranchProbToNext, 2781 unsigned Reg, 2782 BitTestCase &B, 2783 MachineBasicBlock *SwitchBB) { 2784 SDLoc dl = getCurSDLoc(); 2785 MVT VT = BB.RegVT; 2786 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2787 SDValue Cmp; 2788 unsigned PopCount = countPopulation(B.Mask); 2789 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2790 if (PopCount == 1) { 2791 // Testing for a single bit; just compare the shift count with what it 2792 // would need to be to shift a 1 bit in that position. 2793 Cmp = DAG.getSetCC( 2794 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2795 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2796 ISD::SETEQ); 2797 } else if (PopCount == BB.Range) { 2798 // There is only one zero bit in the range, test for it directly. 2799 Cmp = DAG.getSetCC( 2800 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2801 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2802 ISD::SETNE); 2803 } else { 2804 // Make desired shift 2805 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2806 DAG.getConstant(1, dl, VT), ShiftOp); 2807 2808 // Emit bit tests and jumps 2809 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2810 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2811 Cmp = DAG.getSetCC( 2812 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2813 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2814 } 2815 2816 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2817 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2818 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2819 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2820 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2821 // one as they are relative probabilities (and thus work more like weights), 2822 // and hence we need to normalize them to let the sum of them become one. 2823 SwitchBB->normalizeSuccProbs(); 2824 2825 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2826 MVT::Other, getControlRoot(), 2827 Cmp, DAG.getBasicBlock(B.TargetBB)); 2828 2829 // Avoid emitting unnecessary branches to the next block. 2830 if (NextMBB != NextBlock(SwitchBB)) 2831 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2832 DAG.getBasicBlock(NextMBB)); 2833 2834 DAG.setRoot(BrAnd); 2835 } 2836 2837 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2838 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2839 2840 // Retrieve successors. Look through artificial IR level blocks like 2841 // catchswitch for successors. 2842 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2843 const BasicBlock *EHPadBB = I.getSuccessor(1); 2844 2845 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2846 // have to do anything here to lower funclet bundles. 2847 assert(!I.hasOperandBundlesOtherThan( 2848 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 2849 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 2850 LLVMContext::OB_cfguardtarget, 2851 LLVMContext::OB_clang_arc_attachedcall}) && 2852 "Cannot lower invokes with arbitrary operand bundles yet!"); 2853 2854 const Value *Callee(I.getCalledOperand()); 2855 const Function *Fn = dyn_cast<Function>(Callee); 2856 if (isa<InlineAsm>(Callee)) 2857 visitInlineAsm(I); 2858 else if (Fn && Fn->isIntrinsic()) { 2859 switch (Fn->getIntrinsicID()) { 2860 default: 2861 llvm_unreachable("Cannot invoke this intrinsic"); 2862 case Intrinsic::donothing: 2863 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2864 break; 2865 case Intrinsic::experimental_patchpoint_void: 2866 case Intrinsic::experimental_patchpoint_i64: 2867 visitPatchpoint(I, EHPadBB); 2868 break; 2869 case Intrinsic::experimental_gc_statepoint: 2870 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 2871 break; 2872 case Intrinsic::wasm_rethrow: { 2873 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2874 // special because it can be invoked, so we manually lower it to a DAG 2875 // node here. 2876 SmallVector<SDValue, 8> Ops; 2877 Ops.push_back(getRoot()); // inchain 2878 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2879 Ops.push_back( 2880 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 2881 TLI.getPointerTy(DAG.getDataLayout()))); 2882 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2883 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2884 break; 2885 } 2886 } 2887 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2888 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2889 // Eventually we will support lowering the @llvm.experimental.deoptimize 2890 // intrinsic, and right now there are no plans to support other intrinsics 2891 // with deopt state. 2892 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2893 } else { 2894 LowerCallTo(I, getValue(Callee), false, EHPadBB); 2895 } 2896 2897 // If the value of the invoke is used outside of its defining block, make it 2898 // available as a virtual register. 2899 // We already took care of the exported value for the statepoint instruction 2900 // during call to the LowerStatepoint. 2901 if (!isa<GCStatepointInst>(I)) { 2902 CopyToExportRegsIfNeeded(&I); 2903 } 2904 2905 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2906 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2907 BranchProbability EHPadBBProb = 2908 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2909 : BranchProbability::getZero(); 2910 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2911 2912 // Update successor info. 2913 addSuccessorWithProb(InvokeMBB, Return); 2914 for (auto &UnwindDest : UnwindDests) { 2915 UnwindDest.first->setIsEHPad(); 2916 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2917 } 2918 InvokeMBB->normalizeSuccProbs(); 2919 2920 // Drop into normal successor. 2921 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 2922 DAG.getBasicBlock(Return))); 2923 } 2924 2925 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 2926 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 2927 2928 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2929 // have to do anything here to lower funclet bundles. 2930 assert(!I.hasOperandBundlesOtherThan( 2931 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2932 "Cannot lower callbrs with arbitrary operand bundles yet!"); 2933 2934 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 2935 visitInlineAsm(I); 2936 CopyToExportRegsIfNeeded(&I); 2937 2938 // Retrieve successors. 2939 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 2940 2941 // Update successor info. 2942 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 2943 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 2944 MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)]; 2945 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 2946 Target->setIsInlineAsmBrIndirectTarget(); 2947 } 2948 CallBrMBB->normalizeSuccProbs(); 2949 2950 // Drop into default successor. 2951 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2952 MVT::Other, getControlRoot(), 2953 DAG.getBasicBlock(Return))); 2954 } 2955 2956 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2957 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2958 } 2959 2960 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2961 assert(FuncInfo.MBB->isEHPad() && 2962 "Call to landingpad not in landing pad!"); 2963 2964 // If there aren't registers to copy the values into (e.g., during SjLj 2965 // exceptions), then don't bother to create these DAG nodes. 2966 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2967 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2968 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2969 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2970 return; 2971 2972 // If landingpad's return type is token type, we don't create DAG nodes 2973 // for its exception pointer and selector value. The extraction of exception 2974 // pointer or selector value from token type landingpads is not currently 2975 // supported. 2976 if (LP.getType()->isTokenTy()) 2977 return; 2978 2979 SmallVector<EVT, 2> ValueVTs; 2980 SDLoc dl = getCurSDLoc(); 2981 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2982 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2983 2984 // Get the two live-in registers as SDValues. The physregs have already been 2985 // copied into virtual registers. 2986 SDValue Ops[2]; 2987 if (FuncInfo.ExceptionPointerVirtReg) { 2988 Ops[0] = DAG.getZExtOrTrunc( 2989 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2990 FuncInfo.ExceptionPointerVirtReg, 2991 TLI.getPointerTy(DAG.getDataLayout())), 2992 dl, ValueVTs[0]); 2993 } else { 2994 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2995 } 2996 Ops[1] = DAG.getZExtOrTrunc( 2997 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2998 FuncInfo.ExceptionSelectorVirtReg, 2999 TLI.getPointerTy(DAG.getDataLayout())), 3000 dl, ValueVTs[1]); 3001 3002 // Merge into one. 3003 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3004 DAG.getVTList(ValueVTs), Ops); 3005 setValue(&LP, Res); 3006 } 3007 3008 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3009 MachineBasicBlock *Last) { 3010 // Update JTCases. 3011 for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i) 3012 if (SL->JTCases[i].first.HeaderBB == First) 3013 SL->JTCases[i].first.HeaderBB = Last; 3014 3015 // Update BitTestCases. 3016 for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i) 3017 if (SL->BitTestCases[i].Parent == First) 3018 SL->BitTestCases[i].Parent = Last; 3019 } 3020 3021 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3022 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3023 3024 // Update machine-CFG edges with unique successors. 3025 SmallSet<BasicBlock*, 32> Done; 3026 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3027 BasicBlock *BB = I.getSuccessor(i); 3028 bool Inserted = Done.insert(BB).second; 3029 if (!Inserted) 3030 continue; 3031 3032 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3033 addSuccessorWithProb(IndirectBrMBB, Succ); 3034 } 3035 IndirectBrMBB->normalizeSuccProbs(); 3036 3037 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3038 MVT::Other, getControlRoot(), 3039 getValue(I.getAddress()))); 3040 } 3041 3042 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3043 if (!DAG.getTarget().Options.TrapUnreachable) 3044 return; 3045 3046 // We may be able to ignore unreachable behind a noreturn call. 3047 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3048 const BasicBlock &BB = *I.getParent(); 3049 if (&I != &BB.front()) { 3050 BasicBlock::const_iterator PredI = 3051 std::prev(BasicBlock::const_iterator(&I)); 3052 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 3053 if (Call->doesNotReturn()) 3054 return; 3055 } 3056 } 3057 } 3058 3059 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3060 } 3061 3062 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3063 SDNodeFlags Flags; 3064 3065 SDValue Op = getValue(I.getOperand(0)); 3066 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3067 Op, Flags); 3068 setValue(&I, UnNodeValue); 3069 } 3070 3071 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3072 SDNodeFlags Flags; 3073 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3074 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3075 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3076 } 3077 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3078 Flags.setExact(ExactOp->isExact()); 3079 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3080 Flags.copyFMF(*FPOp); 3081 3082 SDValue Op1 = getValue(I.getOperand(0)); 3083 SDValue Op2 = getValue(I.getOperand(1)); 3084 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3085 Op1, Op2, Flags); 3086 setValue(&I, BinNodeValue); 3087 } 3088 3089 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3090 SDValue Op1 = getValue(I.getOperand(0)); 3091 SDValue Op2 = getValue(I.getOperand(1)); 3092 3093 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3094 Op1.getValueType(), DAG.getDataLayout()); 3095 3096 // Coerce the shift amount to the right type if we can. 3097 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3098 unsigned ShiftSize = ShiftTy.getSizeInBits(); 3099 unsigned Op2Size = Op2.getValueSizeInBits(); 3100 SDLoc DL = getCurSDLoc(); 3101 3102 // If the operand is smaller than the shift count type, promote it. 3103 if (ShiftSize > Op2Size) 3104 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 3105 3106 // If the operand is larger than the shift count type but the shift 3107 // count type has enough bits to represent any shift value, truncate 3108 // it now. This is a common case and it exposes the truncate to 3109 // optimization early. 3110 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 3111 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 3112 // Otherwise we'll need to temporarily settle for some other convenient 3113 // type. Type legalization will make adjustments once the shiftee is split. 3114 else 3115 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 3116 } 3117 3118 bool nuw = false; 3119 bool nsw = false; 3120 bool exact = false; 3121 3122 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3123 3124 if (const OverflowingBinaryOperator *OFBinOp = 3125 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3126 nuw = OFBinOp->hasNoUnsignedWrap(); 3127 nsw = OFBinOp->hasNoSignedWrap(); 3128 } 3129 if (const PossiblyExactOperator *ExactOp = 3130 dyn_cast<const PossiblyExactOperator>(&I)) 3131 exact = ExactOp->isExact(); 3132 } 3133 SDNodeFlags Flags; 3134 Flags.setExact(exact); 3135 Flags.setNoSignedWrap(nsw); 3136 Flags.setNoUnsignedWrap(nuw); 3137 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3138 Flags); 3139 setValue(&I, Res); 3140 } 3141 3142 void SelectionDAGBuilder::visitSDiv(const User &I) { 3143 SDValue Op1 = getValue(I.getOperand(0)); 3144 SDValue Op2 = getValue(I.getOperand(1)); 3145 3146 SDNodeFlags Flags; 3147 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3148 cast<PossiblyExactOperator>(&I)->isExact()); 3149 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3150 Op2, Flags)); 3151 } 3152 3153 void SelectionDAGBuilder::visitICmp(const User &I) { 3154 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3155 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3156 predicate = IC->getPredicate(); 3157 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3158 predicate = ICmpInst::Predicate(IC->getPredicate()); 3159 SDValue Op1 = getValue(I.getOperand(0)); 3160 SDValue Op2 = getValue(I.getOperand(1)); 3161 ISD::CondCode Opcode = getICmpCondCode(predicate); 3162 3163 auto &TLI = DAG.getTargetLoweringInfo(); 3164 EVT MemVT = 3165 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3166 3167 // If a pointer's DAG type is larger than its memory type then the DAG values 3168 // are zero-extended. This breaks signed comparisons so truncate back to the 3169 // underlying type before doing the compare. 3170 if (Op1.getValueType() != MemVT) { 3171 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3172 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3173 } 3174 3175 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3176 I.getType()); 3177 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3178 } 3179 3180 void SelectionDAGBuilder::visitFCmp(const User &I) { 3181 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3182 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3183 predicate = FC->getPredicate(); 3184 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3185 predicate = FCmpInst::Predicate(FC->getPredicate()); 3186 SDValue Op1 = getValue(I.getOperand(0)); 3187 SDValue Op2 = getValue(I.getOperand(1)); 3188 3189 ISD::CondCode Condition = getFCmpCondCode(predicate); 3190 auto *FPMO = cast<FPMathOperator>(&I); 3191 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3192 Condition = getFCmpCodeWithoutNaN(Condition); 3193 3194 SDNodeFlags Flags; 3195 Flags.copyFMF(*FPMO); 3196 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3197 3198 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3199 I.getType()); 3200 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3201 } 3202 3203 // Check if the condition of the select has one use or two users that are both 3204 // selects with the same condition. 3205 static bool hasOnlySelectUsers(const Value *Cond) { 3206 return llvm::all_of(Cond->users(), [](const Value *V) { 3207 return isa<SelectInst>(V); 3208 }); 3209 } 3210 3211 void SelectionDAGBuilder::visitSelect(const User &I) { 3212 SmallVector<EVT, 4> ValueVTs; 3213 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3214 ValueVTs); 3215 unsigned NumValues = ValueVTs.size(); 3216 if (NumValues == 0) return; 3217 3218 SmallVector<SDValue, 4> Values(NumValues); 3219 SDValue Cond = getValue(I.getOperand(0)); 3220 SDValue LHSVal = getValue(I.getOperand(1)); 3221 SDValue RHSVal = getValue(I.getOperand(2)); 3222 SmallVector<SDValue, 1> BaseOps(1, Cond); 3223 ISD::NodeType OpCode = 3224 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3225 3226 bool IsUnaryAbs = false; 3227 bool Negate = false; 3228 3229 SDNodeFlags Flags; 3230 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3231 Flags.copyFMF(*FPOp); 3232 3233 // Min/max matching is only viable if all output VTs are the same. 3234 if (is_splat(ValueVTs)) { 3235 EVT VT = ValueVTs[0]; 3236 LLVMContext &Ctx = *DAG.getContext(); 3237 auto &TLI = DAG.getTargetLoweringInfo(); 3238 3239 // We care about the legality of the operation after it has been type 3240 // legalized. 3241 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3242 VT = TLI.getTypeToTransformTo(Ctx, VT); 3243 3244 // If the vselect is legal, assume we want to leave this as a vector setcc + 3245 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3246 // min/max is legal on the scalar type. 3247 bool UseScalarMinMax = VT.isVector() && 3248 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3249 3250 Value *LHS, *RHS; 3251 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3252 ISD::NodeType Opc = ISD::DELETED_NODE; 3253 switch (SPR.Flavor) { 3254 case SPF_UMAX: Opc = ISD::UMAX; break; 3255 case SPF_UMIN: Opc = ISD::UMIN; break; 3256 case SPF_SMAX: Opc = ISD::SMAX; break; 3257 case SPF_SMIN: Opc = ISD::SMIN; break; 3258 case SPF_FMINNUM: 3259 switch (SPR.NaNBehavior) { 3260 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3261 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3262 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3263 case SPNB_RETURNS_ANY: { 3264 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3265 Opc = ISD::FMINNUM; 3266 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3267 Opc = ISD::FMINIMUM; 3268 else if (UseScalarMinMax) 3269 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3270 ISD::FMINNUM : ISD::FMINIMUM; 3271 break; 3272 } 3273 } 3274 break; 3275 case SPF_FMAXNUM: 3276 switch (SPR.NaNBehavior) { 3277 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3278 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3279 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3280 case SPNB_RETURNS_ANY: 3281 3282 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3283 Opc = ISD::FMAXNUM; 3284 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3285 Opc = ISD::FMAXIMUM; 3286 else if (UseScalarMinMax) 3287 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3288 ISD::FMAXNUM : ISD::FMAXIMUM; 3289 break; 3290 } 3291 break; 3292 case SPF_NABS: 3293 Negate = true; 3294 LLVM_FALLTHROUGH; 3295 case SPF_ABS: 3296 IsUnaryAbs = true; 3297 Opc = ISD::ABS; 3298 break; 3299 default: break; 3300 } 3301 3302 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3303 (TLI.isOperationLegalOrCustom(Opc, VT) || 3304 (UseScalarMinMax && 3305 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3306 // If the underlying comparison instruction is used by any other 3307 // instruction, the consumed instructions won't be destroyed, so it is 3308 // not profitable to convert to a min/max. 3309 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3310 OpCode = Opc; 3311 LHSVal = getValue(LHS); 3312 RHSVal = getValue(RHS); 3313 BaseOps.clear(); 3314 } 3315 3316 if (IsUnaryAbs) { 3317 OpCode = Opc; 3318 LHSVal = getValue(LHS); 3319 BaseOps.clear(); 3320 } 3321 } 3322 3323 if (IsUnaryAbs) { 3324 for (unsigned i = 0; i != NumValues; ++i) { 3325 SDLoc dl = getCurSDLoc(); 3326 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3327 Values[i] = 3328 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3329 if (Negate) 3330 Values[i] = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), 3331 Values[i]); 3332 } 3333 } else { 3334 for (unsigned i = 0; i != NumValues; ++i) { 3335 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3336 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3337 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3338 Values[i] = DAG.getNode( 3339 OpCode, getCurSDLoc(), 3340 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3341 } 3342 } 3343 3344 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3345 DAG.getVTList(ValueVTs), Values)); 3346 } 3347 3348 void SelectionDAGBuilder::visitTrunc(const User &I) { 3349 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3350 SDValue N = getValue(I.getOperand(0)); 3351 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3352 I.getType()); 3353 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3354 } 3355 3356 void SelectionDAGBuilder::visitZExt(const User &I) { 3357 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3358 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3359 SDValue N = getValue(I.getOperand(0)); 3360 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3361 I.getType()); 3362 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3363 } 3364 3365 void SelectionDAGBuilder::visitSExt(const User &I) { 3366 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3367 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3368 SDValue N = getValue(I.getOperand(0)); 3369 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3370 I.getType()); 3371 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3372 } 3373 3374 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3375 // FPTrunc is never a no-op cast, no need to check 3376 SDValue N = getValue(I.getOperand(0)); 3377 SDLoc dl = getCurSDLoc(); 3378 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3379 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3380 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3381 DAG.getTargetConstant( 3382 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3383 } 3384 3385 void SelectionDAGBuilder::visitFPExt(const User &I) { 3386 // FPExt is never a no-op cast, no need to check 3387 SDValue N = getValue(I.getOperand(0)); 3388 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3389 I.getType()); 3390 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3391 } 3392 3393 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3394 // FPToUI is never a no-op cast, no need to check 3395 SDValue N = getValue(I.getOperand(0)); 3396 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3397 I.getType()); 3398 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3399 } 3400 3401 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3402 // FPToSI is never a no-op cast, no need to check 3403 SDValue N = getValue(I.getOperand(0)); 3404 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3405 I.getType()); 3406 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3407 } 3408 3409 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3410 // UIToFP 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::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3415 } 3416 3417 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3418 // SIToFP 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::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3423 } 3424 3425 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3426 // What to do depends on the size of the integer and the size of the pointer. 3427 // We can either truncate, zero extend, or no-op, accordingly. 3428 SDValue N = getValue(I.getOperand(0)); 3429 auto &TLI = DAG.getTargetLoweringInfo(); 3430 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3431 I.getType()); 3432 EVT PtrMemVT = 3433 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3434 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3435 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3436 setValue(&I, N); 3437 } 3438 3439 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3440 // What to do depends on the size of the integer and the size of the pointer. 3441 // We can either truncate, zero extend, or no-op, accordingly. 3442 SDValue N = getValue(I.getOperand(0)); 3443 auto &TLI = DAG.getTargetLoweringInfo(); 3444 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3445 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3446 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3447 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3448 setValue(&I, N); 3449 } 3450 3451 void SelectionDAGBuilder::visitBitCast(const User &I) { 3452 SDValue N = getValue(I.getOperand(0)); 3453 SDLoc dl = getCurSDLoc(); 3454 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3455 I.getType()); 3456 3457 // BitCast assures us that source and destination are the same size so this is 3458 // either a BITCAST or a no-op. 3459 if (DestVT != N.getValueType()) 3460 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3461 DestVT, N)); // convert types. 3462 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3463 // might fold any kind of constant expression to an integer constant and that 3464 // is not what we are looking for. Only recognize a bitcast of a genuine 3465 // constant integer as an opaque constant. 3466 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3467 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3468 /*isOpaque*/true)); 3469 else 3470 setValue(&I, N); // noop cast. 3471 } 3472 3473 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3474 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3475 const Value *SV = I.getOperand(0); 3476 SDValue N = getValue(SV); 3477 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3478 3479 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3480 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3481 3482 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3483 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3484 3485 setValue(&I, N); 3486 } 3487 3488 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3489 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3490 SDValue InVec = getValue(I.getOperand(0)); 3491 SDValue InVal = getValue(I.getOperand(1)); 3492 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3493 TLI.getVectorIdxTy(DAG.getDataLayout())); 3494 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3495 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3496 InVec, InVal, InIdx)); 3497 } 3498 3499 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3500 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3501 SDValue InVec = getValue(I.getOperand(0)); 3502 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3503 TLI.getVectorIdxTy(DAG.getDataLayout())); 3504 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3505 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3506 InVec, InIdx)); 3507 } 3508 3509 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3510 SDValue Src1 = getValue(I.getOperand(0)); 3511 SDValue Src2 = getValue(I.getOperand(1)); 3512 ArrayRef<int> Mask; 3513 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3514 Mask = SVI->getShuffleMask(); 3515 else 3516 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3517 SDLoc DL = getCurSDLoc(); 3518 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3519 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3520 EVT SrcVT = Src1.getValueType(); 3521 3522 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3523 VT.isScalableVector()) { 3524 // Canonical splat form of first element of first input vector. 3525 SDValue FirstElt = 3526 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3527 DAG.getVectorIdxConstant(0, DL)); 3528 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3529 return; 3530 } 3531 3532 // For now, we only handle splats for scalable vectors. 3533 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3534 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3535 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3536 3537 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3538 unsigned MaskNumElts = Mask.size(); 3539 3540 if (SrcNumElts == MaskNumElts) { 3541 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3542 return; 3543 } 3544 3545 // Normalize the shuffle vector since mask and vector length don't match. 3546 if (SrcNumElts < MaskNumElts) { 3547 // Mask is longer than the source vectors. We can use concatenate vector to 3548 // make the mask and vectors lengths match. 3549 3550 if (MaskNumElts % SrcNumElts == 0) { 3551 // Mask length is a multiple of the source vector length. 3552 // Check if the shuffle is some kind of concatenation of the input 3553 // vectors. 3554 unsigned NumConcat = MaskNumElts / SrcNumElts; 3555 bool IsConcat = true; 3556 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3557 for (unsigned i = 0; i != MaskNumElts; ++i) { 3558 int Idx = Mask[i]; 3559 if (Idx < 0) 3560 continue; 3561 // Ensure the indices in each SrcVT sized piece are sequential and that 3562 // the same source is used for the whole piece. 3563 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3564 (ConcatSrcs[i / SrcNumElts] >= 0 && 3565 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3566 IsConcat = false; 3567 break; 3568 } 3569 // Remember which source this index came from. 3570 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3571 } 3572 3573 // The shuffle is concatenating multiple vectors together. Just emit 3574 // a CONCAT_VECTORS operation. 3575 if (IsConcat) { 3576 SmallVector<SDValue, 8> ConcatOps; 3577 for (auto Src : ConcatSrcs) { 3578 if (Src < 0) 3579 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3580 else if (Src == 0) 3581 ConcatOps.push_back(Src1); 3582 else 3583 ConcatOps.push_back(Src2); 3584 } 3585 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3586 return; 3587 } 3588 } 3589 3590 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3591 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3592 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3593 PaddedMaskNumElts); 3594 3595 // Pad both vectors with undefs to make them the same length as the mask. 3596 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3597 3598 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3599 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3600 MOps1[0] = Src1; 3601 MOps2[0] = Src2; 3602 3603 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3604 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3605 3606 // Readjust mask for new input vector length. 3607 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3608 for (unsigned i = 0; i != MaskNumElts; ++i) { 3609 int Idx = Mask[i]; 3610 if (Idx >= (int)SrcNumElts) 3611 Idx -= SrcNumElts - PaddedMaskNumElts; 3612 MappedOps[i] = Idx; 3613 } 3614 3615 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3616 3617 // If the concatenated vector was padded, extract a subvector with the 3618 // correct number of elements. 3619 if (MaskNumElts != PaddedMaskNumElts) 3620 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3621 DAG.getVectorIdxConstant(0, DL)); 3622 3623 setValue(&I, Result); 3624 return; 3625 } 3626 3627 if (SrcNumElts > MaskNumElts) { 3628 // Analyze the access pattern of the vector to see if we can extract 3629 // two subvectors and do the shuffle. 3630 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3631 bool CanExtract = true; 3632 for (int Idx : Mask) { 3633 unsigned Input = 0; 3634 if (Idx < 0) 3635 continue; 3636 3637 if (Idx >= (int)SrcNumElts) { 3638 Input = 1; 3639 Idx -= SrcNumElts; 3640 } 3641 3642 // If all the indices come from the same MaskNumElts sized portion of 3643 // the sources we can use extract. Also make sure the extract wouldn't 3644 // extract past the end of the source. 3645 int NewStartIdx = alignDown(Idx, MaskNumElts); 3646 if (NewStartIdx + MaskNumElts > SrcNumElts || 3647 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3648 CanExtract = false; 3649 // Make sure we always update StartIdx as we use it to track if all 3650 // elements are undef. 3651 StartIdx[Input] = NewStartIdx; 3652 } 3653 3654 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3655 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3656 return; 3657 } 3658 if (CanExtract) { 3659 // Extract appropriate subvector and generate a vector shuffle 3660 for (unsigned Input = 0; Input < 2; ++Input) { 3661 SDValue &Src = Input == 0 ? Src1 : Src2; 3662 if (StartIdx[Input] < 0) 3663 Src = DAG.getUNDEF(VT); 3664 else { 3665 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3666 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3667 } 3668 } 3669 3670 // Calculate new mask. 3671 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3672 for (int &Idx : MappedOps) { 3673 if (Idx >= (int)SrcNumElts) 3674 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3675 else if (Idx >= 0) 3676 Idx -= StartIdx[0]; 3677 } 3678 3679 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3680 return; 3681 } 3682 } 3683 3684 // We can't use either concat vectors or extract subvectors so fall back to 3685 // replacing the shuffle with extract and build vector. 3686 // to insert and build vector. 3687 EVT EltVT = VT.getVectorElementType(); 3688 SmallVector<SDValue,8> Ops; 3689 for (int Idx : Mask) { 3690 SDValue Res; 3691 3692 if (Idx < 0) { 3693 Res = DAG.getUNDEF(EltVT); 3694 } else { 3695 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3696 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3697 3698 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3699 DAG.getVectorIdxConstant(Idx, DL)); 3700 } 3701 3702 Ops.push_back(Res); 3703 } 3704 3705 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3706 } 3707 3708 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3709 ArrayRef<unsigned> Indices; 3710 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3711 Indices = IV->getIndices(); 3712 else 3713 Indices = cast<ConstantExpr>(&I)->getIndices(); 3714 3715 const Value *Op0 = I.getOperand(0); 3716 const Value *Op1 = I.getOperand(1); 3717 Type *AggTy = I.getType(); 3718 Type *ValTy = Op1->getType(); 3719 bool IntoUndef = isa<UndefValue>(Op0); 3720 bool FromUndef = isa<UndefValue>(Op1); 3721 3722 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3723 3724 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3725 SmallVector<EVT, 4> AggValueVTs; 3726 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3727 SmallVector<EVT, 4> ValValueVTs; 3728 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3729 3730 unsigned NumAggValues = AggValueVTs.size(); 3731 unsigned NumValValues = ValValueVTs.size(); 3732 SmallVector<SDValue, 4> Values(NumAggValues); 3733 3734 // Ignore an insertvalue that produces an empty object 3735 if (!NumAggValues) { 3736 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3737 return; 3738 } 3739 3740 SDValue Agg = getValue(Op0); 3741 unsigned i = 0; 3742 // Copy the beginning value(s) from the original aggregate. 3743 for (; i != LinearIndex; ++i) 3744 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3745 SDValue(Agg.getNode(), Agg.getResNo() + i); 3746 // Copy values from the inserted value(s). 3747 if (NumValValues) { 3748 SDValue Val = getValue(Op1); 3749 for (; i != LinearIndex + NumValValues; ++i) 3750 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3751 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3752 } 3753 // Copy remaining value(s) from the original aggregate. 3754 for (; i != NumAggValues; ++i) 3755 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3756 SDValue(Agg.getNode(), Agg.getResNo() + i); 3757 3758 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3759 DAG.getVTList(AggValueVTs), Values)); 3760 } 3761 3762 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3763 ArrayRef<unsigned> Indices; 3764 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3765 Indices = EV->getIndices(); 3766 else 3767 Indices = cast<ConstantExpr>(&I)->getIndices(); 3768 3769 const Value *Op0 = I.getOperand(0); 3770 Type *AggTy = Op0->getType(); 3771 Type *ValTy = I.getType(); 3772 bool OutOfUndef = isa<UndefValue>(Op0); 3773 3774 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3775 3776 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3777 SmallVector<EVT, 4> ValValueVTs; 3778 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3779 3780 unsigned NumValValues = ValValueVTs.size(); 3781 3782 // Ignore a extractvalue that produces an empty object 3783 if (!NumValValues) { 3784 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3785 return; 3786 } 3787 3788 SmallVector<SDValue, 4> Values(NumValValues); 3789 3790 SDValue Agg = getValue(Op0); 3791 // Copy out the selected value(s). 3792 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3793 Values[i - LinearIndex] = 3794 OutOfUndef ? 3795 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3796 SDValue(Agg.getNode(), Agg.getResNo() + i); 3797 3798 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3799 DAG.getVTList(ValValueVTs), Values)); 3800 } 3801 3802 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3803 Value *Op0 = I.getOperand(0); 3804 // Note that the pointer operand may be a vector of pointers. Take the scalar 3805 // element which holds a pointer. 3806 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3807 SDValue N = getValue(Op0); 3808 SDLoc dl = getCurSDLoc(); 3809 auto &TLI = DAG.getTargetLoweringInfo(); 3810 3811 // Normalize Vector GEP - all scalar operands should be converted to the 3812 // splat vector. 3813 bool IsVectorGEP = I.getType()->isVectorTy(); 3814 ElementCount VectorElementCount = 3815 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3816 : ElementCount::getFixed(0); 3817 3818 if (IsVectorGEP && !N.getValueType().isVector()) { 3819 LLVMContext &Context = *DAG.getContext(); 3820 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3821 if (VectorElementCount.isScalable()) 3822 N = DAG.getSplatVector(VT, dl, N); 3823 else 3824 N = DAG.getSplatBuildVector(VT, dl, N); 3825 } 3826 3827 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3828 GTI != E; ++GTI) { 3829 const Value *Idx = GTI.getOperand(); 3830 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3831 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3832 if (Field) { 3833 // N = N + Offset 3834 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3835 3836 // In an inbounds GEP with an offset that is nonnegative even when 3837 // interpreted as signed, assume there is no unsigned overflow. 3838 SDNodeFlags Flags; 3839 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3840 Flags.setNoUnsignedWrap(true); 3841 3842 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3843 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3844 } 3845 } else { 3846 // IdxSize is the width of the arithmetic according to IR semantics. 3847 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3848 // (and fix up the result later). 3849 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3850 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3851 TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType()); 3852 // We intentionally mask away the high bits here; ElementSize may not 3853 // fit in IdxTy. 3854 APInt ElementMul(IdxSize, ElementSize.getKnownMinSize()); 3855 bool ElementScalable = ElementSize.isScalable(); 3856 3857 // If this is a scalar constant or a splat vector of constants, 3858 // handle it quickly. 3859 const auto *C = dyn_cast<Constant>(Idx); 3860 if (C && isa<VectorType>(C->getType())) 3861 C = C->getSplatValue(); 3862 3863 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 3864 if (CI && CI->isZero()) 3865 continue; 3866 if (CI && !ElementScalable) { 3867 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 3868 LLVMContext &Context = *DAG.getContext(); 3869 SDValue OffsVal; 3870 if (IsVectorGEP) 3871 OffsVal = DAG.getConstant( 3872 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 3873 else 3874 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 3875 3876 // In an inbounds GEP with an offset that is nonnegative even when 3877 // interpreted as signed, assume there is no unsigned overflow. 3878 SDNodeFlags Flags; 3879 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3880 Flags.setNoUnsignedWrap(true); 3881 3882 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3883 3884 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3885 continue; 3886 } 3887 3888 // N = N + Idx * ElementMul; 3889 SDValue IdxN = getValue(Idx); 3890 3891 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 3892 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 3893 VectorElementCount); 3894 if (VectorElementCount.isScalable()) 3895 IdxN = DAG.getSplatVector(VT, dl, IdxN); 3896 else 3897 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3898 } 3899 3900 // If the index is smaller or larger than intptr_t, truncate or extend 3901 // it. 3902 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3903 3904 if (ElementScalable) { 3905 EVT VScaleTy = N.getValueType().getScalarType(); 3906 SDValue VScale = DAG.getNode( 3907 ISD::VSCALE, dl, VScaleTy, 3908 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 3909 if (IsVectorGEP) 3910 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 3911 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 3912 } else { 3913 // If this is a multiply by a power of two, turn it into a shl 3914 // immediately. This is a very common case. 3915 if (ElementMul != 1) { 3916 if (ElementMul.isPowerOf2()) { 3917 unsigned Amt = ElementMul.logBase2(); 3918 IdxN = DAG.getNode(ISD::SHL, dl, 3919 N.getValueType(), IdxN, 3920 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3921 } else { 3922 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 3923 IdxN.getValueType()); 3924 IdxN = DAG.getNode(ISD::MUL, dl, 3925 N.getValueType(), IdxN, Scale); 3926 } 3927 } 3928 } 3929 3930 N = DAG.getNode(ISD::ADD, dl, 3931 N.getValueType(), N, IdxN); 3932 } 3933 } 3934 3935 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 3936 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 3937 if (IsVectorGEP) { 3938 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 3939 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 3940 } 3941 3942 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 3943 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 3944 3945 setValue(&I, N); 3946 } 3947 3948 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3949 // If this is a fixed sized alloca in the entry block of the function, 3950 // allocate it statically on the stack. 3951 if (FuncInfo.StaticAllocaMap.count(&I)) 3952 return; // getValue will auto-populate this. 3953 3954 SDLoc dl = getCurSDLoc(); 3955 Type *Ty = I.getAllocatedType(); 3956 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3957 auto &DL = DAG.getDataLayout(); 3958 uint64_t TySize = DL.getTypeAllocSize(Ty); 3959 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 3960 3961 SDValue AllocSize = getValue(I.getArraySize()); 3962 3963 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3964 if (AllocSize.getValueType() != IntPtr) 3965 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3966 3967 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3968 AllocSize, 3969 DAG.getConstant(TySize, dl, IntPtr)); 3970 3971 // Handle alignment. If the requested alignment is less than or equal to 3972 // the stack alignment, ignore it. If the size is greater than or equal to 3973 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3974 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 3975 if (*Alignment <= StackAlign) 3976 Alignment = None; 3977 3978 const uint64_t StackAlignMask = StackAlign.value() - 1U; 3979 // Round the size of the allocation up to the stack alignment size 3980 // by add SA-1 to the size. This doesn't overflow because we're computing 3981 // an address inside an alloca. 3982 SDNodeFlags Flags; 3983 Flags.setNoUnsignedWrap(true); 3984 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 3985 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 3986 3987 // Mask out the low bits for alignment purposes. 3988 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 3989 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 3990 3991 SDValue Ops[] = { 3992 getRoot(), AllocSize, 3993 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 3994 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 3995 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 3996 setValue(&I, DSA); 3997 DAG.setRoot(DSA.getValue(1)); 3998 3999 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4000 } 4001 4002 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4003 if (I.isAtomic()) 4004 return visitAtomicLoad(I); 4005 4006 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4007 const Value *SV = I.getOperand(0); 4008 if (TLI.supportSwiftError()) { 4009 // Swifterror values can come from either a function parameter with 4010 // swifterror attribute or an alloca with swifterror attribute. 4011 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4012 if (Arg->hasSwiftErrorAttr()) 4013 return visitLoadFromSwiftError(I); 4014 } 4015 4016 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4017 if (Alloca->isSwiftError()) 4018 return visitLoadFromSwiftError(I); 4019 } 4020 } 4021 4022 SDValue Ptr = getValue(SV); 4023 4024 Type *Ty = I.getType(); 4025 Align Alignment = I.getAlign(); 4026 4027 AAMDNodes AAInfo; 4028 I.getAAMetadata(AAInfo); 4029 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4030 4031 SmallVector<EVT, 4> ValueVTs, MemVTs; 4032 SmallVector<uint64_t, 4> Offsets; 4033 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4034 unsigned NumValues = ValueVTs.size(); 4035 if (NumValues == 0) 4036 return; 4037 4038 bool isVolatile = I.isVolatile(); 4039 4040 SDValue Root; 4041 bool ConstantMemory = false; 4042 if (isVolatile) 4043 // Serialize volatile loads with other side effects. 4044 Root = getRoot(); 4045 else if (NumValues > MaxParallelChains) 4046 Root = getMemoryRoot(); 4047 else if (AA && 4048 AA->pointsToConstantMemory(MemoryLocation( 4049 SV, 4050 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4051 AAInfo))) { 4052 // Do not serialize (non-volatile) loads of constant memory with anything. 4053 Root = DAG.getEntryNode(); 4054 ConstantMemory = true; 4055 } else { 4056 // Do not serialize non-volatile loads against each other. 4057 Root = DAG.getRoot(); 4058 } 4059 4060 SDLoc dl = getCurSDLoc(); 4061 4062 if (isVolatile) 4063 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4064 4065 // An aggregate load cannot wrap around the address space, so offsets to its 4066 // parts don't wrap either. 4067 SDNodeFlags Flags; 4068 Flags.setNoUnsignedWrap(true); 4069 4070 SmallVector<SDValue, 4> Values(NumValues); 4071 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4072 EVT PtrVT = Ptr.getValueType(); 4073 4074 MachineMemOperand::Flags MMOFlags 4075 = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4076 4077 unsigned ChainI = 0; 4078 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4079 // Serializing loads here may result in excessive register pressure, and 4080 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4081 // could recover a bit by hoisting nodes upward in the chain by recognizing 4082 // they are side-effect free or do not alias. The optimizer should really 4083 // avoid this case by converting large object/array copies to llvm.memcpy 4084 // (MaxParallelChains should always remain as failsafe). 4085 if (ChainI == MaxParallelChains) { 4086 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4087 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4088 makeArrayRef(Chains.data(), ChainI)); 4089 Root = Chain; 4090 ChainI = 0; 4091 } 4092 SDValue A = DAG.getNode(ISD::ADD, dl, 4093 PtrVT, Ptr, 4094 DAG.getConstant(Offsets[i], dl, PtrVT), 4095 Flags); 4096 4097 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4098 MachinePointerInfo(SV, Offsets[i]), Alignment, 4099 MMOFlags, AAInfo, Ranges); 4100 Chains[ChainI] = L.getValue(1); 4101 4102 if (MemVTs[i] != ValueVTs[i]) 4103 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4104 4105 Values[i] = L; 4106 } 4107 4108 if (!ConstantMemory) { 4109 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4110 makeArrayRef(Chains.data(), ChainI)); 4111 if (isVolatile) 4112 DAG.setRoot(Chain); 4113 else 4114 PendingLoads.push_back(Chain); 4115 } 4116 4117 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4118 DAG.getVTList(ValueVTs), Values)); 4119 } 4120 4121 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4122 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4123 "call visitStoreToSwiftError when backend supports swifterror"); 4124 4125 SmallVector<EVT, 4> ValueVTs; 4126 SmallVector<uint64_t, 4> Offsets; 4127 const Value *SrcV = I.getOperand(0); 4128 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4129 SrcV->getType(), ValueVTs, &Offsets); 4130 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4131 "expect a single EVT for swifterror"); 4132 4133 SDValue Src = getValue(SrcV); 4134 // Create a virtual register, then update the virtual register. 4135 Register VReg = 4136 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4137 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4138 // Chain can be getRoot or getControlRoot. 4139 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4140 SDValue(Src.getNode(), Src.getResNo())); 4141 DAG.setRoot(CopyNode); 4142 } 4143 4144 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4145 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4146 "call visitLoadFromSwiftError when backend supports swifterror"); 4147 4148 assert(!I.isVolatile() && 4149 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4150 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4151 "Support volatile, non temporal, invariant for load_from_swift_error"); 4152 4153 const Value *SV = I.getOperand(0); 4154 Type *Ty = I.getType(); 4155 AAMDNodes AAInfo; 4156 I.getAAMetadata(AAInfo); 4157 assert( 4158 (!AA || 4159 !AA->pointsToConstantMemory(MemoryLocation( 4160 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4161 AAInfo))) && 4162 "load_from_swift_error should not be constant memory"); 4163 4164 SmallVector<EVT, 4> ValueVTs; 4165 SmallVector<uint64_t, 4> Offsets; 4166 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4167 ValueVTs, &Offsets); 4168 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4169 "expect a single EVT for swifterror"); 4170 4171 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4172 SDValue L = DAG.getCopyFromReg( 4173 getRoot(), getCurSDLoc(), 4174 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4175 4176 setValue(&I, L); 4177 } 4178 4179 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4180 if (I.isAtomic()) 4181 return visitAtomicStore(I); 4182 4183 const Value *SrcV = I.getOperand(0); 4184 const Value *PtrV = I.getOperand(1); 4185 4186 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4187 if (TLI.supportSwiftError()) { 4188 // Swifterror values can come from either a function parameter with 4189 // swifterror attribute or an alloca with swifterror attribute. 4190 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4191 if (Arg->hasSwiftErrorAttr()) 4192 return visitStoreToSwiftError(I); 4193 } 4194 4195 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4196 if (Alloca->isSwiftError()) 4197 return visitStoreToSwiftError(I); 4198 } 4199 } 4200 4201 SmallVector<EVT, 4> ValueVTs, MemVTs; 4202 SmallVector<uint64_t, 4> Offsets; 4203 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4204 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4205 unsigned NumValues = ValueVTs.size(); 4206 if (NumValues == 0) 4207 return; 4208 4209 // Get the lowered operands. Note that we do this after 4210 // checking if NumResults is zero, because with zero results 4211 // the operands won't have values in the map. 4212 SDValue Src = getValue(SrcV); 4213 SDValue Ptr = getValue(PtrV); 4214 4215 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4216 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4217 SDLoc dl = getCurSDLoc(); 4218 Align Alignment = I.getAlign(); 4219 AAMDNodes AAInfo; 4220 I.getAAMetadata(AAInfo); 4221 4222 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4223 4224 // An aggregate load cannot wrap around the address space, so offsets to its 4225 // parts don't wrap either. 4226 SDNodeFlags Flags; 4227 Flags.setNoUnsignedWrap(true); 4228 4229 unsigned ChainI = 0; 4230 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4231 // See visitLoad comments. 4232 if (ChainI == MaxParallelChains) { 4233 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4234 makeArrayRef(Chains.data(), ChainI)); 4235 Root = Chain; 4236 ChainI = 0; 4237 } 4238 SDValue Add = 4239 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags); 4240 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4241 if (MemVTs[i] != ValueVTs[i]) 4242 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4243 SDValue St = 4244 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4245 Alignment, MMOFlags, AAInfo); 4246 Chains[ChainI] = St; 4247 } 4248 4249 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4250 makeArrayRef(Chains.data(), ChainI)); 4251 DAG.setRoot(StoreNode); 4252 } 4253 4254 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4255 bool IsCompressing) { 4256 SDLoc sdl = getCurSDLoc(); 4257 4258 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4259 MaybeAlign &Alignment) { 4260 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4261 Src0 = I.getArgOperand(0); 4262 Ptr = I.getArgOperand(1); 4263 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4264 Mask = I.getArgOperand(3); 4265 }; 4266 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4267 MaybeAlign &Alignment) { 4268 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4269 Src0 = I.getArgOperand(0); 4270 Ptr = I.getArgOperand(1); 4271 Mask = I.getArgOperand(2); 4272 Alignment = None; 4273 }; 4274 4275 Value *PtrOperand, *MaskOperand, *Src0Operand; 4276 MaybeAlign Alignment; 4277 if (IsCompressing) 4278 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4279 else 4280 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4281 4282 SDValue Ptr = getValue(PtrOperand); 4283 SDValue Src0 = getValue(Src0Operand); 4284 SDValue Mask = getValue(MaskOperand); 4285 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4286 4287 EVT VT = Src0.getValueType(); 4288 if (!Alignment) 4289 Alignment = DAG.getEVTAlign(VT); 4290 4291 AAMDNodes AAInfo; 4292 I.getAAMetadata(AAInfo); 4293 4294 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4295 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4296 // TODO: Make MachineMemOperands aware of scalable 4297 // vectors. 4298 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo); 4299 SDValue StoreNode = 4300 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4301 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4302 DAG.setRoot(StoreNode); 4303 setValue(&I, StoreNode); 4304 } 4305 4306 // Get a uniform base for the Gather/Scatter intrinsic. 4307 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4308 // We try to represent it as a base pointer + vector of indices. 4309 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4310 // The first operand of the GEP may be a single pointer or a vector of pointers 4311 // Example: 4312 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4313 // or 4314 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4315 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4316 // 4317 // When the first GEP operand is a single pointer - it is the uniform base we 4318 // are looking for. If first operand of the GEP is a splat vector - we 4319 // extract the splat value and use it as a uniform base. 4320 // In all other cases the function returns 'false'. 4321 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4322 ISD::MemIndexType &IndexType, SDValue &Scale, 4323 SelectionDAGBuilder *SDB, const BasicBlock *CurBB) { 4324 SelectionDAG& DAG = SDB->DAG; 4325 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4326 const DataLayout &DL = DAG.getDataLayout(); 4327 4328 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 4329 4330 // Handle splat constant pointer. 4331 if (auto *C = dyn_cast<Constant>(Ptr)) { 4332 C = C->getSplatValue(); 4333 if (!C) 4334 return false; 4335 4336 Base = SDB->getValue(C); 4337 4338 unsigned NumElts = cast<FixedVectorType>(Ptr->getType())->getNumElements(); 4339 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4340 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4341 IndexType = ISD::SIGNED_SCALED; 4342 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4343 return true; 4344 } 4345 4346 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4347 if (!GEP || GEP->getParent() != CurBB) 4348 return false; 4349 4350 if (GEP->getNumOperands() != 2) 4351 return false; 4352 4353 const Value *BasePtr = GEP->getPointerOperand(); 4354 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4355 4356 // Make sure the base is scalar and the index is a vector. 4357 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4358 return false; 4359 4360 Base = SDB->getValue(BasePtr); 4361 Index = SDB->getValue(IndexVal); 4362 IndexType = ISD::SIGNED_SCALED; 4363 Scale = DAG.getTargetConstant( 4364 DL.getTypeAllocSize(GEP->getResultElementType()), 4365 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4366 return true; 4367 } 4368 4369 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4370 SDLoc sdl = getCurSDLoc(); 4371 4372 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4373 const Value *Ptr = I.getArgOperand(1); 4374 SDValue Src0 = getValue(I.getArgOperand(0)); 4375 SDValue Mask = getValue(I.getArgOperand(3)); 4376 EVT VT = Src0.getValueType(); 4377 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4378 ->getMaybeAlignValue() 4379 .getValueOr(DAG.getEVTAlign(VT)); 4380 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4381 4382 AAMDNodes AAInfo; 4383 I.getAAMetadata(AAInfo); 4384 4385 SDValue Base; 4386 SDValue Index; 4387 ISD::MemIndexType IndexType; 4388 SDValue Scale; 4389 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4390 I.getParent()); 4391 4392 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4393 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4394 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4395 // TODO: Make MachineMemOperands aware of scalable 4396 // vectors. 4397 MemoryLocation::UnknownSize, Alignment, AAInfo); 4398 if (!UniformBase) { 4399 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4400 Index = getValue(Ptr); 4401 IndexType = ISD::SIGNED_UNSCALED; 4402 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4403 } 4404 4405 EVT IdxVT = Index.getValueType(); 4406 EVT EltTy = IdxVT.getVectorElementType(); 4407 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4408 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4409 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4410 } 4411 4412 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4413 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4414 Ops, MMO, IndexType, false); 4415 DAG.setRoot(Scatter); 4416 setValue(&I, Scatter); 4417 } 4418 4419 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4420 SDLoc sdl = getCurSDLoc(); 4421 4422 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4423 MaybeAlign &Alignment) { 4424 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4425 Ptr = I.getArgOperand(0); 4426 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4427 Mask = I.getArgOperand(2); 4428 Src0 = I.getArgOperand(3); 4429 }; 4430 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4431 MaybeAlign &Alignment) { 4432 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4433 Ptr = I.getArgOperand(0); 4434 Alignment = None; 4435 Mask = I.getArgOperand(1); 4436 Src0 = I.getArgOperand(2); 4437 }; 4438 4439 Value *PtrOperand, *MaskOperand, *Src0Operand; 4440 MaybeAlign Alignment; 4441 if (IsExpanding) 4442 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4443 else 4444 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4445 4446 SDValue Ptr = getValue(PtrOperand); 4447 SDValue Src0 = getValue(Src0Operand); 4448 SDValue Mask = getValue(MaskOperand); 4449 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4450 4451 EVT VT = Src0.getValueType(); 4452 if (!Alignment) 4453 Alignment = DAG.getEVTAlign(VT); 4454 4455 AAMDNodes AAInfo; 4456 I.getAAMetadata(AAInfo); 4457 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4458 4459 // Do not serialize masked loads of constant memory with anything. 4460 MemoryLocation ML; 4461 if (VT.isScalableVector()) 4462 ML = MemoryLocation::getAfter(PtrOperand); 4463 else 4464 ML = MemoryLocation(PtrOperand, LocationSize::precise( 4465 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4466 AAInfo); 4467 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4468 4469 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4470 4471 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4472 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4473 // TODO: Make MachineMemOperands aware of scalable 4474 // vectors. 4475 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges); 4476 4477 SDValue Load = 4478 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4479 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4480 if (AddToChain) 4481 PendingLoads.push_back(Load.getValue(1)); 4482 setValue(&I, Load); 4483 } 4484 4485 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4486 SDLoc sdl = getCurSDLoc(); 4487 4488 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4489 const Value *Ptr = I.getArgOperand(0); 4490 SDValue Src0 = getValue(I.getArgOperand(3)); 4491 SDValue Mask = getValue(I.getArgOperand(2)); 4492 4493 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4494 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4495 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4496 ->getMaybeAlignValue() 4497 .getValueOr(DAG.getEVTAlign(VT)); 4498 4499 AAMDNodes AAInfo; 4500 I.getAAMetadata(AAInfo); 4501 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4502 4503 SDValue Root = DAG.getRoot(); 4504 SDValue Base; 4505 SDValue Index; 4506 ISD::MemIndexType IndexType; 4507 SDValue Scale; 4508 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4509 I.getParent()); 4510 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4511 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4512 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4513 // TODO: Make MachineMemOperands aware of scalable 4514 // vectors. 4515 MemoryLocation::UnknownSize, Alignment, AAInfo, Ranges); 4516 4517 if (!UniformBase) { 4518 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4519 Index = getValue(Ptr); 4520 IndexType = ISD::SIGNED_UNSCALED; 4521 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4522 } 4523 4524 EVT IdxVT = Index.getValueType(); 4525 EVT EltTy = IdxVT.getVectorElementType(); 4526 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4527 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4528 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4529 } 4530 4531 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4532 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4533 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4534 4535 PendingLoads.push_back(Gather.getValue(1)); 4536 setValue(&I, Gather); 4537 } 4538 4539 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4540 SDLoc dl = getCurSDLoc(); 4541 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4542 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4543 SyncScope::ID SSID = I.getSyncScopeID(); 4544 4545 SDValue InChain = getRoot(); 4546 4547 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4548 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4549 4550 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4551 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4552 4553 MachineFunction &MF = DAG.getMachineFunction(); 4554 MachineMemOperand *MMO = MF.getMachineMemOperand( 4555 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4556 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4557 FailureOrdering); 4558 4559 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4560 dl, MemVT, VTs, InChain, 4561 getValue(I.getPointerOperand()), 4562 getValue(I.getCompareOperand()), 4563 getValue(I.getNewValOperand()), MMO); 4564 4565 SDValue OutChain = L.getValue(2); 4566 4567 setValue(&I, L); 4568 DAG.setRoot(OutChain); 4569 } 4570 4571 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4572 SDLoc dl = getCurSDLoc(); 4573 ISD::NodeType NT; 4574 switch (I.getOperation()) { 4575 default: llvm_unreachable("Unknown atomicrmw operation"); 4576 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4577 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4578 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4579 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4580 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4581 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4582 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4583 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4584 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4585 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4586 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4587 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4588 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4589 } 4590 AtomicOrdering Ordering = I.getOrdering(); 4591 SyncScope::ID SSID = I.getSyncScopeID(); 4592 4593 SDValue InChain = getRoot(); 4594 4595 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4596 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4597 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4598 4599 MachineFunction &MF = DAG.getMachineFunction(); 4600 MachineMemOperand *MMO = MF.getMachineMemOperand( 4601 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4602 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4603 4604 SDValue L = 4605 DAG.getAtomic(NT, dl, MemVT, InChain, 4606 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4607 MMO); 4608 4609 SDValue OutChain = L.getValue(1); 4610 4611 setValue(&I, L); 4612 DAG.setRoot(OutChain); 4613 } 4614 4615 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4616 SDLoc dl = getCurSDLoc(); 4617 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4618 SDValue Ops[3]; 4619 Ops[0] = getRoot(); 4620 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4621 TLI.getFenceOperandTy(DAG.getDataLayout())); 4622 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4623 TLI.getFenceOperandTy(DAG.getDataLayout())); 4624 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4625 } 4626 4627 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4628 SDLoc dl = getCurSDLoc(); 4629 AtomicOrdering Order = I.getOrdering(); 4630 SyncScope::ID SSID = I.getSyncScopeID(); 4631 4632 SDValue InChain = getRoot(); 4633 4634 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4635 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4636 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4637 4638 if (!TLI.supportsUnalignedAtomics() && 4639 I.getAlignment() < MemVT.getSizeInBits() / 8) 4640 report_fatal_error("Cannot generate unaligned atomic load"); 4641 4642 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4643 4644 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4645 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4646 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4647 4648 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4649 4650 SDValue Ptr = getValue(I.getPointerOperand()); 4651 4652 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4653 // TODO: Once this is better exercised by tests, it should be merged with 4654 // the normal path for loads to prevent future divergence. 4655 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4656 if (MemVT != VT) 4657 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4658 4659 setValue(&I, L); 4660 SDValue OutChain = L.getValue(1); 4661 if (!I.isUnordered()) 4662 DAG.setRoot(OutChain); 4663 else 4664 PendingLoads.push_back(OutChain); 4665 return; 4666 } 4667 4668 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4669 Ptr, MMO); 4670 4671 SDValue OutChain = L.getValue(1); 4672 if (MemVT != VT) 4673 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4674 4675 setValue(&I, L); 4676 DAG.setRoot(OutChain); 4677 } 4678 4679 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4680 SDLoc dl = getCurSDLoc(); 4681 4682 AtomicOrdering Ordering = I.getOrdering(); 4683 SyncScope::ID SSID = I.getSyncScopeID(); 4684 4685 SDValue InChain = getRoot(); 4686 4687 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4688 EVT MemVT = 4689 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4690 4691 if (I.getAlignment() < MemVT.getSizeInBits() / 8) 4692 report_fatal_error("Cannot generate unaligned atomic store"); 4693 4694 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4695 4696 MachineFunction &MF = DAG.getMachineFunction(); 4697 MachineMemOperand *MMO = MF.getMachineMemOperand( 4698 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4699 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4700 4701 SDValue Val = getValue(I.getValueOperand()); 4702 if (Val.getValueType() != MemVT) 4703 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4704 SDValue Ptr = getValue(I.getPointerOperand()); 4705 4706 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4707 // TODO: Once this is better exercised by tests, it should be merged with 4708 // the normal path for stores to prevent future divergence. 4709 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4710 DAG.setRoot(S); 4711 return; 4712 } 4713 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4714 Ptr, Val, MMO); 4715 4716 4717 DAG.setRoot(OutChain); 4718 } 4719 4720 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4721 /// node. 4722 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4723 unsigned Intrinsic) { 4724 // Ignore the callsite's attributes. A specific call site may be marked with 4725 // readnone, but the lowering code will expect the chain based on the 4726 // definition. 4727 const Function *F = I.getCalledFunction(); 4728 bool HasChain = !F->doesNotAccessMemory(); 4729 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4730 4731 // Build the operand list. 4732 SmallVector<SDValue, 8> Ops; 4733 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4734 if (OnlyLoad) { 4735 // We don't need to serialize loads against other loads. 4736 Ops.push_back(DAG.getRoot()); 4737 } else { 4738 Ops.push_back(getRoot()); 4739 } 4740 } 4741 4742 // Info is set by getTgtMemInstrinsic 4743 TargetLowering::IntrinsicInfo Info; 4744 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4745 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4746 DAG.getMachineFunction(), 4747 Intrinsic); 4748 4749 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4750 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4751 Info.opc == ISD::INTRINSIC_W_CHAIN) 4752 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4753 TLI.getPointerTy(DAG.getDataLayout()))); 4754 4755 // Add all operands of the call to the operand list. 4756 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4757 const Value *Arg = I.getArgOperand(i); 4758 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4759 Ops.push_back(getValue(Arg)); 4760 continue; 4761 } 4762 4763 // Use TargetConstant instead of a regular constant for immarg. 4764 EVT VT = TLI.getValueType(*DL, Arg->getType(), true); 4765 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4766 assert(CI->getBitWidth() <= 64 && 4767 "large intrinsic immediates not handled"); 4768 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4769 } else { 4770 Ops.push_back( 4771 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4772 } 4773 } 4774 4775 SmallVector<EVT, 4> ValueVTs; 4776 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4777 4778 if (HasChain) 4779 ValueVTs.push_back(MVT::Other); 4780 4781 SDVTList VTs = DAG.getVTList(ValueVTs); 4782 4783 // Create the node. 4784 SDValue Result; 4785 if (IsTgtIntrinsic) { 4786 // This is target intrinsic that touches memory 4787 AAMDNodes AAInfo; 4788 I.getAAMetadata(AAInfo); 4789 Result = 4790 DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT, 4791 MachinePointerInfo(Info.ptrVal, Info.offset), 4792 Info.align, Info.flags, Info.size, AAInfo); 4793 } else if (!HasChain) { 4794 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4795 } else if (!I.getType()->isVoidTy()) { 4796 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4797 } else { 4798 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4799 } 4800 4801 if (HasChain) { 4802 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4803 if (OnlyLoad) 4804 PendingLoads.push_back(Chain); 4805 else 4806 DAG.setRoot(Chain); 4807 } 4808 4809 if (!I.getType()->isVoidTy()) { 4810 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4811 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4812 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4813 } else 4814 Result = lowerRangeToAssertZExt(DAG, I, Result); 4815 4816 MaybeAlign Alignment = I.getRetAlign(); 4817 if (!Alignment) 4818 Alignment = F->getAttributes().getRetAlignment(); 4819 // Insert `assertalign` node if there's an alignment. 4820 if (InsertAssertAlign && Alignment) { 4821 Result = 4822 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 4823 } 4824 4825 setValue(&I, Result); 4826 } 4827 } 4828 4829 /// GetSignificand - Get the significand and build it into a floating-point 4830 /// number with exponent of 1: 4831 /// 4832 /// Op = (Op & 0x007fffff) | 0x3f800000; 4833 /// 4834 /// where Op is the hexadecimal representation of floating point value. 4835 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4836 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4837 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4838 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4839 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4840 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4841 } 4842 4843 /// GetExponent - Get the exponent: 4844 /// 4845 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4846 /// 4847 /// where Op is the hexadecimal representation of floating point value. 4848 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4849 const TargetLowering &TLI, const SDLoc &dl) { 4850 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4851 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4852 SDValue t1 = DAG.getNode( 4853 ISD::SRL, dl, MVT::i32, t0, 4854 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4855 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4856 DAG.getConstant(127, dl, MVT::i32)); 4857 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4858 } 4859 4860 /// getF32Constant - Get 32-bit floating point constant. 4861 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4862 const SDLoc &dl) { 4863 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4864 MVT::f32); 4865 } 4866 4867 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4868 SelectionDAG &DAG) { 4869 // TODO: What fast-math-flags should be set on the floating-point nodes? 4870 4871 // IntegerPartOfX = ((int32_t)(t0); 4872 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4873 4874 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4875 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4876 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4877 4878 // IntegerPartOfX <<= 23; 4879 IntegerPartOfX = DAG.getNode( 4880 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4881 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4882 DAG.getDataLayout()))); 4883 4884 SDValue TwoToFractionalPartOfX; 4885 if (LimitFloatPrecision <= 6) { 4886 // For floating-point precision of 6: 4887 // 4888 // TwoToFractionalPartOfX = 4889 // 0.997535578f + 4890 // (0.735607626f + 0.252464424f * x) * x; 4891 // 4892 // error 0.0144103317, which is 6 bits 4893 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4894 getF32Constant(DAG, 0x3e814304, dl)); 4895 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4896 getF32Constant(DAG, 0x3f3c50c8, dl)); 4897 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4898 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4899 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4900 } else if (LimitFloatPrecision <= 12) { 4901 // For floating-point precision of 12: 4902 // 4903 // TwoToFractionalPartOfX = 4904 // 0.999892986f + 4905 // (0.696457318f + 4906 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4907 // 4908 // error 0.000107046256, which is 13 to 14 bits 4909 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4910 getF32Constant(DAG, 0x3da235e3, dl)); 4911 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4912 getF32Constant(DAG, 0x3e65b8f3, dl)); 4913 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4914 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4915 getF32Constant(DAG, 0x3f324b07, dl)); 4916 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4917 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4918 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4919 } else { // LimitFloatPrecision <= 18 4920 // For floating-point precision of 18: 4921 // 4922 // TwoToFractionalPartOfX = 4923 // 0.999999982f + 4924 // (0.693148872f + 4925 // (0.240227044f + 4926 // (0.554906021e-1f + 4927 // (0.961591928e-2f + 4928 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4929 // error 2.47208000*10^(-7), which is better than 18 bits 4930 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4931 getF32Constant(DAG, 0x3924b03e, dl)); 4932 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4933 getF32Constant(DAG, 0x3ab24b87, dl)); 4934 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4935 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4936 getF32Constant(DAG, 0x3c1d8c17, dl)); 4937 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4938 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4939 getF32Constant(DAG, 0x3d634a1d, dl)); 4940 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4941 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4942 getF32Constant(DAG, 0x3e75fe14, dl)); 4943 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4944 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4945 getF32Constant(DAG, 0x3f317234, dl)); 4946 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4947 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4948 getF32Constant(DAG, 0x3f800000, dl)); 4949 } 4950 4951 // Add the exponent into the result in integer domain. 4952 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4953 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4954 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4955 } 4956 4957 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4958 /// limited-precision mode. 4959 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4960 const TargetLowering &TLI, SDNodeFlags Flags) { 4961 if (Op.getValueType() == MVT::f32 && 4962 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4963 4964 // Put the exponent in the right bit position for later addition to the 4965 // final result: 4966 // 4967 // t0 = Op * log2(e) 4968 4969 // TODO: What fast-math-flags should be set here? 4970 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 4971 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 4972 return getLimitedPrecisionExp2(t0, dl, DAG); 4973 } 4974 4975 // No special expansion. 4976 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 4977 } 4978 4979 /// expandLog - Lower a log intrinsic. Handles the special sequences for 4980 /// limited-precision mode. 4981 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4982 const TargetLowering &TLI, SDNodeFlags Flags) { 4983 // TODO: What fast-math-flags should be set on the floating-point nodes? 4984 4985 if (Op.getValueType() == MVT::f32 && 4986 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4987 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4988 4989 // Scale the exponent by log(2). 4990 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4991 SDValue LogOfExponent = 4992 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4993 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 4994 4995 // Get the significand and build it into a floating-point number with 4996 // exponent of 1. 4997 SDValue X = GetSignificand(DAG, Op1, dl); 4998 4999 SDValue LogOfMantissa; 5000 if (LimitFloatPrecision <= 6) { 5001 // For floating-point precision of 6: 5002 // 5003 // LogofMantissa = 5004 // -1.1609546f + 5005 // (1.4034025f - 0.23903021f * x) * x; 5006 // 5007 // error 0.0034276066, which is better than 8 bits 5008 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5009 getF32Constant(DAG, 0xbe74c456, dl)); 5010 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5011 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5012 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5013 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5014 getF32Constant(DAG, 0x3f949a29, dl)); 5015 } else if (LimitFloatPrecision <= 12) { 5016 // For floating-point precision of 12: 5017 // 5018 // LogOfMantissa = 5019 // -1.7417939f + 5020 // (2.8212026f + 5021 // (-1.4699568f + 5022 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5023 // 5024 // error 0.000061011436, which is 14 bits 5025 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5026 getF32Constant(DAG, 0xbd67b6d6, dl)); 5027 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5028 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5029 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5030 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5031 getF32Constant(DAG, 0x3fbc278b, dl)); 5032 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5033 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5034 getF32Constant(DAG, 0x40348e95, dl)); 5035 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5036 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5037 getF32Constant(DAG, 0x3fdef31a, dl)); 5038 } else { // LimitFloatPrecision <= 18 5039 // For floating-point precision of 18: 5040 // 5041 // LogOfMantissa = 5042 // -2.1072184f + 5043 // (4.2372794f + 5044 // (-3.7029485f + 5045 // (2.2781945f + 5046 // (-0.87823314f + 5047 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5048 // 5049 // error 0.0000023660568, which is better than 18 bits 5050 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5051 getF32Constant(DAG, 0xbc91e5ac, dl)); 5052 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5053 getF32Constant(DAG, 0x3e4350aa, dl)); 5054 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5055 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5056 getF32Constant(DAG, 0x3f60d3e3, dl)); 5057 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5058 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5059 getF32Constant(DAG, 0x4011cdf0, dl)); 5060 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5061 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5062 getF32Constant(DAG, 0x406cfd1c, dl)); 5063 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5064 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5065 getF32Constant(DAG, 0x408797cb, dl)); 5066 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5067 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5068 getF32Constant(DAG, 0x4006dcab, dl)); 5069 } 5070 5071 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5072 } 5073 5074 // No special expansion. 5075 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5076 } 5077 5078 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5079 /// limited-precision mode. 5080 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5081 const TargetLowering &TLI, SDNodeFlags Flags) { 5082 // TODO: What fast-math-flags should be set on the floating-point nodes? 5083 5084 if (Op.getValueType() == MVT::f32 && 5085 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5086 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5087 5088 // Get the exponent. 5089 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5090 5091 // Get the significand and build it into a floating-point number with 5092 // exponent of 1. 5093 SDValue X = GetSignificand(DAG, Op1, dl); 5094 5095 // Different possible minimax approximations of significand in 5096 // floating-point for various degrees of accuracy over [1,2]. 5097 SDValue Log2ofMantissa; 5098 if (LimitFloatPrecision <= 6) { 5099 // For floating-point precision of 6: 5100 // 5101 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5102 // 5103 // error 0.0049451742, which is more than 7 bits 5104 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5105 getF32Constant(DAG, 0xbeb08fe0, dl)); 5106 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5107 getF32Constant(DAG, 0x40019463, dl)); 5108 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5109 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5110 getF32Constant(DAG, 0x3fd6633d, dl)); 5111 } else if (LimitFloatPrecision <= 12) { 5112 // For floating-point precision of 12: 5113 // 5114 // Log2ofMantissa = 5115 // -2.51285454f + 5116 // (4.07009056f + 5117 // (-2.12067489f + 5118 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5119 // 5120 // error 0.0000876136000, which is better than 13 bits 5121 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5122 getF32Constant(DAG, 0xbda7262e, dl)); 5123 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5124 getF32Constant(DAG, 0x3f25280b, dl)); 5125 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5126 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5127 getF32Constant(DAG, 0x4007b923, dl)); 5128 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5129 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5130 getF32Constant(DAG, 0x40823e2f, dl)); 5131 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5132 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5133 getF32Constant(DAG, 0x4020d29c, dl)); 5134 } else { // LimitFloatPrecision <= 18 5135 // For floating-point precision of 18: 5136 // 5137 // Log2ofMantissa = 5138 // -3.0400495f + 5139 // (6.1129976f + 5140 // (-5.3420409f + 5141 // (3.2865683f + 5142 // (-1.2669343f + 5143 // (0.27515199f - 5144 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5145 // 5146 // error 0.0000018516, which is better than 18 bits 5147 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5148 getF32Constant(DAG, 0xbcd2769e, dl)); 5149 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5150 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5151 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5152 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5153 getF32Constant(DAG, 0x3fa22ae7, dl)); 5154 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5155 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5156 getF32Constant(DAG, 0x40525723, dl)); 5157 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5158 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5159 getF32Constant(DAG, 0x40aaf200, dl)); 5160 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5161 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5162 getF32Constant(DAG, 0x40c39dad, dl)); 5163 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5164 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5165 getF32Constant(DAG, 0x4042902c, dl)); 5166 } 5167 5168 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5169 } 5170 5171 // No special expansion. 5172 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5173 } 5174 5175 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5176 /// limited-precision mode. 5177 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5178 const TargetLowering &TLI, SDNodeFlags Flags) { 5179 // TODO: What fast-math-flags should be set on the floating-point nodes? 5180 5181 if (Op.getValueType() == MVT::f32 && 5182 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5183 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5184 5185 // Scale the exponent by log10(2) [0.30102999f]. 5186 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5187 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5188 getF32Constant(DAG, 0x3e9a209a, dl)); 5189 5190 // Get the significand and build it into a floating-point number with 5191 // exponent of 1. 5192 SDValue X = GetSignificand(DAG, Op1, dl); 5193 5194 SDValue Log10ofMantissa; 5195 if (LimitFloatPrecision <= 6) { 5196 // For floating-point precision of 6: 5197 // 5198 // Log10ofMantissa = 5199 // -0.50419619f + 5200 // (0.60948995f - 0.10380950f * x) * x; 5201 // 5202 // error 0.0014886165, which is 6 bits 5203 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5204 getF32Constant(DAG, 0xbdd49a13, dl)); 5205 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5206 getF32Constant(DAG, 0x3f1c0789, dl)); 5207 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5208 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5209 getF32Constant(DAG, 0x3f011300, dl)); 5210 } else if (LimitFloatPrecision <= 12) { 5211 // For floating-point precision of 12: 5212 // 5213 // Log10ofMantissa = 5214 // -0.64831180f + 5215 // (0.91751397f + 5216 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5217 // 5218 // error 0.00019228036, which is better than 12 bits 5219 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5220 getF32Constant(DAG, 0x3d431f31, dl)); 5221 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5222 getF32Constant(DAG, 0x3ea21fb2, dl)); 5223 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5224 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5225 getF32Constant(DAG, 0x3f6ae232, dl)); 5226 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5227 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5228 getF32Constant(DAG, 0x3f25f7c3, dl)); 5229 } else { // LimitFloatPrecision <= 18 5230 // For floating-point precision of 18: 5231 // 5232 // Log10ofMantissa = 5233 // -0.84299375f + 5234 // (1.5327582f + 5235 // (-1.0688956f + 5236 // (0.49102474f + 5237 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5238 // 5239 // error 0.0000037995730, which is better than 18 bits 5240 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5241 getF32Constant(DAG, 0x3c5d51ce, dl)); 5242 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5243 getF32Constant(DAG, 0x3e00685a, dl)); 5244 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5245 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5246 getF32Constant(DAG, 0x3efb6798, dl)); 5247 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5248 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5249 getF32Constant(DAG, 0x3f88d192, dl)); 5250 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5251 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5252 getF32Constant(DAG, 0x3fc4316c, dl)); 5253 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5254 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5255 getF32Constant(DAG, 0x3f57ce70, dl)); 5256 } 5257 5258 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5259 } 5260 5261 // No special expansion. 5262 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5263 } 5264 5265 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5266 /// limited-precision mode. 5267 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5268 const TargetLowering &TLI, SDNodeFlags Flags) { 5269 if (Op.getValueType() == MVT::f32 && 5270 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5271 return getLimitedPrecisionExp2(Op, dl, DAG); 5272 5273 // No special expansion. 5274 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5275 } 5276 5277 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5278 /// limited-precision mode with x == 10.0f. 5279 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5280 SelectionDAG &DAG, const TargetLowering &TLI, 5281 SDNodeFlags Flags) { 5282 bool IsExp10 = false; 5283 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5284 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5285 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5286 APFloat Ten(10.0f); 5287 IsExp10 = LHSC->isExactlyValue(Ten); 5288 } 5289 } 5290 5291 // TODO: What fast-math-flags should be set on the FMUL node? 5292 if (IsExp10) { 5293 // Put the exponent in the right bit position for later addition to the 5294 // final result: 5295 // 5296 // #define LOG2OF10 3.3219281f 5297 // t0 = Op * LOG2OF10; 5298 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5299 getF32Constant(DAG, 0x40549a78, dl)); 5300 return getLimitedPrecisionExp2(t0, dl, DAG); 5301 } 5302 5303 // No special expansion. 5304 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5305 } 5306 5307 /// ExpandPowI - Expand a llvm.powi intrinsic. 5308 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5309 SelectionDAG &DAG) { 5310 // If RHS is a constant, we can expand this out to a multiplication tree, 5311 // otherwise we end up lowering to a call to __powidf2 (for example). When 5312 // optimizing for size, we only want to do this if the expansion would produce 5313 // a small number of multiplies, otherwise we do the full expansion. 5314 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5315 // Get the exponent as a positive value. 5316 unsigned Val = RHSC->getSExtValue(); 5317 if ((int)Val < 0) Val = -Val; 5318 5319 // powi(x, 0) -> 1.0 5320 if (Val == 0) 5321 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5322 5323 bool OptForSize = DAG.shouldOptForSize(); 5324 if (!OptForSize || 5325 // If optimizing for size, don't insert too many multiplies. 5326 // This inserts up to 5 multiplies. 5327 countPopulation(Val) + Log2_32(Val) < 7) { 5328 // We use the simple binary decomposition method to generate the multiply 5329 // sequence. There are more optimal ways to do this (for example, 5330 // powi(x,15) generates one more multiply than it should), but this has 5331 // the benefit of being both really simple and much better than a libcall. 5332 SDValue Res; // Logically starts equal to 1.0 5333 SDValue CurSquare = LHS; 5334 // TODO: Intrinsics should have fast-math-flags that propagate to these 5335 // nodes. 5336 while (Val) { 5337 if (Val & 1) { 5338 if (Res.getNode()) 5339 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 5340 else 5341 Res = CurSquare; // 1.0*CurSquare. 5342 } 5343 5344 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5345 CurSquare, CurSquare); 5346 Val >>= 1; 5347 } 5348 5349 // If the original was negative, invert the result, producing 1/(x*x*x). 5350 if (RHSC->getSExtValue() < 0) 5351 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5352 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5353 return Res; 5354 } 5355 } 5356 5357 // Otherwise, expand to a libcall. 5358 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5359 } 5360 5361 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5362 SDValue LHS, SDValue RHS, SDValue Scale, 5363 SelectionDAG &DAG, const TargetLowering &TLI) { 5364 EVT VT = LHS.getValueType(); 5365 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5366 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5367 LLVMContext &Ctx = *DAG.getContext(); 5368 5369 // If the type is legal but the operation isn't, this node might survive all 5370 // the way to operation legalization. If we end up there and we do not have 5371 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5372 // node. 5373 5374 // Coax the legalizer into expanding the node during type legalization instead 5375 // by bumping the size by one bit. This will force it to Promote, enabling the 5376 // early expansion and avoiding the need to expand later. 5377 5378 // We don't have to do this if Scale is 0; that can always be expanded, unless 5379 // it's a saturating signed operation. Those can experience true integer 5380 // division overflow, a case which we must avoid. 5381 5382 // FIXME: We wouldn't have to do this (or any of the early 5383 // expansion/promotion) if it was possible to expand a libcall of an 5384 // illegal type during operation legalization. But it's not, so things 5385 // get a bit hacky. 5386 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5387 if ((ScaleInt > 0 || (Saturating && Signed)) && 5388 (TLI.isTypeLegal(VT) || 5389 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5390 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5391 Opcode, VT, ScaleInt); 5392 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5393 EVT PromVT; 5394 if (VT.isScalarInteger()) 5395 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5396 else if (VT.isVector()) { 5397 PromVT = VT.getVectorElementType(); 5398 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5399 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5400 } else 5401 llvm_unreachable("Wrong VT for DIVFIX?"); 5402 if (Signed) { 5403 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5404 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5405 } else { 5406 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5407 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5408 } 5409 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5410 // For saturating operations, we need to shift up the LHS to get the 5411 // proper saturation width, and then shift down again afterwards. 5412 if (Saturating) 5413 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5414 DAG.getConstant(1, DL, ShiftTy)); 5415 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5416 if (Saturating) 5417 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5418 DAG.getConstant(1, DL, ShiftTy)); 5419 return DAG.getZExtOrTrunc(Res, DL, VT); 5420 } 5421 } 5422 5423 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5424 } 5425 5426 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5427 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5428 static void 5429 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5430 const SDValue &N) { 5431 switch (N.getOpcode()) { 5432 case ISD::CopyFromReg: { 5433 SDValue Op = N.getOperand(1); 5434 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5435 Op.getValueType().getSizeInBits()); 5436 return; 5437 } 5438 case ISD::BITCAST: 5439 case ISD::AssertZext: 5440 case ISD::AssertSext: 5441 case ISD::TRUNCATE: 5442 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5443 return; 5444 case ISD::BUILD_PAIR: 5445 case ISD::BUILD_VECTOR: 5446 case ISD::CONCAT_VECTORS: 5447 for (SDValue Op : N->op_values()) 5448 getUnderlyingArgRegs(Regs, Op); 5449 return; 5450 default: 5451 return; 5452 } 5453 } 5454 5455 /// If the DbgValueInst is a dbg_value of a function argument, create the 5456 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5457 /// instruction selection, they will be inserted to the entry BB. 5458 /// We don't currently support this for variadic dbg_values, as they shouldn't 5459 /// appear for function arguments or in the prologue. 5460 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5461 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5462 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 5463 const Argument *Arg = dyn_cast<Argument>(V); 5464 if (!Arg) 5465 return false; 5466 5467 if (!IsDbgDeclare) { 5468 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5469 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5470 // the entry block. 5471 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5472 if (!IsInEntryBlock) 5473 return false; 5474 5475 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5476 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5477 // variable that also is a param. 5478 // 5479 // Although, if we are at the top of the entry block already, we can still 5480 // emit using ArgDbgValue. This might catch some situations when the 5481 // dbg.value refers to an argument that isn't used in the entry block, so 5482 // any CopyToReg node would be optimized out and the only way to express 5483 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5484 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5485 // we should only emit as ArgDbgValue if the Variable is an argument to the 5486 // current function, and the dbg.value intrinsic is found in the entry 5487 // block. 5488 bool VariableIsFunctionInputArg = Variable->isParameter() && 5489 !DL->getInlinedAt(); 5490 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5491 if (!IsInPrologue && !VariableIsFunctionInputArg) 5492 return false; 5493 5494 // Here we assume that a function argument on IR level only can be used to 5495 // describe one input parameter on source level. If we for example have 5496 // source code like this 5497 // 5498 // struct A { long x, y; }; 5499 // void foo(struct A a, long b) { 5500 // ... 5501 // b = a.x; 5502 // ... 5503 // } 5504 // 5505 // and IR like this 5506 // 5507 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5508 // entry: 5509 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5510 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5511 // call void @llvm.dbg.value(metadata i32 %b, "b", 5512 // ... 5513 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5514 // ... 5515 // 5516 // then the last dbg.value is describing a parameter "b" using a value that 5517 // is an argument. But since we already has used %a1 to describe a parameter 5518 // we should not handle that last dbg.value here (that would result in an 5519 // incorrect hoisting of the DBG_VALUE to the function entry). 5520 // Notice that we allow one dbg.value per IR level argument, to accommodate 5521 // for the situation with fragments above. 5522 if (VariableIsFunctionInputArg) { 5523 unsigned ArgNo = Arg->getArgNo(); 5524 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5525 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5526 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5527 return false; 5528 FuncInfo.DescribedArgs.set(ArgNo); 5529 } 5530 } 5531 5532 MachineFunction &MF = DAG.getMachineFunction(); 5533 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5534 5535 bool IsIndirect = false; 5536 Optional<MachineOperand> Op; 5537 // Some arguments' frame index is recorded during argument lowering. 5538 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5539 if (FI != std::numeric_limits<int>::max()) 5540 Op = MachineOperand::CreateFI(FI); 5541 5542 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 5543 if (!Op && N.getNode()) { 5544 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5545 Register Reg; 5546 if (ArgRegsAndSizes.size() == 1) 5547 Reg = ArgRegsAndSizes.front().first; 5548 5549 if (Reg && Reg.isVirtual()) { 5550 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5551 Register PR = RegInfo.getLiveInPhysReg(Reg); 5552 if (PR) 5553 Reg = PR; 5554 } 5555 if (Reg) { 5556 Op = MachineOperand::CreateReg(Reg, false); 5557 IsIndirect = IsDbgDeclare; 5558 } 5559 } 5560 5561 if (!Op && N.getNode()) { 5562 // Check if frame index is available. 5563 SDValue LCandidate = peekThroughBitcasts(N); 5564 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5565 if (FrameIndexSDNode *FINode = 5566 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5567 Op = MachineOperand::CreateFI(FINode->getIndex()); 5568 } 5569 5570 if (!Op) { 5571 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5572 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 5573 SplitRegs) { 5574 unsigned Offset = 0; 5575 for (auto RegAndSize : SplitRegs) { 5576 // If the expression is already a fragment, the current register 5577 // offset+size might extend beyond the fragment. In this case, only 5578 // the register bits that are inside the fragment are relevant. 5579 int RegFragmentSizeInBits = RegAndSize.second; 5580 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5581 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5582 // The register is entirely outside the expression fragment, 5583 // so is irrelevant for debug info. 5584 if (Offset >= ExprFragmentSizeInBits) 5585 break; 5586 // The register is partially outside the expression fragment, only 5587 // the low bits within the fragment are relevant for debug info. 5588 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5589 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5590 } 5591 } 5592 5593 auto FragmentExpr = DIExpression::createFragmentExpression( 5594 Expr, Offset, RegFragmentSizeInBits); 5595 Offset += RegAndSize.second; 5596 // If a valid fragment expression cannot be created, the variable's 5597 // correct value cannot be determined and so it is set as Undef. 5598 if (!FragmentExpr) { 5599 SDDbgValue *SDV = DAG.getConstantDbgValue( 5600 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5601 DAG.AddDbgValue(SDV, false); 5602 continue; 5603 } 5604 assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?"); 5605 FuncInfo.ArgDbgValues.push_back( 5606 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare, 5607 RegAndSize.first, Variable, *FragmentExpr)); 5608 } 5609 }; 5610 5611 // Check if ValueMap has reg number. 5612 DenseMap<const Value *, Register>::const_iterator 5613 VMI = FuncInfo.ValueMap.find(V); 5614 if (VMI != FuncInfo.ValueMap.end()) { 5615 const auto &TLI = DAG.getTargetLoweringInfo(); 5616 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5617 V->getType(), None); 5618 if (RFV.occupiesMultipleRegs()) { 5619 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5620 return true; 5621 } 5622 5623 Op = MachineOperand::CreateReg(VMI->second, false); 5624 IsIndirect = IsDbgDeclare; 5625 } else if (ArgRegsAndSizes.size() > 1) { 5626 // This was split due to the calling convention, and no virtual register 5627 // mapping exists for the value. 5628 splitMultiRegDbgValue(ArgRegsAndSizes); 5629 return true; 5630 } 5631 } 5632 5633 if (!Op) 5634 return false; 5635 5636 assert(Variable->isValidLocationForIntrinsic(DL) && 5637 "Expected inlined-at fields to agree"); 5638 IsIndirect = (Op->isReg()) ? IsIndirect : true; 5639 FuncInfo.ArgDbgValues.push_back( 5640 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 5641 *Op, Variable, Expr)); 5642 5643 return true; 5644 } 5645 5646 /// Return the appropriate SDDbgValue based on N. 5647 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5648 DILocalVariable *Variable, 5649 DIExpression *Expr, 5650 const DebugLoc &dl, 5651 unsigned DbgSDNodeOrder) { 5652 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5653 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5654 // stack slot locations. 5655 // 5656 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5657 // debug values here after optimization: 5658 // 5659 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5660 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5661 // 5662 // Both describe the direct values of their associated variables. 5663 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5664 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5665 } 5666 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5667 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5668 } 5669 5670 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5671 switch (Intrinsic) { 5672 case Intrinsic::smul_fix: 5673 return ISD::SMULFIX; 5674 case Intrinsic::umul_fix: 5675 return ISD::UMULFIX; 5676 case Intrinsic::smul_fix_sat: 5677 return ISD::SMULFIXSAT; 5678 case Intrinsic::umul_fix_sat: 5679 return ISD::UMULFIXSAT; 5680 case Intrinsic::sdiv_fix: 5681 return ISD::SDIVFIX; 5682 case Intrinsic::udiv_fix: 5683 return ISD::UDIVFIX; 5684 case Intrinsic::sdiv_fix_sat: 5685 return ISD::SDIVFIXSAT; 5686 case Intrinsic::udiv_fix_sat: 5687 return ISD::UDIVFIXSAT; 5688 default: 5689 llvm_unreachable("Unhandled fixed point intrinsic"); 5690 } 5691 } 5692 5693 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5694 const char *FunctionName) { 5695 assert(FunctionName && "FunctionName must not be nullptr"); 5696 SDValue Callee = DAG.getExternalSymbol( 5697 FunctionName, 5698 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5699 LowerCallTo(I, Callee, I.isTailCall()); 5700 } 5701 5702 /// Given a @llvm.call.preallocated.setup, return the corresponding 5703 /// preallocated call. 5704 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5705 assert(cast<CallBase>(PreallocatedSetup) 5706 ->getCalledFunction() 5707 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5708 "expected call_preallocated_setup Value"); 5709 for (auto *U : PreallocatedSetup->users()) { 5710 auto *UseCall = cast<CallBase>(U); 5711 const Function *Fn = UseCall->getCalledFunction(); 5712 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5713 return UseCall; 5714 } 5715 } 5716 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5717 } 5718 5719 /// Lower the call to the specified intrinsic function. 5720 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5721 unsigned Intrinsic) { 5722 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5723 SDLoc sdl = getCurSDLoc(); 5724 DebugLoc dl = getCurDebugLoc(); 5725 SDValue Res; 5726 5727 SDNodeFlags Flags; 5728 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 5729 Flags.copyFMF(*FPOp); 5730 5731 switch (Intrinsic) { 5732 default: 5733 // By default, turn this into a target intrinsic node. 5734 visitTargetIntrinsic(I, Intrinsic); 5735 return; 5736 case Intrinsic::vscale: { 5737 match(&I, m_VScale(DAG.getDataLayout())); 5738 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5739 setValue(&I, 5740 DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1))); 5741 return; 5742 } 5743 case Intrinsic::vastart: visitVAStart(I); return; 5744 case Intrinsic::vaend: visitVAEnd(I); return; 5745 case Intrinsic::vacopy: visitVACopy(I); return; 5746 case Intrinsic::returnaddress: 5747 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5748 TLI.getPointerTy(DAG.getDataLayout()), 5749 getValue(I.getArgOperand(0)))); 5750 return; 5751 case Intrinsic::addressofreturnaddress: 5752 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5753 TLI.getPointerTy(DAG.getDataLayout()))); 5754 return; 5755 case Intrinsic::sponentry: 5756 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5757 TLI.getFrameIndexTy(DAG.getDataLayout()))); 5758 return; 5759 case Intrinsic::frameaddress: 5760 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5761 TLI.getFrameIndexTy(DAG.getDataLayout()), 5762 getValue(I.getArgOperand(0)))); 5763 return; 5764 case Intrinsic::read_volatile_register: 5765 case Intrinsic::read_register: { 5766 Value *Reg = I.getArgOperand(0); 5767 SDValue Chain = getRoot(); 5768 SDValue RegName = 5769 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5770 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5771 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5772 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5773 setValue(&I, Res); 5774 DAG.setRoot(Res.getValue(1)); 5775 return; 5776 } 5777 case Intrinsic::write_register: { 5778 Value *Reg = I.getArgOperand(0); 5779 Value *RegValue = I.getArgOperand(1); 5780 SDValue Chain = getRoot(); 5781 SDValue RegName = 5782 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5783 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5784 RegName, getValue(RegValue))); 5785 return; 5786 } 5787 case Intrinsic::memcpy: { 5788 const auto &MCI = cast<MemCpyInst>(I); 5789 SDValue Op1 = getValue(I.getArgOperand(0)); 5790 SDValue Op2 = getValue(I.getArgOperand(1)); 5791 SDValue Op3 = getValue(I.getArgOperand(2)); 5792 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5793 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5794 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5795 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5796 bool isVol = MCI.isVolatile(); 5797 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5798 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5799 // node. 5800 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5801 SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5802 /* AlwaysInline */ false, isTC, 5803 MachinePointerInfo(I.getArgOperand(0)), 5804 MachinePointerInfo(I.getArgOperand(1))); 5805 updateDAGForMaybeTailCall(MC); 5806 return; 5807 } 5808 case Intrinsic::memcpy_inline: { 5809 const auto &MCI = cast<MemCpyInlineInst>(I); 5810 SDValue Dst = getValue(I.getArgOperand(0)); 5811 SDValue Src = getValue(I.getArgOperand(1)); 5812 SDValue Size = getValue(I.getArgOperand(2)); 5813 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 5814 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 5815 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5816 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5817 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5818 bool isVol = MCI.isVolatile(); 5819 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5820 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5821 // node. 5822 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 5823 /* AlwaysInline */ true, isTC, 5824 MachinePointerInfo(I.getArgOperand(0)), 5825 MachinePointerInfo(I.getArgOperand(1))); 5826 updateDAGForMaybeTailCall(MC); 5827 return; 5828 } 5829 case Intrinsic::memset: { 5830 const auto &MSI = cast<MemSetInst>(I); 5831 SDValue Op1 = getValue(I.getArgOperand(0)); 5832 SDValue Op2 = getValue(I.getArgOperand(1)); 5833 SDValue Op3 = getValue(I.getArgOperand(2)); 5834 // @llvm.memset defines 0 and 1 to both mean no alignment. 5835 Align Alignment = MSI.getDestAlign().valueOrOne(); 5836 bool isVol = MSI.isVolatile(); 5837 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5838 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5839 SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC, 5840 MachinePointerInfo(I.getArgOperand(0))); 5841 updateDAGForMaybeTailCall(MS); 5842 return; 5843 } 5844 case Intrinsic::memmove: { 5845 const auto &MMI = cast<MemMoveInst>(I); 5846 SDValue Op1 = getValue(I.getArgOperand(0)); 5847 SDValue Op2 = getValue(I.getArgOperand(1)); 5848 SDValue Op3 = getValue(I.getArgOperand(2)); 5849 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5850 Align DstAlign = MMI.getDestAlign().valueOrOne(); 5851 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 5852 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5853 bool isVol = MMI.isVolatile(); 5854 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5855 // FIXME: Support passing different dest/src alignments to the memmove DAG 5856 // node. 5857 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5858 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5859 isTC, MachinePointerInfo(I.getArgOperand(0)), 5860 MachinePointerInfo(I.getArgOperand(1))); 5861 updateDAGForMaybeTailCall(MM); 5862 return; 5863 } 5864 case Intrinsic::memcpy_element_unordered_atomic: { 5865 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5866 SDValue Dst = getValue(MI.getRawDest()); 5867 SDValue Src = getValue(MI.getRawSource()); 5868 SDValue Length = getValue(MI.getLength()); 5869 5870 unsigned DstAlign = MI.getDestAlignment(); 5871 unsigned SrcAlign = MI.getSourceAlignment(); 5872 Type *LengthTy = MI.getLength()->getType(); 5873 unsigned ElemSz = MI.getElementSizeInBytes(); 5874 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5875 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5876 SrcAlign, Length, LengthTy, ElemSz, isTC, 5877 MachinePointerInfo(MI.getRawDest()), 5878 MachinePointerInfo(MI.getRawSource())); 5879 updateDAGForMaybeTailCall(MC); 5880 return; 5881 } 5882 case Intrinsic::memmove_element_unordered_atomic: { 5883 auto &MI = cast<AtomicMemMoveInst>(I); 5884 SDValue Dst = getValue(MI.getRawDest()); 5885 SDValue Src = getValue(MI.getRawSource()); 5886 SDValue Length = getValue(MI.getLength()); 5887 5888 unsigned DstAlign = MI.getDestAlignment(); 5889 unsigned SrcAlign = MI.getSourceAlignment(); 5890 Type *LengthTy = MI.getLength()->getType(); 5891 unsigned ElemSz = MI.getElementSizeInBytes(); 5892 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5893 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5894 SrcAlign, Length, LengthTy, ElemSz, isTC, 5895 MachinePointerInfo(MI.getRawDest()), 5896 MachinePointerInfo(MI.getRawSource())); 5897 updateDAGForMaybeTailCall(MC); 5898 return; 5899 } 5900 case Intrinsic::memset_element_unordered_atomic: { 5901 auto &MI = cast<AtomicMemSetInst>(I); 5902 SDValue Dst = getValue(MI.getRawDest()); 5903 SDValue Val = getValue(MI.getValue()); 5904 SDValue Length = getValue(MI.getLength()); 5905 5906 unsigned DstAlign = MI.getDestAlignment(); 5907 Type *LengthTy = MI.getLength()->getType(); 5908 unsigned ElemSz = MI.getElementSizeInBytes(); 5909 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5910 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5911 LengthTy, ElemSz, isTC, 5912 MachinePointerInfo(MI.getRawDest())); 5913 updateDAGForMaybeTailCall(MC); 5914 return; 5915 } 5916 case Intrinsic::call_preallocated_setup: { 5917 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 5918 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 5919 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 5920 getRoot(), SrcValue); 5921 setValue(&I, Res); 5922 DAG.setRoot(Res); 5923 return; 5924 } 5925 case Intrinsic::call_preallocated_arg: { 5926 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 5927 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 5928 SDValue Ops[3]; 5929 Ops[0] = getRoot(); 5930 Ops[1] = SrcValue; 5931 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 5932 MVT::i32); // arg index 5933 SDValue Res = DAG.getNode( 5934 ISD::PREALLOCATED_ARG, sdl, 5935 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 5936 setValue(&I, Res); 5937 DAG.setRoot(Res.getValue(1)); 5938 return; 5939 } 5940 case Intrinsic::dbg_addr: 5941 case Intrinsic::dbg_declare: { 5942 // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e. 5943 // they are non-variadic. 5944 const auto &DI = cast<DbgVariableIntrinsic>(I); 5945 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 5946 DILocalVariable *Variable = DI.getVariable(); 5947 DIExpression *Expression = DI.getExpression(); 5948 dropDanglingDebugInfo(Variable, Expression); 5949 assert(Variable && "Missing variable"); 5950 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 5951 << "\n"); 5952 // Check if address has undef value. 5953 const Value *Address = DI.getVariableLocationOp(0); 5954 if (!Address || isa<UndefValue>(Address) || 5955 (Address->use_empty() && !isa<Argument>(Address))) { 5956 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 5957 << " (bad/undef/unused-arg address)\n"); 5958 return; 5959 } 5960 5961 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5962 5963 // Check if this variable can be described by a frame index, typically 5964 // either as a static alloca or a byval parameter. 5965 int FI = std::numeric_limits<int>::max(); 5966 if (const auto *AI = 5967 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5968 if (AI->isStaticAlloca()) { 5969 auto I = FuncInfo.StaticAllocaMap.find(AI); 5970 if (I != FuncInfo.StaticAllocaMap.end()) 5971 FI = I->second; 5972 } 5973 } else if (const auto *Arg = dyn_cast<Argument>( 5974 Address->stripInBoundsConstantOffsets())) { 5975 FI = FuncInfo.getArgumentFrameIndex(Arg); 5976 } 5977 5978 // llvm.dbg.addr is control dependent and always generates indirect 5979 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5980 // the MachineFunction variable table. 5981 if (FI != std::numeric_limits<int>::max()) { 5982 if (Intrinsic == Intrinsic::dbg_addr) { 5983 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 5984 Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true, 5985 dl, SDNodeOrder); 5986 DAG.AddDbgValue(SDV, isParameter); 5987 } else { 5988 LLVM_DEBUG(dbgs() << "Skipping " << DI 5989 << " (variable info stashed in MF side table)\n"); 5990 } 5991 return; 5992 } 5993 5994 SDValue &N = NodeMap[Address]; 5995 if (!N.getNode() && isa<Argument>(Address)) 5996 // Check unused arguments map. 5997 N = UnusedArgNodeMap[Address]; 5998 SDDbgValue *SDV; 5999 if (N.getNode()) { 6000 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 6001 Address = BCI->getOperand(0); 6002 // Parameters are handled specially. 6003 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 6004 if (isParameter && FINode) { 6005 // Byval parameter. We have a frame index at this point. 6006 SDV = 6007 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 6008 /*IsIndirect*/ true, dl, SDNodeOrder); 6009 } else if (isa<Argument>(Address)) { 6010 // Address is an argument, so try to emit its dbg value using 6011 // virtual register info from the FuncInfo.ValueMap. 6012 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 6013 return; 6014 } else { 6015 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 6016 true, dl, SDNodeOrder); 6017 } 6018 DAG.AddDbgValue(SDV, isParameter); 6019 } else { 6020 // If Address is an argument then try to emit its dbg value using 6021 // virtual register info from the FuncInfo.ValueMap. 6022 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 6023 N)) { 6024 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6025 << " (could not emit func-arg dbg_value)\n"); 6026 } 6027 } 6028 return; 6029 } 6030 case Intrinsic::dbg_label: { 6031 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6032 DILabel *Label = DI.getLabel(); 6033 assert(Label && "Missing label"); 6034 6035 SDDbgLabel *SDV; 6036 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6037 DAG.AddDbgLabel(SDV); 6038 return; 6039 } 6040 case Intrinsic::dbg_value: { 6041 const DbgValueInst &DI = cast<DbgValueInst>(I); 6042 assert(DI.getVariable() && "Missing variable"); 6043 6044 DILocalVariable *Variable = DI.getVariable(); 6045 DIExpression *Expression = DI.getExpression(); 6046 dropDanglingDebugInfo(Variable, Expression); 6047 SmallVector<Value *> Values(DI.getValues()); 6048 if (Values.empty()) 6049 return; 6050 6051 if (std::count(Values.begin(), Values.end(), nullptr)) 6052 return; 6053 6054 bool IsVariadic = DI.hasArgList(); 6055 if (!handleDebugValue(Values, Variable, Expression, dl, DI.getDebugLoc(), 6056 SDNodeOrder, IsVariadic)) 6057 addDanglingDebugInfo(&DI, dl, SDNodeOrder); 6058 return; 6059 } 6060 6061 case Intrinsic::eh_typeid_for: { 6062 // Find the type id for the given typeinfo. 6063 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6064 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6065 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6066 setValue(&I, Res); 6067 return; 6068 } 6069 6070 case Intrinsic::eh_return_i32: 6071 case Intrinsic::eh_return_i64: 6072 DAG.getMachineFunction().setCallsEHReturn(true); 6073 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6074 MVT::Other, 6075 getControlRoot(), 6076 getValue(I.getArgOperand(0)), 6077 getValue(I.getArgOperand(1)))); 6078 return; 6079 case Intrinsic::eh_unwind_init: 6080 DAG.getMachineFunction().setCallsUnwindInit(true); 6081 return; 6082 case Intrinsic::eh_dwarf_cfa: 6083 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6084 TLI.getPointerTy(DAG.getDataLayout()), 6085 getValue(I.getArgOperand(0)))); 6086 return; 6087 case Intrinsic::eh_sjlj_callsite: { 6088 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6089 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 6090 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 6091 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6092 6093 MMI.setCurrentCallSite(CI->getZExtValue()); 6094 return; 6095 } 6096 case Intrinsic::eh_sjlj_functioncontext: { 6097 // Get and store the index of the function context. 6098 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6099 AllocaInst *FnCtx = 6100 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6101 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6102 MFI.setFunctionContextIndex(FI); 6103 return; 6104 } 6105 case Intrinsic::eh_sjlj_setjmp: { 6106 SDValue Ops[2]; 6107 Ops[0] = getRoot(); 6108 Ops[1] = getValue(I.getArgOperand(0)); 6109 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6110 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6111 setValue(&I, Op.getValue(0)); 6112 DAG.setRoot(Op.getValue(1)); 6113 return; 6114 } 6115 case Intrinsic::eh_sjlj_longjmp: 6116 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6117 getRoot(), getValue(I.getArgOperand(0)))); 6118 return; 6119 case Intrinsic::eh_sjlj_setup_dispatch: 6120 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6121 getRoot())); 6122 return; 6123 case Intrinsic::masked_gather: 6124 visitMaskedGather(I); 6125 return; 6126 case Intrinsic::masked_load: 6127 visitMaskedLoad(I); 6128 return; 6129 case Intrinsic::masked_scatter: 6130 visitMaskedScatter(I); 6131 return; 6132 case Intrinsic::masked_store: 6133 visitMaskedStore(I); 6134 return; 6135 case Intrinsic::masked_expandload: 6136 visitMaskedLoad(I, true /* IsExpanding */); 6137 return; 6138 case Intrinsic::masked_compressstore: 6139 visitMaskedStore(I, true /* IsCompressing */); 6140 return; 6141 case Intrinsic::powi: 6142 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6143 getValue(I.getArgOperand(1)), DAG)); 6144 return; 6145 case Intrinsic::log: 6146 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6147 return; 6148 case Intrinsic::log2: 6149 setValue(&I, 6150 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6151 return; 6152 case Intrinsic::log10: 6153 setValue(&I, 6154 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6155 return; 6156 case Intrinsic::exp: 6157 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6158 return; 6159 case Intrinsic::exp2: 6160 setValue(&I, 6161 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6162 return; 6163 case Intrinsic::pow: 6164 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6165 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6166 return; 6167 case Intrinsic::sqrt: 6168 case Intrinsic::fabs: 6169 case Intrinsic::sin: 6170 case Intrinsic::cos: 6171 case Intrinsic::floor: 6172 case Intrinsic::ceil: 6173 case Intrinsic::trunc: 6174 case Intrinsic::rint: 6175 case Intrinsic::nearbyint: 6176 case Intrinsic::round: 6177 case Intrinsic::roundeven: 6178 case Intrinsic::canonicalize: { 6179 unsigned Opcode; 6180 switch (Intrinsic) { 6181 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6182 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6183 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6184 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6185 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6186 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6187 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6188 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6189 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6190 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6191 case Intrinsic::round: Opcode = ISD::FROUND; break; 6192 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6193 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6194 } 6195 6196 setValue(&I, DAG.getNode(Opcode, sdl, 6197 getValue(I.getArgOperand(0)).getValueType(), 6198 getValue(I.getArgOperand(0)), Flags)); 6199 return; 6200 } 6201 case Intrinsic::lround: 6202 case Intrinsic::llround: 6203 case Intrinsic::lrint: 6204 case Intrinsic::llrint: { 6205 unsigned Opcode; 6206 switch (Intrinsic) { 6207 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6208 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6209 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6210 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6211 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6212 } 6213 6214 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6215 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6216 getValue(I.getArgOperand(0)))); 6217 return; 6218 } 6219 case Intrinsic::minnum: 6220 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6221 getValue(I.getArgOperand(0)).getValueType(), 6222 getValue(I.getArgOperand(0)), 6223 getValue(I.getArgOperand(1)), Flags)); 6224 return; 6225 case Intrinsic::maxnum: 6226 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6227 getValue(I.getArgOperand(0)).getValueType(), 6228 getValue(I.getArgOperand(0)), 6229 getValue(I.getArgOperand(1)), Flags)); 6230 return; 6231 case Intrinsic::minimum: 6232 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6233 getValue(I.getArgOperand(0)).getValueType(), 6234 getValue(I.getArgOperand(0)), 6235 getValue(I.getArgOperand(1)), Flags)); 6236 return; 6237 case Intrinsic::maximum: 6238 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6239 getValue(I.getArgOperand(0)).getValueType(), 6240 getValue(I.getArgOperand(0)), 6241 getValue(I.getArgOperand(1)), Flags)); 6242 return; 6243 case Intrinsic::copysign: 6244 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6245 getValue(I.getArgOperand(0)).getValueType(), 6246 getValue(I.getArgOperand(0)), 6247 getValue(I.getArgOperand(1)), Flags)); 6248 return; 6249 case Intrinsic::fma: 6250 setValue(&I, DAG.getNode( 6251 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6252 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6253 getValue(I.getArgOperand(2)), Flags)); 6254 return; 6255 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6256 case Intrinsic::INTRINSIC: 6257 #include "llvm/IR/ConstrainedOps.def" 6258 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6259 return; 6260 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6261 #include "llvm/IR/VPIntrinsics.def" 6262 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6263 return; 6264 case Intrinsic::fmuladd: { 6265 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6266 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6267 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6268 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6269 getValue(I.getArgOperand(0)).getValueType(), 6270 getValue(I.getArgOperand(0)), 6271 getValue(I.getArgOperand(1)), 6272 getValue(I.getArgOperand(2)), Flags)); 6273 } else { 6274 // TODO: Intrinsic calls should have fast-math-flags. 6275 SDValue Mul = DAG.getNode( 6276 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6277 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6278 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6279 getValue(I.getArgOperand(0)).getValueType(), 6280 Mul, getValue(I.getArgOperand(2)), Flags); 6281 setValue(&I, Add); 6282 } 6283 return; 6284 } 6285 case Intrinsic::convert_to_fp16: 6286 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6287 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6288 getValue(I.getArgOperand(0)), 6289 DAG.getTargetConstant(0, sdl, 6290 MVT::i32)))); 6291 return; 6292 case Intrinsic::convert_from_fp16: 6293 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6294 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6295 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6296 getValue(I.getArgOperand(0))))); 6297 return; 6298 case Intrinsic::fptosi_sat: { 6299 EVT Type = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6300 SDValue SatW = DAG.getConstant(Type.getScalarSizeInBits(), sdl, MVT::i32); 6301 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, Type, 6302 getValue(I.getArgOperand(0)), SatW)); 6303 return; 6304 } 6305 case Intrinsic::fptoui_sat: { 6306 EVT Type = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6307 SDValue SatW = DAG.getConstant(Type.getScalarSizeInBits(), sdl, MVT::i32); 6308 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, Type, 6309 getValue(I.getArgOperand(0)), SatW)); 6310 return; 6311 } 6312 case Intrinsic::set_rounding: 6313 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6314 {getRoot(), getValue(I.getArgOperand(0))}); 6315 setValue(&I, Res); 6316 DAG.setRoot(Res.getValue(0)); 6317 return; 6318 case Intrinsic::pcmarker: { 6319 SDValue Tmp = getValue(I.getArgOperand(0)); 6320 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6321 return; 6322 } 6323 case Intrinsic::readcyclecounter: { 6324 SDValue Op = getRoot(); 6325 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6326 DAG.getVTList(MVT::i64, MVT::Other), Op); 6327 setValue(&I, Res); 6328 DAG.setRoot(Res.getValue(1)); 6329 return; 6330 } 6331 case Intrinsic::bitreverse: 6332 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6333 getValue(I.getArgOperand(0)).getValueType(), 6334 getValue(I.getArgOperand(0)))); 6335 return; 6336 case Intrinsic::bswap: 6337 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6338 getValue(I.getArgOperand(0)).getValueType(), 6339 getValue(I.getArgOperand(0)))); 6340 return; 6341 case Intrinsic::cttz: { 6342 SDValue Arg = getValue(I.getArgOperand(0)); 6343 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6344 EVT Ty = Arg.getValueType(); 6345 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6346 sdl, Ty, Arg)); 6347 return; 6348 } 6349 case Intrinsic::ctlz: { 6350 SDValue Arg = getValue(I.getArgOperand(0)); 6351 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6352 EVT Ty = Arg.getValueType(); 6353 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6354 sdl, Ty, Arg)); 6355 return; 6356 } 6357 case Intrinsic::ctpop: { 6358 SDValue Arg = getValue(I.getArgOperand(0)); 6359 EVT Ty = Arg.getValueType(); 6360 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6361 return; 6362 } 6363 case Intrinsic::fshl: 6364 case Intrinsic::fshr: { 6365 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6366 SDValue X = getValue(I.getArgOperand(0)); 6367 SDValue Y = getValue(I.getArgOperand(1)); 6368 SDValue Z = getValue(I.getArgOperand(2)); 6369 EVT VT = X.getValueType(); 6370 6371 if (X == Y) { 6372 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6373 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6374 } else { 6375 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6376 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6377 } 6378 return; 6379 } 6380 case Intrinsic::sadd_sat: { 6381 SDValue Op1 = getValue(I.getArgOperand(0)); 6382 SDValue Op2 = getValue(I.getArgOperand(1)); 6383 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6384 return; 6385 } 6386 case Intrinsic::uadd_sat: { 6387 SDValue Op1 = getValue(I.getArgOperand(0)); 6388 SDValue Op2 = getValue(I.getArgOperand(1)); 6389 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6390 return; 6391 } 6392 case Intrinsic::ssub_sat: { 6393 SDValue Op1 = getValue(I.getArgOperand(0)); 6394 SDValue Op2 = getValue(I.getArgOperand(1)); 6395 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6396 return; 6397 } 6398 case Intrinsic::usub_sat: { 6399 SDValue Op1 = getValue(I.getArgOperand(0)); 6400 SDValue Op2 = getValue(I.getArgOperand(1)); 6401 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6402 return; 6403 } 6404 case Intrinsic::sshl_sat: { 6405 SDValue Op1 = getValue(I.getArgOperand(0)); 6406 SDValue Op2 = getValue(I.getArgOperand(1)); 6407 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6408 return; 6409 } 6410 case Intrinsic::ushl_sat: { 6411 SDValue Op1 = getValue(I.getArgOperand(0)); 6412 SDValue Op2 = getValue(I.getArgOperand(1)); 6413 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6414 return; 6415 } 6416 case Intrinsic::smul_fix: 6417 case Intrinsic::umul_fix: 6418 case Intrinsic::smul_fix_sat: 6419 case Intrinsic::umul_fix_sat: { 6420 SDValue Op1 = getValue(I.getArgOperand(0)); 6421 SDValue Op2 = getValue(I.getArgOperand(1)); 6422 SDValue Op3 = getValue(I.getArgOperand(2)); 6423 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6424 Op1.getValueType(), Op1, Op2, Op3)); 6425 return; 6426 } 6427 case Intrinsic::sdiv_fix: 6428 case Intrinsic::udiv_fix: 6429 case Intrinsic::sdiv_fix_sat: 6430 case Intrinsic::udiv_fix_sat: { 6431 SDValue Op1 = getValue(I.getArgOperand(0)); 6432 SDValue Op2 = getValue(I.getArgOperand(1)); 6433 SDValue Op3 = getValue(I.getArgOperand(2)); 6434 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6435 Op1, Op2, Op3, DAG, TLI)); 6436 return; 6437 } 6438 case Intrinsic::smax: { 6439 SDValue Op1 = getValue(I.getArgOperand(0)); 6440 SDValue Op2 = getValue(I.getArgOperand(1)); 6441 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6442 return; 6443 } 6444 case Intrinsic::smin: { 6445 SDValue Op1 = getValue(I.getArgOperand(0)); 6446 SDValue Op2 = getValue(I.getArgOperand(1)); 6447 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6448 return; 6449 } 6450 case Intrinsic::umax: { 6451 SDValue Op1 = getValue(I.getArgOperand(0)); 6452 SDValue Op2 = getValue(I.getArgOperand(1)); 6453 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6454 return; 6455 } 6456 case Intrinsic::umin: { 6457 SDValue Op1 = getValue(I.getArgOperand(0)); 6458 SDValue Op2 = getValue(I.getArgOperand(1)); 6459 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6460 return; 6461 } 6462 case Intrinsic::abs: { 6463 // TODO: Preserve "int min is poison" arg in SDAG? 6464 SDValue Op1 = getValue(I.getArgOperand(0)); 6465 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6466 return; 6467 } 6468 case Intrinsic::stacksave: { 6469 SDValue Op = getRoot(); 6470 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6471 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6472 setValue(&I, Res); 6473 DAG.setRoot(Res.getValue(1)); 6474 return; 6475 } 6476 case Intrinsic::stackrestore: 6477 Res = getValue(I.getArgOperand(0)); 6478 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6479 return; 6480 case Intrinsic::get_dynamic_area_offset: { 6481 SDValue Op = getRoot(); 6482 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6483 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6484 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6485 // target. 6486 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 6487 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6488 " intrinsic!"); 6489 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6490 Op); 6491 DAG.setRoot(Op); 6492 setValue(&I, Res); 6493 return; 6494 } 6495 case Intrinsic::stackguard: { 6496 MachineFunction &MF = DAG.getMachineFunction(); 6497 const Module &M = *MF.getFunction().getParent(); 6498 SDValue Chain = getRoot(); 6499 if (TLI.useLoadStackGuardNode()) { 6500 Res = getLoadStackGuard(DAG, sdl, Chain); 6501 } else { 6502 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6503 const Value *Global = TLI.getSDagStackGuard(M); 6504 Align Align = DL->getPrefTypeAlign(Global->getType()); 6505 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6506 MachinePointerInfo(Global, 0), Align, 6507 MachineMemOperand::MOVolatile); 6508 } 6509 if (TLI.useStackGuardXorFP()) 6510 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6511 DAG.setRoot(Chain); 6512 setValue(&I, Res); 6513 return; 6514 } 6515 case Intrinsic::stackprotector: { 6516 // Emit code into the DAG to store the stack guard onto the stack. 6517 MachineFunction &MF = DAG.getMachineFunction(); 6518 MachineFrameInfo &MFI = MF.getFrameInfo(); 6519 SDValue Src, Chain = getRoot(); 6520 6521 if (TLI.useLoadStackGuardNode()) 6522 Src = getLoadStackGuard(DAG, sdl, Chain); 6523 else 6524 Src = getValue(I.getArgOperand(0)); // The guard's value. 6525 6526 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6527 6528 int FI = FuncInfo.StaticAllocaMap[Slot]; 6529 MFI.setStackProtectorIndex(FI); 6530 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6531 6532 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6533 6534 // Store the stack protector onto the stack. 6535 Res = DAG.getStore( 6536 Chain, sdl, Src, FIN, 6537 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 6538 MaybeAlign(), MachineMemOperand::MOVolatile); 6539 setValue(&I, Res); 6540 DAG.setRoot(Res); 6541 return; 6542 } 6543 case Intrinsic::objectsize: 6544 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6545 6546 case Intrinsic::is_constant: 6547 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6548 6549 case Intrinsic::annotation: 6550 case Intrinsic::ptr_annotation: 6551 case Intrinsic::launder_invariant_group: 6552 case Intrinsic::strip_invariant_group: 6553 // Drop the intrinsic, but forward the value 6554 setValue(&I, getValue(I.getOperand(0))); 6555 return; 6556 6557 case Intrinsic::assume: 6558 case Intrinsic::experimental_noalias_scope_decl: 6559 case Intrinsic::var_annotation: 6560 case Intrinsic::sideeffect: 6561 // Discard annotate attributes, noalias scope declarations, assumptions, and 6562 // artificial side-effects. 6563 return; 6564 6565 case Intrinsic::codeview_annotation: { 6566 // Emit a label associated with this metadata. 6567 MachineFunction &MF = DAG.getMachineFunction(); 6568 MCSymbol *Label = 6569 MF.getMMI().getContext().createTempSymbol("annotation", true); 6570 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6571 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6572 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6573 DAG.setRoot(Res); 6574 return; 6575 } 6576 6577 case Intrinsic::init_trampoline: { 6578 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6579 6580 SDValue Ops[6]; 6581 Ops[0] = getRoot(); 6582 Ops[1] = getValue(I.getArgOperand(0)); 6583 Ops[2] = getValue(I.getArgOperand(1)); 6584 Ops[3] = getValue(I.getArgOperand(2)); 6585 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6586 Ops[5] = DAG.getSrcValue(F); 6587 6588 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6589 6590 DAG.setRoot(Res); 6591 return; 6592 } 6593 case Intrinsic::adjust_trampoline: 6594 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6595 TLI.getPointerTy(DAG.getDataLayout()), 6596 getValue(I.getArgOperand(0)))); 6597 return; 6598 case Intrinsic::gcroot: { 6599 assert(DAG.getMachineFunction().getFunction().hasGC() && 6600 "only valid in functions with gc specified, enforced by Verifier"); 6601 assert(GFI && "implied by previous"); 6602 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6603 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6604 6605 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6606 GFI->addStackRoot(FI->getIndex(), TypeMap); 6607 return; 6608 } 6609 case Intrinsic::gcread: 6610 case Intrinsic::gcwrite: 6611 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6612 case Intrinsic::flt_rounds: 6613 Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot()); 6614 setValue(&I, Res); 6615 DAG.setRoot(Res.getValue(1)); 6616 return; 6617 6618 case Intrinsic::expect: 6619 // Just replace __builtin_expect(exp, c) with EXP. 6620 setValue(&I, getValue(I.getArgOperand(0))); 6621 return; 6622 6623 case Intrinsic::ubsantrap: 6624 case Intrinsic::debugtrap: 6625 case Intrinsic::trap: { 6626 StringRef TrapFuncName = 6627 I.getAttributes() 6628 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6629 .getValueAsString(); 6630 if (TrapFuncName.empty()) { 6631 switch (Intrinsic) { 6632 case Intrinsic::trap: 6633 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 6634 break; 6635 case Intrinsic::debugtrap: 6636 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 6637 break; 6638 case Intrinsic::ubsantrap: 6639 DAG.setRoot(DAG.getNode( 6640 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 6641 DAG.getTargetConstant( 6642 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 6643 MVT::i32))); 6644 break; 6645 default: llvm_unreachable("unknown trap intrinsic"); 6646 } 6647 return; 6648 } 6649 TargetLowering::ArgListTy Args; 6650 if (Intrinsic == Intrinsic::ubsantrap) { 6651 Args.push_back(TargetLoweringBase::ArgListEntry()); 6652 Args[0].Val = I.getArgOperand(0); 6653 Args[0].Node = getValue(Args[0].Val); 6654 Args[0].Ty = Args[0].Val->getType(); 6655 } 6656 6657 TargetLowering::CallLoweringInfo CLI(DAG); 6658 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6659 CallingConv::C, I.getType(), 6660 DAG.getExternalSymbol(TrapFuncName.data(), 6661 TLI.getPointerTy(DAG.getDataLayout())), 6662 std::move(Args)); 6663 6664 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6665 DAG.setRoot(Result.second); 6666 return; 6667 } 6668 6669 case Intrinsic::uadd_with_overflow: 6670 case Intrinsic::sadd_with_overflow: 6671 case Intrinsic::usub_with_overflow: 6672 case Intrinsic::ssub_with_overflow: 6673 case Intrinsic::umul_with_overflow: 6674 case Intrinsic::smul_with_overflow: { 6675 ISD::NodeType Op; 6676 switch (Intrinsic) { 6677 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6678 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6679 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6680 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6681 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6682 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6683 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6684 } 6685 SDValue Op1 = getValue(I.getArgOperand(0)); 6686 SDValue Op2 = getValue(I.getArgOperand(1)); 6687 6688 EVT ResultVT = Op1.getValueType(); 6689 EVT OverflowVT = MVT::i1; 6690 if (ResultVT.isVector()) 6691 OverflowVT = EVT::getVectorVT( 6692 *Context, OverflowVT, ResultVT.getVectorElementCount()); 6693 6694 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6695 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6696 return; 6697 } 6698 case Intrinsic::prefetch: { 6699 SDValue Ops[5]; 6700 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6701 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6702 Ops[0] = DAG.getRoot(); 6703 Ops[1] = getValue(I.getArgOperand(0)); 6704 Ops[2] = getValue(I.getArgOperand(1)); 6705 Ops[3] = getValue(I.getArgOperand(2)); 6706 Ops[4] = getValue(I.getArgOperand(3)); 6707 SDValue Result = DAG.getMemIntrinsicNode( 6708 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 6709 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 6710 /* align */ None, Flags); 6711 6712 // Chain the prefetch in parallell with any pending loads, to stay out of 6713 // the way of later optimizations. 6714 PendingLoads.push_back(Result); 6715 Result = getRoot(); 6716 DAG.setRoot(Result); 6717 return; 6718 } 6719 case Intrinsic::lifetime_start: 6720 case Intrinsic::lifetime_end: { 6721 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6722 // Stack coloring is not enabled in O0, discard region information. 6723 if (TM.getOptLevel() == CodeGenOpt::None) 6724 return; 6725 6726 const int64_t ObjectSize = 6727 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6728 Value *const ObjectPtr = I.getArgOperand(1); 6729 SmallVector<const Value *, 4> Allocas; 6730 getUnderlyingObjects(ObjectPtr, Allocas); 6731 6732 for (const Value *Alloca : Allocas) { 6733 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 6734 6735 // Could not find an Alloca. 6736 if (!LifetimeObject) 6737 continue; 6738 6739 // First check that the Alloca is static, otherwise it won't have a 6740 // valid frame index. 6741 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6742 if (SI == FuncInfo.StaticAllocaMap.end()) 6743 return; 6744 6745 const int FrameIndex = SI->second; 6746 int64_t Offset; 6747 if (GetPointerBaseWithConstantOffset( 6748 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6749 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6750 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6751 Offset); 6752 DAG.setRoot(Res); 6753 } 6754 return; 6755 } 6756 case Intrinsic::pseudoprobe: { 6757 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 6758 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6759 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 6760 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 6761 DAG.setRoot(Res); 6762 return; 6763 } 6764 case Intrinsic::invariant_start: 6765 // Discard region information. 6766 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6767 return; 6768 case Intrinsic::invariant_end: 6769 // Discard region information. 6770 return; 6771 case Intrinsic::clear_cache: 6772 /// FunctionName may be null. 6773 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6774 lowerCallToExternalSymbol(I, FunctionName); 6775 return; 6776 case Intrinsic::donothing: 6777 // ignore 6778 return; 6779 case Intrinsic::experimental_stackmap: 6780 visitStackmap(I); 6781 return; 6782 case Intrinsic::experimental_patchpoint_void: 6783 case Intrinsic::experimental_patchpoint_i64: 6784 visitPatchpoint(I); 6785 return; 6786 case Intrinsic::experimental_gc_statepoint: 6787 LowerStatepoint(cast<GCStatepointInst>(I)); 6788 return; 6789 case Intrinsic::experimental_gc_result: 6790 visitGCResult(cast<GCResultInst>(I)); 6791 return; 6792 case Intrinsic::experimental_gc_relocate: 6793 visitGCRelocate(cast<GCRelocateInst>(I)); 6794 return; 6795 case Intrinsic::instrprof_increment: 6796 llvm_unreachable("instrprof failed to lower an increment"); 6797 case Intrinsic::instrprof_value_profile: 6798 llvm_unreachable("instrprof failed to lower a value profiling call"); 6799 case Intrinsic::localescape: { 6800 MachineFunction &MF = DAG.getMachineFunction(); 6801 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6802 6803 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6804 // is the same on all targets. 6805 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6806 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6807 if (isa<ConstantPointerNull>(Arg)) 6808 continue; // Skip null pointers. They represent a hole in index space. 6809 AllocaInst *Slot = cast<AllocaInst>(Arg); 6810 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6811 "can only escape static allocas"); 6812 int FI = FuncInfo.StaticAllocaMap[Slot]; 6813 MCSymbol *FrameAllocSym = 6814 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6815 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6816 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6817 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6818 .addSym(FrameAllocSym) 6819 .addFrameIndex(FI); 6820 } 6821 6822 return; 6823 } 6824 6825 case Intrinsic::localrecover: { 6826 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6827 MachineFunction &MF = DAG.getMachineFunction(); 6828 6829 // Get the symbol that defines the frame offset. 6830 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6831 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6832 unsigned IdxVal = 6833 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6834 MCSymbol *FrameAllocSym = 6835 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6836 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6837 6838 Value *FP = I.getArgOperand(1); 6839 SDValue FPVal = getValue(FP); 6840 EVT PtrVT = FPVal.getValueType(); 6841 6842 // Create a MCSymbol for the label to avoid any target lowering 6843 // that would make this PC relative. 6844 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6845 SDValue OffsetVal = 6846 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6847 6848 // Add the offset to the FP. 6849 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 6850 setValue(&I, Add); 6851 6852 return; 6853 } 6854 6855 case Intrinsic::eh_exceptionpointer: 6856 case Intrinsic::eh_exceptioncode: { 6857 // Get the exception pointer vreg, copy from it, and resize it to fit. 6858 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6859 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6860 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6861 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6862 SDValue N = 6863 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6864 if (Intrinsic == Intrinsic::eh_exceptioncode) 6865 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6866 setValue(&I, N); 6867 return; 6868 } 6869 case Intrinsic::xray_customevent: { 6870 // Here we want to make sure that the intrinsic behaves as if it has a 6871 // specific calling convention, and only for x86_64. 6872 // FIXME: Support other platforms later. 6873 const auto &Triple = DAG.getTarget().getTargetTriple(); 6874 if (Triple.getArch() != Triple::x86_64) 6875 return; 6876 6877 SDLoc DL = getCurSDLoc(); 6878 SmallVector<SDValue, 8> Ops; 6879 6880 // We want to say that we always want the arguments in registers. 6881 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6882 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6883 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6884 SDValue Chain = getRoot(); 6885 Ops.push_back(LogEntryVal); 6886 Ops.push_back(StrSizeVal); 6887 Ops.push_back(Chain); 6888 6889 // We need to enforce the calling convention for the callsite, so that 6890 // argument ordering is enforced correctly, and that register allocation can 6891 // see that some registers may be assumed clobbered and have to preserve 6892 // them across calls to the intrinsic. 6893 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6894 DL, NodeTys, Ops); 6895 SDValue patchableNode = SDValue(MN, 0); 6896 DAG.setRoot(patchableNode); 6897 setValue(&I, patchableNode); 6898 return; 6899 } 6900 case Intrinsic::xray_typedevent: { 6901 // Here we want to make sure that the intrinsic behaves as if it has a 6902 // specific calling convention, and only for x86_64. 6903 // FIXME: Support other platforms later. 6904 const auto &Triple = DAG.getTarget().getTargetTriple(); 6905 if (Triple.getArch() != Triple::x86_64) 6906 return; 6907 6908 SDLoc DL = getCurSDLoc(); 6909 SmallVector<SDValue, 8> Ops; 6910 6911 // We want to say that we always want the arguments in registers. 6912 // It's unclear to me how manipulating the selection DAG here forces callers 6913 // to provide arguments in registers instead of on the stack. 6914 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6915 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6916 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6917 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6918 SDValue Chain = getRoot(); 6919 Ops.push_back(LogTypeId); 6920 Ops.push_back(LogEntryVal); 6921 Ops.push_back(StrSizeVal); 6922 Ops.push_back(Chain); 6923 6924 // We need to enforce the calling convention for the callsite, so that 6925 // argument ordering is enforced correctly, and that register allocation can 6926 // see that some registers may be assumed clobbered and have to preserve 6927 // them across calls to the intrinsic. 6928 MachineSDNode *MN = DAG.getMachineNode( 6929 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6930 SDValue patchableNode = SDValue(MN, 0); 6931 DAG.setRoot(patchableNode); 6932 setValue(&I, patchableNode); 6933 return; 6934 } 6935 case Intrinsic::experimental_deoptimize: 6936 LowerDeoptimizeCall(&I); 6937 return; 6938 6939 case Intrinsic::vector_reduce_fadd: 6940 case Intrinsic::vector_reduce_fmul: 6941 case Intrinsic::vector_reduce_add: 6942 case Intrinsic::vector_reduce_mul: 6943 case Intrinsic::vector_reduce_and: 6944 case Intrinsic::vector_reduce_or: 6945 case Intrinsic::vector_reduce_xor: 6946 case Intrinsic::vector_reduce_smax: 6947 case Intrinsic::vector_reduce_smin: 6948 case Intrinsic::vector_reduce_umax: 6949 case Intrinsic::vector_reduce_umin: 6950 case Intrinsic::vector_reduce_fmax: 6951 case Intrinsic::vector_reduce_fmin: 6952 visitVectorReduce(I, Intrinsic); 6953 return; 6954 6955 case Intrinsic::icall_branch_funnel: { 6956 SmallVector<SDValue, 16> Ops; 6957 Ops.push_back(getValue(I.getArgOperand(0))); 6958 6959 int64_t Offset; 6960 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6961 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6962 if (!Base) 6963 report_fatal_error( 6964 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6965 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6966 6967 struct BranchFunnelTarget { 6968 int64_t Offset; 6969 SDValue Target; 6970 }; 6971 SmallVector<BranchFunnelTarget, 8> Targets; 6972 6973 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6974 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6975 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6976 if (ElemBase != Base) 6977 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6978 "to the same GlobalValue"); 6979 6980 SDValue Val = getValue(I.getArgOperand(Op + 1)); 6981 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 6982 if (!GA) 6983 report_fatal_error( 6984 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6985 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 6986 GA->getGlobal(), getCurSDLoc(), 6987 Val.getValueType(), GA->getOffset())}); 6988 } 6989 llvm::sort(Targets, 6990 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 6991 return T1.Offset < T2.Offset; 6992 }); 6993 6994 for (auto &T : Targets) { 6995 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 6996 Ops.push_back(T.Target); 6997 } 6998 6999 Ops.push_back(DAG.getRoot()); // Chain 7000 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 7001 getCurSDLoc(), MVT::Other, Ops), 7002 0); 7003 DAG.setRoot(N); 7004 setValue(&I, N); 7005 HasTailCall = true; 7006 return; 7007 } 7008 7009 case Intrinsic::wasm_landingpad_index: 7010 // Information this intrinsic contained has been transferred to 7011 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7012 // delete it now. 7013 return; 7014 7015 case Intrinsic::aarch64_settag: 7016 case Intrinsic::aarch64_settag_zero: { 7017 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7018 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7019 SDValue Val = TSI.EmitTargetCodeForSetTag( 7020 DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)), 7021 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7022 ZeroMemory); 7023 DAG.setRoot(Val); 7024 setValue(&I, Val); 7025 return; 7026 } 7027 case Intrinsic::ptrmask: { 7028 SDValue Ptr = getValue(I.getOperand(0)); 7029 SDValue Const = getValue(I.getOperand(1)); 7030 7031 EVT PtrVT = Ptr.getValueType(); 7032 setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), PtrVT, Ptr, 7033 DAG.getZExtOrTrunc(Const, getCurSDLoc(), PtrVT))); 7034 return; 7035 } 7036 case Intrinsic::get_active_lane_mask: { 7037 auto DL = getCurSDLoc(); 7038 SDValue Index = getValue(I.getOperand(0)); 7039 SDValue TripCount = getValue(I.getOperand(1)); 7040 Type *ElementTy = I.getOperand(0)->getType(); 7041 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7042 unsigned VecWidth = VT.getVectorNumElements(); 7043 7044 SmallVector<SDValue, 16> OpsTripCount; 7045 SmallVector<SDValue, 16> OpsIndex; 7046 SmallVector<SDValue, 16> OpsStepConstants; 7047 for (unsigned i = 0; i < VecWidth; i++) { 7048 OpsTripCount.push_back(TripCount); 7049 OpsIndex.push_back(Index); 7050 OpsStepConstants.push_back( 7051 DAG.getConstant(i, DL, EVT::getEVT(ElementTy))); 7052 } 7053 7054 EVT CCVT = EVT::getVectorVT(I.getContext(), MVT::i1, VecWidth); 7055 7056 auto VecTy = EVT::getEVT(FixedVectorType::get(ElementTy, VecWidth)); 7057 SDValue VectorIndex = DAG.getBuildVector(VecTy, DL, OpsIndex); 7058 SDValue VectorStep = DAG.getBuildVector(VecTy, DL, OpsStepConstants); 7059 SDValue VectorInduction = DAG.getNode( 7060 ISD::UADDO, DL, DAG.getVTList(VecTy, CCVT), VectorIndex, VectorStep); 7061 SDValue VectorTripCount = DAG.getBuildVector(VecTy, DL, OpsTripCount); 7062 SDValue SetCC = DAG.getSetCC(DL, CCVT, VectorInduction.getValue(0), 7063 VectorTripCount, ISD::CondCode::SETULT); 7064 setValue(&I, DAG.getNode(ISD::AND, DL, CCVT, 7065 DAG.getNOT(DL, VectorInduction.getValue(1), CCVT), 7066 SetCC)); 7067 return; 7068 } 7069 case Intrinsic::experimental_vector_insert: { 7070 auto DL = getCurSDLoc(); 7071 7072 SDValue Vec = getValue(I.getOperand(0)); 7073 SDValue SubVec = getValue(I.getOperand(1)); 7074 SDValue Index = getValue(I.getOperand(2)); 7075 7076 // The intrinsic's index type is i64, but the SDNode requires an index type 7077 // suitable for the target. Convert the index as required. 7078 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7079 if (Index.getValueType() != VectorIdxTy) 7080 Index = DAG.getVectorIdxConstant( 7081 cast<ConstantSDNode>(Index)->getZExtValue(), DL); 7082 7083 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7084 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ResultVT, Vec, SubVec, 7085 Index)); 7086 return; 7087 } 7088 case Intrinsic::experimental_vector_extract: { 7089 auto DL = getCurSDLoc(); 7090 7091 SDValue Vec = getValue(I.getOperand(0)); 7092 SDValue Index = getValue(I.getOperand(1)); 7093 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7094 7095 // The intrinsic's index type is i64, but the SDNode requires an index type 7096 // suitable for the target. Convert the index as required. 7097 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7098 if (Index.getValueType() != VectorIdxTy) 7099 Index = DAG.getVectorIdxConstant( 7100 cast<ConstantSDNode>(Index)->getZExtValue(), DL); 7101 7102 setValue(&I, DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResultVT, Vec, Index)); 7103 return; 7104 } 7105 case Intrinsic::experimental_vector_reverse: 7106 visitVectorReverse(I); 7107 return; 7108 } 7109 } 7110 7111 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7112 const ConstrainedFPIntrinsic &FPI) { 7113 SDLoc sdl = getCurSDLoc(); 7114 7115 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7116 SmallVector<EVT, 4> ValueVTs; 7117 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 7118 ValueVTs.push_back(MVT::Other); // Out chain 7119 7120 // We do not need to serialize constrained FP intrinsics against 7121 // each other or against (nonvolatile) loads, so they can be 7122 // chained like loads. 7123 SDValue Chain = DAG.getRoot(); 7124 SmallVector<SDValue, 4> Opers; 7125 Opers.push_back(Chain); 7126 if (FPI.isUnaryOp()) { 7127 Opers.push_back(getValue(FPI.getArgOperand(0))); 7128 } else if (FPI.isTernaryOp()) { 7129 Opers.push_back(getValue(FPI.getArgOperand(0))); 7130 Opers.push_back(getValue(FPI.getArgOperand(1))); 7131 Opers.push_back(getValue(FPI.getArgOperand(2))); 7132 } else { 7133 Opers.push_back(getValue(FPI.getArgOperand(0))); 7134 Opers.push_back(getValue(FPI.getArgOperand(1))); 7135 } 7136 7137 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7138 assert(Result.getNode()->getNumValues() == 2); 7139 7140 // Push node to the appropriate list so that future instructions can be 7141 // chained up correctly. 7142 SDValue OutChain = Result.getValue(1); 7143 switch (EB) { 7144 case fp::ExceptionBehavior::ebIgnore: 7145 // The only reason why ebIgnore nodes still need to be chained is that 7146 // they might depend on the current rounding mode, and therefore must 7147 // not be moved across instruction that may change that mode. 7148 LLVM_FALLTHROUGH; 7149 case fp::ExceptionBehavior::ebMayTrap: 7150 // These must not be moved across calls or instructions that may change 7151 // floating-point exception masks. 7152 PendingConstrainedFP.push_back(OutChain); 7153 break; 7154 case fp::ExceptionBehavior::ebStrict: 7155 // These must not be moved across calls or instructions that may change 7156 // floating-point exception masks or read floating-point exception flags. 7157 // In addition, they cannot be optimized out even if unused. 7158 PendingConstrainedFPStrict.push_back(OutChain); 7159 break; 7160 } 7161 }; 7162 7163 SDVTList VTs = DAG.getVTList(ValueVTs); 7164 fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue(); 7165 7166 SDNodeFlags Flags; 7167 if (EB == fp::ExceptionBehavior::ebIgnore) 7168 Flags.setNoFPExcept(true); 7169 7170 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7171 Flags.copyFMF(*FPOp); 7172 7173 unsigned Opcode; 7174 switch (FPI.getIntrinsicID()) { 7175 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7176 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7177 case Intrinsic::INTRINSIC: \ 7178 Opcode = ISD::STRICT_##DAGN; \ 7179 break; 7180 #include "llvm/IR/ConstrainedOps.def" 7181 case Intrinsic::experimental_constrained_fmuladd: { 7182 Opcode = ISD::STRICT_FMA; 7183 // Break fmuladd into fmul and fadd. 7184 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7185 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), 7186 ValueVTs[0])) { 7187 Opers.pop_back(); 7188 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7189 pushOutChain(Mul, EB); 7190 Opcode = ISD::STRICT_FADD; 7191 Opers.clear(); 7192 Opers.push_back(Mul.getValue(1)); 7193 Opers.push_back(Mul.getValue(0)); 7194 Opers.push_back(getValue(FPI.getArgOperand(2))); 7195 } 7196 break; 7197 } 7198 } 7199 7200 // A few strict DAG nodes carry additional operands that are not 7201 // set up by the default code above. 7202 switch (Opcode) { 7203 default: break; 7204 case ISD::STRICT_FP_ROUND: 7205 Opers.push_back( 7206 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7207 break; 7208 case ISD::STRICT_FSETCC: 7209 case ISD::STRICT_FSETCCS: { 7210 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7211 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 7212 if (TM.Options.NoNaNsFPMath) 7213 Condition = getFCmpCodeWithoutNaN(Condition); 7214 Opers.push_back(DAG.getCondCode(Condition)); 7215 break; 7216 } 7217 } 7218 7219 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7220 pushOutChain(Result, EB); 7221 7222 SDValue FPResult = Result.getValue(0); 7223 setValue(&FPI, FPResult); 7224 } 7225 7226 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 7227 Optional<unsigned> ResOPC; 7228 switch (VPIntrin.getIntrinsicID()) { 7229 #define BEGIN_REGISTER_VP_INTRINSIC(INTRIN, ...) case Intrinsic::INTRIN: 7230 #define BEGIN_REGISTER_VP_SDNODE(VPSDID, ...) ResOPC = ISD::VPSDID; 7231 #define END_REGISTER_VP_INTRINSIC(...) break; 7232 #include "llvm/IR/VPIntrinsics.def" 7233 } 7234 7235 if (!ResOPC.hasValue()) 7236 llvm_unreachable( 7237 "Inconsistency: no SDNode available for this VPIntrinsic!"); 7238 7239 return ResOPC.getValue(); 7240 } 7241 7242 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 7243 const VPIntrinsic &VPIntrin) { 7244 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 7245 7246 SmallVector<EVT, 4> ValueVTs; 7247 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7248 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 7249 SDVTList VTs = DAG.getVTList(ValueVTs); 7250 7251 // Request operands. 7252 SmallVector<SDValue, 7> OpValues; 7253 for (int i = 0; i < (int)VPIntrin.getNumArgOperands(); ++i) 7254 OpValues.push_back(getValue(VPIntrin.getArgOperand(i))); 7255 7256 SDLoc DL = getCurSDLoc(); 7257 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues); 7258 setValue(&VPIntrin, Result); 7259 } 7260 7261 std::pair<SDValue, SDValue> 7262 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7263 const BasicBlock *EHPadBB) { 7264 MachineFunction &MF = DAG.getMachineFunction(); 7265 MachineModuleInfo &MMI = MF.getMMI(); 7266 MCSymbol *BeginLabel = nullptr; 7267 7268 if (EHPadBB) { 7269 // Insert a label before the invoke call to mark the try range. This can be 7270 // used to detect deletion of the invoke via the MachineModuleInfo. 7271 BeginLabel = MMI.getContext().createTempSymbol(); 7272 7273 // For SjLj, keep track of which landing pads go with which invokes 7274 // so as to maintain the ordering of pads in the LSDA. 7275 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7276 if (CallSiteIndex) { 7277 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7278 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7279 7280 // Now that the call site is handled, stop tracking it. 7281 MMI.setCurrentCallSite(0); 7282 } 7283 7284 // Both PendingLoads and PendingExports must be flushed here; 7285 // this call might not return. 7286 (void)getRoot(); 7287 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 7288 7289 CLI.setChain(getRoot()); 7290 } 7291 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7292 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7293 7294 assert((CLI.IsTailCall || Result.second.getNode()) && 7295 "Non-null chain expected with non-tail call!"); 7296 assert((Result.second.getNode() || !Result.first.getNode()) && 7297 "Null value expected with tail call!"); 7298 7299 if (!Result.second.getNode()) { 7300 // As a special case, a null chain means that a tail call has been emitted 7301 // and the DAG root is already updated. 7302 HasTailCall = true; 7303 7304 // Since there's no actual continuation from this block, nothing can be 7305 // relying on us setting vregs for them. 7306 PendingExports.clear(); 7307 } else { 7308 DAG.setRoot(Result.second); 7309 } 7310 7311 if (EHPadBB) { 7312 // Insert a label at the end of the invoke call to mark the try range. This 7313 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7314 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7315 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 7316 7317 // Inform MachineModuleInfo of range. 7318 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7319 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7320 // actually use outlined funclets and their LSDA info style. 7321 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7322 assert(CLI.CB); 7323 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 7324 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CB), BeginLabel, EndLabel); 7325 } else if (!isScopedEHPersonality(Pers)) { 7326 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7327 } 7328 } 7329 7330 return Result; 7331 } 7332 7333 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 7334 bool isTailCall, 7335 const BasicBlock *EHPadBB) { 7336 auto &DL = DAG.getDataLayout(); 7337 FunctionType *FTy = CB.getFunctionType(); 7338 Type *RetTy = CB.getType(); 7339 7340 TargetLowering::ArgListTy Args; 7341 Args.reserve(CB.arg_size()); 7342 7343 const Value *SwiftErrorVal = nullptr; 7344 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7345 7346 if (isTailCall) { 7347 // Avoid emitting tail calls in functions with the disable-tail-calls 7348 // attribute. 7349 auto *Caller = CB.getParent()->getParent(); 7350 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7351 "true") 7352 isTailCall = false; 7353 7354 // We can't tail call inside a function with a swifterror argument. Lowering 7355 // does not support this yet. It would have to move into the swifterror 7356 // register before the call. 7357 if (TLI.supportSwiftError() && 7358 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7359 isTailCall = false; 7360 } 7361 7362 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 7363 TargetLowering::ArgListEntry Entry; 7364 const Value *V = *I; 7365 7366 // Skip empty types 7367 if (V->getType()->isEmptyTy()) 7368 continue; 7369 7370 SDValue ArgNode = getValue(V); 7371 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7372 7373 Entry.setAttributes(&CB, I - CB.arg_begin()); 7374 7375 // Use swifterror virtual register as input to the call. 7376 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7377 SwiftErrorVal = V; 7378 // We find the virtual register for the actual swifterror argument. 7379 // Instead of using the Value, we use the virtual register instead. 7380 Entry.Node = 7381 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 7382 EVT(TLI.getPointerTy(DL))); 7383 } 7384 7385 Args.push_back(Entry); 7386 7387 // If we have an explicit sret argument that is an Instruction, (i.e., it 7388 // might point to function-local memory), we can't meaningfully tail-call. 7389 if (Entry.IsSRet && isa<Instruction>(V)) 7390 isTailCall = false; 7391 } 7392 7393 // If call site has a cfguardtarget operand bundle, create and add an 7394 // additional ArgListEntry. 7395 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7396 TargetLowering::ArgListEntry Entry; 7397 Value *V = Bundle->Inputs[0]; 7398 SDValue ArgNode = getValue(V); 7399 Entry.Node = ArgNode; 7400 Entry.Ty = V->getType(); 7401 Entry.IsCFGuardTarget = true; 7402 Args.push_back(Entry); 7403 } 7404 7405 // Check if target-independent constraints permit a tail call here. 7406 // Target-dependent constraints are checked within TLI->LowerCallTo. 7407 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 7408 isTailCall = false; 7409 7410 // Disable tail calls if there is an swifterror argument. Targets have not 7411 // been updated to support tail calls. 7412 if (TLI.supportSwiftError() && SwiftErrorVal) 7413 isTailCall = false; 7414 7415 TargetLowering::CallLoweringInfo CLI(DAG); 7416 CLI.setDebugLoc(getCurSDLoc()) 7417 .setChain(getRoot()) 7418 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 7419 .setTailCall(isTailCall) 7420 .setConvergent(CB.isConvergent()) 7421 .setIsPreallocated( 7422 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 7423 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7424 7425 if (Result.first.getNode()) { 7426 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 7427 setValue(&CB, Result.first); 7428 } 7429 7430 // The last element of CLI.InVals has the SDValue for swifterror return. 7431 // Here we copy it to a virtual register and update SwiftErrorMap for 7432 // book-keeping. 7433 if (SwiftErrorVal && TLI.supportSwiftError()) { 7434 // Get the last element of InVals. 7435 SDValue Src = CLI.InVals.back(); 7436 Register VReg = 7437 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 7438 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7439 DAG.setRoot(CopyNode); 7440 } 7441 } 7442 7443 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7444 SelectionDAGBuilder &Builder) { 7445 // Check to see if this load can be trivially constant folded, e.g. if the 7446 // input is from a string literal. 7447 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7448 // Cast pointer to the type we really want to load. 7449 Type *LoadTy = 7450 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7451 if (LoadVT.isVector()) 7452 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7453 7454 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7455 PointerType::getUnqual(LoadTy)); 7456 7457 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 7458 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 7459 return Builder.getValue(LoadCst); 7460 } 7461 7462 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7463 // still constant memory, the input chain can be the entry node. 7464 SDValue Root; 7465 bool ConstantMemory = false; 7466 7467 // Do not serialize (non-volatile) loads of constant memory with anything. 7468 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7469 Root = Builder.DAG.getEntryNode(); 7470 ConstantMemory = true; 7471 } else { 7472 // Do not serialize non-volatile loads against each other. 7473 Root = Builder.DAG.getRoot(); 7474 } 7475 7476 SDValue Ptr = Builder.getValue(PtrVal); 7477 SDValue LoadVal = 7478 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 7479 MachinePointerInfo(PtrVal), Align(1)); 7480 7481 if (!ConstantMemory) 7482 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7483 return LoadVal; 7484 } 7485 7486 /// Record the value for an instruction that produces an integer result, 7487 /// converting the type where necessary. 7488 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7489 SDValue Value, 7490 bool IsSigned) { 7491 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7492 I.getType(), true); 7493 if (IsSigned) 7494 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7495 else 7496 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7497 setValue(&I, Value); 7498 } 7499 7500 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 7501 /// true and lower it. Otherwise return false, and it will be lowered like a 7502 /// normal call. 7503 /// The caller already checked that \p I calls the appropriate LibFunc with a 7504 /// correct prototype. 7505 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 7506 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 7507 const Value *Size = I.getArgOperand(2); 7508 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 7509 if (CSize && CSize->getZExtValue() == 0) { 7510 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7511 I.getType(), true); 7512 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 7513 return true; 7514 } 7515 7516 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7517 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 7518 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 7519 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 7520 if (Res.first.getNode()) { 7521 processIntegerCallValue(I, Res.first, true); 7522 PendingLoads.push_back(Res.second); 7523 return true; 7524 } 7525 7526 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 7527 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 7528 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 7529 return false; 7530 7531 // If the target has a fast compare for the given size, it will return a 7532 // preferred load type for that size. Require that the load VT is legal and 7533 // that the target supports unaligned loads of that type. Otherwise, return 7534 // INVALID. 7535 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 7536 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7537 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 7538 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 7539 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 7540 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 7541 // TODO: Check alignment of src and dest ptrs. 7542 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 7543 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 7544 if (!TLI.isTypeLegal(LVT) || 7545 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 7546 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 7547 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 7548 } 7549 7550 return LVT; 7551 }; 7552 7553 // This turns into unaligned loads. We only do this if the target natively 7554 // supports the MVT we'll be loading or if it is small enough (<= 4) that 7555 // we'll only produce a small number of byte loads. 7556 MVT LoadVT; 7557 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 7558 switch (NumBitsToCompare) { 7559 default: 7560 return false; 7561 case 16: 7562 LoadVT = MVT::i16; 7563 break; 7564 case 32: 7565 LoadVT = MVT::i32; 7566 break; 7567 case 64: 7568 case 128: 7569 case 256: 7570 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 7571 break; 7572 } 7573 7574 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 7575 return false; 7576 7577 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 7578 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 7579 7580 // Bitcast to a wide integer type if the loads are vectors. 7581 if (LoadVT.isVector()) { 7582 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 7583 LoadL = DAG.getBitcast(CmpVT, LoadL); 7584 LoadR = DAG.getBitcast(CmpVT, LoadR); 7585 } 7586 7587 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 7588 processIntegerCallValue(I, Cmp, false); 7589 return true; 7590 } 7591 7592 /// See if we can lower a memchr call into an optimized form. If so, return 7593 /// true and lower it. Otherwise return false, and it will be lowered like a 7594 /// normal call. 7595 /// The caller already checked that \p I calls the appropriate LibFunc with a 7596 /// correct prototype. 7597 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 7598 const Value *Src = I.getArgOperand(0); 7599 const Value *Char = I.getArgOperand(1); 7600 const Value *Length = I.getArgOperand(2); 7601 7602 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7603 std::pair<SDValue, SDValue> Res = 7604 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 7605 getValue(Src), getValue(Char), getValue(Length), 7606 MachinePointerInfo(Src)); 7607 if (Res.first.getNode()) { 7608 setValue(&I, Res.first); 7609 PendingLoads.push_back(Res.second); 7610 return true; 7611 } 7612 7613 return false; 7614 } 7615 7616 /// See if we can lower a mempcpy call into an optimized form. If so, return 7617 /// true and lower it. Otherwise return false, and it will be lowered like a 7618 /// normal call. 7619 /// The caller already checked that \p I calls the appropriate LibFunc with a 7620 /// correct prototype. 7621 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 7622 SDValue Dst = getValue(I.getArgOperand(0)); 7623 SDValue Src = getValue(I.getArgOperand(1)); 7624 SDValue Size = getValue(I.getArgOperand(2)); 7625 7626 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 7627 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 7628 // DAG::getMemcpy needs Alignment to be defined. 7629 Align Alignment = std::min(DstAlign, SrcAlign); 7630 7631 bool isVol = false; 7632 SDLoc sdl = getCurSDLoc(); 7633 7634 // In the mempcpy context we need to pass in a false value for isTailCall 7635 // because the return pointer needs to be adjusted by the size of 7636 // the copied memory. 7637 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 7638 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false, 7639 /*isTailCall=*/false, 7640 MachinePointerInfo(I.getArgOperand(0)), 7641 MachinePointerInfo(I.getArgOperand(1))); 7642 assert(MC.getNode() != nullptr && 7643 "** memcpy should not be lowered as TailCall in mempcpy context **"); 7644 DAG.setRoot(MC); 7645 7646 // Check if Size needs to be truncated or extended. 7647 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 7648 7649 // Adjust return pointer to point just past the last dst byte. 7650 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 7651 Dst, Size); 7652 setValue(&I, DstPlusSize); 7653 return true; 7654 } 7655 7656 /// See if we can lower a strcpy call into an optimized form. If so, return 7657 /// true and lower it, otherwise return false and it will be lowered like a 7658 /// normal call. 7659 /// The caller already checked that \p I calls the appropriate LibFunc with a 7660 /// correct prototype. 7661 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 7662 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7663 7664 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7665 std::pair<SDValue, SDValue> Res = 7666 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 7667 getValue(Arg0), getValue(Arg1), 7668 MachinePointerInfo(Arg0), 7669 MachinePointerInfo(Arg1), isStpcpy); 7670 if (Res.first.getNode()) { 7671 setValue(&I, Res.first); 7672 DAG.setRoot(Res.second); 7673 return true; 7674 } 7675 7676 return false; 7677 } 7678 7679 /// See if we can lower a strcmp call into an optimized form. If so, return 7680 /// true and lower it, otherwise return false and it will be lowered like a 7681 /// normal call. 7682 /// The caller already checked that \p I calls the appropriate LibFunc with a 7683 /// correct prototype. 7684 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 7685 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7686 7687 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7688 std::pair<SDValue, SDValue> Res = 7689 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 7690 getValue(Arg0), getValue(Arg1), 7691 MachinePointerInfo(Arg0), 7692 MachinePointerInfo(Arg1)); 7693 if (Res.first.getNode()) { 7694 processIntegerCallValue(I, Res.first, true); 7695 PendingLoads.push_back(Res.second); 7696 return true; 7697 } 7698 7699 return false; 7700 } 7701 7702 /// See if we can lower a strlen call into an optimized form. If so, return 7703 /// true and lower it, otherwise return false and it will be lowered like a 7704 /// normal call. 7705 /// The caller already checked that \p I calls the appropriate LibFunc with a 7706 /// correct prototype. 7707 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 7708 const Value *Arg0 = I.getArgOperand(0); 7709 7710 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7711 std::pair<SDValue, SDValue> Res = 7712 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 7713 getValue(Arg0), MachinePointerInfo(Arg0)); 7714 if (Res.first.getNode()) { 7715 processIntegerCallValue(I, Res.first, false); 7716 PendingLoads.push_back(Res.second); 7717 return true; 7718 } 7719 7720 return false; 7721 } 7722 7723 /// See if we can lower a strnlen call into an optimized form. If so, return 7724 /// true and lower it, otherwise return false and it will be lowered like a 7725 /// normal call. 7726 /// The caller already checked that \p I calls the appropriate LibFunc with a 7727 /// correct prototype. 7728 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 7729 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7730 7731 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7732 std::pair<SDValue, SDValue> Res = 7733 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 7734 getValue(Arg0), getValue(Arg1), 7735 MachinePointerInfo(Arg0)); 7736 if (Res.first.getNode()) { 7737 processIntegerCallValue(I, Res.first, false); 7738 PendingLoads.push_back(Res.second); 7739 return true; 7740 } 7741 7742 return false; 7743 } 7744 7745 /// See if we can lower a unary floating-point operation into an SDNode with 7746 /// the specified Opcode. If so, return true and lower it, otherwise return 7747 /// false and it will be lowered like a normal call. 7748 /// The caller already checked that \p I calls the appropriate LibFunc with a 7749 /// correct prototype. 7750 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 7751 unsigned Opcode) { 7752 // We already checked this call's prototype; verify it doesn't modify errno. 7753 if (!I.onlyReadsMemory()) 7754 return false; 7755 7756 SDNodeFlags Flags; 7757 Flags.copyFMF(cast<FPMathOperator>(I)); 7758 7759 SDValue Tmp = getValue(I.getArgOperand(0)); 7760 setValue(&I, 7761 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 7762 return true; 7763 } 7764 7765 /// See if we can lower a binary floating-point operation into an SDNode with 7766 /// the specified Opcode. If so, return true and lower it. Otherwise return 7767 /// false, and it will be lowered like a normal call. 7768 /// The caller already checked that \p I calls the appropriate LibFunc with a 7769 /// correct prototype. 7770 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 7771 unsigned Opcode) { 7772 // We already checked this call's prototype; verify it doesn't modify errno. 7773 if (!I.onlyReadsMemory()) 7774 return false; 7775 7776 SDNodeFlags Flags; 7777 Flags.copyFMF(cast<FPMathOperator>(I)); 7778 7779 SDValue Tmp0 = getValue(I.getArgOperand(0)); 7780 SDValue Tmp1 = getValue(I.getArgOperand(1)); 7781 EVT VT = Tmp0.getValueType(); 7782 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 7783 return true; 7784 } 7785 7786 void SelectionDAGBuilder::visitCall(const CallInst &I) { 7787 // Handle inline assembly differently. 7788 if (I.isInlineAsm()) { 7789 visitInlineAsm(I); 7790 return; 7791 } 7792 7793 if (Function *F = I.getCalledFunction()) { 7794 if (F->isDeclaration()) { 7795 // Is this an LLVM intrinsic or a target-specific intrinsic? 7796 unsigned IID = F->getIntrinsicID(); 7797 if (!IID) 7798 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7799 IID = II->getIntrinsicID(F); 7800 7801 if (IID) { 7802 visitIntrinsicCall(I, IID); 7803 return; 7804 } 7805 } 7806 7807 // Check for well-known libc/libm calls. If the function is internal, it 7808 // can't be a library call. Don't do the check if marked as nobuiltin for 7809 // some reason or the call site requires strict floating point semantics. 7810 LibFunc Func; 7811 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7812 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7813 LibInfo->hasOptimizedCodeGen(Func)) { 7814 switch (Func) { 7815 default: break; 7816 case LibFunc_bcmp: 7817 if (visitMemCmpBCmpCall(I)) 7818 return; 7819 break; 7820 case LibFunc_copysign: 7821 case LibFunc_copysignf: 7822 case LibFunc_copysignl: 7823 // We already checked this call's prototype; verify it doesn't modify 7824 // errno. 7825 if (I.onlyReadsMemory()) { 7826 SDValue LHS = getValue(I.getArgOperand(0)); 7827 SDValue RHS = getValue(I.getArgOperand(1)); 7828 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7829 LHS.getValueType(), LHS, RHS)); 7830 return; 7831 } 7832 break; 7833 case LibFunc_fabs: 7834 case LibFunc_fabsf: 7835 case LibFunc_fabsl: 7836 if (visitUnaryFloatCall(I, ISD::FABS)) 7837 return; 7838 break; 7839 case LibFunc_fmin: 7840 case LibFunc_fminf: 7841 case LibFunc_fminl: 7842 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7843 return; 7844 break; 7845 case LibFunc_fmax: 7846 case LibFunc_fmaxf: 7847 case LibFunc_fmaxl: 7848 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7849 return; 7850 break; 7851 case LibFunc_sin: 7852 case LibFunc_sinf: 7853 case LibFunc_sinl: 7854 if (visitUnaryFloatCall(I, ISD::FSIN)) 7855 return; 7856 break; 7857 case LibFunc_cos: 7858 case LibFunc_cosf: 7859 case LibFunc_cosl: 7860 if (visitUnaryFloatCall(I, ISD::FCOS)) 7861 return; 7862 break; 7863 case LibFunc_sqrt: 7864 case LibFunc_sqrtf: 7865 case LibFunc_sqrtl: 7866 case LibFunc_sqrt_finite: 7867 case LibFunc_sqrtf_finite: 7868 case LibFunc_sqrtl_finite: 7869 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7870 return; 7871 break; 7872 case LibFunc_floor: 7873 case LibFunc_floorf: 7874 case LibFunc_floorl: 7875 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7876 return; 7877 break; 7878 case LibFunc_nearbyint: 7879 case LibFunc_nearbyintf: 7880 case LibFunc_nearbyintl: 7881 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7882 return; 7883 break; 7884 case LibFunc_ceil: 7885 case LibFunc_ceilf: 7886 case LibFunc_ceill: 7887 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7888 return; 7889 break; 7890 case LibFunc_rint: 7891 case LibFunc_rintf: 7892 case LibFunc_rintl: 7893 if (visitUnaryFloatCall(I, ISD::FRINT)) 7894 return; 7895 break; 7896 case LibFunc_round: 7897 case LibFunc_roundf: 7898 case LibFunc_roundl: 7899 if (visitUnaryFloatCall(I, ISD::FROUND)) 7900 return; 7901 break; 7902 case LibFunc_trunc: 7903 case LibFunc_truncf: 7904 case LibFunc_truncl: 7905 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7906 return; 7907 break; 7908 case LibFunc_log2: 7909 case LibFunc_log2f: 7910 case LibFunc_log2l: 7911 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7912 return; 7913 break; 7914 case LibFunc_exp2: 7915 case LibFunc_exp2f: 7916 case LibFunc_exp2l: 7917 if (visitUnaryFloatCall(I, ISD::FEXP2)) 7918 return; 7919 break; 7920 case LibFunc_memcmp: 7921 if (visitMemCmpBCmpCall(I)) 7922 return; 7923 break; 7924 case LibFunc_mempcpy: 7925 if (visitMemPCpyCall(I)) 7926 return; 7927 break; 7928 case LibFunc_memchr: 7929 if (visitMemChrCall(I)) 7930 return; 7931 break; 7932 case LibFunc_strcpy: 7933 if (visitStrCpyCall(I, false)) 7934 return; 7935 break; 7936 case LibFunc_stpcpy: 7937 if (visitStrCpyCall(I, true)) 7938 return; 7939 break; 7940 case LibFunc_strcmp: 7941 if (visitStrCmpCall(I)) 7942 return; 7943 break; 7944 case LibFunc_strlen: 7945 if (visitStrLenCall(I)) 7946 return; 7947 break; 7948 case LibFunc_strnlen: 7949 if (visitStrNLenCall(I)) 7950 return; 7951 break; 7952 } 7953 } 7954 } 7955 7956 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 7957 // have to do anything here to lower funclet bundles. 7958 // CFGuardTarget bundles are lowered in LowerCallTo. 7959 assert(!I.hasOperandBundlesOtherThan( 7960 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 7961 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 7962 LLVMContext::OB_clang_arc_attachedcall}) && 7963 "Cannot lower calls with arbitrary operand bundles!"); 7964 7965 SDValue Callee = getValue(I.getCalledOperand()); 7966 7967 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 7968 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 7969 else 7970 // Check if we can potentially perform a tail call. More detailed checking 7971 // is be done within LowerCallTo, after more information about the call is 7972 // known. 7973 LowerCallTo(I, Callee, I.isTailCall()); 7974 } 7975 7976 namespace { 7977 7978 /// AsmOperandInfo - This contains information for each constraint that we are 7979 /// lowering. 7980 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 7981 public: 7982 /// CallOperand - If this is the result output operand or a clobber 7983 /// this is null, otherwise it is the incoming operand to the CallInst. 7984 /// This gets modified as the asm is processed. 7985 SDValue CallOperand; 7986 7987 /// AssignedRegs - If this is a register or register class operand, this 7988 /// contains the set of register corresponding to the operand. 7989 RegsForValue AssignedRegs; 7990 7991 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 7992 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 7993 } 7994 7995 /// Whether or not this operand accesses memory 7996 bool hasMemory(const TargetLowering &TLI) const { 7997 // Indirect operand accesses access memory. 7998 if (isIndirect) 7999 return true; 8000 8001 for (const auto &Code : Codes) 8002 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 8003 return true; 8004 8005 return false; 8006 } 8007 8008 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 8009 /// corresponds to. If there is no Value* for this operand, it returns 8010 /// MVT::Other. 8011 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 8012 const DataLayout &DL) const { 8013 if (!CallOperandVal) return MVT::Other; 8014 8015 if (isa<BasicBlock>(CallOperandVal)) 8016 return TLI.getProgramPointerTy(DL); 8017 8018 llvm::Type *OpTy = CallOperandVal->getType(); 8019 8020 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 8021 // If this is an indirect operand, the operand is a pointer to the 8022 // accessed type. 8023 if (isIndirect) { 8024 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 8025 if (!PtrTy) 8026 report_fatal_error("Indirect operand for inline asm not a pointer!"); 8027 OpTy = PtrTy->getElementType(); 8028 } 8029 8030 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 8031 if (StructType *STy = dyn_cast<StructType>(OpTy)) 8032 if (STy->getNumElements() == 1) 8033 OpTy = STy->getElementType(0); 8034 8035 // If OpTy is not a single value, it may be a struct/union that we 8036 // can tile with integers. 8037 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 8038 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 8039 switch (BitSize) { 8040 default: break; 8041 case 1: 8042 case 8: 8043 case 16: 8044 case 32: 8045 case 64: 8046 case 128: 8047 OpTy = IntegerType::get(Context, BitSize); 8048 break; 8049 } 8050 } 8051 8052 return TLI.getValueType(DL, OpTy, true); 8053 } 8054 }; 8055 8056 8057 } // end anonymous namespace 8058 8059 /// Make sure that the output operand \p OpInfo and its corresponding input 8060 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 8061 /// out). 8062 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 8063 SDISelAsmOperandInfo &MatchingOpInfo, 8064 SelectionDAG &DAG) { 8065 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 8066 return; 8067 8068 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 8069 const auto &TLI = DAG.getTargetLoweringInfo(); 8070 8071 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 8072 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 8073 OpInfo.ConstraintVT); 8074 std::pair<unsigned, const TargetRegisterClass *> InputRC = 8075 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 8076 MatchingOpInfo.ConstraintVT); 8077 if ((OpInfo.ConstraintVT.isInteger() != 8078 MatchingOpInfo.ConstraintVT.isInteger()) || 8079 (MatchRC.second != InputRC.second)) { 8080 // FIXME: error out in a more elegant fashion 8081 report_fatal_error("Unsupported asm: input constraint" 8082 " with a matching output constraint of" 8083 " incompatible type!"); 8084 } 8085 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 8086 } 8087 8088 /// Get a direct memory input to behave well as an indirect operand. 8089 /// This may introduce stores, hence the need for a \p Chain. 8090 /// \return The (possibly updated) chain. 8091 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 8092 SDISelAsmOperandInfo &OpInfo, 8093 SelectionDAG &DAG) { 8094 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8095 8096 // If we don't have an indirect input, put it in the constpool if we can, 8097 // otherwise spill it to a stack slot. 8098 // TODO: This isn't quite right. We need to handle these according to 8099 // the addressing mode that the constraint wants. Also, this may take 8100 // an additional register for the computation and we don't want that 8101 // either. 8102 8103 // If the operand is a float, integer, or vector constant, spill to a 8104 // constant pool entry to get its address. 8105 const Value *OpVal = OpInfo.CallOperandVal; 8106 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 8107 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 8108 OpInfo.CallOperand = DAG.getConstantPool( 8109 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 8110 return Chain; 8111 } 8112 8113 // Otherwise, create a stack slot and emit a store to it before the asm. 8114 Type *Ty = OpVal->getType(); 8115 auto &DL = DAG.getDataLayout(); 8116 uint64_t TySize = DL.getTypeAllocSize(Ty); 8117 MachineFunction &MF = DAG.getMachineFunction(); 8118 int SSFI = MF.getFrameInfo().CreateStackObject( 8119 TySize, DL.getPrefTypeAlign(Ty), false); 8120 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 8121 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 8122 MachinePointerInfo::getFixedStack(MF, SSFI), 8123 TLI.getMemValueType(DL, Ty)); 8124 OpInfo.CallOperand = StackSlot; 8125 8126 return Chain; 8127 } 8128 8129 /// GetRegistersForValue - Assign registers (virtual or physical) for the 8130 /// specified operand. We prefer to assign virtual registers, to allow the 8131 /// register allocator to handle the assignment process. However, if the asm 8132 /// uses features that we can't model on machineinstrs, we have SDISel do the 8133 /// allocation. This produces generally horrible, but correct, code. 8134 /// 8135 /// OpInfo describes the operand 8136 /// RefOpInfo describes the matching operand if any, the operand otherwise 8137 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 8138 SDISelAsmOperandInfo &OpInfo, 8139 SDISelAsmOperandInfo &RefOpInfo) { 8140 LLVMContext &Context = *DAG.getContext(); 8141 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8142 8143 MachineFunction &MF = DAG.getMachineFunction(); 8144 SmallVector<unsigned, 4> Regs; 8145 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8146 8147 // No work to do for memory operations. 8148 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 8149 return; 8150 8151 // If this is a constraint for a single physreg, or a constraint for a 8152 // register class, find it. 8153 unsigned AssignedReg; 8154 const TargetRegisterClass *RC; 8155 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 8156 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 8157 // RC is unset only on failure. Return immediately. 8158 if (!RC) 8159 return; 8160 8161 // Get the actual register value type. This is important, because the user 8162 // may have asked for (e.g.) the AX register in i32 type. We need to 8163 // remember that AX is actually i16 to get the right extension. 8164 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 8165 8166 if (OpInfo.ConstraintVT != MVT::Other) { 8167 // If this is an FP operand in an integer register (or visa versa), or more 8168 // generally if the operand value disagrees with the register class we plan 8169 // to stick it in, fix the operand type. 8170 // 8171 // If this is an input value, the bitcast to the new type is done now. 8172 // Bitcast for output value is done at the end of visitInlineAsm(). 8173 if ((OpInfo.Type == InlineAsm::isOutput || 8174 OpInfo.Type == InlineAsm::isInput) && 8175 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 8176 // Try to convert to the first EVT that the reg class contains. If the 8177 // types are identical size, use a bitcast to convert (e.g. two differing 8178 // vector types). Note: output bitcast is done at the end of 8179 // visitInlineAsm(). 8180 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 8181 // Exclude indirect inputs while they are unsupported because the code 8182 // to perform the load is missing and thus OpInfo.CallOperand still 8183 // refers to the input address rather than the pointed-to value. 8184 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 8185 OpInfo.CallOperand = 8186 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 8187 OpInfo.ConstraintVT = RegVT; 8188 // If the operand is an FP value and we want it in integer registers, 8189 // use the corresponding integer type. This turns an f64 value into 8190 // i64, which can be passed with two i32 values on a 32-bit machine. 8191 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 8192 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 8193 if (OpInfo.Type == InlineAsm::isInput) 8194 OpInfo.CallOperand = 8195 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 8196 OpInfo.ConstraintVT = VT; 8197 } 8198 } 8199 } 8200 8201 // No need to allocate a matching input constraint since the constraint it's 8202 // matching to has already been allocated. 8203 if (OpInfo.isMatchingInputConstraint()) 8204 return; 8205 8206 EVT ValueVT = OpInfo.ConstraintVT; 8207 if (OpInfo.ConstraintVT == MVT::Other) 8208 ValueVT = RegVT; 8209 8210 // Initialize NumRegs. 8211 unsigned NumRegs = 1; 8212 if (OpInfo.ConstraintVT != MVT::Other) 8213 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 8214 8215 // If this is a constraint for a specific physical register, like {r17}, 8216 // assign it now. 8217 8218 // If this associated to a specific register, initialize iterator to correct 8219 // place. If virtual, make sure we have enough registers 8220 8221 // Initialize iterator if necessary 8222 TargetRegisterClass::iterator I = RC->begin(); 8223 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8224 8225 // Do not check for single registers. 8226 if (AssignedReg) { 8227 for (; *I != AssignedReg; ++I) 8228 assert(I != RC->end() && "AssignedReg should be member of RC"); 8229 } 8230 8231 for (; NumRegs; --NumRegs, ++I) { 8232 assert(I != RC->end() && "Ran out of registers to allocate!"); 8233 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8234 Regs.push_back(R); 8235 } 8236 8237 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8238 } 8239 8240 static unsigned 8241 findMatchingInlineAsmOperand(unsigned OperandNo, 8242 const std::vector<SDValue> &AsmNodeOperands) { 8243 // Scan until we find the definition we already emitted of this operand. 8244 unsigned CurOp = InlineAsm::Op_FirstOperand; 8245 for (; OperandNo; --OperandNo) { 8246 // Advance to the next operand. 8247 unsigned OpFlag = 8248 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8249 assert((InlineAsm::isRegDefKind(OpFlag) || 8250 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8251 InlineAsm::isMemKind(OpFlag)) && 8252 "Skipped past definitions?"); 8253 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8254 } 8255 return CurOp; 8256 } 8257 8258 namespace { 8259 8260 class ExtraFlags { 8261 unsigned Flags = 0; 8262 8263 public: 8264 explicit ExtraFlags(const CallBase &Call) { 8265 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8266 if (IA->hasSideEffects()) 8267 Flags |= InlineAsm::Extra_HasSideEffects; 8268 if (IA->isAlignStack()) 8269 Flags |= InlineAsm::Extra_IsAlignStack; 8270 if (Call.isConvergent()) 8271 Flags |= InlineAsm::Extra_IsConvergent; 8272 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8273 } 8274 8275 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8276 // Ideally, we would only check against memory constraints. However, the 8277 // meaning of an Other constraint can be target-specific and we can't easily 8278 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8279 // for Other constraints as well. 8280 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8281 OpInfo.ConstraintType == TargetLowering::C_Other) { 8282 if (OpInfo.Type == InlineAsm::isInput) 8283 Flags |= InlineAsm::Extra_MayLoad; 8284 else if (OpInfo.Type == InlineAsm::isOutput) 8285 Flags |= InlineAsm::Extra_MayStore; 8286 else if (OpInfo.Type == InlineAsm::isClobber) 8287 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8288 } 8289 } 8290 8291 unsigned get() const { return Flags; } 8292 }; 8293 8294 } // end anonymous namespace 8295 8296 /// visitInlineAsm - Handle a call to an InlineAsm object. 8297 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call) { 8298 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8299 8300 /// ConstraintOperands - Information about all of the constraints. 8301 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 8302 8303 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8304 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8305 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 8306 8307 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8308 // AsmDialect, MayLoad, MayStore). 8309 bool HasSideEffect = IA->hasSideEffects(); 8310 ExtraFlags ExtraInfo(Call); 8311 8312 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 8313 unsigned ResNo = 0; // ResNo - The result number of the next output. 8314 unsigned NumMatchingOps = 0; 8315 for (auto &T : TargetConstraints) { 8316 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8317 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8318 8319 // Compute the value type for each operand. 8320 if (OpInfo.Type == InlineAsm::isInput || 8321 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 8322 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++); 8323 8324 // Process the call argument. BasicBlocks are labels, currently appearing 8325 // only in asm's. 8326 if (isa<CallBrInst>(Call) && 8327 ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() - 8328 cast<CallBrInst>(&Call)->getNumIndirectDests() - 8329 NumMatchingOps) && 8330 (NumMatchingOps == 0 || 8331 ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() - 8332 NumMatchingOps))) { 8333 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal); 8334 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true); 8335 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT); 8336 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 8337 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 8338 } else { 8339 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8340 } 8341 8342 EVT VT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, 8343 DAG.getDataLayout()); 8344 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other; 8345 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 8346 // The return value of the call is this value. As such, there is no 8347 // corresponding argument. 8348 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8349 if (StructType *STy = dyn_cast<StructType>(Call.getType())) { 8350 OpInfo.ConstraintVT = TLI.getSimpleValueType( 8351 DAG.getDataLayout(), STy->getElementType(ResNo)); 8352 } else { 8353 assert(ResNo == 0 && "Asm only has one result!"); 8354 OpInfo.ConstraintVT = 8355 TLI.getSimpleValueType(DAG.getDataLayout(), Call.getType()); 8356 } 8357 ++ResNo; 8358 } else { 8359 OpInfo.ConstraintVT = MVT::Other; 8360 } 8361 8362 if (OpInfo.hasMatchingInput()) 8363 ++NumMatchingOps; 8364 8365 if (!HasSideEffect) 8366 HasSideEffect = OpInfo.hasMemory(TLI); 8367 8368 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8369 // FIXME: Could we compute this on OpInfo rather than T? 8370 8371 // Compute the constraint code and ConstraintType to use. 8372 TLI.ComputeConstraintToUse(T, SDValue()); 8373 8374 if (T.ConstraintType == TargetLowering::C_Immediate && 8375 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8376 // We've delayed emitting a diagnostic like the "n" constraint because 8377 // inlining could cause an integer showing up. 8378 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 8379 "' expects an integer constant " 8380 "expression"); 8381 8382 ExtraInfo.update(T); 8383 } 8384 8385 8386 // We won't need to flush pending loads if this asm doesn't touch 8387 // memory and is nonvolatile. 8388 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8389 8390 bool IsCallBr = isa<CallBrInst>(Call); 8391 if (IsCallBr) { 8392 // If this is a callbr we need to flush pending exports since inlineasm_br 8393 // is a terminator. We need to do this before nodes are glued to 8394 // the inlineasm_br node. 8395 Chain = getControlRoot(); 8396 } 8397 8398 // Second pass over the constraints: compute which constraint option to use. 8399 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8400 // If this is an output operand with a matching input operand, look up the 8401 // matching input. If their types mismatch, e.g. one is an integer, the 8402 // other is floating point, or their sizes are different, flag it as an 8403 // error. 8404 if (OpInfo.hasMatchingInput()) { 8405 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8406 patchMatchingInput(OpInfo, Input, DAG); 8407 } 8408 8409 // Compute the constraint code and ConstraintType to use. 8410 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8411 8412 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8413 OpInfo.Type == InlineAsm::isClobber) 8414 continue; 8415 8416 // If this is a memory input, and if the operand is not indirect, do what we 8417 // need to provide an address for the memory input. 8418 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8419 !OpInfo.isIndirect) { 8420 assert((OpInfo.isMultipleAlternative || 8421 (OpInfo.Type == InlineAsm::isInput)) && 8422 "Can only indirectify direct input operands!"); 8423 8424 // Memory operands really want the address of the value. 8425 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8426 8427 // There is no longer a Value* corresponding to this operand. 8428 OpInfo.CallOperandVal = nullptr; 8429 8430 // It is now an indirect operand. 8431 OpInfo.isIndirect = true; 8432 } 8433 8434 } 8435 8436 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8437 std::vector<SDValue> AsmNodeOperands; 8438 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8439 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8440 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 8441 8442 // If we have a !srcloc metadata node associated with it, we want to attach 8443 // this to the ultimately generated inline asm machineinstr. To do this, we 8444 // pass in the third operand as this (potentially null) inline asm MDNode. 8445 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 8446 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8447 8448 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8449 // bits as operand 3. 8450 AsmNodeOperands.push_back(DAG.getTargetConstant( 8451 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8452 8453 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8454 // this, assign virtual and physical registers for inputs and otput. 8455 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8456 // Assign Registers. 8457 SDISelAsmOperandInfo &RefOpInfo = 8458 OpInfo.isMatchingInputConstraint() 8459 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8460 : OpInfo; 8461 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8462 8463 auto DetectWriteToReservedRegister = [&]() { 8464 const MachineFunction &MF = DAG.getMachineFunction(); 8465 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8466 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 8467 if (Register::isPhysicalRegister(Reg) && 8468 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 8469 const char *RegName = TRI.getName(Reg); 8470 emitInlineAsmError(Call, "write to reserved register '" + 8471 Twine(RegName) + "'"); 8472 return true; 8473 } 8474 } 8475 return false; 8476 }; 8477 8478 switch (OpInfo.Type) { 8479 case InlineAsm::isOutput: 8480 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8481 unsigned ConstraintID = 8482 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8483 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8484 "Failed to convert memory constraint code to constraint id."); 8485 8486 // Add information to the INLINEASM node to know about this output. 8487 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8488 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8489 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8490 MVT::i32)); 8491 AsmNodeOperands.push_back(OpInfo.CallOperand); 8492 } else { 8493 // Otherwise, this outputs to a register (directly for C_Register / 8494 // C_RegisterClass, and a target-defined fashion for 8495 // C_Immediate/C_Other). Find a register that we can use. 8496 if (OpInfo.AssignedRegs.Regs.empty()) { 8497 emitInlineAsmError( 8498 Call, "couldn't allocate output register for constraint '" + 8499 Twine(OpInfo.ConstraintCode) + "'"); 8500 return; 8501 } 8502 8503 if (DetectWriteToReservedRegister()) 8504 return; 8505 8506 // Add information to the INLINEASM node to know that this register is 8507 // set. 8508 OpInfo.AssignedRegs.AddInlineAsmOperands( 8509 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8510 : InlineAsm::Kind_RegDef, 8511 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8512 } 8513 break; 8514 8515 case InlineAsm::isInput: { 8516 SDValue InOperandVal = OpInfo.CallOperand; 8517 8518 if (OpInfo.isMatchingInputConstraint()) { 8519 // If this is required to match an output register we have already set, 8520 // just use its register. 8521 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8522 AsmNodeOperands); 8523 unsigned OpFlag = 8524 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8525 if (InlineAsm::isRegDefKind(OpFlag) || 8526 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8527 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8528 if (OpInfo.isIndirect) { 8529 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8530 emitInlineAsmError(Call, "inline asm not supported yet: " 8531 "don't know how to handle tied " 8532 "indirect register inputs"); 8533 return; 8534 } 8535 8536 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 8537 SmallVector<unsigned, 4> Regs; 8538 8539 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { 8540 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8541 MachineRegisterInfo &RegInfo = 8542 DAG.getMachineFunction().getRegInfo(); 8543 for (unsigned i = 0; i != NumRegs; ++i) 8544 Regs.push_back(RegInfo.createVirtualRegister(RC)); 8545 } else { 8546 emitInlineAsmError(Call, 8547 "inline asm error: This value type register " 8548 "class is not natively supported!"); 8549 return; 8550 } 8551 8552 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8553 8554 SDLoc dl = getCurSDLoc(); 8555 // Use the produced MatchedRegs object to 8556 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call); 8557 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8558 true, OpInfo.getMatchedOperand(), dl, 8559 DAG, AsmNodeOperands); 8560 break; 8561 } 8562 8563 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8564 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8565 "Unexpected number of operands"); 8566 // Add information to the INLINEASM node to know about this input. 8567 // See InlineAsm.h isUseOperandTiedToDef. 8568 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8569 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8570 OpInfo.getMatchedOperand()); 8571 AsmNodeOperands.push_back(DAG.getTargetConstant( 8572 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8573 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8574 break; 8575 } 8576 8577 // Treat indirect 'X' constraint as memory. 8578 if (OpInfo.ConstraintType == TargetLowering::C_Other && 8579 OpInfo.isIndirect) 8580 OpInfo.ConstraintType = TargetLowering::C_Memory; 8581 8582 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 8583 OpInfo.ConstraintType == TargetLowering::C_Other) { 8584 std::vector<SDValue> Ops; 8585 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 8586 Ops, DAG); 8587 if (Ops.empty()) { 8588 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 8589 if (isa<ConstantSDNode>(InOperandVal)) { 8590 emitInlineAsmError(Call, "value out of range for constraint '" + 8591 Twine(OpInfo.ConstraintCode) + "'"); 8592 return; 8593 } 8594 8595 emitInlineAsmError(Call, 8596 "invalid operand for inline asm constraint '" + 8597 Twine(OpInfo.ConstraintCode) + "'"); 8598 return; 8599 } 8600 8601 // Add information to the INLINEASM node to know about this input. 8602 unsigned ResOpType = 8603 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 8604 AsmNodeOperands.push_back(DAG.getTargetConstant( 8605 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8606 llvm::append_range(AsmNodeOperands, Ops); 8607 break; 8608 } 8609 8610 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8611 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 8612 assert(InOperandVal.getValueType() == 8613 TLI.getPointerTy(DAG.getDataLayout()) && 8614 "Memory operands expect pointer values"); 8615 8616 unsigned ConstraintID = 8617 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8618 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8619 "Failed to convert memory constraint code to constraint id."); 8620 8621 // Add information to the INLINEASM node to know about this input. 8622 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8623 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 8624 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 8625 getCurSDLoc(), 8626 MVT::i32)); 8627 AsmNodeOperands.push_back(InOperandVal); 8628 break; 8629 } 8630 8631 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 8632 OpInfo.ConstraintType == TargetLowering::C_Register) && 8633 "Unknown constraint type!"); 8634 8635 // TODO: Support this. 8636 if (OpInfo.isIndirect) { 8637 emitInlineAsmError( 8638 Call, "Don't know how to handle indirect register inputs yet " 8639 "for constraint '" + 8640 Twine(OpInfo.ConstraintCode) + "'"); 8641 return; 8642 } 8643 8644 // Copy the input into the appropriate registers. 8645 if (OpInfo.AssignedRegs.Regs.empty()) { 8646 emitInlineAsmError(Call, 8647 "couldn't allocate input reg for constraint '" + 8648 Twine(OpInfo.ConstraintCode) + "'"); 8649 return; 8650 } 8651 8652 if (DetectWriteToReservedRegister()) 8653 return; 8654 8655 SDLoc dl = getCurSDLoc(); 8656 8657 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 8658 &Call); 8659 8660 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 8661 dl, DAG, AsmNodeOperands); 8662 break; 8663 } 8664 case InlineAsm::isClobber: 8665 // Add the clobbered value to the operand list, so that the register 8666 // allocator is aware that the physreg got clobbered. 8667 if (!OpInfo.AssignedRegs.Regs.empty()) 8668 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 8669 false, 0, getCurSDLoc(), DAG, 8670 AsmNodeOperands); 8671 break; 8672 } 8673 } 8674 8675 // Finish up input operands. Set the input chain and add the flag last. 8676 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 8677 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 8678 8679 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 8680 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 8681 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 8682 Flag = Chain.getValue(1); 8683 8684 // Do additional work to generate outputs. 8685 8686 SmallVector<EVT, 1> ResultVTs; 8687 SmallVector<SDValue, 1> ResultValues; 8688 SmallVector<SDValue, 8> OutChains; 8689 8690 llvm::Type *CallResultType = Call.getType(); 8691 ArrayRef<Type *> ResultTypes; 8692 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 8693 ResultTypes = StructResult->elements(); 8694 else if (!CallResultType->isVoidTy()) 8695 ResultTypes = makeArrayRef(CallResultType); 8696 8697 auto CurResultType = ResultTypes.begin(); 8698 auto handleRegAssign = [&](SDValue V) { 8699 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 8700 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 8701 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 8702 ++CurResultType; 8703 // If the type of the inline asm call site return value is different but has 8704 // same size as the type of the asm output bitcast it. One example of this 8705 // is for vectors with different width / number of elements. This can 8706 // happen for register classes that can contain multiple different value 8707 // types. The preg or vreg allocated may not have the same VT as was 8708 // expected. 8709 // 8710 // This can also happen for a return value that disagrees with the register 8711 // class it is put in, eg. a double in a general-purpose register on a 8712 // 32-bit machine. 8713 if (ResultVT != V.getValueType() && 8714 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 8715 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 8716 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 8717 V.getValueType().isInteger()) { 8718 // If a result value was tied to an input value, the computed result 8719 // may have a wider width than the expected result. Extract the 8720 // relevant portion. 8721 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 8722 } 8723 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 8724 ResultVTs.push_back(ResultVT); 8725 ResultValues.push_back(V); 8726 }; 8727 8728 // Deal with output operands. 8729 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8730 if (OpInfo.Type == InlineAsm::isOutput) { 8731 SDValue Val; 8732 // Skip trivial output operands. 8733 if (OpInfo.AssignedRegs.Regs.empty()) 8734 continue; 8735 8736 switch (OpInfo.ConstraintType) { 8737 case TargetLowering::C_Register: 8738 case TargetLowering::C_RegisterClass: 8739 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 8740 Chain, &Flag, &Call); 8741 break; 8742 case TargetLowering::C_Immediate: 8743 case TargetLowering::C_Other: 8744 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 8745 OpInfo, DAG); 8746 break; 8747 case TargetLowering::C_Memory: 8748 break; // Already handled. 8749 case TargetLowering::C_Unknown: 8750 assert(false && "Unexpected unknown constraint"); 8751 } 8752 8753 // Indirect output manifest as stores. Record output chains. 8754 if (OpInfo.isIndirect) { 8755 const Value *Ptr = OpInfo.CallOperandVal; 8756 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 8757 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 8758 MachinePointerInfo(Ptr)); 8759 OutChains.push_back(Store); 8760 } else { 8761 // generate CopyFromRegs to associated registers. 8762 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8763 if (Val.getOpcode() == ISD::MERGE_VALUES) { 8764 for (const SDValue &V : Val->op_values()) 8765 handleRegAssign(V); 8766 } else 8767 handleRegAssign(Val); 8768 } 8769 } 8770 } 8771 8772 // Set results. 8773 if (!ResultValues.empty()) { 8774 assert(CurResultType == ResultTypes.end() && 8775 "Mismatch in number of ResultTypes"); 8776 assert(ResultValues.size() == ResultTypes.size() && 8777 "Mismatch in number of output operands in asm result"); 8778 8779 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 8780 DAG.getVTList(ResultVTs), ResultValues); 8781 setValue(&Call, V); 8782 } 8783 8784 // Collect store chains. 8785 if (!OutChains.empty()) 8786 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 8787 8788 // Only Update Root if inline assembly has a memory effect. 8789 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr) 8790 DAG.setRoot(Chain); 8791 } 8792 8793 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 8794 const Twine &Message) { 8795 LLVMContext &Ctx = *DAG.getContext(); 8796 Ctx.emitError(&Call, Message); 8797 8798 // Make sure we leave the DAG in a valid state 8799 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8800 SmallVector<EVT, 1> ValueVTs; 8801 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 8802 8803 if (ValueVTs.empty()) 8804 return; 8805 8806 SmallVector<SDValue, 1> Ops; 8807 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 8808 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 8809 8810 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 8811 } 8812 8813 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 8814 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 8815 MVT::Other, getRoot(), 8816 getValue(I.getArgOperand(0)), 8817 DAG.getSrcValue(I.getArgOperand(0)))); 8818 } 8819 8820 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 8821 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8822 const DataLayout &DL = DAG.getDataLayout(); 8823 SDValue V = DAG.getVAArg( 8824 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 8825 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 8826 DL.getABITypeAlign(I.getType()).value()); 8827 DAG.setRoot(V.getValue(1)); 8828 8829 if (I.getType()->isPointerTy()) 8830 V = DAG.getPtrExtOrTrunc( 8831 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 8832 setValue(&I, V); 8833 } 8834 8835 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 8836 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 8837 MVT::Other, getRoot(), 8838 getValue(I.getArgOperand(0)), 8839 DAG.getSrcValue(I.getArgOperand(0)))); 8840 } 8841 8842 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 8843 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 8844 MVT::Other, getRoot(), 8845 getValue(I.getArgOperand(0)), 8846 getValue(I.getArgOperand(1)), 8847 DAG.getSrcValue(I.getArgOperand(0)), 8848 DAG.getSrcValue(I.getArgOperand(1)))); 8849 } 8850 8851 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 8852 const Instruction &I, 8853 SDValue Op) { 8854 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 8855 if (!Range) 8856 return Op; 8857 8858 ConstantRange CR = getConstantRangeFromMetadata(*Range); 8859 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 8860 return Op; 8861 8862 APInt Lo = CR.getUnsignedMin(); 8863 if (!Lo.isMinValue()) 8864 return Op; 8865 8866 APInt Hi = CR.getUnsignedMax(); 8867 unsigned Bits = std::max(Hi.getActiveBits(), 8868 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 8869 8870 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8871 8872 SDLoc SL = getCurSDLoc(); 8873 8874 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8875 DAG.getValueType(SmallVT)); 8876 unsigned NumVals = Op.getNode()->getNumValues(); 8877 if (NumVals == 1) 8878 return ZExt; 8879 8880 SmallVector<SDValue, 4> Ops; 8881 8882 Ops.push_back(ZExt); 8883 for (unsigned I = 1; I != NumVals; ++I) 8884 Ops.push_back(Op.getValue(I)); 8885 8886 return DAG.getMergeValues(Ops, SL); 8887 } 8888 8889 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8890 /// the call being lowered. 8891 /// 8892 /// This is a helper for lowering intrinsics that follow a target calling 8893 /// convention or require stack pointer adjustment. Only a subset of the 8894 /// intrinsic's operands need to participate in the calling convention. 8895 void SelectionDAGBuilder::populateCallLoweringInfo( 8896 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 8897 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8898 bool IsPatchPoint) { 8899 TargetLowering::ArgListTy Args; 8900 Args.reserve(NumArgs); 8901 8902 // Populate the argument list. 8903 // Attributes for args start at offset 1, after the return attribute. 8904 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8905 ArgI != ArgE; ++ArgI) { 8906 const Value *V = Call->getOperand(ArgI); 8907 8908 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 8909 8910 TargetLowering::ArgListEntry Entry; 8911 Entry.Node = getValue(V); 8912 Entry.Ty = V->getType(); 8913 Entry.setAttributes(Call, ArgI); 8914 Args.push_back(Entry); 8915 } 8916 8917 CLI.setDebugLoc(getCurSDLoc()) 8918 .setChain(getRoot()) 8919 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 8920 .setDiscardResult(Call->use_empty()) 8921 .setIsPatchPoint(IsPatchPoint) 8922 .setIsPreallocated( 8923 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 8924 } 8925 8926 /// Add a stack map intrinsic call's live variable operands to a stackmap 8927 /// or patchpoint target node's operand list. 8928 /// 8929 /// Constants are converted to TargetConstants purely as an optimization to 8930 /// avoid constant materialization and register allocation. 8931 /// 8932 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 8933 /// generate addess computation nodes, and so FinalizeISel can convert the 8934 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 8935 /// address materialization and register allocation, but may also be required 8936 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 8937 /// alloca in the entry block, then the runtime may assume that the alloca's 8938 /// StackMap location can be read immediately after compilation and that the 8939 /// location is valid at any point during execution (this is similar to the 8940 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 8941 /// only available in a register, then the runtime would need to trap when 8942 /// execution reaches the StackMap in order to read the alloca's location. 8943 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 8944 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 8945 SelectionDAGBuilder &Builder) { 8946 for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) { 8947 SDValue OpVal = Builder.getValue(Call.getArgOperand(i)); 8948 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 8949 Ops.push_back( 8950 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 8951 Ops.push_back( 8952 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 8953 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 8954 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 8955 Ops.push_back(Builder.DAG.getTargetFrameIndex( 8956 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 8957 } else 8958 Ops.push_back(OpVal); 8959 } 8960 } 8961 8962 /// Lower llvm.experimental.stackmap directly to its target opcode. 8963 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 8964 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 8965 // [live variables...]) 8966 8967 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 8968 8969 SDValue Chain, InFlag, Callee, NullPtr; 8970 SmallVector<SDValue, 32> Ops; 8971 8972 SDLoc DL = getCurSDLoc(); 8973 Callee = getValue(CI.getCalledOperand()); 8974 NullPtr = DAG.getIntPtrConstant(0, DL, true); 8975 8976 // The stackmap intrinsic only records the live variables (the arguments 8977 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 8978 // intrinsic, this won't be lowered to a function call. This means we don't 8979 // have to worry about calling conventions and target specific lowering code. 8980 // Instead we perform the call lowering right here. 8981 // 8982 // chain, flag = CALLSEQ_START(chain, 0, 0) 8983 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 8984 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 8985 // 8986 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 8987 InFlag = Chain.getValue(1); 8988 8989 // Add the <id> and <numBytes> constants. 8990 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 8991 Ops.push_back(DAG.getTargetConstant( 8992 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 8993 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 8994 Ops.push_back(DAG.getTargetConstant( 8995 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 8996 MVT::i32)); 8997 8998 // Push live variables for the stack map. 8999 addStackMapLiveVars(CI, 2, DL, Ops, *this); 9000 9001 // We are not pushing any register mask info here on the operands list, 9002 // because the stackmap doesn't clobber anything. 9003 9004 // Push the chain and the glue flag. 9005 Ops.push_back(Chain); 9006 Ops.push_back(InFlag); 9007 9008 // Create the STACKMAP node. 9009 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9010 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 9011 Chain = SDValue(SM, 0); 9012 InFlag = Chain.getValue(1); 9013 9014 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 9015 9016 // Stackmaps don't generate values, so nothing goes into the NodeMap. 9017 9018 // Set the root to the target-lowered call chain. 9019 DAG.setRoot(Chain); 9020 9021 // Inform the Frame Information that we have a stackmap in this function. 9022 FuncInfo.MF->getFrameInfo().setHasStackMap(); 9023 } 9024 9025 /// Lower llvm.experimental.patchpoint directly to its target opcode. 9026 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 9027 const BasicBlock *EHPadBB) { 9028 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 9029 // i32 <numBytes>, 9030 // i8* <target>, 9031 // i32 <numArgs>, 9032 // [Args...], 9033 // [live variables...]) 9034 9035 CallingConv::ID CC = CB.getCallingConv(); 9036 bool IsAnyRegCC = CC == CallingConv::AnyReg; 9037 bool HasDef = !CB.getType()->isVoidTy(); 9038 SDLoc dl = getCurSDLoc(); 9039 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 9040 9041 // Handle immediate and symbolic callees. 9042 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 9043 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 9044 /*isTarget=*/true); 9045 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 9046 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 9047 SDLoc(SymbolicCallee), 9048 SymbolicCallee->getValueType(0)); 9049 9050 // Get the real number of arguments participating in the call <numArgs> 9051 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 9052 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 9053 9054 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 9055 // Intrinsics include all meta-operands up to but not including CC. 9056 unsigned NumMetaOpers = PatchPointOpers::CCPos; 9057 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 9058 "Not enough arguments provided to the patchpoint intrinsic"); 9059 9060 // For AnyRegCC the arguments are lowered later on manually. 9061 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 9062 Type *ReturnTy = 9063 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 9064 9065 TargetLowering::CallLoweringInfo CLI(DAG); 9066 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 9067 ReturnTy, true); 9068 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 9069 9070 SDNode *CallEnd = Result.second.getNode(); 9071 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 9072 CallEnd = CallEnd->getOperand(0).getNode(); 9073 9074 /// Get a call instruction from the call sequence chain. 9075 /// Tail calls are not allowed. 9076 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 9077 "Expected a callseq node."); 9078 SDNode *Call = CallEnd->getOperand(0).getNode(); 9079 bool HasGlue = Call->getGluedNode(); 9080 9081 // Replace the target specific call node with the patchable intrinsic. 9082 SmallVector<SDValue, 8> Ops; 9083 9084 // Add the <id> and <numBytes> constants. 9085 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 9086 Ops.push_back(DAG.getTargetConstant( 9087 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 9088 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 9089 Ops.push_back(DAG.getTargetConstant( 9090 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 9091 MVT::i32)); 9092 9093 // Add the callee. 9094 Ops.push_back(Callee); 9095 9096 // Adjust <numArgs> to account for any arguments that have been passed on the 9097 // stack instead. 9098 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 9099 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 9100 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 9101 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 9102 9103 // Add the calling convention 9104 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 9105 9106 // Add the arguments we omitted previously. The register allocator should 9107 // place these in any free register. 9108 if (IsAnyRegCC) 9109 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 9110 Ops.push_back(getValue(CB.getArgOperand(i))); 9111 9112 // Push the arguments from the call instruction up to the register mask. 9113 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 9114 Ops.append(Call->op_begin() + 2, e); 9115 9116 // Push live variables for the stack map. 9117 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 9118 9119 // Push the register mask info. 9120 if (HasGlue) 9121 Ops.push_back(*(Call->op_end()-2)); 9122 else 9123 Ops.push_back(*(Call->op_end()-1)); 9124 9125 // Push the chain (this is originally the first operand of the call, but 9126 // becomes now the last or second to last operand). 9127 Ops.push_back(*(Call->op_begin())); 9128 9129 // Push the glue flag (last operand). 9130 if (HasGlue) 9131 Ops.push_back(*(Call->op_end()-1)); 9132 9133 SDVTList NodeTys; 9134 if (IsAnyRegCC && HasDef) { 9135 // Create the return types based on the intrinsic definition 9136 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9137 SmallVector<EVT, 3> ValueVTs; 9138 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 9139 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 9140 9141 // There is always a chain and a glue type at the end 9142 ValueVTs.push_back(MVT::Other); 9143 ValueVTs.push_back(MVT::Glue); 9144 NodeTys = DAG.getVTList(ValueVTs); 9145 } else 9146 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9147 9148 // Replace the target specific call node with a PATCHPOINT node. 9149 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 9150 dl, NodeTys, Ops); 9151 9152 // Update the NodeMap. 9153 if (HasDef) { 9154 if (IsAnyRegCC) 9155 setValue(&CB, SDValue(MN, 0)); 9156 else 9157 setValue(&CB, Result.first); 9158 } 9159 9160 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 9161 // call sequence. Furthermore the location of the chain and glue can change 9162 // when the AnyReg calling convention is used and the intrinsic returns a 9163 // value. 9164 if (IsAnyRegCC && HasDef) { 9165 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 9166 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 9167 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 9168 } else 9169 DAG.ReplaceAllUsesWith(Call, MN); 9170 DAG.DeleteNode(Call); 9171 9172 // Inform the Frame Information that we have a patchpoint in this function. 9173 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 9174 } 9175 9176 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 9177 unsigned Intrinsic) { 9178 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9179 SDValue Op1 = getValue(I.getArgOperand(0)); 9180 SDValue Op2; 9181 if (I.getNumArgOperands() > 1) 9182 Op2 = getValue(I.getArgOperand(1)); 9183 SDLoc dl = getCurSDLoc(); 9184 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 9185 SDValue Res; 9186 SDNodeFlags SDFlags; 9187 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 9188 SDFlags.copyFMF(*FPMO); 9189 9190 switch (Intrinsic) { 9191 case Intrinsic::vector_reduce_fadd: 9192 if (SDFlags.hasAllowReassociation()) 9193 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 9194 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 9195 SDFlags); 9196 else 9197 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 9198 break; 9199 case Intrinsic::vector_reduce_fmul: 9200 if (SDFlags.hasAllowReassociation()) 9201 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 9202 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 9203 SDFlags); 9204 else 9205 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 9206 break; 9207 case Intrinsic::vector_reduce_add: 9208 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 9209 break; 9210 case Intrinsic::vector_reduce_mul: 9211 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 9212 break; 9213 case Intrinsic::vector_reduce_and: 9214 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 9215 break; 9216 case Intrinsic::vector_reduce_or: 9217 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 9218 break; 9219 case Intrinsic::vector_reduce_xor: 9220 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 9221 break; 9222 case Intrinsic::vector_reduce_smax: 9223 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 9224 break; 9225 case Intrinsic::vector_reduce_smin: 9226 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 9227 break; 9228 case Intrinsic::vector_reduce_umax: 9229 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 9230 break; 9231 case Intrinsic::vector_reduce_umin: 9232 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 9233 break; 9234 case Intrinsic::vector_reduce_fmax: 9235 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 9236 break; 9237 case Intrinsic::vector_reduce_fmin: 9238 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 9239 break; 9240 default: 9241 llvm_unreachable("Unhandled vector reduce intrinsic"); 9242 } 9243 setValue(&I, Res); 9244 } 9245 9246 /// Returns an AttributeList representing the attributes applied to the return 9247 /// value of the given call. 9248 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9249 SmallVector<Attribute::AttrKind, 2> Attrs; 9250 if (CLI.RetSExt) 9251 Attrs.push_back(Attribute::SExt); 9252 if (CLI.RetZExt) 9253 Attrs.push_back(Attribute::ZExt); 9254 if (CLI.IsInReg) 9255 Attrs.push_back(Attribute::InReg); 9256 9257 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9258 Attrs); 9259 } 9260 9261 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9262 /// implementation, which just calls LowerCall. 9263 /// FIXME: When all targets are 9264 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9265 std::pair<SDValue, SDValue> 9266 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9267 // Handle the incoming return values from the call. 9268 CLI.Ins.clear(); 9269 Type *OrigRetTy = CLI.RetTy; 9270 SmallVector<EVT, 4> RetTys; 9271 SmallVector<uint64_t, 4> Offsets; 9272 auto &DL = CLI.DAG.getDataLayout(); 9273 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 9274 9275 if (CLI.IsPostTypeLegalization) { 9276 // If we are lowering a libcall after legalization, split the return type. 9277 SmallVector<EVT, 4> OldRetTys; 9278 SmallVector<uint64_t, 4> OldOffsets; 9279 RetTys.swap(OldRetTys); 9280 Offsets.swap(OldOffsets); 9281 9282 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9283 EVT RetVT = OldRetTys[i]; 9284 uint64_t Offset = OldOffsets[i]; 9285 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9286 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9287 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9288 RetTys.append(NumRegs, RegisterVT); 9289 for (unsigned j = 0; j != NumRegs; ++j) 9290 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9291 } 9292 } 9293 9294 SmallVector<ISD::OutputArg, 4> Outs; 9295 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9296 9297 bool CanLowerReturn = 9298 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9299 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9300 9301 SDValue DemoteStackSlot; 9302 int DemoteStackIdx = -100; 9303 if (!CanLowerReturn) { 9304 // FIXME: equivalent assert? 9305 // assert(!CS.hasInAllocaArgument() && 9306 // "sret demotion is incompatible with inalloca"); 9307 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9308 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 9309 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9310 DemoteStackIdx = 9311 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 9312 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9313 DL.getAllocaAddrSpace()); 9314 9315 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9316 ArgListEntry Entry; 9317 Entry.Node = DemoteStackSlot; 9318 Entry.Ty = StackSlotPtrType; 9319 Entry.IsSExt = false; 9320 Entry.IsZExt = false; 9321 Entry.IsInReg = false; 9322 Entry.IsSRet = true; 9323 Entry.IsNest = false; 9324 Entry.IsByVal = false; 9325 Entry.IsByRef = false; 9326 Entry.IsReturned = false; 9327 Entry.IsSwiftSelf = false; 9328 Entry.IsSwiftError = false; 9329 Entry.IsCFGuardTarget = false; 9330 Entry.Alignment = Alignment; 9331 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9332 CLI.NumFixedArgs += 1; 9333 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9334 9335 // sret demotion isn't compatible with tail-calls, since the sret argument 9336 // points into the callers stack frame. 9337 CLI.IsTailCall = false; 9338 } else { 9339 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9340 CLI.RetTy, CLI.CallConv, CLI.IsVarArg); 9341 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9342 ISD::ArgFlagsTy Flags; 9343 if (NeedsRegBlock) { 9344 Flags.setInConsecutiveRegs(); 9345 if (I == RetTys.size() - 1) 9346 Flags.setInConsecutiveRegsLast(); 9347 } 9348 EVT VT = RetTys[I]; 9349 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9350 CLI.CallConv, VT); 9351 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9352 CLI.CallConv, VT); 9353 for (unsigned i = 0; i != NumRegs; ++i) { 9354 ISD::InputArg MyFlags; 9355 MyFlags.Flags = Flags; 9356 MyFlags.VT = RegisterVT; 9357 MyFlags.ArgVT = VT; 9358 MyFlags.Used = CLI.IsReturnValueUsed; 9359 if (CLI.RetTy->isPointerTy()) { 9360 MyFlags.Flags.setPointer(); 9361 MyFlags.Flags.setPointerAddrSpace( 9362 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9363 } 9364 if (CLI.RetSExt) 9365 MyFlags.Flags.setSExt(); 9366 if (CLI.RetZExt) 9367 MyFlags.Flags.setZExt(); 9368 if (CLI.IsInReg) 9369 MyFlags.Flags.setInReg(); 9370 CLI.Ins.push_back(MyFlags); 9371 } 9372 } 9373 } 9374 9375 // We push in swifterror return as the last element of CLI.Ins. 9376 ArgListTy &Args = CLI.getArgs(); 9377 if (supportSwiftError()) { 9378 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9379 if (Args[i].IsSwiftError) { 9380 ISD::InputArg MyFlags; 9381 MyFlags.VT = getPointerTy(DL); 9382 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9383 MyFlags.Flags.setSwiftError(); 9384 CLI.Ins.push_back(MyFlags); 9385 } 9386 } 9387 } 9388 9389 // Handle all of the outgoing arguments. 9390 CLI.Outs.clear(); 9391 CLI.OutVals.clear(); 9392 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9393 SmallVector<EVT, 4> ValueVTs; 9394 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9395 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9396 Type *FinalType = Args[i].Ty; 9397 if (Args[i].IsByVal) 9398 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 9399 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9400 FinalType, CLI.CallConv, CLI.IsVarArg); 9401 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9402 ++Value) { 9403 EVT VT = ValueVTs[Value]; 9404 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9405 SDValue Op = SDValue(Args[i].Node.getNode(), 9406 Args[i].Node.getResNo() + Value); 9407 ISD::ArgFlagsTy Flags; 9408 9409 // Certain targets (such as MIPS), may have a different ABI alignment 9410 // for a type depending on the context. Give the target a chance to 9411 // specify the alignment it wants. 9412 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 9413 9414 if (Args[i].Ty->isPointerTy()) { 9415 Flags.setPointer(); 9416 Flags.setPointerAddrSpace( 9417 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9418 } 9419 if (Args[i].IsZExt) 9420 Flags.setZExt(); 9421 if (Args[i].IsSExt) 9422 Flags.setSExt(); 9423 if (Args[i].IsInReg) { 9424 // If we are using vectorcall calling convention, a structure that is 9425 // passed InReg - is surely an HVA 9426 if (CLI.CallConv == CallingConv::X86_VectorCall && 9427 isa<StructType>(FinalType)) { 9428 // The first value of a structure is marked 9429 if (0 == Value) 9430 Flags.setHvaStart(); 9431 Flags.setHva(); 9432 } 9433 // Set InReg Flag 9434 Flags.setInReg(); 9435 } 9436 if (Args[i].IsSRet) 9437 Flags.setSRet(); 9438 if (Args[i].IsSwiftSelf) 9439 Flags.setSwiftSelf(); 9440 if (Args[i].IsSwiftError) 9441 Flags.setSwiftError(); 9442 if (Args[i].IsCFGuardTarget) 9443 Flags.setCFGuardTarget(); 9444 if (Args[i].IsByVal) 9445 Flags.setByVal(); 9446 if (Args[i].IsByRef) 9447 Flags.setByRef(); 9448 if (Args[i].IsPreallocated) { 9449 Flags.setPreallocated(); 9450 // Set the byval flag for CCAssignFn callbacks that don't know about 9451 // preallocated. This way we can know how many bytes we should've 9452 // allocated and how many bytes a callee cleanup function will pop. If 9453 // we port preallocated to more targets, we'll have to add custom 9454 // preallocated handling in the various CC lowering callbacks. 9455 Flags.setByVal(); 9456 } 9457 if (Args[i].IsInAlloca) { 9458 Flags.setInAlloca(); 9459 // Set the byval flag for CCAssignFn callbacks that don't know about 9460 // inalloca. This way we can know how many bytes we should've allocated 9461 // and how many bytes a callee cleanup function will pop. If we port 9462 // inalloca to more targets, we'll have to add custom inalloca handling 9463 // in the various CC lowering callbacks. 9464 Flags.setByVal(); 9465 } 9466 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 9467 PointerType *Ty = cast<PointerType>(Args[i].Ty); 9468 Type *ElementTy = Ty->getElementType(); 9469 9470 unsigned FrameSize = DL.getTypeAllocSize( 9471 Args[i].ByValType ? Args[i].ByValType : ElementTy); 9472 Flags.setByValSize(FrameSize); 9473 9474 // info is not there but there are cases it cannot get right. 9475 Align FrameAlign; 9476 if (auto MA = Args[i].Alignment) 9477 FrameAlign = *MA; 9478 else 9479 FrameAlign = Align(getByValTypeAlignment(ElementTy, DL)); 9480 Flags.setByValAlign(FrameAlign); 9481 } 9482 if (Args[i].IsNest) 9483 Flags.setNest(); 9484 if (NeedsRegBlock) 9485 Flags.setInConsecutiveRegs(); 9486 Flags.setOrigAlign(OriginalAlignment); 9487 9488 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9489 CLI.CallConv, VT); 9490 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9491 CLI.CallConv, VT); 9492 SmallVector<SDValue, 4> Parts(NumParts); 9493 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9494 9495 if (Args[i].IsSExt) 9496 ExtendKind = ISD::SIGN_EXTEND; 9497 else if (Args[i].IsZExt) 9498 ExtendKind = ISD::ZERO_EXTEND; 9499 9500 // Conservatively only handle 'returned' on non-vectors that can be lowered, 9501 // for now. 9502 if (Args[i].IsReturned && !Op.getValueType().isVector() && 9503 CanLowerReturn) { 9504 assert((CLI.RetTy == Args[i].Ty || 9505 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 9506 CLI.RetTy->getPointerAddressSpace() == 9507 Args[i].Ty->getPointerAddressSpace())) && 9508 RetTys.size() == NumValues && "unexpected use of 'returned'"); 9509 // Before passing 'returned' to the target lowering code, ensure that 9510 // either the register MVT and the actual EVT are the same size or that 9511 // the return value and argument are extended in the same way; in these 9512 // cases it's safe to pass the argument register value unchanged as the 9513 // return register value (although it's at the target's option whether 9514 // to do so) 9515 // TODO: allow code generation to take advantage of partially preserved 9516 // registers rather than clobbering the entire register when the 9517 // parameter extension method is not compatible with the return 9518 // extension method 9519 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9520 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9521 CLI.RetZExt == Args[i].IsZExt)) 9522 Flags.setReturned(); 9523 } 9524 9525 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 9526 CLI.CallConv, ExtendKind); 9527 9528 for (unsigned j = 0; j != NumParts; ++j) { 9529 // if it isn't first piece, alignment must be 1 9530 // For scalable vectors the scalable part is currently handled 9531 // by individual targets, so we just use the known minimum size here. 9532 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 9533 i < CLI.NumFixedArgs, i, 9534 j*Parts[j].getValueType().getStoreSize().getKnownMinSize()); 9535 if (NumParts > 1 && j == 0) 9536 MyFlags.Flags.setSplit(); 9537 else if (j != 0) { 9538 MyFlags.Flags.setOrigAlign(Align(1)); 9539 if (j == NumParts - 1) 9540 MyFlags.Flags.setSplitEnd(); 9541 } 9542 9543 CLI.Outs.push_back(MyFlags); 9544 CLI.OutVals.push_back(Parts[j]); 9545 } 9546 9547 if (NeedsRegBlock && Value == NumValues - 1) 9548 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 9549 } 9550 } 9551 9552 SmallVector<SDValue, 4> InVals; 9553 CLI.Chain = LowerCall(CLI, InVals); 9554 9555 // Update CLI.InVals to use outside of this function. 9556 CLI.InVals = InVals; 9557 9558 // Verify that the target's LowerCall behaved as expected. 9559 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 9560 "LowerCall didn't return a valid chain!"); 9561 assert((!CLI.IsTailCall || InVals.empty()) && 9562 "LowerCall emitted a return value for a tail call!"); 9563 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9564 "LowerCall didn't emit the correct number of values!"); 9565 9566 // For a tail call, the return value is merely live-out and there aren't 9567 // any nodes in the DAG representing it. Return a special value to 9568 // indicate that a tail call has been emitted and no more Instructions 9569 // should be processed in the current block. 9570 if (CLI.IsTailCall) { 9571 CLI.DAG.setRoot(CLI.Chain); 9572 return std::make_pair(SDValue(), SDValue()); 9573 } 9574 9575 #ifndef NDEBUG 9576 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 9577 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 9578 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 9579 "LowerCall emitted a value with the wrong type!"); 9580 } 9581 #endif 9582 9583 SmallVector<SDValue, 4> ReturnValues; 9584 if (!CanLowerReturn) { 9585 // The instruction result is the result of loading from the 9586 // hidden sret parameter. 9587 SmallVector<EVT, 1> PVTs; 9588 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 9589 9590 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 9591 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 9592 EVT PtrVT = PVTs[0]; 9593 9594 unsigned NumValues = RetTys.size(); 9595 ReturnValues.resize(NumValues); 9596 SmallVector<SDValue, 4> Chains(NumValues); 9597 9598 // An aggregate return value cannot wrap around the address space, so 9599 // offsets to its parts don't wrap either. 9600 SDNodeFlags Flags; 9601 Flags.setNoUnsignedWrap(true); 9602 9603 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9604 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 9605 for (unsigned i = 0; i < NumValues; ++i) { 9606 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 9607 CLI.DAG.getConstant(Offsets[i], CLI.DL, 9608 PtrVT), Flags); 9609 SDValue L = CLI.DAG.getLoad( 9610 RetTys[i], CLI.DL, CLI.Chain, Add, 9611 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 9612 DemoteStackIdx, Offsets[i]), 9613 HiddenSRetAlign); 9614 ReturnValues[i] = L; 9615 Chains[i] = L.getValue(1); 9616 } 9617 9618 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 9619 } else { 9620 // Collect the legal value parts into potentially illegal values 9621 // that correspond to the original function's return values. 9622 Optional<ISD::NodeType> AssertOp; 9623 if (CLI.RetSExt) 9624 AssertOp = ISD::AssertSext; 9625 else if (CLI.RetZExt) 9626 AssertOp = ISD::AssertZext; 9627 unsigned CurReg = 0; 9628 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9629 EVT VT = RetTys[I]; 9630 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9631 CLI.CallConv, VT); 9632 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9633 CLI.CallConv, VT); 9634 9635 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 9636 NumRegs, RegisterVT, VT, nullptr, 9637 CLI.CallConv, AssertOp)); 9638 CurReg += NumRegs; 9639 } 9640 9641 // For a function returning void, there is no return value. We can't create 9642 // such a node, so we just return a null return value in that case. In 9643 // that case, nothing will actually look at the value. 9644 if (ReturnValues.empty()) 9645 return std::make_pair(SDValue(), CLI.Chain); 9646 } 9647 9648 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 9649 CLI.DAG.getVTList(RetTys), ReturnValues); 9650 return std::make_pair(Res, CLI.Chain); 9651 } 9652 9653 /// Places new result values for the node in Results (their number 9654 /// and types must exactly match those of the original return values of 9655 /// the node), or leaves Results empty, which indicates that the node is not 9656 /// to be custom lowered after all. 9657 void TargetLowering::LowerOperationWrapper(SDNode *N, 9658 SmallVectorImpl<SDValue> &Results, 9659 SelectionDAG &DAG) const { 9660 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 9661 9662 if (!Res.getNode()) 9663 return; 9664 9665 // If the original node has one result, take the return value from 9666 // LowerOperation as is. It might not be result number 0. 9667 if (N->getNumValues() == 1) { 9668 Results.push_back(Res); 9669 return; 9670 } 9671 9672 // If the original node has multiple results, then the return node should 9673 // have the same number of results. 9674 assert((N->getNumValues() == Res->getNumValues()) && 9675 "Lowering returned the wrong number of results!"); 9676 9677 // Places new result values base on N result number. 9678 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 9679 Results.push_back(Res.getValue(I)); 9680 } 9681 9682 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9683 llvm_unreachable("LowerOperation not implemented for this target!"); 9684 } 9685 9686 void 9687 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 9688 SDValue Op = getNonRegisterValue(V); 9689 assert((Op.getOpcode() != ISD::CopyFromReg || 9690 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 9691 "Copy from a reg to the same reg!"); 9692 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 9693 9694 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9695 // If this is an InlineAsm we have to match the registers required, not the 9696 // notional registers required by the type. 9697 9698 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 9699 None); // This is not an ABI copy. 9700 SDValue Chain = DAG.getEntryNode(); 9701 9702 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 9703 FuncInfo.PreferredExtendType.end()) 9704 ? ISD::ANY_EXTEND 9705 : FuncInfo.PreferredExtendType[V]; 9706 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 9707 PendingExports.push_back(Chain); 9708 } 9709 9710 #include "llvm/CodeGen/SelectionDAGISel.h" 9711 9712 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 9713 /// entry block, return true. This includes arguments used by switches, since 9714 /// the switch may expand into multiple basic blocks. 9715 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 9716 // With FastISel active, we may be splitting blocks, so force creation 9717 // of virtual registers for all non-dead arguments. 9718 if (FastISel) 9719 return A->use_empty(); 9720 9721 const BasicBlock &Entry = A->getParent()->front(); 9722 for (const User *U : A->users()) 9723 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 9724 return false; // Use not in entry block. 9725 9726 return true; 9727 } 9728 9729 using ArgCopyElisionMapTy = 9730 DenseMap<const Argument *, 9731 std::pair<const AllocaInst *, const StoreInst *>>; 9732 9733 /// Scan the entry block of the function in FuncInfo for arguments that look 9734 /// like copies into a local alloca. Record any copied arguments in 9735 /// ArgCopyElisionCandidates. 9736 static void 9737 findArgumentCopyElisionCandidates(const DataLayout &DL, 9738 FunctionLoweringInfo *FuncInfo, 9739 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 9740 // Record the state of every static alloca used in the entry block. Argument 9741 // allocas are all used in the entry block, so we need approximately as many 9742 // entries as we have arguments. 9743 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 9744 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 9745 unsigned NumArgs = FuncInfo->Fn->arg_size(); 9746 StaticAllocas.reserve(NumArgs * 2); 9747 9748 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 9749 if (!V) 9750 return nullptr; 9751 V = V->stripPointerCasts(); 9752 const auto *AI = dyn_cast<AllocaInst>(V); 9753 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 9754 return nullptr; 9755 auto Iter = StaticAllocas.insert({AI, Unknown}); 9756 return &Iter.first->second; 9757 }; 9758 9759 // Look for stores of arguments to static allocas. Look through bitcasts and 9760 // GEPs to handle type coercions, as long as the alloca is fully initialized 9761 // by the store. Any non-store use of an alloca escapes it and any subsequent 9762 // unanalyzed store might write it. 9763 // FIXME: Handle structs initialized with multiple stores. 9764 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 9765 // Look for stores, and handle non-store uses conservatively. 9766 const auto *SI = dyn_cast<StoreInst>(&I); 9767 if (!SI) { 9768 // We will look through cast uses, so ignore them completely. 9769 if (I.isCast()) 9770 continue; 9771 // Ignore debug info and pseudo op intrinsics, they don't escape or store 9772 // to allocas. 9773 if (I.isDebugOrPseudoInst()) 9774 continue; 9775 // This is an unknown instruction. Assume it escapes or writes to all 9776 // static alloca operands. 9777 for (const Use &U : I.operands()) { 9778 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 9779 *Info = StaticAllocaInfo::Clobbered; 9780 } 9781 continue; 9782 } 9783 9784 // If the stored value is a static alloca, mark it as escaped. 9785 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 9786 *Info = StaticAllocaInfo::Clobbered; 9787 9788 // Check if the destination is a static alloca. 9789 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 9790 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 9791 if (!Info) 9792 continue; 9793 const AllocaInst *AI = cast<AllocaInst>(Dst); 9794 9795 // Skip allocas that have been initialized or clobbered. 9796 if (*Info != StaticAllocaInfo::Unknown) 9797 continue; 9798 9799 // Check if the stored value is an argument, and that this store fully 9800 // initializes the alloca. Don't elide copies from the same argument twice. 9801 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 9802 const auto *Arg = dyn_cast<Argument>(Val); 9803 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 9804 Arg->getType()->isEmptyTy() || 9805 DL.getTypeStoreSize(Arg->getType()) != 9806 DL.getTypeAllocSize(AI->getAllocatedType()) || 9807 ArgCopyElisionCandidates.count(Arg)) { 9808 *Info = StaticAllocaInfo::Clobbered; 9809 continue; 9810 } 9811 9812 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 9813 << '\n'); 9814 9815 // Mark this alloca and store for argument copy elision. 9816 *Info = StaticAllocaInfo::Elidable; 9817 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 9818 9819 // Stop scanning if we've seen all arguments. This will happen early in -O0 9820 // builds, which is useful, because -O0 builds have large entry blocks and 9821 // many allocas. 9822 if (ArgCopyElisionCandidates.size() == NumArgs) 9823 break; 9824 } 9825 } 9826 9827 /// Try to elide argument copies from memory into a local alloca. Succeeds if 9828 /// ArgVal is a load from a suitable fixed stack object. 9829 static void tryToElideArgumentCopy( 9830 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 9831 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 9832 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 9833 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 9834 SDValue ArgVal, bool &ArgHasUses) { 9835 // Check if this is a load from a fixed stack object. 9836 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 9837 if (!LNode) 9838 return; 9839 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 9840 if (!FINode) 9841 return; 9842 9843 // Check that the fixed stack object is the right size and alignment. 9844 // Look at the alignment that the user wrote on the alloca instead of looking 9845 // at the stack object. 9846 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 9847 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 9848 const AllocaInst *AI = ArgCopyIter->second.first; 9849 int FixedIndex = FINode->getIndex(); 9850 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 9851 int OldIndex = AllocaIndex; 9852 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 9853 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 9854 LLVM_DEBUG( 9855 dbgs() << " argument copy elision failed due to bad fixed stack " 9856 "object size\n"); 9857 return; 9858 } 9859 Align RequiredAlignment = AI->getAlign(); 9860 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 9861 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 9862 "greater than stack argument alignment (" 9863 << DebugStr(RequiredAlignment) << " vs " 9864 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 9865 return; 9866 } 9867 9868 // Perform the elision. Delete the old stack object and replace its only use 9869 // in the variable info map. Mark the stack object as mutable. 9870 LLVM_DEBUG({ 9871 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 9872 << " Replacing frame index " << OldIndex << " with " << FixedIndex 9873 << '\n'; 9874 }); 9875 MFI.RemoveStackObject(OldIndex); 9876 MFI.setIsImmutableObjectIndex(FixedIndex, false); 9877 AllocaIndex = FixedIndex; 9878 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 9879 Chains.push_back(ArgVal.getValue(1)); 9880 9881 // Avoid emitting code for the store implementing the copy. 9882 const StoreInst *SI = ArgCopyIter->second.second; 9883 ElidedArgCopyInstrs.insert(SI); 9884 9885 // Check for uses of the argument again so that we can avoid exporting ArgVal 9886 // if it is't used by anything other than the store. 9887 for (const Value *U : Arg.users()) { 9888 if (U != SI) { 9889 ArgHasUses = true; 9890 break; 9891 } 9892 } 9893 } 9894 9895 void SelectionDAGISel::LowerArguments(const Function &F) { 9896 SelectionDAG &DAG = SDB->DAG; 9897 SDLoc dl = SDB->getCurSDLoc(); 9898 const DataLayout &DL = DAG.getDataLayout(); 9899 SmallVector<ISD::InputArg, 16> Ins; 9900 9901 // In Naked functions we aren't going to save any registers. 9902 if (F.hasFnAttribute(Attribute::Naked)) 9903 return; 9904 9905 if (!FuncInfo->CanLowerReturn) { 9906 // Put in an sret pointer parameter before all the other parameters. 9907 SmallVector<EVT, 1> ValueVTs; 9908 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9909 F.getReturnType()->getPointerTo( 9910 DAG.getDataLayout().getAllocaAddrSpace()), 9911 ValueVTs); 9912 9913 // NOTE: Assuming that a pointer will never break down to more than one VT 9914 // or one register. 9915 ISD::ArgFlagsTy Flags; 9916 Flags.setSRet(); 9917 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 9918 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 9919 ISD::InputArg::NoArgIndex, 0); 9920 Ins.push_back(RetArg); 9921 } 9922 9923 // Look for stores of arguments to static allocas. Mark such arguments with a 9924 // flag to ask the target to give us the memory location of that argument if 9925 // available. 9926 ArgCopyElisionMapTy ArgCopyElisionCandidates; 9927 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 9928 ArgCopyElisionCandidates); 9929 9930 // Set up the incoming argument description vector. 9931 for (const Argument &Arg : F.args()) { 9932 unsigned ArgNo = Arg.getArgNo(); 9933 SmallVector<EVT, 4> ValueVTs; 9934 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9935 bool isArgValueUsed = !Arg.use_empty(); 9936 unsigned PartBase = 0; 9937 Type *FinalType = Arg.getType(); 9938 if (Arg.hasAttribute(Attribute::ByVal)) 9939 FinalType = Arg.getParamByValType(); 9940 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 9941 FinalType, F.getCallingConv(), F.isVarArg()); 9942 for (unsigned Value = 0, NumValues = ValueVTs.size(); 9943 Value != NumValues; ++Value) { 9944 EVT VT = ValueVTs[Value]; 9945 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 9946 ISD::ArgFlagsTy Flags; 9947 9948 // Certain targets (such as MIPS), may have a different ABI alignment 9949 // for a type depending on the context. Give the target a chance to 9950 // specify the alignment it wants. 9951 const Align OriginalAlignment( 9952 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 9953 9954 if (Arg.getType()->isPointerTy()) { 9955 Flags.setPointer(); 9956 Flags.setPointerAddrSpace( 9957 cast<PointerType>(Arg.getType())->getAddressSpace()); 9958 } 9959 if (Arg.hasAttribute(Attribute::ZExt)) 9960 Flags.setZExt(); 9961 if (Arg.hasAttribute(Attribute::SExt)) 9962 Flags.setSExt(); 9963 if (Arg.hasAttribute(Attribute::InReg)) { 9964 // If we are using vectorcall calling convention, a structure that is 9965 // passed InReg - is surely an HVA 9966 if (F.getCallingConv() == CallingConv::X86_VectorCall && 9967 isa<StructType>(Arg.getType())) { 9968 // The first value of a structure is marked 9969 if (0 == Value) 9970 Flags.setHvaStart(); 9971 Flags.setHva(); 9972 } 9973 // Set InReg Flag 9974 Flags.setInReg(); 9975 } 9976 if (Arg.hasAttribute(Attribute::StructRet)) 9977 Flags.setSRet(); 9978 if (Arg.hasAttribute(Attribute::SwiftSelf)) 9979 Flags.setSwiftSelf(); 9980 if (Arg.hasAttribute(Attribute::SwiftError)) 9981 Flags.setSwiftError(); 9982 if (Arg.hasAttribute(Attribute::ByVal)) 9983 Flags.setByVal(); 9984 if (Arg.hasAttribute(Attribute::ByRef)) 9985 Flags.setByRef(); 9986 if (Arg.hasAttribute(Attribute::InAlloca)) { 9987 Flags.setInAlloca(); 9988 // Set the byval flag for CCAssignFn callbacks that don't know about 9989 // inalloca. This way we can know how many bytes we should've allocated 9990 // and how many bytes a callee cleanup function will pop. If we port 9991 // inalloca to more targets, we'll have to add custom inalloca handling 9992 // in the various CC lowering callbacks. 9993 Flags.setByVal(); 9994 } 9995 if (Arg.hasAttribute(Attribute::Preallocated)) { 9996 Flags.setPreallocated(); 9997 // Set the byval flag for CCAssignFn callbacks that don't know about 9998 // preallocated. This way we can know how many bytes we should've 9999 // allocated and how many bytes a callee cleanup function will pop. If 10000 // we port preallocated to more targets, we'll have to add custom 10001 // preallocated handling in the various CC lowering callbacks. 10002 Flags.setByVal(); 10003 } 10004 10005 Type *ArgMemTy = nullptr; 10006 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 10007 Flags.isByRef()) { 10008 if (!ArgMemTy) 10009 ArgMemTy = Arg.getPointeeInMemoryValueType(); 10010 10011 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 10012 10013 // For in-memory arguments, size and alignment should be passed from FE. 10014 // BE will guess if this info is not there but there are cases it cannot 10015 // get right. 10016 MaybeAlign MemAlign = Arg.getParamAlign(); 10017 if (!MemAlign) 10018 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 10019 10020 if (Flags.isByRef()) { 10021 Flags.setByRefSize(MemSize); 10022 Flags.setByRefAlign(*MemAlign); 10023 } else { 10024 Flags.setByValSize(MemSize); 10025 Flags.setByValAlign(*MemAlign); 10026 } 10027 } 10028 10029 if (Arg.hasAttribute(Attribute::Nest)) 10030 Flags.setNest(); 10031 if (NeedsRegBlock) 10032 Flags.setInConsecutiveRegs(); 10033 Flags.setOrigAlign(OriginalAlignment); 10034 if (ArgCopyElisionCandidates.count(&Arg)) 10035 Flags.setCopyElisionCandidate(); 10036 if (Arg.hasAttribute(Attribute::Returned)) 10037 Flags.setReturned(); 10038 10039 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 10040 *CurDAG->getContext(), F.getCallingConv(), VT); 10041 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 10042 *CurDAG->getContext(), F.getCallingConv(), VT); 10043 for (unsigned i = 0; i != NumRegs; ++i) { 10044 // For scalable vectors, use the minimum size; individual targets 10045 // are responsible for handling scalable vector arguments and 10046 // return values. 10047 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 10048 ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize()); 10049 if (NumRegs > 1 && i == 0) 10050 MyFlags.Flags.setSplit(); 10051 // if it isn't first piece, alignment must be 1 10052 else if (i > 0) { 10053 MyFlags.Flags.setOrigAlign(Align(1)); 10054 if (i == NumRegs - 1) 10055 MyFlags.Flags.setSplitEnd(); 10056 } 10057 Ins.push_back(MyFlags); 10058 } 10059 if (NeedsRegBlock && Value == NumValues - 1) 10060 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 10061 PartBase += VT.getStoreSize().getKnownMinSize(); 10062 } 10063 } 10064 10065 // Call the target to set up the argument values. 10066 SmallVector<SDValue, 8> InVals; 10067 SDValue NewRoot = TLI->LowerFormalArguments( 10068 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 10069 10070 // Verify that the target's LowerFormalArguments behaved as expected. 10071 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 10072 "LowerFormalArguments didn't return a valid chain!"); 10073 assert(InVals.size() == Ins.size() && 10074 "LowerFormalArguments didn't emit the correct number of values!"); 10075 LLVM_DEBUG({ 10076 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 10077 assert(InVals[i].getNode() && 10078 "LowerFormalArguments emitted a null value!"); 10079 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 10080 "LowerFormalArguments emitted a value with the wrong type!"); 10081 } 10082 }); 10083 10084 // Update the DAG with the new chain value resulting from argument lowering. 10085 DAG.setRoot(NewRoot); 10086 10087 // Set up the argument values. 10088 unsigned i = 0; 10089 if (!FuncInfo->CanLowerReturn) { 10090 // Create a virtual register for the sret pointer, and put in a copy 10091 // from the sret argument into it. 10092 SmallVector<EVT, 1> ValueVTs; 10093 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10094 F.getReturnType()->getPointerTo( 10095 DAG.getDataLayout().getAllocaAddrSpace()), 10096 ValueVTs); 10097 MVT VT = ValueVTs[0].getSimpleVT(); 10098 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 10099 Optional<ISD::NodeType> AssertOp = None; 10100 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 10101 nullptr, F.getCallingConv(), AssertOp); 10102 10103 MachineFunction& MF = SDB->DAG.getMachineFunction(); 10104 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 10105 Register SRetReg = 10106 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 10107 FuncInfo->DemoteRegister = SRetReg; 10108 NewRoot = 10109 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 10110 DAG.setRoot(NewRoot); 10111 10112 // i indexes lowered arguments. Bump it past the hidden sret argument. 10113 ++i; 10114 } 10115 10116 SmallVector<SDValue, 4> Chains; 10117 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 10118 for (const Argument &Arg : F.args()) { 10119 SmallVector<SDValue, 4> ArgValues; 10120 SmallVector<EVT, 4> ValueVTs; 10121 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10122 unsigned NumValues = ValueVTs.size(); 10123 if (NumValues == 0) 10124 continue; 10125 10126 bool ArgHasUses = !Arg.use_empty(); 10127 10128 // Elide the copying store if the target loaded this argument from a 10129 // suitable fixed stack object. 10130 if (Ins[i].Flags.isCopyElisionCandidate()) { 10131 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 10132 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 10133 InVals[i], ArgHasUses); 10134 } 10135 10136 // If this argument is unused then remember its value. It is used to generate 10137 // debugging information. 10138 bool isSwiftErrorArg = 10139 TLI->supportSwiftError() && 10140 Arg.hasAttribute(Attribute::SwiftError); 10141 if (!ArgHasUses && !isSwiftErrorArg) { 10142 SDB->setUnusedArgValue(&Arg, InVals[i]); 10143 10144 // Also remember any frame index for use in FastISel. 10145 if (FrameIndexSDNode *FI = 10146 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 10147 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10148 } 10149 10150 for (unsigned Val = 0; Val != NumValues; ++Val) { 10151 EVT VT = ValueVTs[Val]; 10152 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 10153 F.getCallingConv(), VT); 10154 unsigned NumParts = TLI->getNumRegistersForCallingConv( 10155 *CurDAG->getContext(), F.getCallingConv(), VT); 10156 10157 // Even an apparent 'unused' swifterror argument needs to be returned. So 10158 // we do generate a copy for it that can be used on return from the 10159 // function. 10160 if (ArgHasUses || isSwiftErrorArg) { 10161 Optional<ISD::NodeType> AssertOp; 10162 if (Arg.hasAttribute(Attribute::SExt)) 10163 AssertOp = ISD::AssertSext; 10164 else if (Arg.hasAttribute(Attribute::ZExt)) 10165 AssertOp = ISD::AssertZext; 10166 10167 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 10168 PartVT, VT, nullptr, 10169 F.getCallingConv(), AssertOp)); 10170 } 10171 10172 i += NumParts; 10173 } 10174 10175 // We don't need to do anything else for unused arguments. 10176 if (ArgValues.empty()) 10177 continue; 10178 10179 // Note down frame index. 10180 if (FrameIndexSDNode *FI = 10181 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 10182 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10183 10184 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 10185 SDB->getCurSDLoc()); 10186 10187 SDB->setValue(&Arg, Res); 10188 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 10189 // We want to associate the argument with the frame index, among 10190 // involved operands, that correspond to the lowest address. The 10191 // getCopyFromParts function, called earlier, is swapping the order of 10192 // the operands to BUILD_PAIR depending on endianness. The result of 10193 // that swapping is that the least significant bits of the argument will 10194 // be in the first operand of the BUILD_PAIR node, and the most 10195 // significant bits will be in the second operand. 10196 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 10197 if (LoadSDNode *LNode = 10198 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 10199 if (FrameIndexSDNode *FI = 10200 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 10201 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10202 } 10203 10204 // Analyses past this point are naive and don't expect an assertion. 10205 if (Res.getOpcode() == ISD::AssertZext) 10206 Res = Res.getOperand(0); 10207 10208 // Update the SwiftErrorVRegDefMap. 10209 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 10210 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10211 if (Register::isVirtualRegister(Reg)) 10212 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 10213 Reg); 10214 } 10215 10216 // If this argument is live outside of the entry block, insert a copy from 10217 // wherever we got it to the vreg that other BB's will reference it as. 10218 if (Res.getOpcode() == ISD::CopyFromReg) { 10219 // If we can, though, try to skip creating an unnecessary vreg. 10220 // FIXME: This isn't very clean... it would be nice to make this more 10221 // general. 10222 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10223 if (Register::isVirtualRegister(Reg)) { 10224 FuncInfo->ValueMap[&Arg] = Reg; 10225 continue; 10226 } 10227 } 10228 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 10229 FuncInfo->InitializeRegForValue(&Arg); 10230 SDB->CopyToExportRegsIfNeeded(&Arg); 10231 } 10232 } 10233 10234 if (!Chains.empty()) { 10235 Chains.push_back(NewRoot); 10236 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 10237 } 10238 10239 DAG.setRoot(NewRoot); 10240 10241 assert(i == InVals.size() && "Argument register count mismatch!"); 10242 10243 // If any argument copy elisions occurred and we have debug info, update the 10244 // stale frame indices used in the dbg.declare variable info table. 10245 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 10246 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 10247 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 10248 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 10249 if (I != ArgCopyElisionFrameIndexMap.end()) 10250 VI.Slot = I->second; 10251 } 10252 } 10253 10254 // Finally, if the target has anything special to do, allow it to do so. 10255 emitFunctionEntryCode(); 10256 } 10257 10258 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 10259 /// ensure constants are generated when needed. Remember the virtual registers 10260 /// that need to be added to the Machine PHI nodes as input. We cannot just 10261 /// directly add them, because expansion might result in multiple MBB's for one 10262 /// BB. As such, the start of the BB might correspond to a different MBB than 10263 /// the end. 10264 void 10265 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 10266 const Instruction *TI = LLVMBB->getTerminator(); 10267 10268 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 10269 10270 // Check PHI nodes in successors that expect a value to be available from this 10271 // block. 10272 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 10273 const BasicBlock *SuccBB = TI->getSuccessor(succ); 10274 if (!isa<PHINode>(SuccBB->begin())) continue; 10275 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 10276 10277 // If this terminator has multiple identical successors (common for 10278 // switches), only handle each succ once. 10279 if (!SuccsHandled.insert(SuccMBB).second) 10280 continue; 10281 10282 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 10283 10284 // At this point we know that there is a 1-1 correspondence between LLVM PHI 10285 // nodes and Machine PHI nodes, but the incoming operands have not been 10286 // emitted yet. 10287 for (const PHINode &PN : SuccBB->phis()) { 10288 // Ignore dead phi's. 10289 if (PN.use_empty()) 10290 continue; 10291 10292 // Skip empty types 10293 if (PN.getType()->isEmptyTy()) 10294 continue; 10295 10296 unsigned Reg; 10297 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 10298 10299 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 10300 unsigned &RegOut = ConstantsOut[C]; 10301 if (RegOut == 0) { 10302 RegOut = FuncInfo.CreateRegs(C); 10303 CopyValueToVirtualRegister(C, RegOut); 10304 } 10305 Reg = RegOut; 10306 } else { 10307 DenseMap<const Value *, Register>::iterator I = 10308 FuncInfo.ValueMap.find(PHIOp); 10309 if (I != FuncInfo.ValueMap.end()) 10310 Reg = I->second; 10311 else { 10312 assert(isa<AllocaInst>(PHIOp) && 10313 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 10314 "Didn't codegen value into a register!??"); 10315 Reg = FuncInfo.CreateRegs(PHIOp); 10316 CopyValueToVirtualRegister(PHIOp, Reg); 10317 } 10318 } 10319 10320 // Remember that this register needs to added to the machine PHI node as 10321 // the input for this MBB. 10322 SmallVector<EVT, 4> ValueVTs; 10323 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10324 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 10325 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 10326 EVT VT = ValueVTs[vti]; 10327 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 10328 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 10329 FuncInfo.PHINodesToUpdate.push_back( 10330 std::make_pair(&*MBBI++, Reg + i)); 10331 Reg += NumRegisters; 10332 } 10333 } 10334 } 10335 10336 ConstantsOut.clear(); 10337 } 10338 10339 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 10340 /// is 0. 10341 MachineBasicBlock * 10342 SelectionDAGBuilder::StackProtectorDescriptor:: 10343 AddSuccessorMBB(const BasicBlock *BB, 10344 MachineBasicBlock *ParentMBB, 10345 bool IsLikely, 10346 MachineBasicBlock *SuccMBB) { 10347 // If SuccBB has not been created yet, create it. 10348 if (!SuccMBB) { 10349 MachineFunction *MF = ParentMBB->getParent(); 10350 MachineFunction::iterator BBI(ParentMBB); 10351 SuccMBB = MF->CreateMachineBasicBlock(BB); 10352 MF->insert(++BBI, SuccMBB); 10353 } 10354 // Add it as a successor of ParentMBB. 10355 ParentMBB->addSuccessor( 10356 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 10357 return SuccMBB; 10358 } 10359 10360 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 10361 MachineFunction::iterator I(MBB); 10362 if (++I == FuncInfo.MF->end()) 10363 return nullptr; 10364 return &*I; 10365 } 10366 10367 /// During lowering new call nodes can be created (such as memset, etc.). 10368 /// Those will become new roots of the current DAG, but complications arise 10369 /// when they are tail calls. In such cases, the call lowering will update 10370 /// the root, but the builder still needs to know that a tail call has been 10371 /// lowered in order to avoid generating an additional return. 10372 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 10373 // If the node is null, we do have a tail call. 10374 if (MaybeTC.getNode() != nullptr) 10375 DAG.setRoot(MaybeTC); 10376 else 10377 HasTailCall = true; 10378 } 10379 10380 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10381 MachineBasicBlock *SwitchMBB, 10382 MachineBasicBlock *DefaultMBB) { 10383 MachineFunction *CurMF = FuncInfo.MF; 10384 MachineBasicBlock *NextMBB = nullptr; 10385 MachineFunction::iterator BBI(W.MBB); 10386 if (++BBI != FuncInfo.MF->end()) 10387 NextMBB = &*BBI; 10388 10389 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10390 10391 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10392 10393 if (Size == 2 && W.MBB == SwitchMBB) { 10394 // If any two of the cases has the same destination, and if one value 10395 // is the same as the other, but has one bit unset that the other has set, 10396 // use bit manipulation to do two compares at once. For example: 10397 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10398 // TODO: This could be extended to merge any 2 cases in switches with 3 10399 // cases. 10400 // TODO: Handle cases where W.CaseBB != SwitchBB. 10401 CaseCluster &Small = *W.FirstCluster; 10402 CaseCluster &Big = *W.LastCluster; 10403 10404 if (Small.Low == Small.High && Big.Low == Big.High && 10405 Small.MBB == Big.MBB) { 10406 const APInt &SmallValue = Small.Low->getValue(); 10407 const APInt &BigValue = Big.Low->getValue(); 10408 10409 // Check that there is only one bit different. 10410 APInt CommonBit = BigValue ^ SmallValue; 10411 if (CommonBit.isPowerOf2()) { 10412 SDValue CondLHS = getValue(Cond); 10413 EVT VT = CondLHS.getValueType(); 10414 SDLoc DL = getCurSDLoc(); 10415 10416 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10417 DAG.getConstant(CommonBit, DL, VT)); 10418 SDValue Cond = DAG.getSetCC( 10419 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10420 ISD::SETEQ); 10421 10422 // Update successor info. 10423 // Both Small and Big will jump to Small.BB, so we sum up the 10424 // probabilities. 10425 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10426 if (BPI) 10427 addSuccessorWithProb( 10428 SwitchMBB, DefaultMBB, 10429 // The default destination is the first successor in IR. 10430 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10431 else 10432 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10433 10434 // Insert the true branch. 10435 SDValue BrCond = 10436 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10437 DAG.getBasicBlock(Small.MBB)); 10438 // Insert the false branch. 10439 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10440 DAG.getBasicBlock(DefaultMBB)); 10441 10442 DAG.setRoot(BrCond); 10443 return; 10444 } 10445 } 10446 } 10447 10448 if (TM.getOptLevel() != CodeGenOpt::None) { 10449 // Here, we order cases by probability so the most likely case will be 10450 // checked first. However, two clusters can have the same probability in 10451 // which case their relative ordering is non-deterministic. So we use Low 10452 // as a tie-breaker as clusters are guaranteed to never overlap. 10453 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10454 [](const CaseCluster &a, const CaseCluster &b) { 10455 return a.Prob != b.Prob ? 10456 a.Prob > b.Prob : 10457 a.Low->getValue().slt(b.Low->getValue()); 10458 }); 10459 10460 // Rearrange the case blocks so that the last one falls through if possible 10461 // without changing the order of probabilities. 10462 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10463 --I; 10464 if (I->Prob > W.LastCluster->Prob) 10465 break; 10466 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10467 std::swap(*I, *W.LastCluster); 10468 break; 10469 } 10470 } 10471 } 10472 10473 // Compute total probability. 10474 BranchProbability DefaultProb = W.DefaultProb; 10475 BranchProbability UnhandledProbs = DefaultProb; 10476 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10477 UnhandledProbs += I->Prob; 10478 10479 MachineBasicBlock *CurMBB = W.MBB; 10480 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10481 bool FallthroughUnreachable = false; 10482 MachineBasicBlock *Fallthrough; 10483 if (I == W.LastCluster) { 10484 // For the last cluster, fall through to the default destination. 10485 Fallthrough = DefaultMBB; 10486 FallthroughUnreachable = isa<UnreachableInst>( 10487 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10488 } else { 10489 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10490 CurMF->insert(BBI, Fallthrough); 10491 // Put Cond in a virtual register to make it available from the new blocks. 10492 ExportFromCurrentBlock(Cond); 10493 } 10494 UnhandledProbs -= I->Prob; 10495 10496 switch (I->Kind) { 10497 case CC_JumpTable: { 10498 // FIXME: Optimize away range check based on pivot comparisons. 10499 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 10500 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 10501 10502 // The jump block hasn't been inserted yet; insert it here. 10503 MachineBasicBlock *JumpMBB = JT->MBB; 10504 CurMF->insert(BBI, JumpMBB); 10505 10506 auto JumpProb = I->Prob; 10507 auto FallthroughProb = UnhandledProbs; 10508 10509 // If the default statement is a target of the jump table, we evenly 10510 // distribute the default probability to successors of CurMBB. Also 10511 // update the probability on the edge from JumpMBB to Fallthrough. 10512 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10513 SE = JumpMBB->succ_end(); 10514 SI != SE; ++SI) { 10515 if (*SI == DefaultMBB) { 10516 JumpProb += DefaultProb / 2; 10517 FallthroughProb -= DefaultProb / 2; 10518 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10519 JumpMBB->normalizeSuccProbs(); 10520 break; 10521 } 10522 } 10523 10524 if (FallthroughUnreachable) { 10525 // Skip the range check if the fallthrough block is unreachable. 10526 JTH->OmitRangeCheck = true; 10527 } 10528 10529 if (!JTH->OmitRangeCheck) 10530 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10531 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10532 CurMBB->normalizeSuccProbs(); 10533 10534 // The jump table header will be inserted in our current block, do the 10535 // range check, and fall through to our fallthrough block. 10536 JTH->HeaderBB = CurMBB; 10537 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10538 10539 // If we're in the right place, emit the jump table header right now. 10540 if (CurMBB == SwitchMBB) { 10541 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10542 JTH->Emitted = true; 10543 } 10544 break; 10545 } 10546 case CC_BitTests: { 10547 // FIXME: Optimize away range check based on pivot comparisons. 10548 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 10549 10550 // The bit test blocks haven't been inserted yet; insert them here. 10551 for (BitTestCase &BTC : BTB->Cases) 10552 CurMF->insert(BBI, BTC.ThisBB); 10553 10554 // Fill in fields of the BitTestBlock. 10555 BTB->Parent = CurMBB; 10556 BTB->Default = Fallthrough; 10557 10558 BTB->DefaultProb = UnhandledProbs; 10559 // If the cases in bit test don't form a contiguous range, we evenly 10560 // distribute the probability on the edge to Fallthrough to two 10561 // successors of CurMBB. 10562 if (!BTB->ContiguousRange) { 10563 BTB->Prob += DefaultProb / 2; 10564 BTB->DefaultProb -= DefaultProb / 2; 10565 } 10566 10567 if (FallthroughUnreachable) { 10568 // Skip the range check if the fallthrough block is unreachable. 10569 BTB->OmitRangeCheck = true; 10570 } 10571 10572 // If we're in the right place, emit the bit test header right now. 10573 if (CurMBB == SwitchMBB) { 10574 visitBitTestHeader(*BTB, SwitchMBB); 10575 BTB->Emitted = true; 10576 } 10577 break; 10578 } 10579 case CC_Range: { 10580 const Value *RHS, *LHS, *MHS; 10581 ISD::CondCode CC; 10582 if (I->Low == I->High) { 10583 // Check Cond == I->Low. 10584 CC = ISD::SETEQ; 10585 LHS = Cond; 10586 RHS=I->Low; 10587 MHS = nullptr; 10588 } else { 10589 // Check I->Low <= Cond <= I->High. 10590 CC = ISD::SETLE; 10591 LHS = I->Low; 10592 MHS = Cond; 10593 RHS = I->High; 10594 } 10595 10596 // If Fallthrough is unreachable, fold away the comparison. 10597 if (FallthroughUnreachable) 10598 CC = ISD::SETTRUE; 10599 10600 // The false probability is the sum of all unhandled cases. 10601 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10602 getCurSDLoc(), I->Prob, UnhandledProbs); 10603 10604 if (CurMBB == SwitchMBB) 10605 visitSwitchCase(CB, SwitchMBB); 10606 else 10607 SL->SwitchCases.push_back(CB); 10608 10609 break; 10610 } 10611 } 10612 CurMBB = Fallthrough; 10613 } 10614 } 10615 10616 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10617 CaseClusterIt First, 10618 CaseClusterIt Last) { 10619 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10620 if (X.Prob != CC.Prob) 10621 return X.Prob > CC.Prob; 10622 10623 // Ties are broken by comparing the case value. 10624 return X.Low->getValue().slt(CC.Low->getValue()); 10625 }); 10626 } 10627 10628 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10629 const SwitchWorkListItem &W, 10630 Value *Cond, 10631 MachineBasicBlock *SwitchMBB) { 10632 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10633 "Clusters not sorted?"); 10634 10635 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10636 10637 // Balance the tree based on branch probabilities to create a near-optimal (in 10638 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10639 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10640 CaseClusterIt LastLeft = W.FirstCluster; 10641 CaseClusterIt FirstRight = W.LastCluster; 10642 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10643 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10644 10645 // Move LastLeft and FirstRight towards each other from opposite directions to 10646 // find a partitioning of the clusters which balances the probability on both 10647 // sides. If LeftProb and RightProb are equal, alternate which side is 10648 // taken to ensure 0-probability nodes are distributed evenly. 10649 unsigned I = 0; 10650 while (LastLeft + 1 < FirstRight) { 10651 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10652 LeftProb += (++LastLeft)->Prob; 10653 else 10654 RightProb += (--FirstRight)->Prob; 10655 I++; 10656 } 10657 10658 while (true) { 10659 // Our binary search tree differs from a typical BST in that ours can have up 10660 // to three values in each leaf. The pivot selection above doesn't take that 10661 // into account, which means the tree might require more nodes and be less 10662 // efficient. We compensate for this here. 10663 10664 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10665 unsigned NumRight = W.LastCluster - FirstRight + 1; 10666 10667 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10668 // If one side has less than 3 clusters, and the other has more than 3, 10669 // consider taking a cluster from the other side. 10670 10671 if (NumLeft < NumRight) { 10672 // Consider moving the first cluster on the right to the left side. 10673 CaseCluster &CC = *FirstRight; 10674 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10675 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10676 if (LeftSideRank <= RightSideRank) { 10677 // Moving the cluster to the left does not demote it. 10678 ++LastLeft; 10679 ++FirstRight; 10680 continue; 10681 } 10682 } else { 10683 assert(NumRight < NumLeft); 10684 // Consider moving the last element on the left to the right side. 10685 CaseCluster &CC = *LastLeft; 10686 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10687 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10688 if (RightSideRank <= LeftSideRank) { 10689 // Moving the cluster to the right does not demot it. 10690 --LastLeft; 10691 --FirstRight; 10692 continue; 10693 } 10694 } 10695 } 10696 break; 10697 } 10698 10699 assert(LastLeft + 1 == FirstRight); 10700 assert(LastLeft >= W.FirstCluster); 10701 assert(FirstRight <= W.LastCluster); 10702 10703 // Use the first element on the right as pivot since we will make less-than 10704 // comparisons against it. 10705 CaseClusterIt PivotCluster = FirstRight; 10706 assert(PivotCluster > W.FirstCluster); 10707 assert(PivotCluster <= W.LastCluster); 10708 10709 CaseClusterIt FirstLeft = W.FirstCluster; 10710 CaseClusterIt LastRight = W.LastCluster; 10711 10712 const ConstantInt *Pivot = PivotCluster->Low; 10713 10714 // New blocks will be inserted immediately after the current one. 10715 MachineFunction::iterator BBI(W.MBB); 10716 ++BBI; 10717 10718 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10719 // we can branch to its destination directly if it's squeezed exactly in 10720 // between the known lower bound and Pivot - 1. 10721 MachineBasicBlock *LeftMBB; 10722 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10723 FirstLeft->Low == W.GE && 10724 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10725 LeftMBB = FirstLeft->MBB; 10726 } else { 10727 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10728 FuncInfo.MF->insert(BBI, LeftMBB); 10729 WorkList.push_back( 10730 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10731 // Put Cond in a virtual register to make it available from the new blocks. 10732 ExportFromCurrentBlock(Cond); 10733 } 10734 10735 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10736 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10737 // directly if RHS.High equals the current upper bound. 10738 MachineBasicBlock *RightMBB; 10739 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10740 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10741 RightMBB = FirstRight->MBB; 10742 } else { 10743 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10744 FuncInfo.MF->insert(BBI, RightMBB); 10745 WorkList.push_back( 10746 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10747 // Put Cond in a virtual register to make it available from the new blocks. 10748 ExportFromCurrentBlock(Cond); 10749 } 10750 10751 // Create the CaseBlock record that will be used to lower the branch. 10752 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10753 getCurSDLoc(), LeftProb, RightProb); 10754 10755 if (W.MBB == SwitchMBB) 10756 visitSwitchCase(CB, SwitchMBB); 10757 else 10758 SL->SwitchCases.push_back(CB); 10759 } 10760 10761 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10762 // from the swith statement. 10763 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10764 BranchProbability PeeledCaseProb) { 10765 if (PeeledCaseProb == BranchProbability::getOne()) 10766 return BranchProbability::getZero(); 10767 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10768 10769 uint32_t Numerator = CaseProb.getNumerator(); 10770 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10771 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10772 } 10773 10774 // Try to peel the top probability case if it exceeds the threshold. 10775 // Return current MachineBasicBlock for the switch statement if the peeling 10776 // does not occur. 10777 // If the peeling is performed, return the newly created MachineBasicBlock 10778 // for the peeled switch statement. Also update Clusters to remove the peeled 10779 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10780 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10781 const SwitchInst &SI, CaseClusterVector &Clusters, 10782 BranchProbability &PeeledCaseProb) { 10783 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10784 // Don't perform if there is only one cluster or optimizing for size. 10785 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10786 TM.getOptLevel() == CodeGenOpt::None || 10787 SwitchMBB->getParent()->getFunction().hasMinSize()) 10788 return SwitchMBB; 10789 10790 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10791 unsigned PeeledCaseIndex = 0; 10792 bool SwitchPeeled = false; 10793 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10794 CaseCluster &CC = Clusters[Index]; 10795 if (CC.Prob < TopCaseProb) 10796 continue; 10797 TopCaseProb = CC.Prob; 10798 PeeledCaseIndex = Index; 10799 SwitchPeeled = true; 10800 } 10801 if (!SwitchPeeled) 10802 return SwitchMBB; 10803 10804 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10805 << TopCaseProb << "\n"); 10806 10807 // Record the MBB for the peeled switch statement. 10808 MachineFunction::iterator BBI(SwitchMBB); 10809 ++BBI; 10810 MachineBasicBlock *PeeledSwitchMBB = 10811 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10812 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10813 10814 ExportFromCurrentBlock(SI.getCondition()); 10815 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10816 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10817 nullptr, nullptr, TopCaseProb.getCompl()}; 10818 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10819 10820 Clusters.erase(PeeledCaseIt); 10821 for (CaseCluster &CC : Clusters) { 10822 LLVM_DEBUG( 10823 dbgs() << "Scale the probablity for one cluster, before scaling: " 10824 << CC.Prob << "\n"); 10825 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10826 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10827 } 10828 PeeledCaseProb = TopCaseProb; 10829 return PeeledSwitchMBB; 10830 } 10831 10832 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10833 // Extract cases from the switch. 10834 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10835 CaseClusterVector Clusters; 10836 Clusters.reserve(SI.getNumCases()); 10837 for (auto I : SI.cases()) { 10838 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10839 const ConstantInt *CaseVal = I.getCaseValue(); 10840 BranchProbability Prob = 10841 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10842 : BranchProbability(1, SI.getNumCases() + 1); 10843 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10844 } 10845 10846 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10847 10848 // Cluster adjacent cases with the same destination. We do this at all 10849 // optimization levels because it's cheap to do and will make codegen faster 10850 // if there are many clusters. 10851 sortAndRangeify(Clusters); 10852 10853 // The branch probablity of the peeled case. 10854 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10855 MachineBasicBlock *PeeledSwitchMBB = 10856 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10857 10858 // If there is only the default destination, jump there directly. 10859 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10860 if (Clusters.empty()) { 10861 assert(PeeledSwitchMBB == SwitchMBB); 10862 SwitchMBB->addSuccessor(DefaultMBB); 10863 if (DefaultMBB != NextBlock(SwitchMBB)) { 10864 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10865 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10866 } 10867 return; 10868 } 10869 10870 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 10871 SL->findBitTestClusters(Clusters, &SI); 10872 10873 LLVM_DEBUG({ 10874 dbgs() << "Case clusters: "; 10875 for (const CaseCluster &C : Clusters) { 10876 if (C.Kind == CC_JumpTable) 10877 dbgs() << "JT:"; 10878 if (C.Kind == CC_BitTests) 10879 dbgs() << "BT:"; 10880 10881 C.Low->getValue().print(dbgs(), true); 10882 if (C.Low != C.High) { 10883 dbgs() << '-'; 10884 C.High->getValue().print(dbgs(), true); 10885 } 10886 dbgs() << ' '; 10887 } 10888 dbgs() << '\n'; 10889 }); 10890 10891 assert(!Clusters.empty()); 10892 SwitchWorkList WorkList; 10893 CaseClusterIt First = Clusters.begin(); 10894 CaseClusterIt Last = Clusters.end() - 1; 10895 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10896 // Scale the branchprobability for DefaultMBB if the peel occurs and 10897 // DefaultMBB is not replaced. 10898 if (PeeledCaseProb != BranchProbability::getZero() && 10899 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10900 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10901 WorkList.push_back( 10902 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10903 10904 while (!WorkList.empty()) { 10905 SwitchWorkListItem W = WorkList.pop_back_val(); 10906 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10907 10908 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10909 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 10910 // For optimized builds, lower large range as a balanced binary tree. 10911 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10912 continue; 10913 } 10914 10915 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10916 } 10917 } 10918 10919 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 10920 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10921 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 10922 10923 SDLoc DL = getCurSDLoc(); 10924 SDValue V = getValue(I.getOperand(0)); 10925 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 10926 10927 if (VT.isScalableVector()) { 10928 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 10929 return; 10930 } 10931 10932 // Use VECTOR_SHUFFLE for the fixed-length vector 10933 // to maintain existing behavior. 10934 SmallVector<int, 8> Mask; 10935 unsigned NumElts = VT.getVectorMinNumElements(); 10936 for (unsigned i = 0; i != NumElts; ++i) 10937 Mask.push_back(NumElts - 1 - i); 10938 10939 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 10940 } 10941 10942 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 10943 SmallVector<EVT, 4> ValueVTs; 10944 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 10945 ValueVTs); 10946 unsigned NumValues = ValueVTs.size(); 10947 if (NumValues == 0) return; 10948 10949 SmallVector<SDValue, 4> Values(NumValues); 10950 SDValue Op = getValue(I.getOperand(0)); 10951 10952 for (unsigned i = 0; i != NumValues; ++i) 10953 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 10954 SDValue(Op.getNode(), Op.getResNo() + i)); 10955 10956 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 10957 DAG.getVTList(ValueVTs), Values)); 10958 } 10959