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