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