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/ArrayRef.h" 18 #include "llvm/ADT/BitVector.h" 19 #include "llvm/ADT/DenseMap.h" 20 #include "llvm/ADT/None.h" 21 #include "llvm/ADT/Optional.h" 22 #include "llvm/ADT/STLExtras.h" 23 #include "llvm/ADT/SmallPtrSet.h" 24 #include "llvm/ADT/SmallSet.h" 25 #include "llvm/ADT/SmallVector.h" 26 #include "llvm/ADT/StringRef.h" 27 #include "llvm/ADT/Triple.h" 28 #include "llvm/ADT/Twine.h" 29 #include "llvm/Analysis/AliasAnalysis.h" 30 #include "llvm/Analysis/BlockFrequencyInfo.h" 31 #include "llvm/Analysis/BranchProbabilityInfo.h" 32 #include "llvm/Analysis/ConstantFolding.h" 33 #include "llvm/Analysis/EHPersonalities.h" 34 #include "llvm/Analysis/Loads.h" 35 #include "llvm/Analysis/MemoryLocation.h" 36 #include "llvm/Analysis/ProfileSummaryInfo.h" 37 #include "llvm/Analysis/TargetLibraryInfo.h" 38 #include "llvm/Analysis/ValueTracking.h" 39 #include "llvm/Analysis/VectorUtils.h" 40 #include "llvm/CodeGen/Analysis.h" 41 #include "llvm/CodeGen/FunctionLoweringInfo.h" 42 #include "llvm/CodeGen/GCMetadata.h" 43 #include "llvm/CodeGen/ISDOpcodes.h" 44 #include "llvm/CodeGen/MachineBasicBlock.h" 45 #include "llvm/CodeGen/MachineFrameInfo.h" 46 #include "llvm/CodeGen/MachineFunction.h" 47 #include "llvm/CodeGen/MachineInstr.h" 48 #include "llvm/CodeGen/MachineInstrBuilder.h" 49 #include "llvm/CodeGen/MachineJumpTableInfo.h" 50 #include "llvm/CodeGen/MachineMemOperand.h" 51 #include "llvm/CodeGen/MachineModuleInfo.h" 52 #include "llvm/CodeGen/MachineOperand.h" 53 #include "llvm/CodeGen/MachineRegisterInfo.h" 54 #include "llvm/CodeGen/RuntimeLibcalls.h" 55 #include "llvm/CodeGen/SelectionDAG.h" 56 #include "llvm/CodeGen/SelectionDAGNodes.h" 57 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 58 #include "llvm/CodeGen/StackMaps.h" 59 #include "llvm/CodeGen/SwiftErrorValueTracking.h" 60 #include "llvm/CodeGen/TargetFrameLowering.h" 61 #include "llvm/CodeGen/TargetInstrInfo.h" 62 #include "llvm/CodeGen/TargetLowering.h" 63 #include "llvm/CodeGen/TargetOpcodes.h" 64 #include "llvm/CodeGen/TargetRegisterInfo.h" 65 #include "llvm/CodeGen/TargetSubtargetInfo.h" 66 #include "llvm/CodeGen/ValueTypes.h" 67 #include "llvm/CodeGen/WinEHFuncInfo.h" 68 #include "llvm/IR/Argument.h" 69 #include "llvm/IR/Attributes.h" 70 #include "llvm/IR/BasicBlock.h" 71 #include "llvm/IR/CFG.h" 72 #include "llvm/IR/CallSite.h" 73 #include "llvm/IR/CallingConv.h" 74 #include "llvm/IR/Constant.h" 75 #include "llvm/IR/ConstantRange.h" 76 #include "llvm/IR/Constants.h" 77 #include "llvm/IR/DataLayout.h" 78 #include "llvm/IR/DebugInfoMetadata.h" 79 #include "llvm/IR/DebugLoc.h" 80 #include "llvm/IR/DerivedTypes.h" 81 #include "llvm/IR/Function.h" 82 #include "llvm/IR/GetElementPtrTypeIterator.h" 83 #include "llvm/IR/InlineAsm.h" 84 #include "llvm/IR/InstrTypes.h" 85 #include "llvm/IR/Instruction.h" 86 #include "llvm/IR/Instructions.h" 87 #include "llvm/IR/IntrinsicInst.h" 88 #include "llvm/IR/Intrinsics.h" 89 #include "llvm/IR/IntrinsicsAArch64.h" 90 #include "llvm/IR/IntrinsicsWebAssembly.h" 91 #include "llvm/IR/LLVMContext.h" 92 #include "llvm/IR/Metadata.h" 93 #include "llvm/IR/Module.h" 94 #include "llvm/IR/Operator.h" 95 #include "llvm/IR/PatternMatch.h" 96 #include "llvm/IR/Statepoint.h" 97 #include "llvm/IR/Type.h" 98 #include "llvm/IR/User.h" 99 #include "llvm/IR/Value.h" 100 #include "llvm/MC/MCContext.h" 101 #include "llvm/MC/MCSymbol.h" 102 #include "llvm/Support/AtomicOrdering.h" 103 #include "llvm/Support/BranchProbability.h" 104 #include "llvm/Support/Casting.h" 105 #include "llvm/Support/CodeGen.h" 106 #include "llvm/Support/CommandLine.h" 107 #include "llvm/Support/Compiler.h" 108 #include "llvm/Support/Debug.h" 109 #include "llvm/Support/ErrorHandling.h" 110 #include "llvm/Support/MachineValueType.h" 111 #include "llvm/Support/MathExtras.h" 112 #include "llvm/Support/raw_ostream.h" 113 #include "llvm/Target/TargetIntrinsicInfo.h" 114 #include "llvm/Target/TargetMachine.h" 115 #include "llvm/Target/TargetOptions.h" 116 #include "llvm/Transforms/Utils/Local.h" 117 #include <algorithm> 118 #include <cassert> 119 #include <cstddef> 120 #include <cstdint> 121 #include <cstring> 122 #include <iterator> 123 #include <limits> 124 #include <numeric> 125 #include <tuple> 126 #include <utility> 127 #include <vector> 128 129 using namespace llvm; 130 using namespace PatternMatch; 131 using namespace SwitchCG; 132 133 #define DEBUG_TYPE "isel" 134 135 /// LimitFloatPrecision - Generate low-precision inline sequences for 136 /// some float libcalls (6, 8 or 12 bits). 137 static unsigned LimitFloatPrecision; 138 139 static cl::opt<unsigned, true> 140 LimitFPPrecision("limit-float-precision", 141 cl::desc("Generate low-precision inline sequences " 142 "for some float libcalls"), 143 cl::location(LimitFloatPrecision), cl::Hidden, 144 cl::init(0)); 145 146 static cl::opt<unsigned> SwitchPeelThreshold( 147 "switch-peel-threshold", cl::Hidden, cl::init(66), 148 cl::desc("Set the case probability threshold for peeling the case from a " 149 "switch statement. A value greater than 100 will void this " 150 "optimization")); 151 152 // Limit the width of DAG chains. This is important in general to prevent 153 // DAG-based analysis from blowing up. For example, alias analysis and 154 // load clustering may not complete in reasonable time. It is difficult to 155 // recognize and avoid this situation within each individual analysis, and 156 // future analyses are likely to have the same behavior. Limiting DAG width is 157 // the safe approach and will be especially important with global DAGs. 158 // 159 // MaxParallelChains default is arbitrarily high to avoid affecting 160 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 161 // sequence over this should have been converted to llvm.memcpy by the 162 // frontend. It is easy to induce this behavior with .ll code such as: 163 // %buffer = alloca [4096 x i8] 164 // %data = load [4096 x i8]* %argPtr 165 // store [4096 x i8] %data, [4096 x i8]* %buffer 166 static const unsigned MaxParallelChains = 64; 167 168 // Return the calling convention if the Value passed requires ABI mangling as it 169 // is a parameter to a function or a return value from a function which is not 170 // an intrinsic. 171 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) { 172 if (auto *R = dyn_cast<ReturnInst>(V)) 173 return R->getParent()->getParent()->getCallingConv(); 174 175 if (auto *CI = dyn_cast<CallInst>(V)) { 176 const bool IsInlineAsm = CI->isInlineAsm(); 177 const bool IsIndirectFunctionCall = 178 !IsInlineAsm && !CI->getCalledFunction(); 179 180 // It is possible that the call instruction is an inline asm statement or an 181 // indirect function call in which case the return value of 182 // getCalledFunction() would be nullptr. 183 const bool IsInstrinsicCall = 184 !IsInlineAsm && !IsIndirectFunctionCall && 185 CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic; 186 187 if (!IsInlineAsm && !IsInstrinsicCall) 188 return CI->getCallingConv(); 189 } 190 191 return None; 192 } 193 194 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 195 const SDValue *Parts, unsigned NumParts, 196 MVT PartVT, EVT ValueVT, const Value *V, 197 Optional<CallingConv::ID> CC); 198 199 /// getCopyFromParts - Create a value that contains the specified legal parts 200 /// combined into the value they represent. If the parts combine to a type 201 /// larger than ValueVT then AssertOp can be used to specify whether the extra 202 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 203 /// (ISD::AssertSext). 204 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 205 const SDValue *Parts, unsigned NumParts, 206 MVT PartVT, EVT ValueVT, const Value *V, 207 Optional<CallingConv::ID> CC = None, 208 Optional<ISD::NodeType> AssertOp = None) { 209 if (ValueVT.isVector()) 210 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 211 CC); 212 213 assert(NumParts > 0 && "No parts to assemble!"); 214 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 215 SDValue Val = Parts[0]; 216 217 if (NumParts > 1) { 218 // Assemble the value from multiple parts. 219 if (ValueVT.isInteger()) { 220 unsigned PartBits = PartVT.getSizeInBits(); 221 unsigned ValueBits = ValueVT.getSizeInBits(); 222 223 // Assemble the power of 2 part. 224 unsigned RoundParts = 225 (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts; 226 unsigned RoundBits = PartBits * RoundParts; 227 EVT RoundVT = RoundBits == ValueBits ? 228 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 229 SDValue Lo, Hi; 230 231 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 232 233 if (RoundParts > 2) { 234 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 235 PartVT, HalfVT, V); 236 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 237 RoundParts / 2, PartVT, HalfVT, V); 238 } else { 239 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 240 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 241 } 242 243 if (DAG.getDataLayout().isBigEndian()) 244 std::swap(Lo, Hi); 245 246 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 247 248 if (RoundParts < NumParts) { 249 // Assemble the trailing non-power-of-2 part. 250 unsigned OddParts = NumParts - RoundParts; 251 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 252 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 253 OddVT, V, CC); 254 255 // Combine the round and odd parts. 256 Lo = Val; 257 if (DAG.getDataLayout().isBigEndian()) 258 std::swap(Lo, Hi); 259 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 260 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 261 Hi = 262 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 263 DAG.getConstant(Lo.getValueSizeInBits(), DL, 264 TLI.getPointerTy(DAG.getDataLayout()))); 265 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 266 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 267 } 268 } else if (PartVT.isFloatingPoint()) { 269 // FP split into multiple FP parts (for ppcf128) 270 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 271 "Unexpected split"); 272 SDValue Lo, Hi; 273 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 274 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 275 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 276 std::swap(Lo, Hi); 277 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 278 } else { 279 // FP split into integer parts (soft fp) 280 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 281 !PartVT.isVector() && "Unexpected split"); 282 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 283 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 284 } 285 } 286 287 // There is now one part, held in Val. Correct it to match ValueVT. 288 // PartEVT is the type of the register class that holds the value. 289 // ValueVT is the type of the inline asm operation. 290 EVT PartEVT = Val.getValueType(); 291 292 if (PartEVT == ValueVT) 293 return Val; 294 295 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 296 ValueVT.bitsLT(PartEVT)) { 297 // For an FP value in an integer part, we need to truncate to the right 298 // width first. 299 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 300 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 301 } 302 303 // Handle types that have the same size. 304 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 305 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 306 307 // Handle types with different sizes. 308 if (PartEVT.isInteger() && ValueVT.isInteger()) { 309 if (ValueVT.bitsLT(PartEVT)) { 310 // For a truncate, see if we have any information to 311 // indicate whether the truncated bits will always be 312 // zero or sign-extension. 313 if (AssertOp.hasValue()) 314 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 315 DAG.getValueType(ValueVT)); 316 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 317 } 318 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 319 } 320 321 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 322 // FP_ROUND's are always exact here. 323 if (ValueVT.bitsLT(Val.getValueType())) 324 return DAG.getNode( 325 ISD::FP_ROUND, DL, ValueVT, Val, 326 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 327 328 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 329 } 330 331 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 332 // then truncating. 333 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 334 ValueVT.bitsLT(PartEVT)) { 335 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 336 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 337 } 338 339 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 340 } 341 342 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 343 const Twine &ErrMsg) { 344 const Instruction *I = dyn_cast_or_null<Instruction>(V); 345 if (!V) 346 return Ctx.emitError(ErrMsg); 347 348 const char *AsmError = ", possible invalid constraint for vector type"; 349 if (const CallInst *CI = dyn_cast<CallInst>(I)) 350 if (isa<InlineAsm>(CI->getCalledValue())) 351 return Ctx.emitError(I, ErrMsg + AsmError); 352 353 return Ctx.emitError(I, ErrMsg); 354 } 355 356 /// getCopyFromPartsVector - Create a value that contains the specified legal 357 /// parts combined into the value they represent. If the parts combine to a 358 /// type larger than ValueVT then AssertOp can be used to specify whether the 359 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 360 /// ValueVT (ISD::AssertSext). 361 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 362 const SDValue *Parts, unsigned NumParts, 363 MVT PartVT, EVT ValueVT, const Value *V, 364 Optional<CallingConv::ID> CallConv) { 365 assert(ValueVT.isVector() && "Not a vector value"); 366 assert(NumParts > 0 && "No parts to assemble!"); 367 const bool IsABIRegCopy = CallConv.hasValue(); 368 369 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 370 SDValue Val = Parts[0]; 371 372 // Handle a multi-element vector. 373 if (NumParts > 1) { 374 EVT IntermediateVT; 375 MVT RegisterVT; 376 unsigned NumIntermediates; 377 unsigned NumRegs; 378 379 if (IsABIRegCopy) { 380 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 381 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 382 NumIntermediates, RegisterVT); 383 } else { 384 NumRegs = 385 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 386 NumIntermediates, RegisterVT); 387 } 388 389 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 390 NumParts = NumRegs; // Silence a compiler warning. 391 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 392 assert(RegisterVT.getSizeInBits() == 393 Parts[0].getSimpleValueType().getSizeInBits() && 394 "Part type sizes don't match!"); 395 396 // Assemble the parts into intermediate operands. 397 SmallVector<SDValue, 8> Ops(NumIntermediates); 398 if (NumIntermediates == NumParts) { 399 // If the register was not expanded, truncate or copy the value, 400 // as appropriate. 401 for (unsigned i = 0; i != NumParts; ++i) 402 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 403 PartVT, IntermediateVT, V); 404 } else if (NumParts > 0) { 405 // If the intermediate type was expanded, build the intermediate 406 // operands from the parts. 407 assert(NumParts % NumIntermediates == 0 && 408 "Must expand into a divisible number of parts!"); 409 unsigned Factor = NumParts / NumIntermediates; 410 for (unsigned i = 0; i != NumIntermediates; ++i) 411 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 412 PartVT, IntermediateVT, V); 413 } 414 415 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 416 // intermediate operands. 417 EVT BuiltVectorTy = 418 EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(), 419 (IntermediateVT.isVector() 420 ? IntermediateVT.getVectorNumElements() * NumParts 421 : NumIntermediates)); 422 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 423 : ISD::BUILD_VECTOR, 424 DL, BuiltVectorTy, Ops); 425 } 426 427 // There is now one part, held in Val. Correct it to match ValueVT. 428 EVT PartEVT = Val.getValueType(); 429 430 if (PartEVT == ValueVT) 431 return Val; 432 433 if (PartEVT.isVector()) { 434 // If the element type of the source/dest vectors are the same, but the 435 // parts vector has more elements than the value vector, then we have a 436 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 437 // elements we want. 438 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { 439 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() && 440 "Cannot narrow, it would be a lossy transformation"); 441 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 442 DAG.getVectorIdxConstant(0, DL)); 443 } 444 445 // Vector/Vector bitcast. 446 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 447 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 448 449 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() && 450 "Cannot handle this kind of promotion"); 451 // Promoted vector extract 452 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 453 454 } 455 456 // Trivial bitcast if the types are the same size and the destination 457 // vector type is legal. 458 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 459 TLI.isTypeLegal(ValueVT)) 460 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 461 462 if (ValueVT.getVectorNumElements() != 1) { 463 // Certain ABIs require that vectors are passed as integers. For vectors 464 // are the same size, this is an obvious bitcast. 465 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 466 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 467 } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) { 468 // Bitcast Val back the original type and extract the corresponding 469 // vector we want. 470 unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits(); 471 EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(), 472 ValueVT.getVectorElementType(), Elts); 473 Val = DAG.getBitcast(WiderVecType, Val); 474 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 475 DAG.getVectorIdxConstant(0, DL)); 476 } 477 478 diagnosePossiblyInvalidConstraint( 479 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 480 return DAG.getUNDEF(ValueVT); 481 } 482 483 // Handle cases such as i8 -> <1 x i1> 484 EVT ValueSVT = ValueVT.getVectorElementType(); 485 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) 486 Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 487 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 488 489 return DAG.getBuildVector(ValueVT, DL, Val); 490 } 491 492 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 493 SDValue Val, SDValue *Parts, unsigned NumParts, 494 MVT PartVT, const Value *V, 495 Optional<CallingConv::ID> CallConv); 496 497 /// getCopyToParts - Create a series of nodes that contain the specified value 498 /// split into legal parts. If the parts contain more bits than Val, then, for 499 /// integers, ExtendKind can be used to specify how to generate the extra bits. 500 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 501 SDValue *Parts, unsigned NumParts, MVT PartVT, 502 const Value *V, 503 Optional<CallingConv::ID> CallConv = None, 504 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 505 EVT ValueVT = Val.getValueType(); 506 507 // Handle the vector case separately. 508 if (ValueVT.isVector()) 509 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 510 CallConv); 511 512 unsigned PartBits = PartVT.getSizeInBits(); 513 unsigned OrigNumParts = NumParts; 514 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 515 "Copying to an illegal type!"); 516 517 if (NumParts == 0) 518 return; 519 520 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 521 EVT PartEVT = PartVT; 522 if (PartEVT == ValueVT) { 523 assert(NumParts == 1 && "No-op copy with multiple parts!"); 524 Parts[0] = Val; 525 return; 526 } 527 528 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 529 // If the parts cover more bits than the value has, promote the value. 530 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 531 assert(NumParts == 1 && "Do not know what to promote to!"); 532 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 533 } else { 534 if (ValueVT.isFloatingPoint()) { 535 // FP values need to be bitcast, then extended if they are being put 536 // into a larger container. 537 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 538 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 539 } 540 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 541 ValueVT.isInteger() && 542 "Unknown mismatch!"); 543 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 544 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 545 if (PartVT == MVT::x86mmx) 546 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 547 } 548 } else if (PartBits == ValueVT.getSizeInBits()) { 549 // Different types of the same size. 550 assert(NumParts == 1 && PartEVT != ValueVT); 551 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 552 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 553 // If the parts cover less bits than value has, truncate the value. 554 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 555 ValueVT.isInteger() && 556 "Unknown mismatch!"); 557 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 558 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 559 if (PartVT == MVT::x86mmx) 560 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 561 } 562 563 // The value may have changed - recompute ValueVT. 564 ValueVT = Val.getValueType(); 565 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 566 "Failed to tile the value with PartVT!"); 567 568 if (NumParts == 1) { 569 if (PartEVT != ValueVT) { 570 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 571 "scalar-to-vector conversion failed"); 572 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 573 } 574 575 Parts[0] = Val; 576 return; 577 } 578 579 // Expand the value into multiple parts. 580 if (NumParts & (NumParts - 1)) { 581 // The number of parts is not a power of 2. Split off and copy the tail. 582 assert(PartVT.isInteger() && ValueVT.isInteger() && 583 "Do not know what to expand to!"); 584 unsigned RoundParts = 1 << Log2_32(NumParts); 585 unsigned RoundBits = RoundParts * PartBits; 586 unsigned OddParts = NumParts - RoundParts; 587 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 588 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false)); 589 590 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 591 CallConv); 592 593 if (DAG.getDataLayout().isBigEndian()) 594 // The odd parts were reversed by getCopyToParts - unreverse them. 595 std::reverse(Parts + RoundParts, Parts + NumParts); 596 597 NumParts = RoundParts; 598 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 599 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 600 } 601 602 // The number of parts is a power of 2. Repeatedly bisect the value using 603 // EXTRACT_ELEMENT. 604 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 605 EVT::getIntegerVT(*DAG.getContext(), 606 ValueVT.getSizeInBits()), 607 Val); 608 609 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 610 for (unsigned i = 0; i < NumParts; i += StepSize) { 611 unsigned ThisBits = StepSize * PartBits / 2; 612 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 613 SDValue &Part0 = Parts[i]; 614 SDValue &Part1 = Parts[i+StepSize/2]; 615 616 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 617 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 618 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 619 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 620 621 if (ThisBits == PartBits && ThisVT != PartVT) { 622 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 623 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 624 } 625 } 626 } 627 628 if (DAG.getDataLayout().isBigEndian()) 629 std::reverse(Parts, Parts + OrigNumParts); 630 } 631 632 static SDValue widenVectorToPartType(SelectionDAG &DAG, 633 SDValue Val, const SDLoc &DL, EVT PartVT) { 634 if (!PartVT.isVector()) 635 return SDValue(); 636 637 EVT ValueVT = Val.getValueType(); 638 unsigned PartNumElts = PartVT.getVectorNumElements(); 639 unsigned ValueNumElts = ValueVT.getVectorNumElements(); 640 if (PartNumElts > ValueNumElts && 641 PartVT.getVectorElementType() == ValueVT.getVectorElementType()) { 642 EVT ElementVT = PartVT.getVectorElementType(); 643 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 644 // undef elements. 645 SmallVector<SDValue, 16> Ops; 646 DAG.ExtractVectorElements(Val, Ops); 647 SDValue EltUndef = DAG.getUNDEF(ElementVT); 648 for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i) 649 Ops.push_back(EltUndef); 650 651 // FIXME: Use CONCAT for 2x -> 4x. 652 return DAG.getBuildVector(PartVT, DL, Ops); 653 } 654 655 return SDValue(); 656 } 657 658 /// getCopyToPartsVector - Create a series of nodes that contain the specified 659 /// value split into legal parts. 660 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 661 SDValue Val, SDValue *Parts, unsigned NumParts, 662 MVT PartVT, const Value *V, 663 Optional<CallingConv::ID> CallConv) { 664 EVT ValueVT = Val.getValueType(); 665 assert(ValueVT.isVector() && "Not a vector"); 666 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 667 const bool IsABIRegCopy = CallConv.hasValue(); 668 669 if (NumParts == 1) { 670 EVT PartEVT = PartVT; 671 if (PartEVT == ValueVT) { 672 // Nothing to do. 673 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 674 // Bitconvert vector->vector case. 675 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 676 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 677 Val = Widened; 678 } else if (PartVT.isVector() && 679 PartEVT.getVectorElementType().bitsGE( 680 ValueVT.getVectorElementType()) && 681 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) { 682 683 // Promoted vector extract 684 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 685 } else { 686 if (ValueVT.getVectorNumElements() == 1) { 687 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 688 DAG.getVectorIdxConstant(0, DL)); 689 } else { 690 assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() && 691 "lossy conversion of vector to scalar type"); 692 EVT IntermediateType = 693 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 694 Val = DAG.getBitcast(IntermediateType, Val); 695 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 696 } 697 } 698 699 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 700 Parts[0] = Val; 701 return; 702 } 703 704 // Handle a multi-element vector. 705 EVT IntermediateVT; 706 MVT RegisterVT; 707 unsigned NumIntermediates; 708 unsigned NumRegs; 709 if (IsABIRegCopy) { 710 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 711 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 712 NumIntermediates, RegisterVT); 713 } else { 714 NumRegs = 715 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 716 NumIntermediates, RegisterVT); 717 } 718 719 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 720 NumParts = NumRegs; // Silence a compiler warning. 721 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 722 723 unsigned IntermediateNumElts = IntermediateVT.isVector() ? 724 IntermediateVT.getVectorNumElements() : 1; 725 726 // Convert the vector to the appropriate type if necessary. 727 unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts; 728 729 EVT BuiltVectorTy = EVT::getVectorVT( 730 *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts); 731 if (ValueVT != BuiltVectorTy) { 732 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) 733 Val = Widened; 734 735 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 736 } 737 738 // Split the vector into intermediate operands. 739 SmallVector<SDValue, 8> Ops(NumIntermediates); 740 for (unsigned i = 0; i != NumIntermediates; ++i) { 741 if (IntermediateVT.isVector()) { 742 Ops[i] = 743 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 744 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 745 } else { 746 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 747 DAG.getVectorIdxConstant(i, DL)); 748 } 749 } 750 751 // Split the intermediate operands into legal parts. 752 if (NumParts == NumIntermediates) { 753 // If the register was not expanded, promote or copy the value, 754 // as appropriate. 755 for (unsigned i = 0; i != NumParts; ++i) 756 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 757 } else if (NumParts > 0) { 758 // If the intermediate type was expanded, split each the value into 759 // legal parts. 760 assert(NumIntermediates != 0 && "division by zero"); 761 assert(NumParts % NumIntermediates == 0 && 762 "Must expand into a divisible number of parts!"); 763 unsigned Factor = NumParts / NumIntermediates; 764 for (unsigned i = 0; i != NumIntermediates; ++i) 765 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 766 CallConv); 767 } 768 } 769 770 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 771 EVT valuevt, Optional<CallingConv::ID> CC) 772 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 773 RegCount(1, regs.size()), CallConv(CC) {} 774 775 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 776 const DataLayout &DL, unsigned Reg, Type *Ty, 777 Optional<CallingConv::ID> CC) { 778 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 779 780 CallConv = CC; 781 782 for (EVT ValueVT : ValueVTs) { 783 unsigned NumRegs = 784 isABIMangled() 785 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) 786 : TLI.getNumRegisters(Context, ValueVT); 787 MVT RegisterVT = 788 isABIMangled() 789 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) 790 : TLI.getRegisterType(Context, ValueVT); 791 for (unsigned i = 0; i != NumRegs; ++i) 792 Regs.push_back(Reg + i); 793 RegVTs.push_back(RegisterVT); 794 RegCount.push_back(NumRegs); 795 Reg += NumRegs; 796 } 797 } 798 799 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 800 FunctionLoweringInfo &FuncInfo, 801 const SDLoc &dl, SDValue &Chain, 802 SDValue *Flag, const Value *V) const { 803 // A Value with type {} or [0 x %t] needs no registers. 804 if (ValueVTs.empty()) 805 return SDValue(); 806 807 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 808 809 // Assemble the legal parts into the final values. 810 SmallVector<SDValue, 4> Values(ValueVTs.size()); 811 SmallVector<SDValue, 8> Parts; 812 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 813 // Copy the legal parts from the registers. 814 EVT ValueVT = ValueVTs[Value]; 815 unsigned NumRegs = RegCount[Value]; 816 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 817 *DAG.getContext(), 818 CallConv.getValue(), RegVTs[Value]) 819 : RegVTs[Value]; 820 821 Parts.resize(NumRegs); 822 for (unsigned i = 0; i != NumRegs; ++i) { 823 SDValue P; 824 if (!Flag) { 825 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 826 } else { 827 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 828 *Flag = P.getValue(2); 829 } 830 831 Chain = P.getValue(1); 832 Parts[i] = P; 833 834 // If the source register was virtual and if we know something about it, 835 // add an assert node. 836 if (!Register::isVirtualRegister(Regs[Part + i]) || 837 !RegisterVT.isInteger()) 838 continue; 839 840 const FunctionLoweringInfo::LiveOutInfo *LOI = 841 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 842 if (!LOI) 843 continue; 844 845 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 846 unsigned NumSignBits = LOI->NumSignBits; 847 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 848 849 if (NumZeroBits == RegSize) { 850 // The current value is a zero. 851 // Explicitly express that as it would be easier for 852 // optimizations to kick in. 853 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 854 continue; 855 } 856 857 // FIXME: We capture more information than the dag can represent. For 858 // now, just use the tightest assertzext/assertsext possible. 859 bool isSExt; 860 EVT FromVT(MVT::Other); 861 if (NumZeroBits) { 862 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 863 isSExt = false; 864 } else if (NumSignBits > 1) { 865 FromVT = 866 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 867 isSExt = true; 868 } else { 869 continue; 870 } 871 // Add an assertion node. 872 assert(FromVT != MVT::Other); 873 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 874 RegisterVT, P, DAG.getValueType(FromVT)); 875 } 876 877 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 878 RegisterVT, ValueVT, V, CallConv); 879 Part += NumRegs; 880 Parts.clear(); 881 } 882 883 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 884 } 885 886 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 887 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 888 const Value *V, 889 ISD::NodeType PreferredExtendType) const { 890 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 891 ISD::NodeType ExtendKind = PreferredExtendType; 892 893 // Get the list of the values's legal parts. 894 unsigned NumRegs = Regs.size(); 895 SmallVector<SDValue, 8> Parts(NumRegs); 896 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 897 unsigned NumParts = RegCount[Value]; 898 899 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 900 *DAG.getContext(), 901 CallConv.getValue(), RegVTs[Value]) 902 : RegVTs[Value]; 903 904 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 905 ExtendKind = ISD::ZERO_EXTEND; 906 907 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 908 NumParts, RegisterVT, V, CallConv, ExtendKind); 909 Part += NumParts; 910 } 911 912 // Copy the parts into the registers. 913 SmallVector<SDValue, 8> Chains(NumRegs); 914 for (unsigned i = 0; i != NumRegs; ++i) { 915 SDValue Part; 916 if (!Flag) { 917 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 918 } else { 919 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 920 *Flag = Part.getValue(1); 921 } 922 923 Chains[i] = Part.getValue(0); 924 } 925 926 if (NumRegs == 1 || Flag) 927 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 928 // flagged to it. That is the CopyToReg nodes and the user are considered 929 // a single scheduling unit. If we create a TokenFactor and return it as 930 // chain, then the TokenFactor is both a predecessor (operand) of the 931 // user as well as a successor (the TF operands are flagged to the user). 932 // c1, f1 = CopyToReg 933 // c2, f2 = CopyToReg 934 // c3 = TokenFactor c1, c2 935 // ... 936 // = op c3, ..., f2 937 Chain = Chains[NumRegs-1]; 938 else 939 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 940 } 941 942 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 943 unsigned MatchingIdx, const SDLoc &dl, 944 SelectionDAG &DAG, 945 std::vector<SDValue> &Ops) const { 946 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 947 948 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 949 if (HasMatching) 950 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 951 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 952 // Put the register class of the virtual registers in the flag word. That 953 // way, later passes can recompute register class constraints for inline 954 // assembly as well as normal instructions. 955 // Don't do this for tied operands that can use the regclass information 956 // from the def. 957 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 958 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 959 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 960 } 961 962 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 963 Ops.push_back(Res); 964 965 if (Code == InlineAsm::Kind_Clobber) { 966 // Clobbers should always have a 1:1 mapping with registers, and may 967 // reference registers that have illegal (e.g. vector) types. Hence, we 968 // shouldn't try to apply any sort of splitting logic to them. 969 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 970 "No 1:1 mapping from clobbers to regs?"); 971 unsigned SP = TLI.getStackPointerRegisterToSaveRestore(); 972 (void)SP; 973 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 974 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 975 assert( 976 (Regs[I] != SP || 977 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 978 "If we clobbered the stack pointer, MFI should know about it."); 979 } 980 return; 981 } 982 983 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 984 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 985 MVT RegisterVT = RegVTs[Value]; 986 for (unsigned i = 0; i != NumRegs; ++i) { 987 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 988 unsigned TheReg = Regs[Reg++]; 989 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 990 } 991 } 992 } 993 994 SmallVector<std::pair<unsigned, unsigned>, 4> 995 RegsForValue::getRegsAndSizes() const { 996 SmallVector<std::pair<unsigned, unsigned>, 4> OutVec; 997 unsigned I = 0; 998 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 999 unsigned RegCount = std::get<0>(CountAndVT); 1000 MVT RegisterVT = std::get<1>(CountAndVT); 1001 unsigned RegisterSize = RegisterVT.getSizeInBits(); 1002 for (unsigned E = I + RegCount; I != E; ++I) 1003 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1004 } 1005 return OutVec; 1006 } 1007 1008 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1009 const TargetLibraryInfo *li) { 1010 AA = aa; 1011 GFI = gfi; 1012 LibInfo = li; 1013 DL = &DAG.getDataLayout(); 1014 Context = DAG.getContext(); 1015 LPadToCallSiteMap.clear(); 1016 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1017 } 1018 1019 void SelectionDAGBuilder::clear() { 1020 NodeMap.clear(); 1021 UnusedArgNodeMap.clear(); 1022 PendingLoads.clear(); 1023 PendingExports.clear(); 1024 PendingConstrainedFP.clear(); 1025 PendingConstrainedFPStrict.clear(); 1026 CurInst = nullptr; 1027 HasTailCall = false; 1028 SDNodeOrder = LowestSDNodeOrder; 1029 StatepointLowering.clear(); 1030 } 1031 1032 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1033 DanglingDebugInfoMap.clear(); 1034 } 1035 1036 // Update DAG root to include dependencies on Pending chains. 1037 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1038 SDValue Root = DAG.getRoot(); 1039 1040 if (Pending.empty()) 1041 return Root; 1042 1043 // Add current root to PendingChains, unless we already indirectly 1044 // depend on it. 1045 if (Root.getOpcode() != ISD::EntryToken) { 1046 unsigned i = 0, e = Pending.size(); 1047 for (; i != e; ++i) { 1048 assert(Pending[i].getNode()->getNumOperands() > 1); 1049 if (Pending[i].getNode()->getOperand(0) == Root) 1050 break; // Don't add the root if we already indirectly depend on it. 1051 } 1052 1053 if (i == e) 1054 Pending.push_back(Root); 1055 } 1056 1057 if (Pending.size() == 1) 1058 Root = Pending[0]; 1059 else 1060 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1061 1062 DAG.setRoot(Root); 1063 Pending.clear(); 1064 return Root; 1065 } 1066 1067 SDValue SelectionDAGBuilder::getMemoryRoot() { 1068 return updateRoot(PendingLoads); 1069 } 1070 1071 SDValue SelectionDAGBuilder::getRoot() { 1072 // Chain up all pending constrained intrinsics together with all 1073 // pending loads, by simply appending them to PendingLoads and 1074 // then calling getMemoryRoot(). 1075 PendingLoads.reserve(PendingLoads.size() + 1076 PendingConstrainedFP.size() + 1077 PendingConstrainedFPStrict.size()); 1078 PendingLoads.append(PendingConstrainedFP.begin(), 1079 PendingConstrainedFP.end()); 1080 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1081 PendingConstrainedFPStrict.end()); 1082 PendingConstrainedFP.clear(); 1083 PendingConstrainedFPStrict.clear(); 1084 return getMemoryRoot(); 1085 } 1086 1087 SDValue SelectionDAGBuilder::getControlRoot() { 1088 // We need to emit pending fpexcept.strict constrained intrinsics, 1089 // so append them to the PendingExports list. 1090 PendingExports.append(PendingConstrainedFPStrict.begin(), 1091 PendingConstrainedFPStrict.end()); 1092 PendingConstrainedFPStrict.clear(); 1093 return updateRoot(PendingExports); 1094 } 1095 1096 void SelectionDAGBuilder::visit(const Instruction &I) { 1097 // Set up outgoing PHI node register values before emitting the terminator. 1098 if (I.isTerminator()) { 1099 HandlePHINodesInSuccessorBlocks(I.getParent()); 1100 } 1101 1102 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1103 if (!isa<DbgInfoIntrinsic>(I)) 1104 ++SDNodeOrder; 1105 1106 CurInst = &I; 1107 1108 visit(I.getOpcode(), I); 1109 1110 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) { 1111 // Propagate the fast-math-flags of this IR instruction to the DAG node that 1112 // maps to this instruction. 1113 // TODO: We could handle all flags (nsw, etc) here. 1114 // TODO: If an IR instruction maps to >1 node, only the final node will have 1115 // flags set. 1116 if (SDNode *Node = getNodeForIRValue(&I)) { 1117 SDNodeFlags IncomingFlags; 1118 IncomingFlags.copyFMF(*FPMO); 1119 if (!Node->getFlags().isDefined()) 1120 Node->setFlags(IncomingFlags); 1121 else 1122 Node->intersectFlagsWith(IncomingFlags); 1123 } 1124 } 1125 // Constrained FP intrinsics with fpexcept.ignore should also get 1126 // the NoFPExcept flag. 1127 if (auto *FPI = dyn_cast<ConstrainedFPIntrinsic>(&I)) 1128 if (FPI->getExceptionBehavior() == fp::ExceptionBehavior::ebIgnore) 1129 if (SDNode *Node = getNodeForIRValue(&I)) { 1130 SDNodeFlags Flags = Node->getFlags(); 1131 Flags.setNoFPExcept(true); 1132 Node->setFlags(Flags); 1133 } 1134 1135 if (!I.isTerminator() && !HasTailCall && 1136 !isStatepoint(&I)) // statepoints handle their exports internally 1137 CopyToExportRegsIfNeeded(&I); 1138 1139 CurInst = nullptr; 1140 } 1141 1142 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1143 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1144 } 1145 1146 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1147 // Note: this doesn't use InstVisitor, because it has to work with 1148 // ConstantExpr's in addition to instructions. 1149 switch (Opcode) { 1150 default: llvm_unreachable("Unknown instruction type encountered!"); 1151 // Build the switch statement using the Instruction.def file. 1152 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1153 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1154 #include "llvm/IR/Instruction.def" 1155 } 1156 } 1157 1158 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1159 const DIExpression *Expr) { 1160 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1161 const DbgValueInst *DI = DDI.getDI(); 1162 DIVariable *DanglingVariable = DI->getVariable(); 1163 DIExpression *DanglingExpr = DI->getExpression(); 1164 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1165 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1166 return true; 1167 } 1168 return false; 1169 }; 1170 1171 for (auto &DDIMI : DanglingDebugInfoMap) { 1172 DanglingDebugInfoVector &DDIV = DDIMI.second; 1173 1174 // If debug info is to be dropped, run it through final checks to see 1175 // whether it can be salvaged. 1176 for (auto &DDI : DDIV) 1177 if (isMatchingDbgValue(DDI)) 1178 salvageUnresolvedDbgValue(DDI); 1179 1180 DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end()); 1181 } 1182 } 1183 1184 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1185 // generate the debug data structures now that we've seen its definition. 1186 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1187 SDValue Val) { 1188 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1189 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1190 return; 1191 1192 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1193 for (auto &DDI : DDIV) { 1194 const DbgValueInst *DI = DDI.getDI(); 1195 assert(DI && "Ill-formed DanglingDebugInfo"); 1196 DebugLoc dl = DDI.getdl(); 1197 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1198 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1199 DILocalVariable *Variable = DI->getVariable(); 1200 DIExpression *Expr = DI->getExpression(); 1201 assert(Variable->isValidLocationForIntrinsic(dl) && 1202 "Expected inlined-at fields to agree"); 1203 SDDbgValue *SDV; 1204 if (Val.getNode()) { 1205 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1206 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1207 // we couldn't resolve it directly when examining the DbgValue intrinsic 1208 // in the first place we should not be more successful here). Unless we 1209 // have some test case that prove this to be correct we should avoid 1210 // calling EmitFuncArgumentDbgValue here. 1211 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1212 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1213 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1214 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1215 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1216 // inserted after the definition of Val when emitting the instructions 1217 // after ISel. An alternative could be to teach 1218 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1219 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1220 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1221 << ValSDNodeOrder << "\n"); 1222 SDV = getDbgValue(Val, Variable, Expr, dl, 1223 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1224 DAG.AddDbgValue(SDV, Val.getNode(), false); 1225 } else 1226 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1227 << "in EmitFuncArgumentDbgValue\n"); 1228 } else { 1229 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1230 auto Undef = 1231 UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1232 auto SDV = 1233 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); 1234 DAG.AddDbgValue(SDV, nullptr, false); 1235 } 1236 } 1237 DDIV.clear(); 1238 } 1239 1240 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1241 Value *V = DDI.getDI()->getValue(); 1242 DILocalVariable *Var = DDI.getDI()->getVariable(); 1243 DIExpression *Expr = DDI.getDI()->getExpression(); 1244 DebugLoc DL = DDI.getdl(); 1245 DebugLoc InstDL = DDI.getDI()->getDebugLoc(); 1246 unsigned SDOrder = DDI.getSDNodeOrder(); 1247 1248 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1249 // that DW_OP_stack_value is desired. 1250 assert(isa<DbgValueInst>(DDI.getDI())); 1251 bool StackValue = true; 1252 1253 // Can this Value can be encoded without any further work? 1254 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) 1255 return; 1256 1257 // Attempt to salvage back through as many instructions as possible. Bail if 1258 // a non-instruction is seen, such as a constant expression or global 1259 // variable. FIXME: Further work could recover those too. 1260 while (isa<Instruction>(V)) { 1261 Instruction &VAsInst = *cast<Instruction>(V); 1262 DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue); 1263 1264 // If we cannot salvage any further, and haven't yet found a suitable debug 1265 // expression, bail out. 1266 if (!NewExpr) 1267 break; 1268 1269 // New value and expr now represent this debuginfo. 1270 V = VAsInst.getOperand(0); 1271 Expr = NewExpr; 1272 1273 // Some kind of simplification occurred: check whether the operand of the 1274 // salvaged debug expression can be encoded in this DAG. 1275 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) { 1276 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n " 1277 << DDI.getDI() << "\nBy stripping back to:\n " << V); 1278 return; 1279 } 1280 } 1281 1282 // This was the final opportunity to salvage this debug information, and it 1283 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1284 // any earlier variable location. 1285 auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1286 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1287 DAG.AddDbgValue(SDV, nullptr, false); 1288 1289 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI() 1290 << "\n"); 1291 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0) 1292 << "\n"); 1293 } 1294 1295 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var, 1296 DIExpression *Expr, DebugLoc dl, 1297 DebugLoc InstDL, unsigned Order) { 1298 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1299 SDDbgValue *SDV; 1300 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1301 isa<ConstantPointerNull>(V)) { 1302 SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder); 1303 DAG.AddDbgValue(SDV, nullptr, false); 1304 return true; 1305 } 1306 1307 // If the Value is a frame index, we can create a FrameIndex debug value 1308 // without relying on the DAG at all. 1309 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1310 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1311 if (SI != FuncInfo.StaticAllocaMap.end()) { 1312 auto SDV = 1313 DAG.getFrameIndexDbgValue(Var, Expr, SI->second, 1314 /*IsIndirect*/ false, dl, SDNodeOrder); 1315 // Do not attach the SDNodeDbgValue to an SDNode: this variable location 1316 // is still available even if the SDNode gets optimized out. 1317 DAG.AddDbgValue(SDV, nullptr, false); 1318 return true; 1319 } 1320 } 1321 1322 // Do not use getValue() in here; we don't want to generate code at 1323 // this point if it hasn't been done yet. 1324 SDValue N = NodeMap[V]; 1325 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1326 N = UnusedArgNodeMap[V]; 1327 if (N.getNode()) { 1328 if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N)) 1329 return true; 1330 SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder); 1331 DAG.AddDbgValue(SDV, N.getNode(), false); 1332 return true; 1333 } 1334 1335 // Special rules apply for the first dbg.values of parameter variables in a 1336 // function. Identify them by the fact they reference Argument Values, that 1337 // they're parameters, and they are parameters of the current function. We 1338 // need to let them dangle until they get an SDNode. 1339 bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() && 1340 !InstDL.getInlinedAt(); 1341 if (!IsParamOfFunc) { 1342 // The value is not used in this block yet (or it would have an SDNode). 1343 // We still want the value to appear for the user if possible -- if it has 1344 // an associated VReg, we can refer to that instead. 1345 auto VMI = FuncInfo.ValueMap.find(V); 1346 if (VMI != FuncInfo.ValueMap.end()) { 1347 unsigned Reg = VMI->second; 1348 // If this is a PHI node, it may be split up into several MI PHI nodes 1349 // (in FunctionLoweringInfo::set). 1350 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1351 V->getType(), None); 1352 if (RFV.occupiesMultipleRegs()) { 1353 unsigned Offset = 0; 1354 unsigned BitsToDescribe = 0; 1355 if (auto VarSize = Var->getSizeInBits()) 1356 BitsToDescribe = *VarSize; 1357 if (auto Fragment = Expr->getFragmentInfo()) 1358 BitsToDescribe = Fragment->SizeInBits; 1359 for (auto RegAndSize : RFV.getRegsAndSizes()) { 1360 unsigned RegisterSize = RegAndSize.second; 1361 // Bail out if all bits are described already. 1362 if (Offset >= BitsToDescribe) 1363 break; 1364 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1365 ? BitsToDescribe - Offset 1366 : RegisterSize; 1367 auto FragmentExpr = DIExpression::createFragmentExpression( 1368 Expr, Offset, FragmentSize); 1369 if (!FragmentExpr) 1370 continue; 1371 SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first, 1372 false, dl, SDNodeOrder); 1373 DAG.AddDbgValue(SDV, nullptr, false); 1374 Offset += RegisterSize; 1375 } 1376 } else { 1377 SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder); 1378 DAG.AddDbgValue(SDV, nullptr, false); 1379 } 1380 return true; 1381 } 1382 } 1383 1384 return false; 1385 } 1386 1387 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1388 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1389 for (auto &Pair : DanglingDebugInfoMap) 1390 for (auto &DDI : Pair.second) 1391 salvageUnresolvedDbgValue(DDI); 1392 clearDanglingDebugInfo(); 1393 } 1394 1395 /// getCopyFromRegs - If there was virtual register allocated for the value V 1396 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1397 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1398 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V); 1399 SDValue Result; 1400 1401 if (It != FuncInfo.ValueMap.end()) { 1402 unsigned InReg = It->second; 1403 1404 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1405 DAG.getDataLayout(), InReg, Ty, 1406 None); // This is not an ABI copy. 1407 SDValue Chain = DAG.getEntryNode(); 1408 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1409 V); 1410 resolveDanglingDebugInfo(V, Result); 1411 } 1412 1413 return Result; 1414 } 1415 1416 /// getValue - Return an SDValue for the given Value. 1417 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1418 // If we already have an SDValue for this value, use it. It's important 1419 // to do this first, so that we don't create a CopyFromReg if we already 1420 // have a regular SDValue. 1421 SDValue &N = NodeMap[V]; 1422 if (N.getNode()) return N; 1423 1424 // If there's a virtual register allocated and initialized for this 1425 // value, use it. 1426 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1427 return copyFromReg; 1428 1429 // Otherwise create a new SDValue and remember it. 1430 SDValue Val = getValueImpl(V); 1431 NodeMap[V] = Val; 1432 resolveDanglingDebugInfo(V, Val); 1433 return Val; 1434 } 1435 1436 // Return true if SDValue exists for the given Value 1437 bool SelectionDAGBuilder::findValue(const Value *V) const { 1438 return (NodeMap.find(V) != NodeMap.end()) || 1439 (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end()); 1440 } 1441 1442 /// getNonRegisterValue - Return an SDValue for the given Value, but 1443 /// don't look in FuncInfo.ValueMap for a virtual register. 1444 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1445 // If we already have an SDValue for this value, use it. 1446 SDValue &N = NodeMap[V]; 1447 if (N.getNode()) { 1448 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1449 // Remove the debug location from the node as the node is about to be used 1450 // in a location which may differ from the original debug location. This 1451 // is relevant to Constant and ConstantFP nodes because they can appear 1452 // as constant expressions inside PHI nodes. 1453 N->setDebugLoc(DebugLoc()); 1454 } 1455 return N; 1456 } 1457 1458 // Otherwise create a new SDValue and remember it. 1459 SDValue Val = getValueImpl(V); 1460 NodeMap[V] = Val; 1461 resolveDanglingDebugInfo(V, Val); 1462 return Val; 1463 } 1464 1465 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1466 /// Create an SDValue for the given value. 1467 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1468 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1469 1470 if (const Constant *C = dyn_cast<Constant>(V)) { 1471 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1472 1473 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1474 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1475 1476 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1477 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1478 1479 if (isa<ConstantPointerNull>(C)) { 1480 unsigned AS = V->getType()->getPointerAddressSpace(); 1481 return DAG.getConstant(0, getCurSDLoc(), 1482 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1483 } 1484 1485 if (match(C, m_VScale(DAG.getDataLayout()))) 1486 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1487 1488 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1489 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1490 1491 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1492 return DAG.getUNDEF(VT); 1493 1494 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1495 visit(CE->getOpcode(), *CE); 1496 SDValue N1 = NodeMap[V]; 1497 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1498 return N1; 1499 } 1500 1501 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1502 SmallVector<SDValue, 4> Constants; 1503 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 1504 OI != OE; ++OI) { 1505 SDNode *Val = getValue(*OI).getNode(); 1506 // If the operand is an empty aggregate, there are no values. 1507 if (!Val) continue; 1508 // Add each leaf value from the operand to the Constants list 1509 // to form a flattened list of all the values. 1510 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1511 Constants.push_back(SDValue(Val, i)); 1512 } 1513 1514 return DAG.getMergeValues(Constants, getCurSDLoc()); 1515 } 1516 1517 if (const ConstantDataSequential *CDS = 1518 dyn_cast<ConstantDataSequential>(C)) { 1519 SmallVector<SDValue, 4> Ops; 1520 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1521 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1522 // Add each leaf value from the operand to the Constants list 1523 // to form a flattened list of all the values. 1524 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1525 Ops.push_back(SDValue(Val, i)); 1526 } 1527 1528 if (isa<ArrayType>(CDS->getType())) 1529 return DAG.getMergeValues(Ops, getCurSDLoc()); 1530 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1531 } 1532 1533 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1534 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1535 "Unknown struct or array constant!"); 1536 1537 SmallVector<EVT, 4> ValueVTs; 1538 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1539 unsigned NumElts = ValueVTs.size(); 1540 if (NumElts == 0) 1541 return SDValue(); // empty struct 1542 SmallVector<SDValue, 4> Constants(NumElts); 1543 for (unsigned i = 0; i != NumElts; ++i) { 1544 EVT EltVT = ValueVTs[i]; 1545 if (isa<UndefValue>(C)) 1546 Constants[i] = DAG.getUNDEF(EltVT); 1547 else if (EltVT.isFloatingPoint()) 1548 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1549 else 1550 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1551 } 1552 1553 return DAG.getMergeValues(Constants, getCurSDLoc()); 1554 } 1555 1556 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1557 return DAG.getBlockAddress(BA, VT); 1558 1559 VectorType *VecTy = cast<VectorType>(V->getType()); 1560 unsigned NumElements = VecTy->getNumElements(); 1561 1562 // Now that we know the number and type of the elements, get that number of 1563 // elements into the Ops array based on what kind of constant it is. 1564 SmallVector<SDValue, 16> Ops; 1565 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1566 for (unsigned i = 0; i != NumElements; ++i) 1567 Ops.push_back(getValue(CV->getOperand(i))); 1568 } else { 1569 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!"); 1570 EVT EltVT = 1571 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1572 1573 SDValue Op; 1574 if (EltVT.isFloatingPoint()) 1575 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1576 else 1577 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1578 Ops.assign(NumElements, Op); 1579 } 1580 1581 // Create a BUILD_VECTOR node. 1582 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1583 } 1584 1585 // If this is a static alloca, generate it as the frameindex instead of 1586 // computation. 1587 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1588 DenseMap<const AllocaInst*, int>::iterator SI = 1589 FuncInfo.StaticAllocaMap.find(AI); 1590 if (SI != FuncInfo.StaticAllocaMap.end()) 1591 return DAG.getFrameIndex(SI->second, 1592 TLI.getFrameIndexTy(DAG.getDataLayout())); 1593 } 1594 1595 // If this is an instruction which fast-isel has deferred, select it now. 1596 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1597 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1598 1599 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1600 Inst->getType(), getABIRegCopyCC(V)); 1601 SDValue Chain = DAG.getEntryNode(); 1602 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1603 } 1604 1605 llvm_unreachable("Can't get register for value!"); 1606 } 1607 1608 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1609 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1610 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1611 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1612 bool IsSEH = isAsynchronousEHPersonality(Pers); 1613 bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX; 1614 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1615 if (!IsSEH) 1616 CatchPadMBB->setIsEHScopeEntry(); 1617 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1618 if (IsMSVCCXX || IsCoreCLR) 1619 CatchPadMBB->setIsEHFuncletEntry(); 1620 // Wasm does not need catchpads anymore 1621 if (!IsWasmCXX) 1622 DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other, 1623 getControlRoot())); 1624 } 1625 1626 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1627 // Update machine-CFG edge. 1628 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1629 FuncInfo.MBB->addSuccessor(TargetMBB); 1630 1631 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1632 bool IsSEH = isAsynchronousEHPersonality(Pers); 1633 if (IsSEH) { 1634 // If this is not a fall-through branch or optimizations are switched off, 1635 // emit the branch. 1636 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1637 TM.getOptLevel() == CodeGenOpt::None) 1638 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1639 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1640 return; 1641 } 1642 1643 // Figure out the funclet membership for the catchret's successor. 1644 // This will be used by the FuncletLayout pass to determine how to order the 1645 // BB's. 1646 // A 'catchret' returns to the outer scope's color. 1647 Value *ParentPad = I.getCatchSwitchParentPad(); 1648 const BasicBlock *SuccessorColor; 1649 if (isa<ConstantTokenNone>(ParentPad)) 1650 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1651 else 1652 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1653 assert(SuccessorColor && "No parent funclet for catchret!"); 1654 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1655 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1656 1657 // Create the terminator node. 1658 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1659 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1660 DAG.getBasicBlock(SuccessorColorMBB)); 1661 DAG.setRoot(Ret); 1662 } 1663 1664 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1665 // Don't emit any special code for the cleanuppad instruction. It just marks 1666 // the start of an EH scope/funclet. 1667 FuncInfo.MBB->setIsEHScopeEntry(); 1668 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1669 if (Pers != EHPersonality::Wasm_CXX) { 1670 FuncInfo.MBB->setIsEHFuncletEntry(); 1671 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1672 } 1673 } 1674 1675 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and 1676 // the control flow always stops at the single catch pad, as it does for a 1677 // cleanup pad. In case the exception caught is not of the types the catch pad 1678 // catches, it will be rethrown by a rethrow. 1679 static void findWasmUnwindDestinations( 1680 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1681 BranchProbability Prob, 1682 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1683 &UnwindDests) { 1684 while (EHPadBB) { 1685 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1686 if (isa<CleanupPadInst>(Pad)) { 1687 // Stop on cleanup pads. 1688 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1689 UnwindDests.back().first->setIsEHScopeEntry(); 1690 break; 1691 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1692 // Add the catchpad handlers to the possible destinations. We don't 1693 // continue to the unwind destination of the catchswitch for wasm. 1694 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1695 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1696 UnwindDests.back().first->setIsEHScopeEntry(); 1697 } 1698 break; 1699 } else { 1700 continue; 1701 } 1702 } 1703 } 1704 1705 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1706 /// many places it could ultimately go. In the IR, we have a single unwind 1707 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1708 /// This function skips over imaginary basic blocks that hold catchswitch 1709 /// instructions, and finds all the "real" machine 1710 /// basic block destinations. As those destinations may not be successors of 1711 /// EHPadBB, here we also calculate the edge probability to those destinations. 1712 /// The passed-in Prob is the edge probability to EHPadBB. 1713 static void findUnwindDestinations( 1714 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1715 BranchProbability Prob, 1716 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1717 &UnwindDests) { 1718 EHPersonality Personality = 1719 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1720 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1721 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1722 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1723 bool IsSEH = isAsynchronousEHPersonality(Personality); 1724 1725 if (IsWasmCXX) { 1726 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1727 assert(UnwindDests.size() <= 1 && 1728 "There should be at most one unwind destination for wasm"); 1729 return; 1730 } 1731 1732 while (EHPadBB) { 1733 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1734 BasicBlock *NewEHPadBB = nullptr; 1735 if (isa<LandingPadInst>(Pad)) { 1736 // Stop on landingpads. They are not funclets. 1737 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1738 break; 1739 } else if (isa<CleanupPadInst>(Pad)) { 1740 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1741 // personalities. 1742 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1743 UnwindDests.back().first->setIsEHScopeEntry(); 1744 UnwindDests.back().first->setIsEHFuncletEntry(); 1745 break; 1746 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1747 // Add the catchpad handlers to the possible destinations. 1748 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1749 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1750 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1751 if (IsMSVCCXX || IsCoreCLR) 1752 UnwindDests.back().first->setIsEHFuncletEntry(); 1753 if (!IsSEH) 1754 UnwindDests.back().first->setIsEHScopeEntry(); 1755 } 1756 NewEHPadBB = CatchSwitch->getUnwindDest(); 1757 } else { 1758 continue; 1759 } 1760 1761 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1762 if (BPI && NewEHPadBB) 1763 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1764 EHPadBB = NewEHPadBB; 1765 } 1766 } 1767 1768 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1769 // Update successor info. 1770 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1771 auto UnwindDest = I.getUnwindDest(); 1772 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1773 BranchProbability UnwindDestProb = 1774 (BPI && UnwindDest) 1775 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1776 : BranchProbability::getZero(); 1777 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1778 for (auto &UnwindDest : UnwindDests) { 1779 UnwindDest.first->setIsEHPad(); 1780 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1781 } 1782 FuncInfo.MBB->normalizeSuccProbs(); 1783 1784 // Create the terminator node. 1785 SDValue Ret = 1786 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1787 DAG.setRoot(Ret); 1788 } 1789 1790 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1791 report_fatal_error("visitCatchSwitch not yet implemented!"); 1792 } 1793 1794 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1795 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1796 auto &DL = DAG.getDataLayout(); 1797 SDValue Chain = getControlRoot(); 1798 SmallVector<ISD::OutputArg, 8> Outs; 1799 SmallVector<SDValue, 8> OutVals; 1800 1801 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1802 // lower 1803 // 1804 // %val = call <ty> @llvm.experimental.deoptimize() 1805 // ret <ty> %val 1806 // 1807 // differently. 1808 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1809 LowerDeoptimizingReturn(); 1810 return; 1811 } 1812 1813 if (!FuncInfo.CanLowerReturn) { 1814 unsigned DemoteReg = FuncInfo.DemoteRegister; 1815 const Function *F = I.getParent()->getParent(); 1816 1817 // Emit a store of the return value through the virtual register. 1818 // Leave Outs empty so that LowerReturn won't try to load return 1819 // registers the usual way. 1820 SmallVector<EVT, 1> PtrValueVTs; 1821 ComputeValueVTs(TLI, DL, 1822 F->getReturnType()->getPointerTo( 1823 DAG.getDataLayout().getAllocaAddrSpace()), 1824 PtrValueVTs); 1825 1826 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1827 DemoteReg, PtrValueVTs[0]); 1828 SDValue RetOp = getValue(I.getOperand(0)); 1829 1830 SmallVector<EVT, 4> ValueVTs, MemVTs; 1831 SmallVector<uint64_t, 4> Offsets; 1832 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1833 &Offsets); 1834 unsigned NumValues = ValueVTs.size(); 1835 1836 SmallVector<SDValue, 4> Chains(NumValues); 1837 for (unsigned i = 0; i != NumValues; ++i) { 1838 // An aggregate return value cannot wrap around the address space, so 1839 // offsets to its parts don't wrap either. 1840 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]); 1841 1842 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 1843 if (MemVTs[i] != ValueVTs[i]) 1844 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 1845 Chains[i] = DAG.getStore(Chain, getCurSDLoc(), Val, 1846 // FIXME: better loc info would be nice. 1847 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction())); 1848 } 1849 1850 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1851 MVT::Other, Chains); 1852 } else if (I.getNumOperands() != 0) { 1853 SmallVector<EVT, 4> ValueVTs; 1854 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1855 unsigned NumValues = ValueVTs.size(); 1856 if (NumValues) { 1857 SDValue RetOp = getValue(I.getOperand(0)); 1858 1859 const Function *F = I.getParent()->getParent(); 1860 1861 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 1862 I.getOperand(0)->getType(), F->getCallingConv(), 1863 /*IsVarArg*/ false); 1864 1865 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1866 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1867 Attribute::SExt)) 1868 ExtendKind = ISD::SIGN_EXTEND; 1869 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1870 Attribute::ZExt)) 1871 ExtendKind = ISD::ZERO_EXTEND; 1872 1873 LLVMContext &Context = F->getContext(); 1874 bool RetInReg = F->getAttributes().hasAttribute( 1875 AttributeList::ReturnIndex, Attribute::InReg); 1876 1877 for (unsigned j = 0; j != NumValues; ++j) { 1878 EVT VT = ValueVTs[j]; 1879 1880 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1881 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1882 1883 CallingConv::ID CC = F->getCallingConv(); 1884 1885 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1886 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1887 SmallVector<SDValue, 4> Parts(NumParts); 1888 getCopyToParts(DAG, getCurSDLoc(), 1889 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1890 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1891 1892 // 'inreg' on function refers to return value 1893 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1894 if (RetInReg) 1895 Flags.setInReg(); 1896 1897 if (I.getOperand(0)->getType()->isPointerTy()) { 1898 Flags.setPointer(); 1899 Flags.setPointerAddrSpace( 1900 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 1901 } 1902 1903 if (NeedsRegBlock) { 1904 Flags.setInConsecutiveRegs(); 1905 if (j == NumValues - 1) 1906 Flags.setInConsecutiveRegsLast(); 1907 } 1908 1909 // Propagate extension type if any 1910 if (ExtendKind == ISD::SIGN_EXTEND) 1911 Flags.setSExt(); 1912 else if (ExtendKind == ISD::ZERO_EXTEND) 1913 Flags.setZExt(); 1914 1915 for (unsigned i = 0; i < NumParts; ++i) { 1916 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1917 VT, /*isfixed=*/true, 0, 0)); 1918 OutVals.push_back(Parts[i]); 1919 } 1920 } 1921 } 1922 } 1923 1924 // Push in swifterror virtual register as the last element of Outs. This makes 1925 // sure swifterror virtual register will be returned in the swifterror 1926 // physical register. 1927 const Function *F = I.getParent()->getParent(); 1928 if (TLI.supportSwiftError() && 1929 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 1930 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 1931 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1932 Flags.setSwiftError(); 1933 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 1934 EVT(TLI.getPointerTy(DL)) /*argvt*/, 1935 true /*isfixed*/, 1 /*origidx*/, 1936 0 /*partOffs*/)); 1937 // Create SDNode for the swifterror virtual register. 1938 OutVals.push_back( 1939 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 1940 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 1941 EVT(TLI.getPointerTy(DL)))); 1942 } 1943 1944 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 1945 CallingConv::ID CallConv = 1946 DAG.getMachineFunction().getFunction().getCallingConv(); 1947 Chain = DAG.getTargetLoweringInfo().LowerReturn( 1948 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 1949 1950 // Verify that the target's LowerReturn behaved as expected. 1951 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 1952 "LowerReturn didn't return a valid chain!"); 1953 1954 // Update the DAG with the new chain value resulting from return lowering. 1955 DAG.setRoot(Chain); 1956 } 1957 1958 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 1959 /// created for it, emit nodes to copy the value into the virtual 1960 /// registers. 1961 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 1962 // Skip empty types 1963 if (V->getType()->isEmptyTy()) 1964 return; 1965 1966 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 1967 if (VMI != FuncInfo.ValueMap.end()) { 1968 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 1969 CopyValueToVirtualRegister(V, VMI->second); 1970 } 1971 } 1972 1973 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 1974 /// the current basic block, add it to ValueMap now so that we'll get a 1975 /// CopyTo/FromReg. 1976 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 1977 // No need to export constants. 1978 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 1979 1980 // Already exported? 1981 if (FuncInfo.isExportedInst(V)) return; 1982 1983 unsigned Reg = FuncInfo.InitializeRegForValue(V); 1984 CopyValueToVirtualRegister(V, Reg); 1985 } 1986 1987 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 1988 const BasicBlock *FromBB) { 1989 // The operands of the setcc have to be in this block. We don't know 1990 // how to export them from some other block. 1991 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 1992 // Can export from current BB. 1993 if (VI->getParent() == FromBB) 1994 return true; 1995 1996 // Is already exported, noop. 1997 return FuncInfo.isExportedInst(V); 1998 } 1999 2000 // If this is an argument, we can export it if the BB is the entry block or 2001 // if it is already exported. 2002 if (isa<Argument>(V)) { 2003 if (FromBB == &FromBB->getParent()->getEntryBlock()) 2004 return true; 2005 2006 // Otherwise, can only export this if it is already exported. 2007 return FuncInfo.isExportedInst(V); 2008 } 2009 2010 // Otherwise, constants can always be exported. 2011 return true; 2012 } 2013 2014 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2015 BranchProbability 2016 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2017 const MachineBasicBlock *Dst) const { 2018 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2019 const BasicBlock *SrcBB = Src->getBasicBlock(); 2020 const BasicBlock *DstBB = Dst->getBasicBlock(); 2021 if (!BPI) { 2022 // If BPI is not available, set the default probability as 1 / N, where N is 2023 // the number of successors. 2024 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2025 return BranchProbability(1, SuccSize); 2026 } 2027 return BPI->getEdgeProbability(SrcBB, DstBB); 2028 } 2029 2030 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2031 MachineBasicBlock *Dst, 2032 BranchProbability Prob) { 2033 if (!FuncInfo.BPI) 2034 Src->addSuccessorWithoutProb(Dst); 2035 else { 2036 if (Prob.isUnknown()) 2037 Prob = getEdgeProbability(Src, Dst); 2038 Src->addSuccessor(Dst, Prob); 2039 } 2040 } 2041 2042 static bool InBlock(const Value *V, const BasicBlock *BB) { 2043 if (const Instruction *I = dyn_cast<Instruction>(V)) 2044 return I->getParent() == BB; 2045 return true; 2046 } 2047 2048 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2049 /// This function emits a branch and is used at the leaves of an OR or an 2050 /// AND operator tree. 2051 void 2052 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2053 MachineBasicBlock *TBB, 2054 MachineBasicBlock *FBB, 2055 MachineBasicBlock *CurBB, 2056 MachineBasicBlock *SwitchBB, 2057 BranchProbability TProb, 2058 BranchProbability FProb, 2059 bool InvertCond) { 2060 const BasicBlock *BB = CurBB->getBasicBlock(); 2061 2062 // If the leaf of the tree is a comparison, merge the condition into 2063 // the caseblock. 2064 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2065 // The operands of the cmp have to be in this block. We don't know 2066 // how to export them from some other block. If this is the first block 2067 // of the sequence, no exporting is needed. 2068 if (CurBB == SwitchBB || 2069 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2070 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2071 ISD::CondCode Condition; 2072 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2073 ICmpInst::Predicate Pred = 2074 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2075 Condition = getICmpCondCode(Pred); 2076 } else { 2077 const FCmpInst *FC = cast<FCmpInst>(Cond); 2078 FCmpInst::Predicate Pred = 2079 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2080 Condition = getFCmpCondCode(Pred); 2081 if (TM.Options.NoNaNsFPMath) 2082 Condition = getFCmpCodeWithoutNaN(Condition); 2083 } 2084 2085 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2086 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2087 SL->SwitchCases.push_back(CB); 2088 return; 2089 } 2090 } 2091 2092 // Create a CaseBlock record representing this branch. 2093 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2094 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2095 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2096 SL->SwitchCases.push_back(CB); 2097 } 2098 2099 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2100 MachineBasicBlock *TBB, 2101 MachineBasicBlock *FBB, 2102 MachineBasicBlock *CurBB, 2103 MachineBasicBlock *SwitchBB, 2104 Instruction::BinaryOps Opc, 2105 BranchProbability TProb, 2106 BranchProbability FProb, 2107 bool InvertCond) { 2108 // Skip over not part of the tree and remember to invert op and operands at 2109 // next level. 2110 Value *NotCond; 2111 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2112 InBlock(NotCond, CurBB->getBasicBlock())) { 2113 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2114 !InvertCond); 2115 return; 2116 } 2117 2118 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2119 // Compute the effective opcode for Cond, taking into account whether it needs 2120 // to be inverted, e.g. 2121 // and (not (or A, B)), C 2122 // gets lowered as 2123 // and (and (not A, not B), C) 2124 unsigned BOpc = 0; 2125 if (BOp) { 2126 BOpc = BOp->getOpcode(); 2127 if (InvertCond) { 2128 if (BOpc == Instruction::And) 2129 BOpc = Instruction::Or; 2130 else if (BOpc == Instruction::Or) 2131 BOpc = Instruction::And; 2132 } 2133 } 2134 2135 // If this node is not part of the or/and tree, emit it as a branch. 2136 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 2137 BOpc != unsigned(Opc) || !BOp->hasOneUse() || 2138 BOp->getParent() != CurBB->getBasicBlock() || 2139 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 2140 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 2141 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2142 TProb, FProb, InvertCond); 2143 return; 2144 } 2145 2146 // Create TmpBB after CurBB. 2147 MachineFunction::iterator BBI(CurBB); 2148 MachineFunction &MF = DAG.getMachineFunction(); 2149 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2150 CurBB->getParent()->insert(++BBI, TmpBB); 2151 2152 if (Opc == Instruction::Or) { 2153 // Codegen X | Y as: 2154 // BB1: 2155 // jmp_if_X TBB 2156 // jmp TmpBB 2157 // TmpBB: 2158 // jmp_if_Y TBB 2159 // jmp FBB 2160 // 2161 2162 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2163 // The requirement is that 2164 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2165 // = TrueProb for original BB. 2166 // Assuming the original probabilities are A and B, one choice is to set 2167 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2168 // A/(1+B) and 2B/(1+B). This choice assumes that 2169 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2170 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2171 // TmpBB, but the math is more complicated. 2172 2173 auto NewTrueProb = TProb / 2; 2174 auto NewFalseProb = TProb / 2 + FProb; 2175 // Emit the LHS condition. 2176 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc, 2177 NewTrueProb, NewFalseProb, InvertCond); 2178 2179 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2180 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2181 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2182 // Emit the RHS condition into TmpBB. 2183 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2184 Probs[0], Probs[1], InvertCond); 2185 } else { 2186 assert(Opc == Instruction::And && "Unknown merge op!"); 2187 // Codegen X & Y as: 2188 // BB1: 2189 // jmp_if_X TmpBB 2190 // jmp FBB 2191 // TmpBB: 2192 // jmp_if_Y TBB 2193 // jmp FBB 2194 // 2195 // This requires creation of TmpBB after CurBB. 2196 2197 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2198 // The requirement is that 2199 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2200 // = FalseProb for original BB. 2201 // Assuming the original probabilities are A and B, one choice is to set 2202 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2203 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2204 // TrueProb for BB1 * FalseProb for TmpBB. 2205 2206 auto NewTrueProb = TProb + FProb / 2; 2207 auto NewFalseProb = FProb / 2; 2208 // Emit the LHS condition. 2209 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc, 2210 NewTrueProb, NewFalseProb, InvertCond); 2211 2212 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2213 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2214 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2215 // Emit the RHS condition into TmpBB. 2216 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2217 Probs[0], Probs[1], InvertCond); 2218 } 2219 } 2220 2221 /// If the set of cases should be emitted as a series of branches, return true. 2222 /// If we should emit this as a bunch of and/or'd together conditions, return 2223 /// false. 2224 bool 2225 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2226 if (Cases.size() != 2) return true; 2227 2228 // If this is two comparisons of the same values or'd or and'd together, they 2229 // will get folded into a single comparison, so don't emit two blocks. 2230 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2231 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2232 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2233 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2234 return false; 2235 } 2236 2237 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2238 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2239 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2240 Cases[0].CC == Cases[1].CC && 2241 isa<Constant>(Cases[0].CmpRHS) && 2242 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2243 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2244 return false; 2245 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2246 return false; 2247 } 2248 2249 return true; 2250 } 2251 2252 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2253 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2254 2255 // Update machine-CFG edges. 2256 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2257 2258 if (I.isUnconditional()) { 2259 // Update machine-CFG edges. 2260 BrMBB->addSuccessor(Succ0MBB); 2261 2262 // If this is not a fall-through branch or optimizations are switched off, 2263 // emit the branch. 2264 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2265 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2266 MVT::Other, getControlRoot(), 2267 DAG.getBasicBlock(Succ0MBB))); 2268 2269 return; 2270 } 2271 2272 // If this condition is one of the special cases we handle, do special stuff 2273 // now. 2274 const Value *CondVal = I.getCondition(); 2275 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2276 2277 // If this is a series of conditions that are or'd or and'd together, emit 2278 // this as a sequence of branches instead of setcc's with and/or operations. 2279 // As long as jumps are not expensive, this should improve performance. 2280 // For example, instead of something like: 2281 // cmp A, B 2282 // C = seteq 2283 // cmp D, E 2284 // F = setle 2285 // or C, F 2286 // jnz foo 2287 // Emit: 2288 // cmp A, B 2289 // je foo 2290 // cmp D, E 2291 // jle foo 2292 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 2293 Instruction::BinaryOps Opcode = BOp->getOpcode(); 2294 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() && 2295 !I.hasMetadata(LLVMContext::MD_unpredictable) && 2296 (Opcode == Instruction::And || Opcode == Instruction::Or)) { 2297 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, 2298 Opcode, 2299 getEdgeProbability(BrMBB, Succ0MBB), 2300 getEdgeProbability(BrMBB, Succ1MBB), 2301 /*InvertCond=*/false); 2302 // If the compares in later blocks need to use values not currently 2303 // exported from this block, export them now. This block should always 2304 // be the first entry. 2305 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2306 2307 // Allow some cases to be rejected. 2308 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2309 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2310 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2311 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2312 } 2313 2314 // Emit the branch for this block. 2315 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2316 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2317 return; 2318 } 2319 2320 // Okay, we decided not to do this, remove any inserted MBB's and clear 2321 // SwitchCases. 2322 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2323 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2324 2325 SL->SwitchCases.clear(); 2326 } 2327 } 2328 2329 // Create a CaseBlock record representing this branch. 2330 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2331 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2332 2333 // Use visitSwitchCase to actually insert the fast branch sequence for this 2334 // cond branch. 2335 visitSwitchCase(CB, BrMBB); 2336 } 2337 2338 /// visitSwitchCase - Emits the necessary code to represent a single node in 2339 /// the binary search tree resulting from lowering a switch instruction. 2340 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2341 MachineBasicBlock *SwitchBB) { 2342 SDValue Cond; 2343 SDValue CondLHS = getValue(CB.CmpLHS); 2344 SDLoc dl = CB.DL; 2345 2346 if (CB.CC == ISD::SETTRUE) { 2347 // Branch or fall through to TrueBB. 2348 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2349 SwitchBB->normalizeSuccProbs(); 2350 if (CB.TrueBB != NextBlock(SwitchBB)) { 2351 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2352 DAG.getBasicBlock(CB.TrueBB))); 2353 } 2354 return; 2355 } 2356 2357 auto &TLI = DAG.getTargetLoweringInfo(); 2358 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2359 2360 // Build the setcc now. 2361 if (!CB.CmpMHS) { 2362 // Fold "(X == true)" to X and "(X == false)" to !X to 2363 // handle common cases produced by branch lowering. 2364 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2365 CB.CC == ISD::SETEQ) 2366 Cond = CondLHS; 2367 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2368 CB.CC == ISD::SETEQ) { 2369 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2370 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2371 } else { 2372 SDValue CondRHS = getValue(CB.CmpRHS); 2373 2374 // If a pointer's DAG type is larger than its memory type then the DAG 2375 // values are zero-extended. This breaks signed comparisons so truncate 2376 // back to the underlying type before doing the compare. 2377 if (CondLHS.getValueType() != MemVT) { 2378 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2379 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2380 } 2381 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2382 } 2383 } else { 2384 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2385 2386 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2387 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2388 2389 SDValue CmpOp = getValue(CB.CmpMHS); 2390 EVT VT = CmpOp.getValueType(); 2391 2392 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2393 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2394 ISD::SETLE); 2395 } else { 2396 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2397 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2398 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2399 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2400 } 2401 } 2402 2403 // Update successor info 2404 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2405 // TrueBB and FalseBB are always different unless the incoming IR is 2406 // degenerate. This only happens when running llc on weird IR. 2407 if (CB.TrueBB != CB.FalseBB) 2408 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2409 SwitchBB->normalizeSuccProbs(); 2410 2411 // If the lhs block is the next block, invert the condition so that we can 2412 // fall through to the lhs instead of the rhs block. 2413 if (CB.TrueBB == NextBlock(SwitchBB)) { 2414 std::swap(CB.TrueBB, CB.FalseBB); 2415 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2416 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2417 } 2418 2419 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2420 MVT::Other, getControlRoot(), Cond, 2421 DAG.getBasicBlock(CB.TrueBB)); 2422 2423 // Insert the false branch. Do this even if it's a fall through branch, 2424 // this makes it easier to do DAG optimizations which require inverting 2425 // the branch condition. 2426 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2427 DAG.getBasicBlock(CB.FalseBB)); 2428 2429 DAG.setRoot(BrCond); 2430 } 2431 2432 /// visitJumpTable - Emit JumpTable node in the current MBB 2433 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2434 // Emit the code for the jump table 2435 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2436 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2437 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2438 JT.Reg, PTy); 2439 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2440 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2441 MVT::Other, Index.getValue(1), 2442 Table, Index); 2443 DAG.setRoot(BrJumpTable); 2444 } 2445 2446 /// visitJumpTableHeader - This function emits necessary code to produce index 2447 /// in the JumpTable from switch case. 2448 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2449 JumpTableHeader &JTH, 2450 MachineBasicBlock *SwitchBB) { 2451 SDLoc dl = getCurSDLoc(); 2452 2453 // Subtract the lowest switch case value from the value being switched on. 2454 SDValue SwitchOp = getValue(JTH.SValue); 2455 EVT VT = SwitchOp.getValueType(); 2456 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2457 DAG.getConstant(JTH.First, dl, VT)); 2458 2459 // The SDNode we just created, which holds the value being switched on minus 2460 // the smallest case value, needs to be copied to a virtual register so it 2461 // can be used as an index into the jump table in a subsequent basic block. 2462 // This value may be smaller or larger than the target's pointer type, and 2463 // therefore require extension or truncating. 2464 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2465 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2466 2467 unsigned JumpTableReg = 2468 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2469 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2470 JumpTableReg, SwitchOp); 2471 JT.Reg = JumpTableReg; 2472 2473 if (!JTH.OmitRangeCheck) { 2474 // Emit the range check for the jump table, and branch to the default block 2475 // for the switch statement if the value being switched on exceeds the 2476 // largest case in the switch. 2477 SDValue CMP = DAG.getSetCC( 2478 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2479 Sub.getValueType()), 2480 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2481 2482 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2483 MVT::Other, CopyTo, CMP, 2484 DAG.getBasicBlock(JT.Default)); 2485 2486 // Avoid emitting unnecessary branches to the next block. 2487 if (JT.MBB != NextBlock(SwitchBB)) 2488 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2489 DAG.getBasicBlock(JT.MBB)); 2490 2491 DAG.setRoot(BrCond); 2492 } else { 2493 // Avoid emitting unnecessary branches to the next block. 2494 if (JT.MBB != NextBlock(SwitchBB)) 2495 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2496 DAG.getBasicBlock(JT.MBB))); 2497 else 2498 DAG.setRoot(CopyTo); 2499 } 2500 } 2501 2502 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2503 /// variable if there exists one. 2504 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2505 SDValue &Chain) { 2506 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2507 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2508 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2509 MachineFunction &MF = DAG.getMachineFunction(); 2510 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2511 MachineSDNode *Node = 2512 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2513 if (Global) { 2514 MachinePointerInfo MPInfo(Global); 2515 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2516 MachineMemOperand::MODereferenceable; 2517 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2518 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy)); 2519 DAG.setNodeMemRefs(Node, {MemRef}); 2520 } 2521 if (PtrTy != PtrMemTy) 2522 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2523 return SDValue(Node, 0); 2524 } 2525 2526 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2527 /// tail spliced into a stack protector check success bb. 2528 /// 2529 /// For a high level explanation of how this fits into the stack protector 2530 /// generation see the comment on the declaration of class 2531 /// StackProtectorDescriptor. 2532 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2533 MachineBasicBlock *ParentBB) { 2534 2535 // First create the loads to the guard/stack slot for the comparison. 2536 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2537 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2538 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2539 2540 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2541 int FI = MFI.getStackProtectorIndex(); 2542 2543 SDValue Guard; 2544 SDLoc dl = getCurSDLoc(); 2545 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2546 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2547 unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext())); 2548 2549 // Generate code to load the content of the guard slot. 2550 SDValue GuardVal = DAG.getLoad( 2551 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2552 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2553 MachineMemOperand::MOVolatile); 2554 2555 if (TLI.useStackGuardXorFP()) 2556 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2557 2558 // Retrieve guard check function, nullptr if instrumentation is inlined. 2559 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2560 // The target provides a guard check function to validate the guard value. 2561 // Generate a call to that function with the content of the guard slot as 2562 // argument. 2563 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2564 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2565 2566 TargetLowering::ArgListTy Args; 2567 TargetLowering::ArgListEntry Entry; 2568 Entry.Node = GuardVal; 2569 Entry.Ty = FnTy->getParamType(0); 2570 if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg)) 2571 Entry.IsInReg = true; 2572 Args.push_back(Entry); 2573 2574 TargetLowering::CallLoweringInfo CLI(DAG); 2575 CLI.setDebugLoc(getCurSDLoc()) 2576 .setChain(DAG.getEntryNode()) 2577 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2578 getValue(GuardCheckFn), std::move(Args)); 2579 2580 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2581 DAG.setRoot(Result.second); 2582 return; 2583 } 2584 2585 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2586 // Otherwise, emit a volatile load to retrieve the stack guard value. 2587 SDValue Chain = DAG.getEntryNode(); 2588 if (TLI.useLoadStackGuardNode()) { 2589 Guard = getLoadStackGuard(DAG, dl, Chain); 2590 } else { 2591 const Value *IRGuard = TLI.getSDagStackGuard(M); 2592 SDValue GuardPtr = getValue(IRGuard); 2593 2594 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2595 MachinePointerInfo(IRGuard, 0), Align, 2596 MachineMemOperand::MOVolatile); 2597 } 2598 2599 // Perform the comparison via a subtract/getsetcc. 2600 EVT VT = Guard.getValueType(); 2601 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal); 2602 2603 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2604 *DAG.getContext(), 2605 Sub.getValueType()), 2606 Sub, DAG.getConstant(0, dl, VT), ISD::SETNE); 2607 2608 // If the sub is not 0, then we know the guard/stackslot do not equal, so 2609 // branch to failure MBB. 2610 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2611 MVT::Other, GuardVal.getOperand(0), 2612 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2613 // Otherwise branch to success MBB. 2614 SDValue Br = DAG.getNode(ISD::BR, dl, 2615 MVT::Other, BrCond, 2616 DAG.getBasicBlock(SPD.getSuccessMBB())); 2617 2618 DAG.setRoot(Br); 2619 } 2620 2621 /// Codegen the failure basic block for a stack protector check. 2622 /// 2623 /// A failure stack protector machine basic block consists simply of a call to 2624 /// __stack_chk_fail(). 2625 /// 2626 /// For a high level explanation of how this fits into the stack protector 2627 /// generation see the comment on the declaration of class 2628 /// StackProtectorDescriptor. 2629 void 2630 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2631 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2632 TargetLowering::MakeLibCallOptions CallOptions; 2633 CallOptions.setDiscardResult(true); 2634 SDValue Chain = 2635 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2636 None, CallOptions, getCurSDLoc()).second; 2637 // On PS4, the "return address" must still be within the calling function, 2638 // even if it's at the very end, so emit an explicit TRAP here. 2639 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2640 if (TM.getTargetTriple().isPS4CPU()) 2641 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2642 2643 DAG.setRoot(Chain); 2644 } 2645 2646 /// visitBitTestHeader - This function emits necessary code to produce value 2647 /// suitable for "bit tests" 2648 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2649 MachineBasicBlock *SwitchBB) { 2650 SDLoc dl = getCurSDLoc(); 2651 2652 // Subtract the minimum value. 2653 SDValue SwitchOp = getValue(B.SValue); 2654 EVT VT = SwitchOp.getValueType(); 2655 SDValue RangeSub = 2656 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2657 2658 // Determine the type of the test operands. 2659 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2660 bool UsePtrType = false; 2661 if (!TLI.isTypeLegal(VT)) { 2662 UsePtrType = true; 2663 } else { 2664 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2665 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2666 // Switch table case range are encoded into series of masks. 2667 // Just use pointer type, it's guaranteed to fit. 2668 UsePtrType = true; 2669 break; 2670 } 2671 } 2672 SDValue Sub = RangeSub; 2673 if (UsePtrType) { 2674 VT = TLI.getPointerTy(DAG.getDataLayout()); 2675 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2676 } 2677 2678 B.RegVT = VT.getSimpleVT(); 2679 B.Reg = FuncInfo.CreateReg(B.RegVT); 2680 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2681 2682 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2683 2684 if (!B.OmitRangeCheck) 2685 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2686 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2687 SwitchBB->normalizeSuccProbs(); 2688 2689 SDValue Root = CopyTo; 2690 if (!B.OmitRangeCheck) { 2691 // Conditional branch to the default block. 2692 SDValue RangeCmp = DAG.getSetCC(dl, 2693 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2694 RangeSub.getValueType()), 2695 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2696 ISD::SETUGT); 2697 2698 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2699 DAG.getBasicBlock(B.Default)); 2700 } 2701 2702 // Avoid emitting unnecessary branches to the next block. 2703 if (MBB != NextBlock(SwitchBB)) 2704 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2705 2706 DAG.setRoot(Root); 2707 } 2708 2709 /// visitBitTestCase - this function produces one "bit test" 2710 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2711 MachineBasicBlock* NextMBB, 2712 BranchProbability BranchProbToNext, 2713 unsigned Reg, 2714 BitTestCase &B, 2715 MachineBasicBlock *SwitchBB) { 2716 SDLoc dl = getCurSDLoc(); 2717 MVT VT = BB.RegVT; 2718 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2719 SDValue Cmp; 2720 unsigned PopCount = countPopulation(B.Mask); 2721 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2722 if (PopCount == 1) { 2723 // Testing for a single bit; just compare the shift count with what it 2724 // would need to be to shift a 1 bit in that position. 2725 Cmp = DAG.getSetCC( 2726 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2727 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2728 ISD::SETEQ); 2729 } else if (PopCount == BB.Range) { 2730 // There is only one zero bit in the range, test for it directly. 2731 Cmp = DAG.getSetCC( 2732 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2733 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2734 ISD::SETNE); 2735 } else { 2736 // Make desired shift 2737 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2738 DAG.getConstant(1, dl, VT), ShiftOp); 2739 2740 // Emit bit tests and jumps 2741 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2742 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2743 Cmp = DAG.getSetCC( 2744 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2745 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2746 } 2747 2748 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2749 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2750 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2751 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2752 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2753 // one as they are relative probabilities (and thus work more like weights), 2754 // and hence we need to normalize them to let the sum of them become one. 2755 SwitchBB->normalizeSuccProbs(); 2756 2757 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2758 MVT::Other, getControlRoot(), 2759 Cmp, DAG.getBasicBlock(B.TargetBB)); 2760 2761 // Avoid emitting unnecessary branches to the next block. 2762 if (NextMBB != NextBlock(SwitchBB)) 2763 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2764 DAG.getBasicBlock(NextMBB)); 2765 2766 DAG.setRoot(BrAnd); 2767 } 2768 2769 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2770 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2771 2772 // Retrieve successors. Look through artificial IR level blocks like 2773 // catchswitch for successors. 2774 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2775 const BasicBlock *EHPadBB = I.getSuccessor(1); 2776 2777 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2778 // have to do anything here to lower funclet bundles. 2779 assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt, 2780 LLVMContext::OB_funclet, 2781 LLVMContext::OB_cfguardtarget}) && 2782 "Cannot lower invokes with arbitrary operand bundles yet!"); 2783 2784 const Value *Callee(I.getCalledValue()); 2785 const Function *Fn = dyn_cast<Function>(Callee); 2786 if (isa<InlineAsm>(Callee)) 2787 visitInlineAsm(&I); 2788 else if (Fn && Fn->isIntrinsic()) { 2789 switch (Fn->getIntrinsicID()) { 2790 default: 2791 llvm_unreachable("Cannot invoke this intrinsic"); 2792 case Intrinsic::donothing: 2793 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2794 break; 2795 case Intrinsic::experimental_patchpoint_void: 2796 case Intrinsic::experimental_patchpoint_i64: 2797 visitPatchpoint(&I, EHPadBB); 2798 break; 2799 case Intrinsic::experimental_gc_statepoint: 2800 LowerStatepoint(ImmutableStatepoint(&I), EHPadBB); 2801 break; 2802 case Intrinsic::wasm_rethrow_in_catch: { 2803 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2804 // special because it can be invoked, so we manually lower it to a DAG 2805 // node here. 2806 SmallVector<SDValue, 8> Ops; 2807 Ops.push_back(getRoot()); // inchain 2808 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2809 Ops.push_back( 2810 DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(), 2811 TLI.getPointerTy(DAG.getDataLayout()))); 2812 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2813 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2814 break; 2815 } 2816 } 2817 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2818 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2819 // Eventually we will support lowering the @llvm.experimental.deoptimize 2820 // intrinsic, and right now there are no plans to support other intrinsics 2821 // with deopt state. 2822 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2823 } else { 2824 LowerCallTo(&I, getValue(Callee), false, EHPadBB); 2825 } 2826 2827 // If the value of the invoke is used outside of its defining block, make it 2828 // available as a virtual register. 2829 // We already took care of the exported value for the statepoint instruction 2830 // during call to the LowerStatepoint. 2831 if (!isStatepoint(I)) { 2832 CopyToExportRegsIfNeeded(&I); 2833 } 2834 2835 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2836 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2837 BranchProbability EHPadBBProb = 2838 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2839 : BranchProbability::getZero(); 2840 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2841 2842 // Update successor info. 2843 addSuccessorWithProb(InvokeMBB, Return); 2844 for (auto &UnwindDest : UnwindDests) { 2845 UnwindDest.first->setIsEHPad(); 2846 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2847 } 2848 InvokeMBB->normalizeSuccProbs(); 2849 2850 // Drop into normal successor. 2851 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 2852 DAG.getBasicBlock(Return))); 2853 } 2854 2855 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 2856 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 2857 2858 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2859 // have to do anything here to lower funclet bundles. 2860 assert(!I.hasOperandBundlesOtherThan( 2861 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2862 "Cannot lower callbrs with arbitrary operand bundles yet!"); 2863 2864 assert(isa<InlineAsm>(I.getCalledValue()) && 2865 "Only know how to handle inlineasm callbr"); 2866 visitInlineAsm(&I); 2867 2868 // Retrieve successors. 2869 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 2870 2871 // Update successor info. 2872 addSuccessorWithProb(CallBrMBB, Return); 2873 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 2874 MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)]; 2875 addSuccessorWithProb(CallBrMBB, Target); 2876 } 2877 CallBrMBB->normalizeSuccProbs(); 2878 2879 // Drop into default successor. 2880 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2881 MVT::Other, getControlRoot(), 2882 DAG.getBasicBlock(Return))); 2883 } 2884 2885 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2886 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2887 } 2888 2889 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2890 assert(FuncInfo.MBB->isEHPad() && 2891 "Call to landingpad not in landing pad!"); 2892 2893 // If there aren't registers to copy the values into (e.g., during SjLj 2894 // exceptions), then don't bother to create these DAG nodes. 2895 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2896 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2897 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2898 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2899 return; 2900 2901 // If landingpad's return type is token type, we don't create DAG nodes 2902 // for its exception pointer and selector value. The extraction of exception 2903 // pointer or selector value from token type landingpads is not currently 2904 // supported. 2905 if (LP.getType()->isTokenTy()) 2906 return; 2907 2908 SmallVector<EVT, 2> ValueVTs; 2909 SDLoc dl = getCurSDLoc(); 2910 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2911 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2912 2913 // Get the two live-in registers as SDValues. The physregs have already been 2914 // copied into virtual registers. 2915 SDValue Ops[2]; 2916 if (FuncInfo.ExceptionPointerVirtReg) { 2917 Ops[0] = DAG.getZExtOrTrunc( 2918 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2919 FuncInfo.ExceptionPointerVirtReg, 2920 TLI.getPointerTy(DAG.getDataLayout())), 2921 dl, ValueVTs[0]); 2922 } else { 2923 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2924 } 2925 Ops[1] = DAG.getZExtOrTrunc( 2926 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2927 FuncInfo.ExceptionSelectorVirtReg, 2928 TLI.getPointerTy(DAG.getDataLayout())), 2929 dl, ValueVTs[1]); 2930 2931 // Merge into one. 2932 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 2933 DAG.getVTList(ValueVTs), Ops); 2934 setValue(&LP, Res); 2935 } 2936 2937 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2938 MachineBasicBlock *Last) { 2939 // Update JTCases. 2940 for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i) 2941 if (SL->JTCases[i].first.HeaderBB == First) 2942 SL->JTCases[i].first.HeaderBB = Last; 2943 2944 // Update BitTestCases. 2945 for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i) 2946 if (SL->BitTestCases[i].Parent == First) 2947 SL->BitTestCases[i].Parent = Last; 2948 } 2949 2950 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2951 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2952 2953 // Update machine-CFG edges with unique successors. 2954 SmallSet<BasicBlock*, 32> Done; 2955 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 2956 BasicBlock *BB = I.getSuccessor(i); 2957 bool Inserted = Done.insert(BB).second; 2958 if (!Inserted) 2959 continue; 2960 2961 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 2962 addSuccessorWithProb(IndirectBrMBB, Succ); 2963 } 2964 IndirectBrMBB->normalizeSuccProbs(); 2965 2966 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 2967 MVT::Other, getControlRoot(), 2968 getValue(I.getAddress()))); 2969 } 2970 2971 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 2972 if (!DAG.getTarget().Options.TrapUnreachable) 2973 return; 2974 2975 // We may be able to ignore unreachable behind a noreturn call. 2976 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 2977 const BasicBlock &BB = *I.getParent(); 2978 if (&I != &BB.front()) { 2979 BasicBlock::const_iterator PredI = 2980 std::prev(BasicBlock::const_iterator(&I)); 2981 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 2982 if (Call->doesNotReturn()) 2983 return; 2984 } 2985 } 2986 } 2987 2988 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 2989 } 2990 2991 void SelectionDAGBuilder::visitFSub(const User &I) { 2992 // -0.0 - X --> fneg 2993 Type *Ty = I.getType(); 2994 if (isa<Constant>(I.getOperand(0)) && 2995 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) { 2996 SDValue Op2 = getValue(I.getOperand(1)); 2997 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(), 2998 Op2.getValueType(), Op2)); 2999 return; 3000 } 3001 3002 visitBinary(I, ISD::FSUB); 3003 } 3004 3005 /// Checks if the given instruction performs a vector reduction, in which case 3006 /// we have the freedom to alter the elements in the result as long as the 3007 /// reduction of them stays unchanged. 3008 static bool isVectorReductionOp(const User *I) { 3009 const Instruction *Inst = dyn_cast<Instruction>(I); 3010 if (!Inst || !Inst->getType()->isVectorTy()) 3011 return false; 3012 3013 auto OpCode = Inst->getOpcode(); 3014 switch (OpCode) { 3015 case Instruction::Add: 3016 case Instruction::Mul: 3017 case Instruction::And: 3018 case Instruction::Or: 3019 case Instruction::Xor: 3020 break; 3021 case Instruction::FAdd: 3022 case Instruction::FMul: 3023 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 3024 if (FPOp->getFastMathFlags().isFast()) 3025 break; 3026 LLVM_FALLTHROUGH; 3027 default: 3028 return false; 3029 } 3030 3031 unsigned ElemNum = Inst->getType()->getVectorNumElements(); 3032 // Ensure the reduction size is a power of 2. 3033 if (!isPowerOf2_32(ElemNum)) 3034 return false; 3035 3036 unsigned ElemNumToReduce = ElemNum; 3037 3038 // Do DFS search on the def-use chain from the given instruction. We only 3039 // allow four kinds of operations during the search until we reach the 3040 // instruction that extracts the first element from the vector: 3041 // 3042 // 1. The reduction operation of the same opcode as the given instruction. 3043 // 3044 // 2. PHI node. 3045 // 3046 // 3. ShuffleVector instruction together with a reduction operation that 3047 // does a partial reduction. 3048 // 3049 // 4. ExtractElement that extracts the first element from the vector, and we 3050 // stop searching the def-use chain here. 3051 // 3052 // 3 & 4 above perform a reduction on all elements of the vector. We push defs 3053 // from 1-3 to the stack to continue the DFS. The given instruction is not 3054 // a reduction operation if we meet any other instructions other than those 3055 // listed above. 3056 3057 SmallVector<const User *, 16> UsersToVisit{Inst}; 3058 SmallPtrSet<const User *, 16> Visited; 3059 bool ReduxExtracted = false; 3060 3061 while (!UsersToVisit.empty()) { 3062 auto User = UsersToVisit.back(); 3063 UsersToVisit.pop_back(); 3064 if (!Visited.insert(User).second) 3065 continue; 3066 3067 for (const auto *U : User->users()) { 3068 auto Inst = dyn_cast<Instruction>(U); 3069 if (!Inst) 3070 return false; 3071 3072 if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) { 3073 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 3074 if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast()) 3075 return false; 3076 UsersToVisit.push_back(U); 3077 } else if (const ShuffleVectorInst *ShufInst = 3078 dyn_cast<ShuffleVectorInst>(U)) { 3079 // Detect the following pattern: A ShuffleVector instruction together 3080 // with a reduction that do partial reduction on the first and second 3081 // ElemNumToReduce / 2 elements, and store the result in 3082 // ElemNumToReduce / 2 elements in another vector. 3083 3084 unsigned ResultElements = ShufInst->getType()->getVectorNumElements(); 3085 if (ResultElements < ElemNum) 3086 return false; 3087 3088 if (ElemNumToReduce == 1) 3089 return false; 3090 if (!isa<UndefValue>(U->getOperand(1))) 3091 return false; 3092 for (unsigned i = 0; i < ElemNumToReduce / 2; ++i) 3093 if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2)) 3094 return false; 3095 for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i) 3096 if (ShufInst->getMaskValue(i) != -1) 3097 return false; 3098 3099 // There is only one user of this ShuffleVector instruction, which 3100 // must be a reduction operation. 3101 if (!U->hasOneUse()) 3102 return false; 3103 3104 auto U2 = dyn_cast<Instruction>(*U->user_begin()); 3105 if (!U2 || U2->getOpcode() != OpCode) 3106 return false; 3107 3108 // Check operands of the reduction operation. 3109 if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) || 3110 (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) { 3111 UsersToVisit.push_back(U2); 3112 ElemNumToReduce /= 2; 3113 } else 3114 return false; 3115 } else if (isa<ExtractElementInst>(U)) { 3116 // At this moment we should have reduced all elements in the vector. 3117 if (ElemNumToReduce != 1) 3118 return false; 3119 3120 const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1)); 3121 if (!Val || !Val->isZero()) 3122 return false; 3123 3124 ReduxExtracted = true; 3125 } else 3126 return false; 3127 } 3128 } 3129 return ReduxExtracted; 3130 } 3131 3132 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3133 SDNodeFlags Flags; 3134 3135 SDValue Op = getValue(I.getOperand(0)); 3136 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3137 Op, Flags); 3138 setValue(&I, UnNodeValue); 3139 } 3140 3141 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3142 SDNodeFlags Flags; 3143 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3144 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3145 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3146 } 3147 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) { 3148 Flags.setExact(ExactOp->isExact()); 3149 } 3150 if (isVectorReductionOp(&I)) { 3151 Flags.setVectorReduction(true); 3152 LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n"); 3153 3154 // If no flags are set we will propagate the incoming flags, if any flags 3155 // are set, we will intersect them with the incoming flag and so we need to 3156 // copy the FMF flags here. 3157 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) { 3158 Flags.copyFMF(*FPOp); 3159 } 3160 } 3161 3162 SDValue Op1 = getValue(I.getOperand(0)); 3163 SDValue Op2 = getValue(I.getOperand(1)); 3164 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3165 Op1, Op2, Flags); 3166 setValue(&I, BinNodeValue); 3167 } 3168 3169 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3170 SDValue Op1 = getValue(I.getOperand(0)); 3171 SDValue Op2 = getValue(I.getOperand(1)); 3172 3173 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3174 Op1.getValueType(), DAG.getDataLayout()); 3175 3176 // Coerce the shift amount to the right type if we can. 3177 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3178 unsigned ShiftSize = ShiftTy.getSizeInBits(); 3179 unsigned Op2Size = Op2.getValueSizeInBits(); 3180 SDLoc DL = getCurSDLoc(); 3181 3182 // If the operand is smaller than the shift count type, promote it. 3183 if (ShiftSize > Op2Size) 3184 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 3185 3186 // If the operand is larger than the shift count type but the shift 3187 // count type has enough bits to represent any shift value, truncate 3188 // it now. This is a common case and it exposes the truncate to 3189 // optimization early. 3190 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 3191 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 3192 // Otherwise we'll need to temporarily settle for some other convenient 3193 // type. Type legalization will make adjustments once the shiftee is split. 3194 else 3195 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 3196 } 3197 3198 bool nuw = false; 3199 bool nsw = false; 3200 bool exact = false; 3201 3202 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3203 3204 if (const OverflowingBinaryOperator *OFBinOp = 3205 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3206 nuw = OFBinOp->hasNoUnsignedWrap(); 3207 nsw = OFBinOp->hasNoSignedWrap(); 3208 } 3209 if (const PossiblyExactOperator *ExactOp = 3210 dyn_cast<const PossiblyExactOperator>(&I)) 3211 exact = ExactOp->isExact(); 3212 } 3213 SDNodeFlags Flags; 3214 Flags.setExact(exact); 3215 Flags.setNoSignedWrap(nsw); 3216 Flags.setNoUnsignedWrap(nuw); 3217 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3218 Flags); 3219 setValue(&I, Res); 3220 } 3221 3222 void SelectionDAGBuilder::visitSDiv(const User &I) { 3223 SDValue Op1 = getValue(I.getOperand(0)); 3224 SDValue Op2 = getValue(I.getOperand(1)); 3225 3226 SDNodeFlags Flags; 3227 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3228 cast<PossiblyExactOperator>(&I)->isExact()); 3229 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3230 Op2, Flags)); 3231 } 3232 3233 void SelectionDAGBuilder::visitICmp(const User &I) { 3234 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3235 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3236 predicate = IC->getPredicate(); 3237 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3238 predicate = ICmpInst::Predicate(IC->getPredicate()); 3239 SDValue Op1 = getValue(I.getOperand(0)); 3240 SDValue Op2 = getValue(I.getOperand(1)); 3241 ISD::CondCode Opcode = getICmpCondCode(predicate); 3242 3243 auto &TLI = DAG.getTargetLoweringInfo(); 3244 EVT MemVT = 3245 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3246 3247 // If a pointer's DAG type is larger than its memory type then the DAG values 3248 // are zero-extended. This breaks signed comparisons so truncate back to the 3249 // underlying type before doing the compare. 3250 if (Op1.getValueType() != MemVT) { 3251 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3252 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3253 } 3254 3255 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3256 I.getType()); 3257 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3258 } 3259 3260 void SelectionDAGBuilder::visitFCmp(const User &I) { 3261 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3262 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3263 predicate = FC->getPredicate(); 3264 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3265 predicate = FCmpInst::Predicate(FC->getPredicate()); 3266 SDValue Op1 = getValue(I.getOperand(0)); 3267 SDValue Op2 = getValue(I.getOperand(1)); 3268 3269 ISD::CondCode Condition = getFCmpCondCode(predicate); 3270 auto *FPMO = dyn_cast<FPMathOperator>(&I); 3271 if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath) 3272 Condition = getFCmpCodeWithoutNaN(Condition); 3273 3274 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3275 I.getType()); 3276 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3277 } 3278 3279 // Check if the condition of the select has one use or two users that are both 3280 // selects with the same condition. 3281 static bool hasOnlySelectUsers(const Value *Cond) { 3282 return llvm::all_of(Cond->users(), [](const Value *V) { 3283 return isa<SelectInst>(V); 3284 }); 3285 } 3286 3287 void SelectionDAGBuilder::visitSelect(const User &I) { 3288 SmallVector<EVT, 4> ValueVTs; 3289 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3290 ValueVTs); 3291 unsigned NumValues = ValueVTs.size(); 3292 if (NumValues == 0) return; 3293 3294 SmallVector<SDValue, 4> Values(NumValues); 3295 SDValue Cond = getValue(I.getOperand(0)); 3296 SDValue LHSVal = getValue(I.getOperand(1)); 3297 SDValue RHSVal = getValue(I.getOperand(2)); 3298 auto BaseOps = {Cond}; 3299 ISD::NodeType OpCode = Cond.getValueType().isVector() ? 3300 ISD::VSELECT : ISD::SELECT; 3301 3302 bool IsUnaryAbs = false; 3303 3304 // Min/max matching is only viable if all output VTs are the same. 3305 if (is_splat(ValueVTs)) { 3306 EVT VT = ValueVTs[0]; 3307 LLVMContext &Ctx = *DAG.getContext(); 3308 auto &TLI = DAG.getTargetLoweringInfo(); 3309 3310 // We care about the legality of the operation after it has been type 3311 // legalized. 3312 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3313 VT = TLI.getTypeToTransformTo(Ctx, VT); 3314 3315 // If the vselect is legal, assume we want to leave this as a vector setcc + 3316 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3317 // min/max is legal on the scalar type. 3318 bool UseScalarMinMax = VT.isVector() && 3319 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3320 3321 Value *LHS, *RHS; 3322 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3323 ISD::NodeType Opc = ISD::DELETED_NODE; 3324 switch (SPR.Flavor) { 3325 case SPF_UMAX: Opc = ISD::UMAX; break; 3326 case SPF_UMIN: Opc = ISD::UMIN; break; 3327 case SPF_SMAX: Opc = ISD::SMAX; break; 3328 case SPF_SMIN: Opc = ISD::SMIN; break; 3329 case SPF_FMINNUM: 3330 switch (SPR.NaNBehavior) { 3331 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3332 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3333 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3334 case SPNB_RETURNS_ANY: { 3335 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3336 Opc = ISD::FMINNUM; 3337 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3338 Opc = ISD::FMINIMUM; 3339 else if (UseScalarMinMax) 3340 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3341 ISD::FMINNUM : ISD::FMINIMUM; 3342 break; 3343 } 3344 } 3345 break; 3346 case SPF_FMAXNUM: 3347 switch (SPR.NaNBehavior) { 3348 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3349 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3350 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3351 case SPNB_RETURNS_ANY: 3352 3353 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3354 Opc = ISD::FMAXNUM; 3355 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3356 Opc = ISD::FMAXIMUM; 3357 else if (UseScalarMinMax) 3358 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3359 ISD::FMAXNUM : ISD::FMAXIMUM; 3360 break; 3361 } 3362 break; 3363 case SPF_ABS: 3364 IsUnaryAbs = true; 3365 Opc = ISD::ABS; 3366 break; 3367 case SPF_NABS: 3368 // TODO: we need to produce sub(0, abs(X)). 3369 default: break; 3370 } 3371 3372 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3373 (TLI.isOperationLegalOrCustom(Opc, VT) || 3374 (UseScalarMinMax && 3375 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3376 // If the underlying comparison instruction is used by any other 3377 // instruction, the consumed instructions won't be destroyed, so it is 3378 // not profitable to convert to a min/max. 3379 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3380 OpCode = Opc; 3381 LHSVal = getValue(LHS); 3382 RHSVal = getValue(RHS); 3383 BaseOps = {}; 3384 } 3385 3386 if (IsUnaryAbs) { 3387 OpCode = Opc; 3388 LHSVal = getValue(LHS); 3389 BaseOps = {}; 3390 } 3391 } 3392 3393 if (IsUnaryAbs) { 3394 for (unsigned i = 0; i != NumValues; ++i) { 3395 Values[i] = 3396 DAG.getNode(OpCode, getCurSDLoc(), 3397 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), 3398 SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3399 } 3400 } else { 3401 for (unsigned i = 0; i != NumValues; ++i) { 3402 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3403 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3404 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3405 Values[i] = DAG.getNode( 3406 OpCode, getCurSDLoc(), 3407 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops); 3408 } 3409 } 3410 3411 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3412 DAG.getVTList(ValueVTs), Values)); 3413 } 3414 3415 void SelectionDAGBuilder::visitTrunc(const User &I) { 3416 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3417 SDValue N = getValue(I.getOperand(0)); 3418 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3419 I.getType()); 3420 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3421 } 3422 3423 void SelectionDAGBuilder::visitZExt(const User &I) { 3424 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3425 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3426 SDValue N = getValue(I.getOperand(0)); 3427 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3428 I.getType()); 3429 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3430 } 3431 3432 void SelectionDAGBuilder::visitSExt(const User &I) { 3433 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3434 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3435 SDValue N = getValue(I.getOperand(0)); 3436 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3437 I.getType()); 3438 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3439 } 3440 3441 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3442 // FPTrunc is never a no-op cast, no need to check 3443 SDValue N = getValue(I.getOperand(0)); 3444 SDLoc dl = getCurSDLoc(); 3445 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3446 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3447 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3448 DAG.getTargetConstant( 3449 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3450 } 3451 3452 void SelectionDAGBuilder::visitFPExt(const User &I) { 3453 // FPExt is never a no-op cast, no need to check 3454 SDValue N = getValue(I.getOperand(0)); 3455 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3456 I.getType()); 3457 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3458 } 3459 3460 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3461 // FPToUI is never a no-op cast, no need to check 3462 SDValue N = getValue(I.getOperand(0)); 3463 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3464 I.getType()); 3465 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3466 } 3467 3468 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3469 // FPToSI is never a no-op cast, no need to check 3470 SDValue N = getValue(I.getOperand(0)); 3471 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3472 I.getType()); 3473 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3474 } 3475 3476 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3477 // UIToFP is never a no-op cast, no need to check 3478 SDValue N = getValue(I.getOperand(0)); 3479 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3480 I.getType()); 3481 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3482 } 3483 3484 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3485 // SIToFP is never a no-op cast, no need to check 3486 SDValue N = getValue(I.getOperand(0)); 3487 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3488 I.getType()); 3489 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3490 } 3491 3492 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3493 // What to do depends on the size of the integer and the size of the pointer. 3494 // We can either truncate, zero extend, or no-op, accordingly. 3495 SDValue N = getValue(I.getOperand(0)); 3496 auto &TLI = DAG.getTargetLoweringInfo(); 3497 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3498 I.getType()); 3499 EVT PtrMemVT = 3500 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3501 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3502 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3503 setValue(&I, N); 3504 } 3505 3506 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3507 // What to do depends on the size of the integer and the size of the pointer. 3508 // We can either truncate, zero extend, or no-op, accordingly. 3509 SDValue N = getValue(I.getOperand(0)); 3510 auto &TLI = DAG.getTargetLoweringInfo(); 3511 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3512 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3513 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3514 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3515 setValue(&I, N); 3516 } 3517 3518 void SelectionDAGBuilder::visitBitCast(const User &I) { 3519 SDValue N = getValue(I.getOperand(0)); 3520 SDLoc dl = getCurSDLoc(); 3521 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3522 I.getType()); 3523 3524 // BitCast assures us that source and destination are the same size so this is 3525 // either a BITCAST or a no-op. 3526 if (DestVT != N.getValueType()) 3527 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3528 DestVT, N)); // convert types. 3529 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3530 // might fold any kind of constant expression to an integer constant and that 3531 // is not what we are looking for. Only recognize a bitcast of a genuine 3532 // constant integer as an opaque constant. 3533 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3534 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3535 /*isOpaque*/true)); 3536 else 3537 setValue(&I, N); // noop cast. 3538 } 3539 3540 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3541 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3542 const Value *SV = I.getOperand(0); 3543 SDValue N = getValue(SV); 3544 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3545 3546 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3547 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3548 3549 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) 3550 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3551 3552 setValue(&I, N); 3553 } 3554 3555 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3556 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3557 SDValue InVec = getValue(I.getOperand(0)); 3558 SDValue InVal = getValue(I.getOperand(1)); 3559 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3560 TLI.getVectorIdxTy(DAG.getDataLayout())); 3561 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3562 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3563 InVec, InVal, InIdx)); 3564 } 3565 3566 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3567 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3568 SDValue InVec = getValue(I.getOperand(0)); 3569 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3570 TLI.getVectorIdxTy(DAG.getDataLayout())); 3571 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3572 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3573 InVec, InIdx)); 3574 } 3575 3576 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3577 SDValue Src1 = getValue(I.getOperand(0)); 3578 SDValue Src2 = getValue(I.getOperand(1)); 3579 Constant *MaskV = cast<Constant>(I.getOperand(2)); 3580 SDLoc DL = getCurSDLoc(); 3581 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3582 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3583 EVT SrcVT = Src1.getValueType(); 3584 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3585 3586 if (MaskV->isNullValue() && VT.isScalableVector()) { 3587 // Canonical splat form of first element of first input vector. 3588 SDValue FirstElt = 3589 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3590 DAG.getVectorIdxConstant(0, DL)); 3591 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3592 return; 3593 } 3594 3595 // For now, we only handle splats for scalable vectors. 3596 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3597 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3598 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3599 3600 SmallVector<int, 8> Mask; 3601 ShuffleVectorInst::getShuffleMask(MaskV, Mask); 3602 unsigned MaskNumElts = Mask.size(); 3603 3604 if (SrcNumElts == MaskNumElts) { 3605 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3606 return; 3607 } 3608 3609 // Normalize the shuffle vector since mask and vector length don't match. 3610 if (SrcNumElts < MaskNumElts) { 3611 // Mask is longer than the source vectors. We can use concatenate vector to 3612 // make the mask and vectors lengths match. 3613 3614 if (MaskNumElts % SrcNumElts == 0) { 3615 // Mask length is a multiple of the source vector length. 3616 // Check if the shuffle is some kind of concatenation of the input 3617 // vectors. 3618 unsigned NumConcat = MaskNumElts / SrcNumElts; 3619 bool IsConcat = true; 3620 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3621 for (unsigned i = 0; i != MaskNumElts; ++i) { 3622 int Idx = Mask[i]; 3623 if (Idx < 0) 3624 continue; 3625 // Ensure the indices in each SrcVT sized piece are sequential and that 3626 // the same source is used for the whole piece. 3627 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3628 (ConcatSrcs[i / SrcNumElts] >= 0 && 3629 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3630 IsConcat = false; 3631 break; 3632 } 3633 // Remember which source this index came from. 3634 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3635 } 3636 3637 // The shuffle is concatenating multiple vectors together. Just emit 3638 // a CONCAT_VECTORS operation. 3639 if (IsConcat) { 3640 SmallVector<SDValue, 8> ConcatOps; 3641 for (auto Src : ConcatSrcs) { 3642 if (Src < 0) 3643 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3644 else if (Src == 0) 3645 ConcatOps.push_back(Src1); 3646 else 3647 ConcatOps.push_back(Src2); 3648 } 3649 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3650 return; 3651 } 3652 } 3653 3654 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3655 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3656 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3657 PaddedMaskNumElts); 3658 3659 // Pad both vectors with undefs to make them the same length as the mask. 3660 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3661 3662 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3663 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3664 MOps1[0] = Src1; 3665 MOps2[0] = Src2; 3666 3667 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3668 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3669 3670 // Readjust mask for new input vector length. 3671 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3672 for (unsigned i = 0; i != MaskNumElts; ++i) { 3673 int Idx = Mask[i]; 3674 if (Idx >= (int)SrcNumElts) 3675 Idx -= SrcNumElts - PaddedMaskNumElts; 3676 MappedOps[i] = Idx; 3677 } 3678 3679 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3680 3681 // If the concatenated vector was padded, extract a subvector with the 3682 // correct number of elements. 3683 if (MaskNumElts != PaddedMaskNumElts) 3684 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3685 DAG.getVectorIdxConstant(0, DL)); 3686 3687 setValue(&I, Result); 3688 return; 3689 } 3690 3691 if (SrcNumElts > MaskNumElts) { 3692 // Analyze the access pattern of the vector to see if we can extract 3693 // two subvectors and do the shuffle. 3694 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3695 bool CanExtract = true; 3696 for (int Idx : Mask) { 3697 unsigned Input = 0; 3698 if (Idx < 0) 3699 continue; 3700 3701 if (Idx >= (int)SrcNumElts) { 3702 Input = 1; 3703 Idx -= SrcNumElts; 3704 } 3705 3706 // If all the indices come from the same MaskNumElts sized portion of 3707 // the sources we can use extract. Also make sure the extract wouldn't 3708 // extract past the end of the source. 3709 int NewStartIdx = alignDown(Idx, MaskNumElts); 3710 if (NewStartIdx + MaskNumElts > SrcNumElts || 3711 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3712 CanExtract = false; 3713 // Make sure we always update StartIdx as we use it to track if all 3714 // elements are undef. 3715 StartIdx[Input] = NewStartIdx; 3716 } 3717 3718 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3719 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3720 return; 3721 } 3722 if (CanExtract) { 3723 // Extract appropriate subvector and generate a vector shuffle 3724 for (unsigned Input = 0; Input < 2; ++Input) { 3725 SDValue &Src = Input == 0 ? Src1 : Src2; 3726 if (StartIdx[Input] < 0) 3727 Src = DAG.getUNDEF(VT); 3728 else { 3729 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3730 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3731 } 3732 } 3733 3734 // Calculate new mask. 3735 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3736 for (int &Idx : MappedOps) { 3737 if (Idx >= (int)SrcNumElts) 3738 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3739 else if (Idx >= 0) 3740 Idx -= StartIdx[0]; 3741 } 3742 3743 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3744 return; 3745 } 3746 } 3747 3748 // We can't use either concat vectors or extract subvectors so fall back to 3749 // replacing the shuffle with extract and build vector. 3750 // to insert and build vector. 3751 EVT EltVT = VT.getVectorElementType(); 3752 SmallVector<SDValue,8> Ops; 3753 for (int Idx : Mask) { 3754 SDValue Res; 3755 3756 if (Idx < 0) { 3757 Res = DAG.getUNDEF(EltVT); 3758 } else { 3759 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3760 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3761 3762 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3763 DAG.getVectorIdxConstant(Idx, DL)); 3764 } 3765 3766 Ops.push_back(Res); 3767 } 3768 3769 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3770 } 3771 3772 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3773 ArrayRef<unsigned> Indices; 3774 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3775 Indices = IV->getIndices(); 3776 else 3777 Indices = cast<ConstantExpr>(&I)->getIndices(); 3778 3779 const Value *Op0 = I.getOperand(0); 3780 const Value *Op1 = I.getOperand(1); 3781 Type *AggTy = I.getType(); 3782 Type *ValTy = Op1->getType(); 3783 bool IntoUndef = isa<UndefValue>(Op0); 3784 bool FromUndef = isa<UndefValue>(Op1); 3785 3786 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3787 3788 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3789 SmallVector<EVT, 4> AggValueVTs; 3790 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3791 SmallVector<EVT, 4> ValValueVTs; 3792 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3793 3794 unsigned NumAggValues = AggValueVTs.size(); 3795 unsigned NumValValues = ValValueVTs.size(); 3796 SmallVector<SDValue, 4> Values(NumAggValues); 3797 3798 // Ignore an insertvalue that produces an empty object 3799 if (!NumAggValues) { 3800 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3801 return; 3802 } 3803 3804 SDValue Agg = getValue(Op0); 3805 unsigned i = 0; 3806 // Copy the beginning value(s) from the original aggregate. 3807 for (; i != LinearIndex; ++i) 3808 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3809 SDValue(Agg.getNode(), Agg.getResNo() + i); 3810 // Copy values from the inserted value(s). 3811 if (NumValValues) { 3812 SDValue Val = getValue(Op1); 3813 for (; i != LinearIndex + NumValValues; ++i) 3814 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3815 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3816 } 3817 // Copy remaining value(s) from the original aggregate. 3818 for (; i != NumAggValues; ++i) 3819 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3820 SDValue(Agg.getNode(), Agg.getResNo() + i); 3821 3822 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3823 DAG.getVTList(AggValueVTs), Values)); 3824 } 3825 3826 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3827 ArrayRef<unsigned> Indices; 3828 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3829 Indices = EV->getIndices(); 3830 else 3831 Indices = cast<ConstantExpr>(&I)->getIndices(); 3832 3833 const Value *Op0 = I.getOperand(0); 3834 Type *AggTy = Op0->getType(); 3835 Type *ValTy = I.getType(); 3836 bool OutOfUndef = isa<UndefValue>(Op0); 3837 3838 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3839 3840 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3841 SmallVector<EVT, 4> ValValueVTs; 3842 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3843 3844 unsigned NumValValues = ValValueVTs.size(); 3845 3846 // Ignore a extractvalue that produces an empty object 3847 if (!NumValValues) { 3848 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3849 return; 3850 } 3851 3852 SmallVector<SDValue, 4> Values(NumValValues); 3853 3854 SDValue Agg = getValue(Op0); 3855 // Copy out the selected value(s). 3856 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3857 Values[i - LinearIndex] = 3858 OutOfUndef ? 3859 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3860 SDValue(Agg.getNode(), Agg.getResNo() + i); 3861 3862 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3863 DAG.getVTList(ValValueVTs), Values)); 3864 } 3865 3866 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3867 Value *Op0 = I.getOperand(0); 3868 // Note that the pointer operand may be a vector of pointers. Take the scalar 3869 // element which holds a pointer. 3870 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3871 SDValue N = getValue(Op0); 3872 SDLoc dl = getCurSDLoc(); 3873 auto &TLI = DAG.getTargetLoweringInfo(); 3874 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 3875 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 3876 3877 // Normalize Vector GEP - all scalar operands should be converted to the 3878 // splat vector. 3879 unsigned VectorWidth = I.getType()->isVectorTy() ? 3880 I.getType()->getVectorNumElements() : 0; 3881 3882 if (VectorWidth && !N.getValueType().isVector()) { 3883 LLVMContext &Context = *DAG.getContext(); 3884 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth); 3885 N = DAG.getSplatBuildVector(VT, dl, N); 3886 } 3887 3888 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3889 GTI != E; ++GTI) { 3890 const Value *Idx = GTI.getOperand(); 3891 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3892 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3893 if (Field) { 3894 // N = N + Offset 3895 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3896 3897 // In an inbounds GEP with an offset that is nonnegative even when 3898 // interpreted as signed, assume there is no unsigned overflow. 3899 SDNodeFlags Flags; 3900 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3901 Flags.setNoUnsignedWrap(true); 3902 3903 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3904 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3905 } 3906 } else { 3907 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3908 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3909 APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType())); 3910 3911 // If this is a scalar constant or a splat vector of constants, 3912 // handle it quickly. 3913 const auto *C = dyn_cast<Constant>(Idx); 3914 if (C && isa<VectorType>(C->getType())) 3915 C = C->getSplatValue(); 3916 3917 if (const auto *CI = dyn_cast_or_null<ConstantInt>(C)) { 3918 if (CI->isZero()) 3919 continue; 3920 APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize); 3921 LLVMContext &Context = *DAG.getContext(); 3922 SDValue OffsVal = VectorWidth ? 3923 DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) : 3924 DAG.getConstant(Offs, dl, IdxTy); 3925 3926 // In an inbounds GEP with an offset that is nonnegative even when 3927 // interpreted as signed, assume there is no unsigned overflow. 3928 SDNodeFlags Flags; 3929 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3930 Flags.setNoUnsignedWrap(true); 3931 3932 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3933 3934 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3935 continue; 3936 } 3937 3938 // N = N + Idx * ElementSize; 3939 SDValue IdxN = getValue(Idx); 3940 3941 if (!IdxN.getValueType().isVector() && VectorWidth) { 3942 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth); 3943 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3944 } 3945 3946 // If the index is smaller or larger than intptr_t, truncate or extend 3947 // it. 3948 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3949 3950 // If this is a multiply by a power of two, turn it into a shl 3951 // immediately. This is a very common case. 3952 if (ElementSize != 1) { 3953 if (ElementSize.isPowerOf2()) { 3954 unsigned Amt = ElementSize.logBase2(); 3955 IdxN = DAG.getNode(ISD::SHL, dl, 3956 N.getValueType(), IdxN, 3957 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3958 } else { 3959 SDValue Scale = DAG.getConstant(ElementSize.getZExtValue(), dl, 3960 IdxN.getValueType()); 3961 IdxN = DAG.getNode(ISD::MUL, dl, 3962 N.getValueType(), IdxN, Scale); 3963 } 3964 } 3965 3966 N = DAG.getNode(ISD::ADD, dl, 3967 N.getValueType(), N, IdxN); 3968 } 3969 } 3970 3971 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 3972 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 3973 3974 setValue(&I, N); 3975 } 3976 3977 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3978 // If this is a fixed sized alloca in the entry block of the function, 3979 // allocate it statically on the stack. 3980 if (FuncInfo.StaticAllocaMap.count(&I)) 3981 return; // getValue will auto-populate this. 3982 3983 SDLoc dl = getCurSDLoc(); 3984 Type *Ty = I.getAllocatedType(); 3985 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3986 auto &DL = DAG.getDataLayout(); 3987 uint64_t TySize = DL.getTypeAllocSize(Ty); 3988 unsigned Align = 3989 std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment()); 3990 3991 SDValue AllocSize = getValue(I.getArraySize()); 3992 3993 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3994 if (AllocSize.getValueType() != IntPtr) 3995 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3996 3997 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3998 AllocSize, 3999 DAG.getConstant(TySize, dl, IntPtr)); 4000 4001 // Handle alignment. If the requested alignment is less than or equal to 4002 // the stack alignment, ignore it. If the size is greater than or equal to 4003 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4004 unsigned StackAlign = 4005 DAG.getSubtarget().getFrameLowering()->getStackAlignment(); 4006 if (Align <= StackAlign) 4007 Align = 0; 4008 4009 // Round the size of the allocation up to the stack alignment size 4010 // by add SA-1 to the size. This doesn't overflow because we're computing 4011 // an address inside an alloca. 4012 SDNodeFlags Flags; 4013 Flags.setNoUnsignedWrap(true); 4014 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4015 DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags); 4016 4017 // Mask out the low bits for alignment purposes. 4018 AllocSize = 4019 DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4020 DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr)); 4021 4022 SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)}; 4023 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4024 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4025 setValue(&I, DSA); 4026 DAG.setRoot(DSA.getValue(1)); 4027 4028 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4029 } 4030 4031 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4032 if (I.isAtomic()) 4033 return visitAtomicLoad(I); 4034 4035 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4036 const Value *SV = I.getOperand(0); 4037 if (TLI.supportSwiftError()) { 4038 // Swifterror values can come from either a function parameter with 4039 // swifterror attribute or an alloca with swifterror attribute. 4040 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4041 if (Arg->hasSwiftErrorAttr()) 4042 return visitLoadFromSwiftError(I); 4043 } 4044 4045 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4046 if (Alloca->isSwiftError()) 4047 return visitLoadFromSwiftError(I); 4048 } 4049 } 4050 4051 SDValue Ptr = getValue(SV); 4052 4053 Type *Ty = I.getType(); 4054 unsigned Alignment = I.getAlignment(); 4055 4056 AAMDNodes AAInfo; 4057 I.getAAMetadata(AAInfo); 4058 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4059 4060 SmallVector<EVT, 4> ValueVTs, MemVTs; 4061 SmallVector<uint64_t, 4> Offsets; 4062 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4063 unsigned NumValues = ValueVTs.size(); 4064 if (NumValues == 0) 4065 return; 4066 4067 bool isVolatile = I.isVolatile(); 4068 4069 SDValue Root; 4070 bool ConstantMemory = false; 4071 if (isVolatile) 4072 // Serialize volatile loads with other side effects. 4073 Root = getRoot(); 4074 else if (NumValues > MaxParallelChains) 4075 Root = getMemoryRoot(); 4076 else if (AA && 4077 AA->pointsToConstantMemory(MemoryLocation( 4078 SV, 4079 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4080 AAInfo))) { 4081 // Do not serialize (non-volatile) loads of constant memory with anything. 4082 Root = DAG.getEntryNode(); 4083 ConstantMemory = true; 4084 } else { 4085 // Do not serialize non-volatile loads against each other. 4086 Root = DAG.getRoot(); 4087 } 4088 4089 SDLoc dl = getCurSDLoc(); 4090 4091 if (isVolatile) 4092 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4093 4094 // An aggregate load cannot wrap around the address space, so offsets to its 4095 // parts don't wrap either. 4096 SDNodeFlags Flags; 4097 Flags.setNoUnsignedWrap(true); 4098 4099 SmallVector<SDValue, 4> Values(NumValues); 4100 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4101 EVT PtrVT = Ptr.getValueType(); 4102 4103 MachineMemOperand::Flags MMOFlags 4104 = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4105 4106 unsigned ChainI = 0; 4107 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4108 // Serializing loads here may result in excessive register pressure, and 4109 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4110 // could recover a bit by hoisting nodes upward in the chain by recognizing 4111 // they are side-effect free or do not alias. The optimizer should really 4112 // avoid this case by converting large object/array copies to llvm.memcpy 4113 // (MaxParallelChains should always remain as failsafe). 4114 if (ChainI == MaxParallelChains) { 4115 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4116 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4117 makeArrayRef(Chains.data(), ChainI)); 4118 Root = Chain; 4119 ChainI = 0; 4120 } 4121 SDValue A = DAG.getNode(ISD::ADD, dl, 4122 PtrVT, Ptr, 4123 DAG.getConstant(Offsets[i], dl, PtrVT), 4124 Flags); 4125 4126 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4127 MachinePointerInfo(SV, Offsets[i]), Alignment, 4128 MMOFlags, AAInfo, Ranges); 4129 Chains[ChainI] = L.getValue(1); 4130 4131 if (MemVTs[i] != ValueVTs[i]) 4132 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4133 4134 Values[i] = L; 4135 } 4136 4137 if (!ConstantMemory) { 4138 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4139 makeArrayRef(Chains.data(), ChainI)); 4140 if (isVolatile) 4141 DAG.setRoot(Chain); 4142 else 4143 PendingLoads.push_back(Chain); 4144 } 4145 4146 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4147 DAG.getVTList(ValueVTs), Values)); 4148 } 4149 4150 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4151 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4152 "call visitStoreToSwiftError when backend supports swifterror"); 4153 4154 SmallVector<EVT, 4> ValueVTs; 4155 SmallVector<uint64_t, 4> Offsets; 4156 const Value *SrcV = I.getOperand(0); 4157 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4158 SrcV->getType(), ValueVTs, &Offsets); 4159 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4160 "expect a single EVT for swifterror"); 4161 4162 SDValue Src = getValue(SrcV); 4163 // Create a virtual register, then update the virtual register. 4164 Register VReg = 4165 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4166 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4167 // Chain can be getRoot or getControlRoot. 4168 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4169 SDValue(Src.getNode(), Src.getResNo())); 4170 DAG.setRoot(CopyNode); 4171 } 4172 4173 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4174 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4175 "call visitLoadFromSwiftError when backend supports swifterror"); 4176 4177 assert(!I.isVolatile() && 4178 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4179 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4180 "Support volatile, non temporal, invariant for load_from_swift_error"); 4181 4182 const Value *SV = I.getOperand(0); 4183 Type *Ty = I.getType(); 4184 AAMDNodes AAInfo; 4185 I.getAAMetadata(AAInfo); 4186 assert( 4187 (!AA || 4188 !AA->pointsToConstantMemory(MemoryLocation( 4189 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4190 AAInfo))) && 4191 "load_from_swift_error should not be constant memory"); 4192 4193 SmallVector<EVT, 4> ValueVTs; 4194 SmallVector<uint64_t, 4> Offsets; 4195 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4196 ValueVTs, &Offsets); 4197 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4198 "expect a single EVT for swifterror"); 4199 4200 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4201 SDValue L = DAG.getCopyFromReg( 4202 getRoot(), getCurSDLoc(), 4203 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4204 4205 setValue(&I, L); 4206 } 4207 4208 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4209 if (I.isAtomic()) 4210 return visitAtomicStore(I); 4211 4212 const Value *SrcV = I.getOperand(0); 4213 const Value *PtrV = I.getOperand(1); 4214 4215 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4216 if (TLI.supportSwiftError()) { 4217 // Swifterror values can come from either a function parameter with 4218 // swifterror attribute or an alloca with swifterror attribute. 4219 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4220 if (Arg->hasSwiftErrorAttr()) 4221 return visitStoreToSwiftError(I); 4222 } 4223 4224 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4225 if (Alloca->isSwiftError()) 4226 return visitStoreToSwiftError(I); 4227 } 4228 } 4229 4230 SmallVector<EVT, 4> ValueVTs, MemVTs; 4231 SmallVector<uint64_t, 4> Offsets; 4232 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4233 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4234 unsigned NumValues = ValueVTs.size(); 4235 if (NumValues == 0) 4236 return; 4237 4238 // Get the lowered operands. Note that we do this after 4239 // checking if NumResults is zero, because with zero results 4240 // the operands won't have values in the map. 4241 SDValue Src = getValue(SrcV); 4242 SDValue Ptr = getValue(PtrV); 4243 4244 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4245 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4246 SDLoc dl = getCurSDLoc(); 4247 unsigned Alignment = I.getAlignment(); 4248 AAMDNodes AAInfo; 4249 I.getAAMetadata(AAInfo); 4250 4251 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4252 4253 // An aggregate load cannot wrap around the address space, so offsets to its 4254 // parts don't wrap either. 4255 SDNodeFlags Flags; 4256 Flags.setNoUnsignedWrap(true); 4257 4258 unsigned ChainI = 0; 4259 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4260 // See visitLoad comments. 4261 if (ChainI == MaxParallelChains) { 4262 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4263 makeArrayRef(Chains.data(), ChainI)); 4264 Root = Chain; 4265 ChainI = 0; 4266 } 4267 SDValue Add = DAG.getMemBasePlusOffset(Ptr, Offsets[i], dl, Flags); 4268 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4269 if (MemVTs[i] != ValueVTs[i]) 4270 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4271 SDValue St = 4272 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4273 Alignment, MMOFlags, AAInfo); 4274 Chains[ChainI] = St; 4275 } 4276 4277 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4278 makeArrayRef(Chains.data(), ChainI)); 4279 DAG.setRoot(StoreNode); 4280 } 4281 4282 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4283 bool IsCompressing) { 4284 SDLoc sdl = getCurSDLoc(); 4285 4286 auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4287 unsigned& Alignment) { 4288 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4289 Src0 = I.getArgOperand(0); 4290 Ptr = I.getArgOperand(1); 4291 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 4292 Mask = I.getArgOperand(3); 4293 }; 4294 auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4295 unsigned& Alignment) { 4296 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4297 Src0 = I.getArgOperand(0); 4298 Ptr = I.getArgOperand(1); 4299 Mask = I.getArgOperand(2); 4300 Alignment = 0; 4301 }; 4302 4303 Value *PtrOperand, *MaskOperand, *Src0Operand; 4304 unsigned Alignment; 4305 if (IsCompressing) 4306 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4307 else 4308 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4309 4310 SDValue Ptr = getValue(PtrOperand); 4311 SDValue Src0 = getValue(Src0Operand); 4312 SDValue Mask = getValue(MaskOperand); 4313 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4314 4315 EVT VT = Src0.getValueType(); 4316 if (!Alignment) 4317 Alignment = DAG.getEVTAlignment(VT); 4318 4319 AAMDNodes AAInfo; 4320 I.getAAMetadata(AAInfo); 4321 4322 MachineMemOperand *MMO = 4323 DAG.getMachineFunction(). 4324 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4325 MachineMemOperand::MOStore, 4326 // TODO: Make MachineMemOperands aware of scalable 4327 // vectors. 4328 VT.getStoreSize().getKnownMinSize(), 4329 Alignment, AAInfo); 4330 SDValue StoreNode = 4331 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4332 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4333 DAG.setRoot(StoreNode); 4334 setValue(&I, StoreNode); 4335 } 4336 4337 // Get a uniform base for the Gather/Scatter intrinsic. 4338 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4339 // We try to represent it as a base pointer + vector of indices. 4340 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4341 // The first operand of the GEP may be a single pointer or a vector of pointers 4342 // Example: 4343 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4344 // or 4345 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4346 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4347 // 4348 // When the first GEP operand is a single pointer - it is the uniform base we 4349 // are looking for. If first operand of the GEP is a splat vector - we 4350 // extract the splat value and use it as a uniform base. 4351 // In all other cases the function returns 'false'. 4352 static bool getUniformBase(const Value *&Ptr, SDValue &Base, SDValue &Index, 4353 ISD::MemIndexType &IndexType, SDValue &Scale, 4354 SelectionDAGBuilder *SDB) { 4355 SelectionDAG& DAG = SDB->DAG; 4356 LLVMContext &Context = *DAG.getContext(); 4357 4358 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 4359 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4360 if (!GEP) 4361 return false; 4362 4363 const Value *GEPPtr = GEP->getPointerOperand(); 4364 if (!GEPPtr->getType()->isVectorTy()) 4365 Ptr = GEPPtr; 4366 else if (!(Ptr = getSplatValue(GEPPtr))) 4367 return false; 4368 4369 unsigned FinalIndex = GEP->getNumOperands() - 1; 4370 Value *IndexVal = GEP->getOperand(FinalIndex); 4371 gep_type_iterator GTI = gep_type_begin(*GEP); 4372 4373 // Ensure all the other indices are 0. 4374 for (unsigned i = 1; i < FinalIndex; ++i, ++GTI) { 4375 auto *C = dyn_cast<Constant>(GEP->getOperand(i)); 4376 if (!C) 4377 return false; 4378 if (isa<VectorType>(C->getType())) 4379 C = C->getSplatValue(); 4380 auto *CI = dyn_cast_or_null<ConstantInt>(C); 4381 if (!CI || !CI->isZero()) 4382 return false; 4383 } 4384 4385 // The operands of the GEP may be defined in another basic block. 4386 // In this case we'll not find nodes for the operands. 4387 if (!SDB->findValue(Ptr)) 4388 return false; 4389 Constant *C = dyn_cast<Constant>(IndexVal); 4390 if (!C && !SDB->findValue(IndexVal)) 4391 return false; 4392 4393 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4394 const DataLayout &DL = DAG.getDataLayout(); 4395 StructType *STy = GTI.getStructTypeOrNull(); 4396 4397 if (STy) { 4398 const StructLayout *SL = DL.getStructLayout(STy); 4399 if (isa<VectorType>(C->getType())) { 4400 C = C->getSplatValue(); 4401 // FIXME: If getSplatValue may return nullptr for a structure? 4402 // If not, the following check can be removed. 4403 if (!C) 4404 return false; 4405 } 4406 auto *CI = cast<ConstantInt>(C); 4407 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4408 Index = DAG.getConstant(SL->getElementOffset(CI->getZExtValue()), 4409 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4410 } else { 4411 Scale = DAG.getTargetConstant( 4412 DL.getTypeAllocSize(GEP->getResultElementType()), 4413 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4414 Index = SDB->getValue(IndexVal); 4415 } 4416 Base = SDB->getValue(Ptr); 4417 IndexType = ISD::SIGNED_SCALED; 4418 4419 if (STy || !Index.getValueType().isVector()) { 4420 unsigned GEPWidth = GEP->getType()->getVectorNumElements(); 4421 EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth); 4422 Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index); 4423 } 4424 return true; 4425 } 4426 4427 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4428 SDLoc sdl = getCurSDLoc(); 4429 4430 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4431 const Value *Ptr = I.getArgOperand(1); 4432 SDValue Src0 = getValue(I.getArgOperand(0)); 4433 SDValue Mask = getValue(I.getArgOperand(3)); 4434 EVT VT = Src0.getValueType(); 4435 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue(); 4436 if (!Alignment) 4437 Alignment = DAG.getEVTAlignment(VT); 4438 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4439 4440 AAMDNodes AAInfo; 4441 I.getAAMetadata(AAInfo); 4442 4443 SDValue Base; 4444 SDValue Index; 4445 ISD::MemIndexType IndexType; 4446 SDValue Scale; 4447 const Value *BasePtr = Ptr; 4448 bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale, 4449 this); 4450 4451 const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr; 4452 MachineMemOperand *MMO = DAG.getMachineFunction(). 4453 getMachineMemOperand(MachinePointerInfo(MemOpBasePtr), 4454 MachineMemOperand::MOStore, 4455 // TODO: Make MachineMemOperands aware of scalable 4456 // vectors. 4457 VT.getStoreSize().getKnownMinSize(), 4458 Alignment, AAInfo); 4459 if (!UniformBase) { 4460 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4461 Index = getValue(Ptr); 4462 IndexType = ISD::SIGNED_SCALED; 4463 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4464 } 4465 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4466 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4467 Ops, MMO, IndexType); 4468 DAG.setRoot(Scatter); 4469 setValue(&I, Scatter); 4470 } 4471 4472 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4473 SDLoc sdl = getCurSDLoc(); 4474 4475 auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4476 unsigned& Alignment) { 4477 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4478 Ptr = I.getArgOperand(0); 4479 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 4480 Mask = I.getArgOperand(2); 4481 Src0 = I.getArgOperand(3); 4482 }; 4483 auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4484 unsigned& Alignment) { 4485 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4486 Ptr = I.getArgOperand(0); 4487 Alignment = 0; 4488 Mask = I.getArgOperand(1); 4489 Src0 = I.getArgOperand(2); 4490 }; 4491 4492 Value *PtrOperand, *MaskOperand, *Src0Operand; 4493 unsigned Alignment; 4494 if (IsExpanding) 4495 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4496 else 4497 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4498 4499 SDValue Ptr = getValue(PtrOperand); 4500 SDValue Src0 = getValue(Src0Operand); 4501 SDValue Mask = getValue(MaskOperand); 4502 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4503 4504 EVT VT = Src0.getValueType(); 4505 if (!Alignment) 4506 Alignment = DAG.getEVTAlignment(VT); 4507 4508 AAMDNodes AAInfo; 4509 I.getAAMetadata(AAInfo); 4510 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4511 4512 // Do not serialize masked loads of constant memory with anything. 4513 MemoryLocation ML; 4514 if (VT.isScalableVector()) 4515 ML = MemoryLocation(PtrOperand); 4516 else 4517 ML = MemoryLocation(PtrOperand, LocationSize::precise( 4518 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4519 AAInfo); 4520 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4521 4522 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4523 4524 MachineMemOperand *MMO = 4525 DAG.getMachineFunction(). 4526 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4527 MachineMemOperand::MOLoad, 4528 // TODO: Make MachineMemOperands aware of scalable 4529 // vectors. 4530 VT.getStoreSize().getKnownMinSize(), 4531 Alignment, AAInfo, Ranges); 4532 4533 SDValue Load = 4534 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4535 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4536 if (AddToChain) 4537 PendingLoads.push_back(Load.getValue(1)); 4538 setValue(&I, Load); 4539 } 4540 4541 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4542 SDLoc sdl = getCurSDLoc(); 4543 4544 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4545 const Value *Ptr = I.getArgOperand(0); 4546 SDValue Src0 = getValue(I.getArgOperand(3)); 4547 SDValue Mask = getValue(I.getArgOperand(2)); 4548 4549 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4550 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4551 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue(); 4552 if (!Alignment) 4553 Alignment = DAG.getEVTAlignment(VT); 4554 4555 AAMDNodes AAInfo; 4556 I.getAAMetadata(AAInfo); 4557 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4558 4559 SDValue Root = DAG.getRoot(); 4560 SDValue Base; 4561 SDValue Index; 4562 ISD::MemIndexType IndexType; 4563 SDValue Scale; 4564 const Value *BasePtr = Ptr; 4565 bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale, 4566 this); 4567 bool ConstantMemory = false; 4568 if (UniformBase && AA && 4569 AA->pointsToConstantMemory( 4570 MemoryLocation(BasePtr, 4571 LocationSize::precise( 4572 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4573 AAInfo))) { 4574 // Do not serialize (non-volatile) loads of constant memory with anything. 4575 Root = DAG.getEntryNode(); 4576 ConstantMemory = true; 4577 } 4578 4579 MachineMemOperand *MMO = 4580 DAG.getMachineFunction(). 4581 getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr), 4582 MachineMemOperand::MOLoad, 4583 // TODO: Make MachineMemOperands aware of scalable 4584 // vectors. 4585 VT.getStoreSize().getKnownMinSize(), 4586 Alignment, AAInfo, Ranges); 4587 4588 if (!UniformBase) { 4589 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4590 Index = getValue(Ptr); 4591 IndexType = ISD::SIGNED_SCALED; 4592 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4593 } 4594 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4595 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4596 Ops, MMO, IndexType); 4597 4598 SDValue OutChain = Gather.getValue(1); 4599 if (!ConstantMemory) 4600 PendingLoads.push_back(OutChain); 4601 setValue(&I, Gather); 4602 } 4603 4604 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4605 SDLoc dl = getCurSDLoc(); 4606 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4607 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4608 SyncScope::ID SSID = I.getSyncScopeID(); 4609 4610 SDValue InChain = getRoot(); 4611 4612 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4613 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4614 4615 auto Alignment = DAG.getEVTAlignment(MemVT); 4616 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4617 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4618 4619 MachineFunction &MF = DAG.getMachineFunction(); 4620 MachineMemOperand *MMO = 4621 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4622 Flags, MemVT.getStoreSize(), Alignment, 4623 AAMDNodes(), nullptr, SSID, SuccessOrdering, 4624 FailureOrdering); 4625 4626 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4627 dl, MemVT, VTs, InChain, 4628 getValue(I.getPointerOperand()), 4629 getValue(I.getCompareOperand()), 4630 getValue(I.getNewValOperand()), MMO); 4631 4632 SDValue OutChain = L.getValue(2); 4633 4634 setValue(&I, L); 4635 DAG.setRoot(OutChain); 4636 } 4637 4638 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4639 SDLoc dl = getCurSDLoc(); 4640 ISD::NodeType NT; 4641 switch (I.getOperation()) { 4642 default: llvm_unreachable("Unknown atomicrmw operation"); 4643 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4644 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4645 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4646 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4647 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4648 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4649 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4650 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4651 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4652 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4653 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4654 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4655 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4656 } 4657 AtomicOrdering Ordering = I.getOrdering(); 4658 SyncScope::ID SSID = I.getSyncScopeID(); 4659 4660 SDValue InChain = getRoot(); 4661 4662 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4663 auto Alignment = DAG.getEVTAlignment(MemVT); 4664 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4665 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4666 4667 MachineFunction &MF = DAG.getMachineFunction(); 4668 MachineMemOperand *MMO = 4669 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags, 4670 MemVT.getStoreSize(), Alignment, AAMDNodes(), 4671 nullptr, SSID, Ordering); 4672 4673 SDValue L = 4674 DAG.getAtomic(NT, dl, MemVT, InChain, 4675 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4676 MMO); 4677 4678 SDValue OutChain = L.getValue(1); 4679 4680 setValue(&I, L); 4681 DAG.setRoot(OutChain); 4682 } 4683 4684 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4685 SDLoc dl = getCurSDLoc(); 4686 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4687 SDValue Ops[3]; 4688 Ops[0] = getRoot(); 4689 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4690 TLI.getFenceOperandTy(DAG.getDataLayout())); 4691 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4692 TLI.getFenceOperandTy(DAG.getDataLayout())); 4693 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4694 } 4695 4696 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4697 SDLoc dl = getCurSDLoc(); 4698 AtomicOrdering Order = I.getOrdering(); 4699 SyncScope::ID SSID = I.getSyncScopeID(); 4700 4701 SDValue InChain = getRoot(); 4702 4703 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4704 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4705 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4706 4707 if (!TLI.supportsUnalignedAtomics() && 4708 I.getAlignment() < MemVT.getSizeInBits() / 8) 4709 report_fatal_error("Cannot generate unaligned atomic load"); 4710 4711 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4712 4713 MachineMemOperand *MMO = 4714 DAG.getMachineFunction(). 4715 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4716 Flags, MemVT.getStoreSize(), 4717 I.getAlignment() ? I.getAlignment() : 4718 DAG.getEVTAlignment(MemVT), 4719 AAMDNodes(), nullptr, SSID, Order); 4720 4721 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4722 4723 SDValue Ptr = getValue(I.getPointerOperand()); 4724 4725 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4726 // TODO: Once this is better exercised by tests, it should be merged with 4727 // the normal path for loads to prevent future divergence. 4728 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4729 if (MemVT != VT) 4730 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4731 4732 setValue(&I, L); 4733 SDValue OutChain = L.getValue(1); 4734 if (!I.isUnordered()) 4735 DAG.setRoot(OutChain); 4736 else 4737 PendingLoads.push_back(OutChain); 4738 return; 4739 } 4740 4741 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4742 Ptr, MMO); 4743 4744 SDValue OutChain = L.getValue(1); 4745 if (MemVT != VT) 4746 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4747 4748 setValue(&I, L); 4749 DAG.setRoot(OutChain); 4750 } 4751 4752 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4753 SDLoc dl = getCurSDLoc(); 4754 4755 AtomicOrdering Ordering = I.getOrdering(); 4756 SyncScope::ID SSID = I.getSyncScopeID(); 4757 4758 SDValue InChain = getRoot(); 4759 4760 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4761 EVT MemVT = 4762 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4763 4764 if (I.getAlignment() < MemVT.getSizeInBits() / 8) 4765 report_fatal_error("Cannot generate unaligned atomic store"); 4766 4767 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4768 4769 MachineFunction &MF = DAG.getMachineFunction(); 4770 MachineMemOperand *MMO = 4771 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags, 4772 MemVT.getStoreSize(), I.getAlignment(), AAMDNodes(), 4773 nullptr, SSID, Ordering); 4774 4775 SDValue Val = getValue(I.getValueOperand()); 4776 if (Val.getValueType() != MemVT) 4777 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4778 SDValue Ptr = getValue(I.getPointerOperand()); 4779 4780 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4781 // TODO: Once this is better exercised by tests, it should be merged with 4782 // the normal path for stores to prevent future divergence. 4783 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4784 DAG.setRoot(S); 4785 return; 4786 } 4787 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4788 Ptr, Val, MMO); 4789 4790 4791 DAG.setRoot(OutChain); 4792 } 4793 4794 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4795 /// node. 4796 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4797 unsigned Intrinsic) { 4798 // Ignore the callsite's attributes. A specific call site may be marked with 4799 // readnone, but the lowering code will expect the chain based on the 4800 // definition. 4801 const Function *F = I.getCalledFunction(); 4802 bool HasChain = !F->doesNotAccessMemory(); 4803 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4804 4805 // Build the operand list. 4806 SmallVector<SDValue, 8> Ops; 4807 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4808 if (OnlyLoad) { 4809 // We don't need to serialize loads against other loads. 4810 Ops.push_back(DAG.getRoot()); 4811 } else { 4812 Ops.push_back(getRoot()); 4813 } 4814 } 4815 4816 // Info is set by getTgtMemInstrinsic 4817 TargetLowering::IntrinsicInfo Info; 4818 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4819 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4820 DAG.getMachineFunction(), 4821 Intrinsic); 4822 4823 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4824 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4825 Info.opc == ISD::INTRINSIC_W_CHAIN) 4826 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4827 TLI.getPointerTy(DAG.getDataLayout()))); 4828 4829 // Add all operands of the call to the operand list. 4830 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4831 const Value *Arg = I.getArgOperand(i); 4832 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4833 Ops.push_back(getValue(Arg)); 4834 continue; 4835 } 4836 4837 // Use TargetConstant instead of a regular constant for immarg. 4838 EVT VT = TLI.getValueType(*DL, Arg->getType(), true); 4839 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4840 assert(CI->getBitWidth() <= 64 && 4841 "large intrinsic immediates not handled"); 4842 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4843 } else { 4844 Ops.push_back( 4845 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4846 } 4847 } 4848 4849 SmallVector<EVT, 4> ValueVTs; 4850 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4851 4852 if (HasChain) 4853 ValueVTs.push_back(MVT::Other); 4854 4855 SDVTList VTs = DAG.getVTList(ValueVTs); 4856 4857 // Create the node. 4858 SDValue Result; 4859 if (IsTgtIntrinsic) { 4860 // This is target intrinsic that touches memory 4861 AAMDNodes AAInfo; 4862 I.getAAMetadata(AAInfo); 4863 Result = DAG.getMemIntrinsicNode( 4864 Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT, 4865 MachinePointerInfo(Info.ptrVal, Info.offset), 4866 Info.align ? Info.align->value() : 0, Info.flags, Info.size, AAInfo); 4867 } else if (!HasChain) { 4868 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4869 } else if (!I.getType()->isVoidTy()) { 4870 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4871 } else { 4872 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4873 } 4874 4875 if (HasChain) { 4876 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4877 if (OnlyLoad) 4878 PendingLoads.push_back(Chain); 4879 else 4880 DAG.setRoot(Chain); 4881 } 4882 4883 if (!I.getType()->isVoidTy()) { 4884 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4885 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4886 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4887 } else 4888 Result = lowerRangeToAssertZExt(DAG, I, Result); 4889 4890 setValue(&I, Result); 4891 } 4892 } 4893 4894 /// GetSignificand - Get the significand and build it into a floating-point 4895 /// number with exponent of 1: 4896 /// 4897 /// Op = (Op & 0x007fffff) | 0x3f800000; 4898 /// 4899 /// where Op is the hexadecimal representation of floating point value. 4900 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4901 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4902 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4903 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4904 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4905 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4906 } 4907 4908 /// GetExponent - Get the exponent: 4909 /// 4910 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4911 /// 4912 /// where Op is the hexadecimal representation of floating point value. 4913 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4914 const TargetLowering &TLI, const SDLoc &dl) { 4915 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4916 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4917 SDValue t1 = DAG.getNode( 4918 ISD::SRL, dl, MVT::i32, t0, 4919 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4920 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4921 DAG.getConstant(127, dl, MVT::i32)); 4922 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4923 } 4924 4925 /// getF32Constant - Get 32-bit floating point constant. 4926 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4927 const SDLoc &dl) { 4928 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4929 MVT::f32); 4930 } 4931 4932 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4933 SelectionDAG &DAG) { 4934 // TODO: What fast-math-flags should be set on the floating-point nodes? 4935 4936 // IntegerPartOfX = ((int32_t)(t0); 4937 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4938 4939 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4940 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4941 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4942 4943 // IntegerPartOfX <<= 23; 4944 IntegerPartOfX = DAG.getNode( 4945 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4946 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4947 DAG.getDataLayout()))); 4948 4949 SDValue TwoToFractionalPartOfX; 4950 if (LimitFloatPrecision <= 6) { 4951 // For floating-point precision of 6: 4952 // 4953 // TwoToFractionalPartOfX = 4954 // 0.997535578f + 4955 // (0.735607626f + 0.252464424f * x) * x; 4956 // 4957 // error 0.0144103317, which is 6 bits 4958 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4959 getF32Constant(DAG, 0x3e814304, dl)); 4960 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4961 getF32Constant(DAG, 0x3f3c50c8, dl)); 4962 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4963 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4964 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4965 } else if (LimitFloatPrecision <= 12) { 4966 // For floating-point precision of 12: 4967 // 4968 // TwoToFractionalPartOfX = 4969 // 0.999892986f + 4970 // (0.696457318f + 4971 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4972 // 4973 // error 0.000107046256, which is 13 to 14 bits 4974 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4975 getF32Constant(DAG, 0x3da235e3, dl)); 4976 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4977 getF32Constant(DAG, 0x3e65b8f3, dl)); 4978 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4979 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4980 getF32Constant(DAG, 0x3f324b07, dl)); 4981 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4982 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4983 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4984 } else { // LimitFloatPrecision <= 18 4985 // For floating-point precision of 18: 4986 // 4987 // TwoToFractionalPartOfX = 4988 // 0.999999982f + 4989 // (0.693148872f + 4990 // (0.240227044f + 4991 // (0.554906021e-1f + 4992 // (0.961591928e-2f + 4993 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4994 // error 2.47208000*10^(-7), which is better than 18 bits 4995 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4996 getF32Constant(DAG, 0x3924b03e, dl)); 4997 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4998 getF32Constant(DAG, 0x3ab24b87, dl)); 4999 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5000 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5001 getF32Constant(DAG, 0x3c1d8c17, dl)); 5002 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5003 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5004 getF32Constant(DAG, 0x3d634a1d, dl)); 5005 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5006 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5007 getF32Constant(DAG, 0x3e75fe14, dl)); 5008 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5009 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 5010 getF32Constant(DAG, 0x3f317234, dl)); 5011 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 5012 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 5013 getF32Constant(DAG, 0x3f800000, dl)); 5014 } 5015 5016 // Add the exponent into the result in integer domain. 5017 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 5018 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5019 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 5020 } 5021 5022 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5023 /// limited-precision mode. 5024 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5025 const TargetLowering &TLI) { 5026 if (Op.getValueType() == MVT::f32 && 5027 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5028 5029 // Put the exponent in the right bit position for later addition to the 5030 // final result: 5031 // 5032 // t0 = Op * log2(e) 5033 5034 // TODO: What fast-math-flags should be set here? 5035 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5036 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5037 return getLimitedPrecisionExp2(t0, dl, DAG); 5038 } 5039 5040 // No special expansion. 5041 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op); 5042 } 5043 5044 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5045 /// limited-precision mode. 5046 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5047 const TargetLowering &TLI) { 5048 // TODO: What fast-math-flags should be set on the floating-point nodes? 5049 5050 if (Op.getValueType() == MVT::f32 && 5051 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5052 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5053 5054 // Scale the exponent by log(2). 5055 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5056 SDValue LogOfExponent = 5057 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5058 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5059 5060 // Get the significand and build it into a floating-point number with 5061 // exponent of 1. 5062 SDValue X = GetSignificand(DAG, Op1, dl); 5063 5064 SDValue LogOfMantissa; 5065 if (LimitFloatPrecision <= 6) { 5066 // For floating-point precision of 6: 5067 // 5068 // LogofMantissa = 5069 // -1.1609546f + 5070 // (1.4034025f - 0.23903021f * x) * x; 5071 // 5072 // error 0.0034276066, which is better than 8 bits 5073 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5074 getF32Constant(DAG, 0xbe74c456, dl)); 5075 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5076 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5077 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5078 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5079 getF32Constant(DAG, 0x3f949a29, dl)); 5080 } else if (LimitFloatPrecision <= 12) { 5081 // For floating-point precision of 12: 5082 // 5083 // LogOfMantissa = 5084 // -1.7417939f + 5085 // (2.8212026f + 5086 // (-1.4699568f + 5087 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5088 // 5089 // error 0.000061011436, which is 14 bits 5090 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5091 getF32Constant(DAG, 0xbd67b6d6, dl)); 5092 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5093 getF32Constant(DAG, 0x3ee4f4b8, 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, 0x3fbc278b, 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, 0x40348e95, dl)); 5100 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5101 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5102 getF32Constant(DAG, 0x3fdef31a, dl)); 5103 } else { // LimitFloatPrecision <= 18 5104 // For floating-point precision of 18: 5105 // 5106 // LogOfMantissa = 5107 // -2.1072184f + 5108 // (4.2372794f + 5109 // (-3.7029485f + 5110 // (2.2781945f + 5111 // (-0.87823314f + 5112 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5113 // 5114 // error 0.0000023660568, which is better than 18 bits 5115 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5116 getF32Constant(DAG, 0xbc91e5ac, dl)); 5117 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5118 getF32Constant(DAG, 0x3e4350aa, dl)); 5119 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5120 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5121 getF32Constant(DAG, 0x3f60d3e3, dl)); 5122 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5123 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5124 getF32Constant(DAG, 0x4011cdf0, dl)); 5125 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5126 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5127 getF32Constant(DAG, 0x406cfd1c, dl)); 5128 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5129 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5130 getF32Constant(DAG, 0x408797cb, dl)); 5131 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5132 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5133 getF32Constant(DAG, 0x4006dcab, dl)); 5134 } 5135 5136 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5137 } 5138 5139 // No special expansion. 5140 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op); 5141 } 5142 5143 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5144 /// limited-precision mode. 5145 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5146 const TargetLowering &TLI) { 5147 // TODO: What fast-math-flags should be set on the floating-point nodes? 5148 5149 if (Op.getValueType() == MVT::f32 && 5150 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5151 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5152 5153 // Get the exponent. 5154 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5155 5156 // Get the significand and build it into a floating-point number with 5157 // exponent of 1. 5158 SDValue X = GetSignificand(DAG, Op1, dl); 5159 5160 // Different possible minimax approximations of significand in 5161 // floating-point for various degrees of accuracy over [1,2]. 5162 SDValue Log2ofMantissa; 5163 if (LimitFloatPrecision <= 6) { 5164 // For floating-point precision of 6: 5165 // 5166 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5167 // 5168 // error 0.0049451742, which is more than 7 bits 5169 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5170 getF32Constant(DAG, 0xbeb08fe0, dl)); 5171 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5172 getF32Constant(DAG, 0x40019463, dl)); 5173 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5174 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5175 getF32Constant(DAG, 0x3fd6633d, dl)); 5176 } else if (LimitFloatPrecision <= 12) { 5177 // For floating-point precision of 12: 5178 // 5179 // Log2ofMantissa = 5180 // -2.51285454f + 5181 // (4.07009056f + 5182 // (-2.12067489f + 5183 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5184 // 5185 // error 0.0000876136000, which is better than 13 bits 5186 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5187 getF32Constant(DAG, 0xbda7262e, dl)); 5188 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5189 getF32Constant(DAG, 0x3f25280b, dl)); 5190 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5191 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5192 getF32Constant(DAG, 0x4007b923, dl)); 5193 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5194 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5195 getF32Constant(DAG, 0x40823e2f, dl)); 5196 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5197 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5198 getF32Constant(DAG, 0x4020d29c, dl)); 5199 } else { // LimitFloatPrecision <= 18 5200 // For floating-point precision of 18: 5201 // 5202 // Log2ofMantissa = 5203 // -3.0400495f + 5204 // (6.1129976f + 5205 // (-5.3420409f + 5206 // (3.2865683f + 5207 // (-1.2669343f + 5208 // (0.27515199f - 5209 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5210 // 5211 // error 0.0000018516, which is better than 18 bits 5212 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5213 getF32Constant(DAG, 0xbcd2769e, dl)); 5214 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5215 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5216 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5217 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5218 getF32Constant(DAG, 0x3fa22ae7, dl)); 5219 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5220 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5221 getF32Constant(DAG, 0x40525723, dl)); 5222 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5223 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5224 getF32Constant(DAG, 0x40aaf200, dl)); 5225 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5226 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5227 getF32Constant(DAG, 0x40c39dad, dl)); 5228 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5229 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5230 getF32Constant(DAG, 0x4042902c, dl)); 5231 } 5232 5233 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5234 } 5235 5236 // No special expansion. 5237 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op); 5238 } 5239 5240 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5241 /// limited-precision mode. 5242 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5243 const TargetLowering &TLI) { 5244 // TODO: What fast-math-flags should be set on the floating-point nodes? 5245 5246 if (Op.getValueType() == MVT::f32 && 5247 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5248 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5249 5250 // Scale the exponent by log10(2) [0.30102999f]. 5251 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5252 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5253 getF32Constant(DAG, 0x3e9a209a, dl)); 5254 5255 // Get the significand and build it into a floating-point number with 5256 // exponent of 1. 5257 SDValue X = GetSignificand(DAG, Op1, dl); 5258 5259 SDValue Log10ofMantissa; 5260 if (LimitFloatPrecision <= 6) { 5261 // For floating-point precision of 6: 5262 // 5263 // Log10ofMantissa = 5264 // -0.50419619f + 5265 // (0.60948995f - 0.10380950f * x) * x; 5266 // 5267 // error 0.0014886165, which is 6 bits 5268 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5269 getF32Constant(DAG, 0xbdd49a13, dl)); 5270 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5271 getF32Constant(DAG, 0x3f1c0789, dl)); 5272 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5273 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5274 getF32Constant(DAG, 0x3f011300, dl)); 5275 } else if (LimitFloatPrecision <= 12) { 5276 // For floating-point precision of 12: 5277 // 5278 // Log10ofMantissa = 5279 // -0.64831180f + 5280 // (0.91751397f + 5281 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5282 // 5283 // error 0.00019228036, which is better than 12 bits 5284 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5285 getF32Constant(DAG, 0x3d431f31, dl)); 5286 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5287 getF32Constant(DAG, 0x3ea21fb2, dl)); 5288 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5289 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5290 getF32Constant(DAG, 0x3f6ae232, dl)); 5291 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5292 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5293 getF32Constant(DAG, 0x3f25f7c3, dl)); 5294 } else { // LimitFloatPrecision <= 18 5295 // For floating-point precision of 18: 5296 // 5297 // Log10ofMantissa = 5298 // -0.84299375f + 5299 // (1.5327582f + 5300 // (-1.0688956f + 5301 // (0.49102474f + 5302 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5303 // 5304 // error 0.0000037995730, which is better than 18 bits 5305 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5306 getF32Constant(DAG, 0x3c5d51ce, dl)); 5307 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5308 getF32Constant(DAG, 0x3e00685a, dl)); 5309 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5310 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5311 getF32Constant(DAG, 0x3efb6798, dl)); 5312 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5313 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5314 getF32Constant(DAG, 0x3f88d192, dl)); 5315 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5316 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5317 getF32Constant(DAG, 0x3fc4316c, dl)); 5318 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5319 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5320 getF32Constant(DAG, 0x3f57ce70, dl)); 5321 } 5322 5323 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5324 } 5325 5326 // No special expansion. 5327 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op); 5328 } 5329 5330 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5331 /// limited-precision mode. 5332 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5333 const TargetLowering &TLI) { 5334 if (Op.getValueType() == MVT::f32 && 5335 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5336 return getLimitedPrecisionExp2(Op, dl, DAG); 5337 5338 // No special expansion. 5339 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op); 5340 } 5341 5342 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5343 /// limited-precision mode with x == 10.0f. 5344 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5345 SelectionDAG &DAG, const TargetLowering &TLI) { 5346 bool IsExp10 = false; 5347 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5348 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5349 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5350 APFloat Ten(10.0f); 5351 IsExp10 = LHSC->isExactlyValue(Ten); 5352 } 5353 } 5354 5355 // TODO: What fast-math-flags should be set on the FMUL node? 5356 if (IsExp10) { 5357 // Put the exponent in the right bit position for later addition to the 5358 // final result: 5359 // 5360 // #define LOG2OF10 3.3219281f 5361 // t0 = Op * LOG2OF10; 5362 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5363 getF32Constant(DAG, 0x40549a78, dl)); 5364 return getLimitedPrecisionExp2(t0, dl, DAG); 5365 } 5366 5367 // No special expansion. 5368 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS); 5369 } 5370 5371 /// ExpandPowI - Expand a llvm.powi intrinsic. 5372 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5373 SelectionDAG &DAG) { 5374 // If RHS is a constant, we can expand this out to a multiplication tree, 5375 // otherwise we end up lowering to a call to __powidf2 (for example). When 5376 // optimizing for size, we only want to do this if the expansion would produce 5377 // a small number of multiplies, otherwise we do the full expansion. 5378 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5379 // Get the exponent as a positive value. 5380 unsigned Val = RHSC->getSExtValue(); 5381 if ((int)Val < 0) Val = -Val; 5382 5383 // powi(x, 0) -> 1.0 5384 if (Val == 0) 5385 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5386 5387 bool OptForSize = DAG.shouldOptForSize(); 5388 if (!OptForSize || 5389 // If optimizing for size, don't insert too many multiplies. 5390 // This inserts up to 5 multiplies. 5391 countPopulation(Val) + Log2_32(Val) < 7) { 5392 // We use the simple binary decomposition method to generate the multiply 5393 // sequence. There are more optimal ways to do this (for example, 5394 // powi(x,15) generates one more multiply than it should), but this has 5395 // the benefit of being both really simple and much better than a libcall. 5396 SDValue Res; // Logically starts equal to 1.0 5397 SDValue CurSquare = LHS; 5398 // TODO: Intrinsics should have fast-math-flags that propagate to these 5399 // nodes. 5400 while (Val) { 5401 if (Val & 1) { 5402 if (Res.getNode()) 5403 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 5404 else 5405 Res = CurSquare; // 1.0*CurSquare. 5406 } 5407 5408 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5409 CurSquare, CurSquare); 5410 Val >>= 1; 5411 } 5412 5413 // If the original was negative, invert the result, producing 1/(x*x*x). 5414 if (RHSC->getSExtValue() < 0) 5415 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5416 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5417 return Res; 5418 } 5419 } 5420 5421 // Otherwise, expand to a libcall. 5422 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5423 } 5424 5425 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5426 SDValue LHS, SDValue RHS, SDValue Scale, 5427 SelectionDAG &DAG, const TargetLowering &TLI) { 5428 EVT VT = LHS.getValueType(); 5429 bool Signed = Opcode == ISD::SDIVFIX; 5430 LLVMContext &Ctx = *DAG.getContext(); 5431 5432 // If the type is legal but the operation isn't, this node might survive all 5433 // the way to operation legalization. If we end up there and we do not have 5434 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5435 // node. 5436 5437 // Coax the legalizer into expanding the node during type legalization instead 5438 // by bumping the size by one bit. This will force it to Promote, enabling the 5439 // early expansion and avoiding the need to expand later. 5440 5441 // We don't have to do this if Scale is 0; that can always be expanded. 5442 5443 // FIXME: We wouldn't have to do this (or any of the early 5444 // expansion/promotion) if it was possible to expand a libcall of an 5445 // illegal type during operation legalization. But it's not, so things 5446 // get a bit hacky. 5447 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5448 if (ScaleInt > 0 && 5449 (TLI.isTypeLegal(VT) || 5450 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5451 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5452 Opcode, VT, ScaleInt); 5453 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5454 EVT PromVT; 5455 if (VT.isScalarInteger()) 5456 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5457 else if (VT.isVector()) { 5458 PromVT = VT.getVectorElementType(); 5459 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5460 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5461 } else 5462 llvm_unreachable("Wrong VT for DIVFIX?"); 5463 if (Signed) { 5464 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5465 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5466 } else { 5467 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5468 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5469 } 5470 // TODO: Saturation. 5471 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5472 return DAG.getZExtOrTrunc(Res, DL, VT); 5473 } 5474 } 5475 5476 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5477 } 5478 5479 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5480 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5481 static void 5482 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs, 5483 const SDValue &N) { 5484 switch (N.getOpcode()) { 5485 case ISD::CopyFromReg: { 5486 SDValue Op = N.getOperand(1); 5487 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5488 Op.getValueType().getSizeInBits()); 5489 return; 5490 } 5491 case ISD::BITCAST: 5492 case ISD::AssertZext: 5493 case ISD::AssertSext: 5494 case ISD::TRUNCATE: 5495 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5496 return; 5497 case ISD::BUILD_PAIR: 5498 case ISD::BUILD_VECTOR: 5499 case ISD::CONCAT_VECTORS: 5500 for (SDValue Op : N->op_values()) 5501 getUnderlyingArgRegs(Regs, Op); 5502 return; 5503 default: 5504 return; 5505 } 5506 } 5507 5508 /// If the DbgValueInst is a dbg_value of a function argument, create the 5509 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5510 /// instruction selection, they will be inserted to the entry BB. 5511 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5512 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5513 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 5514 const Argument *Arg = dyn_cast<Argument>(V); 5515 if (!Arg) 5516 return false; 5517 5518 if (!IsDbgDeclare) { 5519 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5520 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5521 // the entry block. 5522 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5523 if (!IsInEntryBlock) 5524 return false; 5525 5526 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5527 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5528 // variable that also is a param. 5529 // 5530 // Although, if we are at the top of the entry block already, we can still 5531 // emit using ArgDbgValue. This might catch some situations when the 5532 // dbg.value refers to an argument that isn't used in the entry block, so 5533 // any CopyToReg node would be optimized out and the only way to express 5534 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5535 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5536 // we should only emit as ArgDbgValue if the Variable is an argument to the 5537 // current function, and the dbg.value intrinsic is found in the entry 5538 // block. 5539 bool VariableIsFunctionInputArg = Variable->isParameter() && 5540 !DL->getInlinedAt(); 5541 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5542 if (!IsInPrologue && !VariableIsFunctionInputArg) 5543 return false; 5544 5545 // Here we assume that a function argument on IR level only can be used to 5546 // describe one input parameter on source level. If we for example have 5547 // source code like this 5548 // 5549 // struct A { long x, y; }; 5550 // void foo(struct A a, long b) { 5551 // ... 5552 // b = a.x; 5553 // ... 5554 // } 5555 // 5556 // and IR like this 5557 // 5558 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5559 // entry: 5560 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5561 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5562 // call void @llvm.dbg.value(metadata i32 %b, "b", 5563 // ... 5564 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5565 // ... 5566 // 5567 // then the last dbg.value is describing a parameter "b" using a value that 5568 // is an argument. But since we already has used %a1 to describe a parameter 5569 // we should not handle that last dbg.value here (that would result in an 5570 // incorrect hoisting of the DBG_VALUE to the function entry). 5571 // Notice that we allow one dbg.value per IR level argument, to accommodate 5572 // for the situation with fragments above. 5573 if (VariableIsFunctionInputArg) { 5574 unsigned ArgNo = Arg->getArgNo(); 5575 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5576 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5577 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5578 return false; 5579 FuncInfo.DescribedArgs.set(ArgNo); 5580 } 5581 } 5582 5583 MachineFunction &MF = DAG.getMachineFunction(); 5584 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5585 5586 Optional<MachineOperand> Op; 5587 // Some arguments' frame index is recorded during argument lowering. 5588 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5589 if (FI != std::numeric_limits<int>::max()) 5590 Op = MachineOperand::CreateFI(FI); 5591 5592 SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes; 5593 if (!Op && N.getNode()) { 5594 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5595 Register Reg; 5596 if (ArgRegsAndSizes.size() == 1) 5597 Reg = ArgRegsAndSizes.front().first; 5598 5599 if (Reg && Reg.isVirtual()) { 5600 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5601 Register PR = RegInfo.getLiveInPhysReg(Reg); 5602 if (PR) 5603 Reg = PR; 5604 } 5605 if (Reg) { 5606 Op = MachineOperand::CreateReg(Reg, false); 5607 } 5608 } 5609 5610 if (!Op && N.getNode()) { 5611 // Check if frame index is available. 5612 SDValue LCandidate = peekThroughBitcasts(N); 5613 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5614 if (FrameIndexSDNode *FINode = 5615 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5616 Op = MachineOperand::CreateFI(FINode->getIndex()); 5617 } 5618 5619 if (!Op) { 5620 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5621 auto splitMultiRegDbgValue 5622 = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) { 5623 unsigned Offset = 0; 5624 for (auto RegAndSize : SplitRegs) { 5625 // If the expression is already a fragment, the current register 5626 // offset+size might extend beyond the fragment. In this case, only 5627 // the register bits that are inside the fragment are relevant. 5628 int RegFragmentSizeInBits = RegAndSize.second; 5629 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5630 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5631 // The register is entirely outside the expression fragment, 5632 // so is irrelevant for debug info. 5633 if (Offset >= ExprFragmentSizeInBits) 5634 break; 5635 // The register is partially outside the expression fragment, only 5636 // the low bits within the fragment are relevant for debug info. 5637 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5638 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5639 } 5640 } 5641 5642 auto FragmentExpr = DIExpression::createFragmentExpression( 5643 Expr, Offset, RegFragmentSizeInBits); 5644 Offset += RegAndSize.second; 5645 // If a valid fragment expression cannot be created, the variable's 5646 // correct value cannot be determined and so it is set as Undef. 5647 if (!FragmentExpr) { 5648 SDDbgValue *SDV = DAG.getConstantDbgValue( 5649 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5650 DAG.AddDbgValue(SDV, nullptr, false); 5651 continue; 5652 } 5653 assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?"); 5654 FuncInfo.ArgDbgValues.push_back( 5655 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), false, 5656 RegAndSize.first, Variable, *FragmentExpr)); 5657 } 5658 }; 5659 5660 // Check if ValueMap has reg number. 5661 DenseMap<const Value *, unsigned>::const_iterator 5662 VMI = FuncInfo.ValueMap.find(V); 5663 if (VMI != FuncInfo.ValueMap.end()) { 5664 const auto &TLI = DAG.getTargetLoweringInfo(); 5665 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5666 V->getType(), getABIRegCopyCC(V)); 5667 if (RFV.occupiesMultipleRegs()) { 5668 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5669 return true; 5670 } 5671 5672 Op = MachineOperand::CreateReg(VMI->second, false); 5673 } else if (ArgRegsAndSizes.size() > 1) { 5674 // This was split due to the calling convention, and no virtual register 5675 // mapping exists for the value. 5676 splitMultiRegDbgValue(ArgRegsAndSizes); 5677 return true; 5678 } 5679 } 5680 5681 if (!Op) 5682 return false; 5683 5684 assert(Variable->isValidLocationForIntrinsic(DL) && 5685 "Expected inlined-at fields to agree"); 5686 5687 // If the argument arrives in a stack slot, then what the IR thought was a 5688 // normal Value is actually in memory, and we must add a deref to load it. 5689 if (Op->isFI()) { 5690 int FI = Op->getIndex(); 5691 unsigned Size = DAG.getMachineFunction().getFrameInfo().getObjectSize(FI); 5692 if (Expr->isImplicit()) { 5693 SmallVector<uint64_t, 2> Ops = {dwarf::DW_OP_deref_size, Size}; 5694 Expr = DIExpression::prependOpcodes(Expr, Ops); 5695 } else { 5696 Expr = DIExpression::prepend(Expr, DIExpression::DerefBefore); 5697 } 5698 } 5699 5700 // If this location was specified with a dbg.declare, then it and its 5701 // expression calculate the address of the variable. Append a deref to 5702 // force it to be a memory location. 5703 if (IsDbgDeclare) 5704 Expr = DIExpression::append(Expr, {dwarf::DW_OP_deref}); 5705 5706 FuncInfo.ArgDbgValues.push_back( 5707 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), false, 5708 *Op, Variable, Expr)); 5709 5710 return true; 5711 } 5712 5713 /// Return the appropriate SDDbgValue based on N. 5714 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5715 DILocalVariable *Variable, 5716 DIExpression *Expr, 5717 const DebugLoc &dl, 5718 unsigned DbgSDNodeOrder) { 5719 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5720 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5721 // stack slot locations. 5722 // 5723 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5724 // debug values here after optimization: 5725 // 5726 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5727 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5728 // 5729 // Both describe the direct values of their associated variables. 5730 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5731 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5732 } 5733 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5734 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5735 } 5736 5737 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5738 switch (Intrinsic) { 5739 case Intrinsic::smul_fix: 5740 return ISD::SMULFIX; 5741 case Intrinsic::umul_fix: 5742 return ISD::UMULFIX; 5743 case Intrinsic::smul_fix_sat: 5744 return ISD::SMULFIXSAT; 5745 case Intrinsic::umul_fix_sat: 5746 return ISD::UMULFIXSAT; 5747 case Intrinsic::sdiv_fix: 5748 return ISD::SDIVFIX; 5749 case Intrinsic::udiv_fix: 5750 return ISD::UDIVFIX; 5751 default: 5752 llvm_unreachable("Unhandled fixed point intrinsic"); 5753 } 5754 } 5755 5756 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5757 const char *FunctionName) { 5758 assert(FunctionName && "FunctionName must not be nullptr"); 5759 SDValue Callee = DAG.getExternalSymbol( 5760 FunctionName, 5761 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5762 LowerCallTo(&I, Callee, I.isTailCall()); 5763 } 5764 5765 /// Lower the call to the specified intrinsic function. 5766 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5767 unsigned Intrinsic) { 5768 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5769 SDLoc sdl = getCurSDLoc(); 5770 DebugLoc dl = getCurDebugLoc(); 5771 SDValue Res; 5772 5773 switch (Intrinsic) { 5774 default: 5775 // By default, turn this into a target intrinsic node. 5776 visitTargetIntrinsic(I, Intrinsic); 5777 return; 5778 case Intrinsic::vscale: { 5779 match(&I, m_VScale(DAG.getDataLayout())); 5780 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5781 setValue(&I, 5782 DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1))); 5783 return; 5784 } 5785 case Intrinsic::vastart: visitVAStart(I); return; 5786 case Intrinsic::vaend: visitVAEnd(I); return; 5787 case Intrinsic::vacopy: visitVACopy(I); return; 5788 case Intrinsic::returnaddress: 5789 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5790 TLI.getPointerTy(DAG.getDataLayout()), 5791 getValue(I.getArgOperand(0)))); 5792 return; 5793 case Intrinsic::addressofreturnaddress: 5794 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5795 TLI.getPointerTy(DAG.getDataLayout()))); 5796 return; 5797 case Intrinsic::sponentry: 5798 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5799 TLI.getFrameIndexTy(DAG.getDataLayout()))); 5800 return; 5801 case Intrinsic::frameaddress: 5802 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5803 TLI.getFrameIndexTy(DAG.getDataLayout()), 5804 getValue(I.getArgOperand(0)))); 5805 return; 5806 case Intrinsic::read_register: { 5807 Value *Reg = I.getArgOperand(0); 5808 SDValue Chain = getRoot(); 5809 SDValue RegName = 5810 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5811 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5812 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5813 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5814 setValue(&I, Res); 5815 DAG.setRoot(Res.getValue(1)); 5816 return; 5817 } 5818 case Intrinsic::write_register: { 5819 Value *Reg = I.getArgOperand(0); 5820 Value *RegValue = I.getArgOperand(1); 5821 SDValue Chain = getRoot(); 5822 SDValue RegName = 5823 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5824 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5825 RegName, getValue(RegValue))); 5826 return; 5827 } 5828 case Intrinsic::memcpy: { 5829 const auto &MCI = cast<MemCpyInst>(I); 5830 SDValue Op1 = getValue(I.getArgOperand(0)); 5831 SDValue Op2 = getValue(I.getArgOperand(1)); 5832 SDValue Op3 = getValue(I.getArgOperand(2)); 5833 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5834 unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1); 5835 unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1); 5836 unsigned Align = MinAlign(DstAlign, SrcAlign); 5837 bool isVol = MCI.isVolatile(); 5838 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5839 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5840 // node. 5841 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5842 SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Align, isVol, 5843 /* AlwaysInline */ false, isTC, 5844 MachinePointerInfo(I.getArgOperand(0)), 5845 MachinePointerInfo(I.getArgOperand(1))); 5846 updateDAGForMaybeTailCall(MC); 5847 return; 5848 } 5849 case Intrinsic::memcpy_inline: { 5850 const auto &MCI = cast<MemCpyInlineInst>(I); 5851 SDValue Dst = getValue(I.getArgOperand(0)); 5852 SDValue Src = getValue(I.getArgOperand(1)); 5853 SDValue Size = getValue(I.getArgOperand(2)); 5854 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 5855 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 5856 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5857 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5858 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5859 bool isVol = MCI.isVolatile(); 5860 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5861 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5862 // node. 5863 SDValue MC = DAG.getMemcpy( 5864 getRoot(), sdl, Dst, Src, Size, Alignment.value(), isVol, 5865 /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)), 5866 MachinePointerInfo(I.getArgOperand(1))); 5867 updateDAGForMaybeTailCall(MC); 5868 return; 5869 } 5870 case Intrinsic::memset: { 5871 const auto &MSI = cast<MemSetInst>(I); 5872 SDValue Op1 = getValue(I.getArgOperand(0)); 5873 SDValue Op2 = getValue(I.getArgOperand(1)); 5874 SDValue Op3 = getValue(I.getArgOperand(2)); 5875 // @llvm.memset defines 0 and 1 to both mean no alignment. 5876 unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1); 5877 bool isVol = MSI.isVolatile(); 5878 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5879 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5880 SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Align, isVol, 5881 isTC, MachinePointerInfo(I.getArgOperand(0))); 5882 updateDAGForMaybeTailCall(MS); 5883 return; 5884 } 5885 case Intrinsic::memmove: { 5886 const auto &MMI = cast<MemMoveInst>(I); 5887 SDValue Op1 = getValue(I.getArgOperand(0)); 5888 SDValue Op2 = getValue(I.getArgOperand(1)); 5889 SDValue Op3 = getValue(I.getArgOperand(2)); 5890 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5891 unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1); 5892 unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1); 5893 unsigned Align = MinAlign(DstAlign, SrcAlign); 5894 bool isVol = MMI.isVolatile(); 5895 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5896 // FIXME: Support passing different dest/src alignments to the memmove DAG 5897 // node. 5898 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5899 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Align, isVol, 5900 isTC, MachinePointerInfo(I.getArgOperand(0)), 5901 MachinePointerInfo(I.getArgOperand(1))); 5902 updateDAGForMaybeTailCall(MM); 5903 return; 5904 } 5905 case Intrinsic::memcpy_element_unordered_atomic: { 5906 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5907 SDValue Dst = getValue(MI.getRawDest()); 5908 SDValue Src = getValue(MI.getRawSource()); 5909 SDValue Length = getValue(MI.getLength()); 5910 5911 unsigned DstAlign = MI.getDestAlignment(); 5912 unsigned SrcAlign = MI.getSourceAlignment(); 5913 Type *LengthTy = MI.getLength()->getType(); 5914 unsigned ElemSz = MI.getElementSizeInBytes(); 5915 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5916 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5917 SrcAlign, Length, LengthTy, ElemSz, isTC, 5918 MachinePointerInfo(MI.getRawDest()), 5919 MachinePointerInfo(MI.getRawSource())); 5920 updateDAGForMaybeTailCall(MC); 5921 return; 5922 } 5923 case Intrinsic::memmove_element_unordered_atomic: { 5924 auto &MI = cast<AtomicMemMoveInst>(I); 5925 SDValue Dst = getValue(MI.getRawDest()); 5926 SDValue Src = getValue(MI.getRawSource()); 5927 SDValue Length = getValue(MI.getLength()); 5928 5929 unsigned DstAlign = MI.getDestAlignment(); 5930 unsigned SrcAlign = MI.getSourceAlignment(); 5931 Type *LengthTy = MI.getLength()->getType(); 5932 unsigned ElemSz = MI.getElementSizeInBytes(); 5933 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5934 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5935 SrcAlign, Length, LengthTy, ElemSz, isTC, 5936 MachinePointerInfo(MI.getRawDest()), 5937 MachinePointerInfo(MI.getRawSource())); 5938 updateDAGForMaybeTailCall(MC); 5939 return; 5940 } 5941 case Intrinsic::memset_element_unordered_atomic: { 5942 auto &MI = cast<AtomicMemSetInst>(I); 5943 SDValue Dst = getValue(MI.getRawDest()); 5944 SDValue Val = getValue(MI.getValue()); 5945 SDValue Length = getValue(MI.getLength()); 5946 5947 unsigned DstAlign = MI.getDestAlignment(); 5948 Type *LengthTy = MI.getLength()->getType(); 5949 unsigned ElemSz = MI.getElementSizeInBytes(); 5950 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5951 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5952 LengthTy, ElemSz, isTC, 5953 MachinePointerInfo(MI.getRawDest())); 5954 updateDAGForMaybeTailCall(MC); 5955 return; 5956 } 5957 case Intrinsic::dbg_addr: 5958 case Intrinsic::dbg_declare: { 5959 const auto &DI = cast<DbgVariableIntrinsic>(I); 5960 DILocalVariable *Variable = DI.getVariable(); 5961 DIExpression *Expression = DI.getExpression(); 5962 dropDanglingDebugInfo(Variable, Expression); 5963 assert(Variable && "Missing variable"); 5964 5965 // Check if address has undef value. 5966 const Value *Address = DI.getVariableLocation(); 5967 if (!Address || isa<UndefValue>(Address) || 5968 (Address->use_empty() && !isa<Argument>(Address))) { 5969 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5970 return; 5971 } 5972 5973 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5974 5975 // Check if this variable can be described by a frame index, typically 5976 // either as a static alloca or a byval parameter. 5977 int FI = std::numeric_limits<int>::max(); 5978 if (const auto *AI = 5979 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5980 if (AI->isStaticAlloca()) { 5981 auto I = FuncInfo.StaticAllocaMap.find(AI); 5982 if (I != FuncInfo.StaticAllocaMap.end()) 5983 FI = I->second; 5984 } 5985 } else if (const auto *Arg = dyn_cast<Argument>( 5986 Address->stripInBoundsConstantOffsets())) { 5987 FI = FuncInfo.getArgumentFrameIndex(Arg); 5988 } 5989 5990 // llvm.dbg.addr is control dependent and always generates indirect 5991 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5992 // the MachineFunction variable table. 5993 if (FI != std::numeric_limits<int>::max()) { 5994 if (Intrinsic == Intrinsic::dbg_addr) { 5995 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 5996 Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder); 5997 DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter); 5998 } 5999 return; 6000 } 6001 6002 SDValue &N = NodeMap[Address]; 6003 if (!N.getNode() && isa<Argument>(Address)) 6004 // Check unused arguments map. 6005 N = UnusedArgNodeMap[Address]; 6006 SDDbgValue *SDV; 6007 if (N.getNode()) { 6008 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 6009 Address = BCI->getOperand(0); 6010 // Parameters are handled specially. 6011 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 6012 if (isParameter && FINode) { 6013 // Byval parameter. We have a frame index at this point. 6014 SDV = 6015 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 6016 /*IsIndirect*/ true, dl, SDNodeOrder); 6017 } else if (isa<Argument>(Address)) { 6018 // Address is an argument, so try to emit its dbg value using 6019 // virtual register info from the FuncInfo.ValueMap. 6020 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 6021 return; 6022 } else { 6023 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 6024 true, dl, SDNodeOrder); 6025 } 6026 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 6027 } else { 6028 // If Address is an argument then try to emit its dbg value using 6029 // virtual register info from the FuncInfo.ValueMap. 6030 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 6031 N)) { 6032 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 6033 } 6034 } 6035 return; 6036 } 6037 case Intrinsic::dbg_label: { 6038 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6039 DILabel *Label = DI.getLabel(); 6040 assert(Label && "Missing label"); 6041 6042 SDDbgLabel *SDV; 6043 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6044 DAG.AddDbgLabel(SDV); 6045 return; 6046 } 6047 case Intrinsic::dbg_value: { 6048 const DbgValueInst &DI = cast<DbgValueInst>(I); 6049 assert(DI.getVariable() && "Missing variable"); 6050 6051 DILocalVariable *Variable = DI.getVariable(); 6052 DIExpression *Expression = DI.getExpression(); 6053 dropDanglingDebugInfo(Variable, Expression); 6054 const Value *V = DI.getValue(); 6055 if (!V) 6056 return; 6057 6058 if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(), 6059 SDNodeOrder)) 6060 return; 6061 6062 // TODO: Dangling debug info will eventually either be resolved or produce 6063 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 6064 // between the original dbg.value location and its resolved DBG_VALUE, which 6065 // we should ideally fill with an extra Undef DBG_VALUE. 6066 6067 DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder); 6068 return; 6069 } 6070 6071 case Intrinsic::eh_typeid_for: { 6072 // Find the type id for the given typeinfo. 6073 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6074 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6075 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6076 setValue(&I, Res); 6077 return; 6078 } 6079 6080 case Intrinsic::eh_return_i32: 6081 case Intrinsic::eh_return_i64: 6082 DAG.getMachineFunction().setCallsEHReturn(true); 6083 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6084 MVT::Other, 6085 getControlRoot(), 6086 getValue(I.getArgOperand(0)), 6087 getValue(I.getArgOperand(1)))); 6088 return; 6089 case Intrinsic::eh_unwind_init: 6090 DAG.getMachineFunction().setCallsUnwindInit(true); 6091 return; 6092 case Intrinsic::eh_dwarf_cfa: 6093 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6094 TLI.getPointerTy(DAG.getDataLayout()), 6095 getValue(I.getArgOperand(0)))); 6096 return; 6097 case Intrinsic::eh_sjlj_callsite: { 6098 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6099 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 6100 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 6101 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6102 6103 MMI.setCurrentCallSite(CI->getZExtValue()); 6104 return; 6105 } 6106 case Intrinsic::eh_sjlj_functioncontext: { 6107 // Get and store the index of the function context. 6108 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6109 AllocaInst *FnCtx = 6110 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6111 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6112 MFI.setFunctionContextIndex(FI); 6113 return; 6114 } 6115 case Intrinsic::eh_sjlj_setjmp: { 6116 SDValue Ops[2]; 6117 Ops[0] = getRoot(); 6118 Ops[1] = getValue(I.getArgOperand(0)); 6119 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6120 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6121 setValue(&I, Op.getValue(0)); 6122 DAG.setRoot(Op.getValue(1)); 6123 return; 6124 } 6125 case Intrinsic::eh_sjlj_longjmp: 6126 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6127 getRoot(), getValue(I.getArgOperand(0)))); 6128 return; 6129 case Intrinsic::eh_sjlj_setup_dispatch: 6130 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6131 getRoot())); 6132 return; 6133 case Intrinsic::masked_gather: 6134 visitMaskedGather(I); 6135 return; 6136 case Intrinsic::masked_load: 6137 visitMaskedLoad(I); 6138 return; 6139 case Intrinsic::masked_scatter: 6140 visitMaskedScatter(I); 6141 return; 6142 case Intrinsic::masked_store: 6143 visitMaskedStore(I); 6144 return; 6145 case Intrinsic::masked_expandload: 6146 visitMaskedLoad(I, true /* IsExpanding */); 6147 return; 6148 case Intrinsic::masked_compressstore: 6149 visitMaskedStore(I, true /* IsCompressing */); 6150 return; 6151 case Intrinsic::powi: 6152 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6153 getValue(I.getArgOperand(1)), DAG)); 6154 return; 6155 case Intrinsic::log: 6156 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6157 return; 6158 case Intrinsic::log2: 6159 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6160 return; 6161 case Intrinsic::log10: 6162 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6163 return; 6164 case Intrinsic::exp: 6165 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6166 return; 6167 case Intrinsic::exp2: 6168 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6169 return; 6170 case Intrinsic::pow: 6171 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6172 getValue(I.getArgOperand(1)), DAG, TLI)); 6173 return; 6174 case Intrinsic::sqrt: 6175 case Intrinsic::fabs: 6176 case Intrinsic::sin: 6177 case Intrinsic::cos: 6178 case Intrinsic::floor: 6179 case Intrinsic::ceil: 6180 case Intrinsic::trunc: 6181 case Intrinsic::rint: 6182 case Intrinsic::nearbyint: 6183 case Intrinsic::round: 6184 case Intrinsic::canonicalize: { 6185 unsigned Opcode; 6186 switch (Intrinsic) { 6187 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6188 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6189 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6190 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6191 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6192 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6193 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6194 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6195 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6196 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6197 case Intrinsic::round: Opcode = ISD::FROUND; break; 6198 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6199 } 6200 6201 setValue(&I, DAG.getNode(Opcode, sdl, 6202 getValue(I.getArgOperand(0)).getValueType(), 6203 getValue(I.getArgOperand(0)))); 6204 return; 6205 } 6206 case Intrinsic::lround: 6207 case Intrinsic::llround: 6208 case Intrinsic::lrint: 6209 case Intrinsic::llrint: { 6210 unsigned Opcode; 6211 switch (Intrinsic) { 6212 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6213 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6214 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6215 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6216 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6217 } 6218 6219 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6220 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6221 getValue(I.getArgOperand(0)))); 6222 return; 6223 } 6224 case Intrinsic::minnum: 6225 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6226 getValue(I.getArgOperand(0)).getValueType(), 6227 getValue(I.getArgOperand(0)), 6228 getValue(I.getArgOperand(1)))); 6229 return; 6230 case Intrinsic::maxnum: 6231 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6232 getValue(I.getArgOperand(0)).getValueType(), 6233 getValue(I.getArgOperand(0)), 6234 getValue(I.getArgOperand(1)))); 6235 return; 6236 case Intrinsic::minimum: 6237 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6238 getValue(I.getArgOperand(0)).getValueType(), 6239 getValue(I.getArgOperand(0)), 6240 getValue(I.getArgOperand(1)))); 6241 return; 6242 case Intrinsic::maximum: 6243 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6244 getValue(I.getArgOperand(0)).getValueType(), 6245 getValue(I.getArgOperand(0)), 6246 getValue(I.getArgOperand(1)))); 6247 return; 6248 case Intrinsic::copysign: 6249 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6250 getValue(I.getArgOperand(0)).getValueType(), 6251 getValue(I.getArgOperand(0)), 6252 getValue(I.getArgOperand(1)))); 6253 return; 6254 case Intrinsic::fma: 6255 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6256 getValue(I.getArgOperand(0)).getValueType(), 6257 getValue(I.getArgOperand(0)), 6258 getValue(I.getArgOperand(1)), 6259 getValue(I.getArgOperand(2)))); 6260 return; 6261 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6262 case Intrinsic::INTRINSIC: 6263 #include "llvm/IR/ConstrainedOps.def" 6264 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6265 return; 6266 case Intrinsic::fmuladd: { 6267 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6268 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6269 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6270 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6271 getValue(I.getArgOperand(0)).getValueType(), 6272 getValue(I.getArgOperand(0)), 6273 getValue(I.getArgOperand(1)), 6274 getValue(I.getArgOperand(2)))); 6275 } else { 6276 // TODO: Intrinsic calls should have fast-math-flags. 6277 SDValue Mul = DAG.getNode(ISD::FMUL, sdl, 6278 getValue(I.getArgOperand(0)).getValueType(), 6279 getValue(I.getArgOperand(0)), 6280 getValue(I.getArgOperand(1))); 6281 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6282 getValue(I.getArgOperand(0)).getValueType(), 6283 Mul, 6284 getValue(I.getArgOperand(2))); 6285 setValue(&I, Add); 6286 } 6287 return; 6288 } 6289 case Intrinsic::convert_to_fp16: 6290 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6291 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6292 getValue(I.getArgOperand(0)), 6293 DAG.getTargetConstant(0, sdl, 6294 MVT::i32)))); 6295 return; 6296 case Intrinsic::convert_from_fp16: 6297 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6298 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6299 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6300 getValue(I.getArgOperand(0))))); 6301 return; 6302 case Intrinsic::pcmarker: { 6303 SDValue Tmp = getValue(I.getArgOperand(0)); 6304 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6305 return; 6306 } 6307 case Intrinsic::readcyclecounter: { 6308 SDValue Op = getRoot(); 6309 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6310 DAG.getVTList(MVT::i64, MVT::Other), Op); 6311 setValue(&I, Res); 6312 DAG.setRoot(Res.getValue(1)); 6313 return; 6314 } 6315 case Intrinsic::bitreverse: 6316 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6317 getValue(I.getArgOperand(0)).getValueType(), 6318 getValue(I.getArgOperand(0)))); 6319 return; 6320 case Intrinsic::bswap: 6321 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6322 getValue(I.getArgOperand(0)).getValueType(), 6323 getValue(I.getArgOperand(0)))); 6324 return; 6325 case Intrinsic::cttz: { 6326 SDValue Arg = getValue(I.getArgOperand(0)); 6327 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6328 EVT Ty = Arg.getValueType(); 6329 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6330 sdl, Ty, Arg)); 6331 return; 6332 } 6333 case Intrinsic::ctlz: { 6334 SDValue Arg = getValue(I.getArgOperand(0)); 6335 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6336 EVT Ty = Arg.getValueType(); 6337 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6338 sdl, Ty, Arg)); 6339 return; 6340 } 6341 case Intrinsic::ctpop: { 6342 SDValue Arg = getValue(I.getArgOperand(0)); 6343 EVT Ty = Arg.getValueType(); 6344 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6345 return; 6346 } 6347 case Intrinsic::fshl: 6348 case Intrinsic::fshr: { 6349 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6350 SDValue X = getValue(I.getArgOperand(0)); 6351 SDValue Y = getValue(I.getArgOperand(1)); 6352 SDValue Z = getValue(I.getArgOperand(2)); 6353 EVT VT = X.getValueType(); 6354 SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT); 6355 SDValue Zero = DAG.getConstant(0, sdl, VT); 6356 SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC); 6357 6358 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6359 if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) { 6360 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6361 return; 6362 } 6363 6364 // When X == Y, this is rotate. If the data type has a power-of-2 size, we 6365 // avoid the select that is necessary in the general case to filter out 6366 // the 0-shift possibility that leads to UB. 6367 if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) { 6368 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6369 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 6370 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6371 return; 6372 } 6373 6374 // Some targets only rotate one way. Try the opposite direction. 6375 RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL; 6376 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 6377 // Negate the shift amount because it is safe to ignore the high bits. 6378 SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 6379 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt)); 6380 return; 6381 } 6382 6383 // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW)) 6384 // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW)) 6385 SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 6386 SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC); 6387 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt); 6388 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt); 6389 setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY)); 6390 return; 6391 } 6392 6393 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 6394 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 6395 SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt); 6396 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt); 6397 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt); 6398 SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY); 6399 6400 // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth, 6401 // and that is undefined. We must compare and select to avoid UB. 6402 EVT CCVT = MVT::i1; 6403 if (VT.isVector()) 6404 CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements()); 6405 6406 // For fshl, 0-shift returns the 1st arg (X). 6407 // For fshr, 0-shift returns the 2nd arg (Y). 6408 SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ); 6409 setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or)); 6410 return; 6411 } 6412 case Intrinsic::sadd_sat: { 6413 SDValue Op1 = getValue(I.getArgOperand(0)); 6414 SDValue Op2 = getValue(I.getArgOperand(1)); 6415 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6416 return; 6417 } 6418 case Intrinsic::uadd_sat: { 6419 SDValue Op1 = getValue(I.getArgOperand(0)); 6420 SDValue Op2 = getValue(I.getArgOperand(1)); 6421 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6422 return; 6423 } 6424 case Intrinsic::ssub_sat: { 6425 SDValue Op1 = getValue(I.getArgOperand(0)); 6426 SDValue Op2 = getValue(I.getArgOperand(1)); 6427 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6428 return; 6429 } 6430 case Intrinsic::usub_sat: { 6431 SDValue Op1 = getValue(I.getArgOperand(0)); 6432 SDValue Op2 = getValue(I.getArgOperand(1)); 6433 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6434 return; 6435 } 6436 case Intrinsic::smul_fix: 6437 case Intrinsic::umul_fix: 6438 case Intrinsic::smul_fix_sat: 6439 case Intrinsic::umul_fix_sat: { 6440 SDValue Op1 = getValue(I.getArgOperand(0)); 6441 SDValue Op2 = getValue(I.getArgOperand(1)); 6442 SDValue Op3 = getValue(I.getArgOperand(2)); 6443 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6444 Op1.getValueType(), Op1, Op2, Op3)); 6445 return; 6446 } 6447 case Intrinsic::sdiv_fix: 6448 case Intrinsic::udiv_fix: { 6449 SDValue Op1 = getValue(I.getArgOperand(0)); 6450 SDValue Op2 = getValue(I.getArgOperand(1)); 6451 SDValue Op3 = getValue(I.getArgOperand(2)); 6452 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6453 Op1, Op2, Op3, DAG, TLI)); 6454 return; 6455 } 6456 case Intrinsic::stacksave: { 6457 SDValue Op = getRoot(); 6458 Res = DAG.getNode( 6459 ISD::STACKSAVE, sdl, 6460 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op); 6461 setValue(&I, Res); 6462 DAG.setRoot(Res.getValue(1)); 6463 return; 6464 } 6465 case Intrinsic::stackrestore: 6466 Res = getValue(I.getArgOperand(0)); 6467 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6468 return; 6469 case Intrinsic::get_dynamic_area_offset: { 6470 SDValue Op = getRoot(); 6471 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6472 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6473 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6474 // target. 6475 if (PtrTy.getSizeInBits() < ResTy.getSizeInBits()) 6476 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6477 " intrinsic!"); 6478 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6479 Op); 6480 DAG.setRoot(Op); 6481 setValue(&I, Res); 6482 return; 6483 } 6484 case Intrinsic::stackguard: { 6485 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6486 MachineFunction &MF = DAG.getMachineFunction(); 6487 const Module &M = *MF.getFunction().getParent(); 6488 SDValue Chain = getRoot(); 6489 if (TLI.useLoadStackGuardNode()) { 6490 Res = getLoadStackGuard(DAG, sdl, Chain); 6491 } else { 6492 const Value *Global = TLI.getSDagStackGuard(M); 6493 unsigned Align = DL->getPrefTypeAlignment(Global->getType()); 6494 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6495 MachinePointerInfo(Global, 0), Align, 6496 MachineMemOperand::MOVolatile); 6497 } 6498 if (TLI.useStackGuardXorFP()) 6499 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6500 DAG.setRoot(Chain); 6501 setValue(&I, Res); 6502 return; 6503 } 6504 case Intrinsic::stackprotector: { 6505 // Emit code into the DAG to store the stack guard onto the stack. 6506 MachineFunction &MF = DAG.getMachineFunction(); 6507 MachineFrameInfo &MFI = MF.getFrameInfo(); 6508 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6509 SDValue Src, Chain = getRoot(); 6510 6511 if (TLI.useLoadStackGuardNode()) 6512 Src = getLoadStackGuard(DAG, sdl, Chain); 6513 else 6514 Src = getValue(I.getArgOperand(0)); // The guard's value. 6515 6516 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6517 6518 int FI = FuncInfo.StaticAllocaMap[Slot]; 6519 MFI.setStackProtectorIndex(FI); 6520 6521 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6522 6523 // Store the stack protector onto the stack. 6524 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack( 6525 DAG.getMachineFunction(), FI), 6526 /* Alignment = */ 0, MachineMemOperand::MOVolatile); 6527 setValue(&I, Res); 6528 DAG.setRoot(Res); 6529 return; 6530 } 6531 case Intrinsic::objectsize: 6532 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6533 6534 case Intrinsic::is_constant: 6535 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6536 6537 case Intrinsic::annotation: 6538 case Intrinsic::ptr_annotation: 6539 case Intrinsic::launder_invariant_group: 6540 case Intrinsic::strip_invariant_group: 6541 // Drop the intrinsic, but forward the value 6542 setValue(&I, getValue(I.getOperand(0))); 6543 return; 6544 case Intrinsic::assume: 6545 case Intrinsic::var_annotation: 6546 case Intrinsic::sideeffect: 6547 // Discard annotate attributes, assumptions, and artificial side-effects. 6548 return; 6549 6550 case Intrinsic::codeview_annotation: { 6551 // Emit a label associated with this metadata. 6552 MachineFunction &MF = DAG.getMachineFunction(); 6553 MCSymbol *Label = 6554 MF.getMMI().getContext().createTempSymbol("annotation", true); 6555 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6556 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6557 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6558 DAG.setRoot(Res); 6559 return; 6560 } 6561 6562 case Intrinsic::init_trampoline: { 6563 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6564 6565 SDValue Ops[6]; 6566 Ops[0] = getRoot(); 6567 Ops[1] = getValue(I.getArgOperand(0)); 6568 Ops[2] = getValue(I.getArgOperand(1)); 6569 Ops[3] = getValue(I.getArgOperand(2)); 6570 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6571 Ops[5] = DAG.getSrcValue(F); 6572 6573 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6574 6575 DAG.setRoot(Res); 6576 return; 6577 } 6578 case Intrinsic::adjust_trampoline: 6579 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6580 TLI.getPointerTy(DAG.getDataLayout()), 6581 getValue(I.getArgOperand(0)))); 6582 return; 6583 case Intrinsic::gcroot: { 6584 assert(DAG.getMachineFunction().getFunction().hasGC() && 6585 "only valid in functions with gc specified, enforced by Verifier"); 6586 assert(GFI && "implied by previous"); 6587 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6588 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6589 6590 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6591 GFI->addStackRoot(FI->getIndex(), TypeMap); 6592 return; 6593 } 6594 case Intrinsic::gcread: 6595 case Intrinsic::gcwrite: 6596 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6597 case Intrinsic::flt_rounds: 6598 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32)); 6599 return; 6600 6601 case Intrinsic::expect: 6602 // Just replace __builtin_expect(exp, c) with EXP. 6603 setValue(&I, getValue(I.getArgOperand(0))); 6604 return; 6605 6606 case Intrinsic::debugtrap: 6607 case Intrinsic::trap: { 6608 StringRef TrapFuncName = 6609 I.getAttributes() 6610 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6611 .getValueAsString(); 6612 if (TrapFuncName.empty()) { 6613 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 6614 ISD::TRAP : ISD::DEBUGTRAP; 6615 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 6616 return; 6617 } 6618 TargetLowering::ArgListTy Args; 6619 6620 TargetLowering::CallLoweringInfo CLI(DAG); 6621 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6622 CallingConv::C, I.getType(), 6623 DAG.getExternalSymbol(TrapFuncName.data(), 6624 TLI.getPointerTy(DAG.getDataLayout())), 6625 std::move(Args)); 6626 6627 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6628 DAG.setRoot(Result.second); 6629 return; 6630 } 6631 6632 case Intrinsic::uadd_with_overflow: 6633 case Intrinsic::sadd_with_overflow: 6634 case Intrinsic::usub_with_overflow: 6635 case Intrinsic::ssub_with_overflow: 6636 case Intrinsic::umul_with_overflow: 6637 case Intrinsic::smul_with_overflow: { 6638 ISD::NodeType Op; 6639 switch (Intrinsic) { 6640 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6641 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6642 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6643 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6644 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6645 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6646 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6647 } 6648 SDValue Op1 = getValue(I.getArgOperand(0)); 6649 SDValue Op2 = getValue(I.getArgOperand(1)); 6650 6651 EVT ResultVT = Op1.getValueType(); 6652 EVT OverflowVT = MVT::i1; 6653 if (ResultVT.isVector()) 6654 OverflowVT = EVT::getVectorVT( 6655 *Context, OverflowVT, ResultVT.getVectorNumElements()); 6656 6657 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6658 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6659 return; 6660 } 6661 case Intrinsic::prefetch: { 6662 SDValue Ops[5]; 6663 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6664 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6665 Ops[0] = DAG.getRoot(); 6666 Ops[1] = getValue(I.getArgOperand(0)); 6667 Ops[2] = getValue(I.getArgOperand(1)); 6668 Ops[3] = getValue(I.getArgOperand(2)); 6669 Ops[4] = getValue(I.getArgOperand(3)); 6670 SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl, 6671 DAG.getVTList(MVT::Other), Ops, 6672 EVT::getIntegerVT(*Context, 8), 6673 MachinePointerInfo(I.getArgOperand(0)), 6674 0, /* align */ 6675 Flags); 6676 6677 // Chain the prefetch in parallell with any pending loads, to stay out of 6678 // the way of later optimizations. 6679 PendingLoads.push_back(Result); 6680 Result = getRoot(); 6681 DAG.setRoot(Result); 6682 return; 6683 } 6684 case Intrinsic::lifetime_start: 6685 case Intrinsic::lifetime_end: { 6686 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6687 // Stack coloring is not enabled in O0, discard region information. 6688 if (TM.getOptLevel() == CodeGenOpt::None) 6689 return; 6690 6691 const int64_t ObjectSize = 6692 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6693 Value *const ObjectPtr = I.getArgOperand(1); 6694 SmallVector<const Value *, 4> Allocas; 6695 GetUnderlyingObjects(ObjectPtr, Allocas, *DL); 6696 6697 for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(), 6698 E = Allocas.end(); Object != E; ++Object) { 6699 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 6700 6701 // Could not find an Alloca. 6702 if (!LifetimeObject) 6703 continue; 6704 6705 // First check that the Alloca is static, otherwise it won't have a 6706 // valid frame index. 6707 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6708 if (SI == FuncInfo.StaticAllocaMap.end()) 6709 return; 6710 6711 const int FrameIndex = SI->second; 6712 int64_t Offset; 6713 if (GetPointerBaseWithConstantOffset( 6714 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6715 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6716 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6717 Offset); 6718 DAG.setRoot(Res); 6719 } 6720 return; 6721 } 6722 case Intrinsic::invariant_start: 6723 // Discard region information. 6724 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6725 return; 6726 case Intrinsic::invariant_end: 6727 // Discard region information. 6728 return; 6729 case Intrinsic::clear_cache: 6730 /// FunctionName may be null. 6731 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6732 lowerCallToExternalSymbol(I, FunctionName); 6733 return; 6734 case Intrinsic::donothing: 6735 // ignore 6736 return; 6737 case Intrinsic::experimental_stackmap: 6738 visitStackmap(I); 6739 return; 6740 case Intrinsic::experimental_patchpoint_void: 6741 case Intrinsic::experimental_patchpoint_i64: 6742 visitPatchpoint(&I); 6743 return; 6744 case Intrinsic::experimental_gc_statepoint: 6745 LowerStatepoint(ImmutableStatepoint(&I)); 6746 return; 6747 case Intrinsic::experimental_gc_result: 6748 visitGCResult(cast<GCResultInst>(I)); 6749 return; 6750 case Intrinsic::experimental_gc_relocate: 6751 visitGCRelocate(cast<GCRelocateInst>(I)); 6752 return; 6753 case Intrinsic::instrprof_increment: 6754 llvm_unreachable("instrprof failed to lower an increment"); 6755 case Intrinsic::instrprof_value_profile: 6756 llvm_unreachable("instrprof failed to lower a value profiling call"); 6757 case Intrinsic::localescape: { 6758 MachineFunction &MF = DAG.getMachineFunction(); 6759 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6760 6761 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6762 // is the same on all targets. 6763 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6764 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6765 if (isa<ConstantPointerNull>(Arg)) 6766 continue; // Skip null pointers. They represent a hole in index space. 6767 AllocaInst *Slot = cast<AllocaInst>(Arg); 6768 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6769 "can only escape static allocas"); 6770 int FI = FuncInfo.StaticAllocaMap[Slot]; 6771 MCSymbol *FrameAllocSym = 6772 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6773 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6774 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6775 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6776 .addSym(FrameAllocSym) 6777 .addFrameIndex(FI); 6778 } 6779 6780 return; 6781 } 6782 6783 case Intrinsic::localrecover: { 6784 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6785 MachineFunction &MF = DAG.getMachineFunction(); 6786 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0); 6787 6788 // Get the symbol that defines the frame offset. 6789 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6790 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6791 unsigned IdxVal = 6792 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6793 MCSymbol *FrameAllocSym = 6794 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6795 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6796 6797 // Create a MCSymbol for the label to avoid any target lowering 6798 // that would make this PC relative. 6799 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6800 SDValue OffsetVal = 6801 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6802 6803 // Add the offset to the FP. 6804 Value *FP = I.getArgOperand(1); 6805 SDValue FPVal = getValue(FP); 6806 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 6807 setValue(&I, Add); 6808 6809 return; 6810 } 6811 6812 case Intrinsic::eh_exceptionpointer: 6813 case Intrinsic::eh_exceptioncode: { 6814 // Get the exception pointer vreg, copy from it, and resize it to fit. 6815 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6816 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6817 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6818 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6819 SDValue N = 6820 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6821 if (Intrinsic == Intrinsic::eh_exceptioncode) 6822 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6823 setValue(&I, N); 6824 return; 6825 } 6826 case Intrinsic::xray_customevent: { 6827 // Here we want to make sure that the intrinsic behaves as if it has a 6828 // specific calling convention, and only for x86_64. 6829 // FIXME: Support other platforms later. 6830 const auto &Triple = DAG.getTarget().getTargetTriple(); 6831 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6832 return; 6833 6834 SDLoc DL = getCurSDLoc(); 6835 SmallVector<SDValue, 8> Ops; 6836 6837 // We want to say that we always want the arguments in registers. 6838 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6839 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6840 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6841 SDValue Chain = getRoot(); 6842 Ops.push_back(LogEntryVal); 6843 Ops.push_back(StrSizeVal); 6844 Ops.push_back(Chain); 6845 6846 // We need to enforce the calling convention for the callsite, so that 6847 // argument ordering is enforced correctly, and that register allocation can 6848 // see that some registers may be assumed clobbered and have to preserve 6849 // them across calls to the intrinsic. 6850 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6851 DL, NodeTys, Ops); 6852 SDValue patchableNode = SDValue(MN, 0); 6853 DAG.setRoot(patchableNode); 6854 setValue(&I, patchableNode); 6855 return; 6856 } 6857 case Intrinsic::xray_typedevent: { 6858 // Here we want to make sure that the intrinsic behaves as if it has a 6859 // specific calling convention, and only for x86_64. 6860 // FIXME: Support other platforms later. 6861 const auto &Triple = DAG.getTarget().getTargetTriple(); 6862 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6863 return; 6864 6865 SDLoc DL = getCurSDLoc(); 6866 SmallVector<SDValue, 8> Ops; 6867 6868 // We want to say that we always want the arguments in registers. 6869 // It's unclear to me how manipulating the selection DAG here forces callers 6870 // to provide arguments in registers instead of on the stack. 6871 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6872 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6873 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6874 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6875 SDValue Chain = getRoot(); 6876 Ops.push_back(LogTypeId); 6877 Ops.push_back(LogEntryVal); 6878 Ops.push_back(StrSizeVal); 6879 Ops.push_back(Chain); 6880 6881 // We need to enforce the calling convention for the callsite, so that 6882 // argument ordering is enforced correctly, and that register allocation can 6883 // see that some registers may be assumed clobbered and have to preserve 6884 // them across calls to the intrinsic. 6885 MachineSDNode *MN = DAG.getMachineNode( 6886 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6887 SDValue patchableNode = SDValue(MN, 0); 6888 DAG.setRoot(patchableNode); 6889 setValue(&I, patchableNode); 6890 return; 6891 } 6892 case Intrinsic::experimental_deoptimize: 6893 LowerDeoptimizeCall(&I); 6894 return; 6895 6896 case Intrinsic::experimental_vector_reduce_v2_fadd: 6897 case Intrinsic::experimental_vector_reduce_v2_fmul: 6898 case Intrinsic::experimental_vector_reduce_add: 6899 case Intrinsic::experimental_vector_reduce_mul: 6900 case Intrinsic::experimental_vector_reduce_and: 6901 case Intrinsic::experimental_vector_reduce_or: 6902 case Intrinsic::experimental_vector_reduce_xor: 6903 case Intrinsic::experimental_vector_reduce_smax: 6904 case Intrinsic::experimental_vector_reduce_smin: 6905 case Intrinsic::experimental_vector_reduce_umax: 6906 case Intrinsic::experimental_vector_reduce_umin: 6907 case Intrinsic::experimental_vector_reduce_fmax: 6908 case Intrinsic::experimental_vector_reduce_fmin: 6909 visitVectorReduce(I, Intrinsic); 6910 return; 6911 6912 case Intrinsic::icall_branch_funnel: { 6913 SmallVector<SDValue, 16> Ops; 6914 Ops.push_back(getValue(I.getArgOperand(0))); 6915 6916 int64_t Offset; 6917 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6918 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6919 if (!Base) 6920 report_fatal_error( 6921 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6922 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6923 6924 struct BranchFunnelTarget { 6925 int64_t Offset; 6926 SDValue Target; 6927 }; 6928 SmallVector<BranchFunnelTarget, 8> Targets; 6929 6930 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6931 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6932 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6933 if (ElemBase != Base) 6934 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6935 "to the same GlobalValue"); 6936 6937 SDValue Val = getValue(I.getArgOperand(Op + 1)); 6938 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 6939 if (!GA) 6940 report_fatal_error( 6941 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6942 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 6943 GA->getGlobal(), getCurSDLoc(), 6944 Val.getValueType(), GA->getOffset())}); 6945 } 6946 llvm::sort(Targets, 6947 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 6948 return T1.Offset < T2.Offset; 6949 }); 6950 6951 for (auto &T : Targets) { 6952 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 6953 Ops.push_back(T.Target); 6954 } 6955 6956 Ops.push_back(DAG.getRoot()); // Chain 6957 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 6958 getCurSDLoc(), MVT::Other, Ops), 6959 0); 6960 DAG.setRoot(N); 6961 setValue(&I, N); 6962 HasTailCall = true; 6963 return; 6964 } 6965 6966 case Intrinsic::wasm_landingpad_index: 6967 // Information this intrinsic contained has been transferred to 6968 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 6969 // delete it now. 6970 return; 6971 6972 case Intrinsic::aarch64_settag: 6973 case Intrinsic::aarch64_settag_zero: { 6974 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6975 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 6976 SDValue Val = TSI.EmitTargetCodeForSetTag( 6977 DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)), 6978 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 6979 ZeroMemory); 6980 DAG.setRoot(Val); 6981 setValue(&I, Val); 6982 return; 6983 } 6984 case Intrinsic::ptrmask: { 6985 SDValue Ptr = getValue(I.getOperand(0)); 6986 SDValue Const = getValue(I.getOperand(1)); 6987 6988 EVT DestVT = 6989 EVT(DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 6990 6991 setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), DestVT, Ptr, 6992 DAG.getZExtOrTrunc(Const, getCurSDLoc(), DestVT))); 6993 return; 6994 } 6995 } 6996 } 6997 6998 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 6999 const ConstrainedFPIntrinsic &FPI) { 7000 SDLoc sdl = getCurSDLoc(); 7001 7002 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7003 SmallVector<EVT, 4> ValueVTs; 7004 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 7005 ValueVTs.push_back(MVT::Other); // Out chain 7006 7007 // We do not need to serialize constrained FP intrinsics against 7008 // each other or against (nonvolatile) loads, so they can be 7009 // chained like loads. 7010 SDValue Chain = DAG.getRoot(); 7011 SmallVector<SDValue, 4> Opers; 7012 Opers.push_back(Chain); 7013 if (FPI.isUnaryOp()) { 7014 Opers.push_back(getValue(FPI.getArgOperand(0))); 7015 } else if (FPI.isTernaryOp()) { 7016 Opers.push_back(getValue(FPI.getArgOperand(0))); 7017 Opers.push_back(getValue(FPI.getArgOperand(1))); 7018 Opers.push_back(getValue(FPI.getArgOperand(2))); 7019 } else { 7020 Opers.push_back(getValue(FPI.getArgOperand(0))); 7021 Opers.push_back(getValue(FPI.getArgOperand(1))); 7022 } 7023 7024 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7025 assert(Result.getNode()->getNumValues() == 2); 7026 7027 // Push node to the appropriate list so that future instructions can be 7028 // chained up correctly. 7029 SDValue OutChain = Result.getValue(1); 7030 switch (EB) { 7031 case fp::ExceptionBehavior::ebIgnore: 7032 // The only reason why ebIgnore nodes still need to be chained is that 7033 // they might depend on the current rounding mode, and therefore must 7034 // not be moved across instruction that may change that mode. 7035 LLVM_FALLTHROUGH; 7036 case fp::ExceptionBehavior::ebMayTrap: 7037 // These must not be moved across calls or instructions that may change 7038 // floating-point exception masks. 7039 PendingConstrainedFP.push_back(OutChain); 7040 break; 7041 case fp::ExceptionBehavior::ebStrict: 7042 // These must not be moved across calls or instructions that may change 7043 // floating-point exception masks or read floating-point exception flags. 7044 // In addition, they cannot be optimized out even if unused. 7045 PendingConstrainedFPStrict.push_back(OutChain); 7046 break; 7047 } 7048 }; 7049 7050 SDVTList VTs = DAG.getVTList(ValueVTs); 7051 fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue(); 7052 7053 unsigned Opcode; 7054 switch (FPI.getIntrinsicID()) { 7055 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7056 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7057 case Intrinsic::INTRINSIC: \ 7058 Opcode = ISD::STRICT_##DAGN; \ 7059 break; 7060 #include "llvm/IR/ConstrainedOps.def" 7061 case Intrinsic::experimental_constrained_fmuladd: { 7062 Opcode = ISD::STRICT_FMA; 7063 // Break fmuladd into fmul and fadd. 7064 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7065 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), 7066 ValueVTs[0])) { 7067 Opers.pop_back(); 7068 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers); 7069 pushOutChain(Mul, EB); 7070 Opcode = ISD::STRICT_FADD; 7071 Opers.clear(); 7072 Opers.push_back(Mul.getValue(1)); 7073 Opers.push_back(Mul.getValue(0)); 7074 Opers.push_back(getValue(FPI.getArgOperand(2))); 7075 } 7076 break; 7077 } 7078 } 7079 7080 // A few strict DAG nodes carry additional operands that are not 7081 // set up by the default code above. 7082 switch (Opcode) { 7083 default: break; 7084 case ISD::STRICT_FP_ROUND: 7085 Opers.push_back( 7086 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7087 break; 7088 case ISD::STRICT_FSETCC: 7089 case ISD::STRICT_FSETCCS: { 7090 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7091 Opers.push_back(DAG.getCondCode(getFCmpCondCode(FPCmp->getPredicate()))); 7092 break; 7093 } 7094 } 7095 7096 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers); 7097 pushOutChain(Result, EB); 7098 7099 SDValue FPResult = Result.getValue(0); 7100 setValue(&FPI, FPResult); 7101 } 7102 7103 std::pair<SDValue, SDValue> 7104 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7105 const BasicBlock *EHPadBB) { 7106 MachineFunction &MF = DAG.getMachineFunction(); 7107 MachineModuleInfo &MMI = MF.getMMI(); 7108 MCSymbol *BeginLabel = nullptr; 7109 7110 if (EHPadBB) { 7111 // Insert a label before the invoke call to mark the try range. This can be 7112 // used to detect deletion of the invoke via the MachineModuleInfo. 7113 BeginLabel = MMI.getContext().createTempSymbol(); 7114 7115 // For SjLj, keep track of which landing pads go with which invokes 7116 // so as to maintain the ordering of pads in the LSDA. 7117 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7118 if (CallSiteIndex) { 7119 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7120 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7121 7122 // Now that the call site is handled, stop tracking it. 7123 MMI.setCurrentCallSite(0); 7124 } 7125 7126 // Both PendingLoads and PendingExports must be flushed here; 7127 // this call might not return. 7128 (void)getRoot(); 7129 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 7130 7131 CLI.setChain(getRoot()); 7132 } 7133 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7134 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7135 7136 assert((CLI.IsTailCall || Result.second.getNode()) && 7137 "Non-null chain expected with non-tail call!"); 7138 assert((Result.second.getNode() || !Result.first.getNode()) && 7139 "Null value expected with tail call!"); 7140 7141 if (!Result.second.getNode()) { 7142 // As a special case, a null chain means that a tail call has been emitted 7143 // and the DAG root is already updated. 7144 HasTailCall = true; 7145 7146 // Since there's no actual continuation from this block, nothing can be 7147 // relying on us setting vregs for them. 7148 PendingExports.clear(); 7149 } else { 7150 DAG.setRoot(Result.second); 7151 } 7152 7153 if (EHPadBB) { 7154 // Insert a label at the end of the invoke call to mark the try range. This 7155 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7156 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7157 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 7158 7159 // Inform MachineModuleInfo of range. 7160 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7161 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7162 // actually use outlined funclets and their LSDA info style. 7163 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7164 assert(CLI.CS); 7165 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 7166 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()), 7167 BeginLabel, EndLabel); 7168 } else if (!isScopedEHPersonality(Pers)) { 7169 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7170 } 7171 } 7172 7173 return Result; 7174 } 7175 7176 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee, 7177 bool isTailCall, 7178 const BasicBlock *EHPadBB) { 7179 auto &DL = DAG.getDataLayout(); 7180 FunctionType *FTy = CS.getFunctionType(); 7181 Type *RetTy = CS.getType(); 7182 7183 TargetLowering::ArgListTy Args; 7184 Args.reserve(CS.arg_size()); 7185 7186 const Value *SwiftErrorVal = nullptr; 7187 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7188 7189 if (isTailCall) { 7190 // Avoid emitting tail calls in functions with the disable-tail-calls 7191 // attribute. 7192 auto *Caller = CS.getInstruction()->getParent()->getParent(); 7193 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7194 "true") 7195 isTailCall = false; 7196 7197 // We can't tail call inside a function with a swifterror argument. Lowering 7198 // does not support this yet. It would have to move into the swifterror 7199 // register before the call. 7200 if (TLI.supportSwiftError() && 7201 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7202 isTailCall = false; 7203 } 7204 7205 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 7206 i != e; ++i) { 7207 TargetLowering::ArgListEntry Entry; 7208 const Value *V = *i; 7209 7210 // Skip empty types 7211 if (V->getType()->isEmptyTy()) 7212 continue; 7213 7214 SDValue ArgNode = getValue(V); 7215 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7216 7217 Entry.setAttributes(&CS, i - CS.arg_begin()); 7218 7219 // Use swifterror virtual register as input to the call. 7220 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7221 SwiftErrorVal = V; 7222 // We find the virtual register for the actual swifterror argument. 7223 // Instead of using the Value, we use the virtual register instead. 7224 Entry.Node = DAG.getRegister( 7225 SwiftError.getOrCreateVRegUseAt(CS.getInstruction(), FuncInfo.MBB, V), 7226 EVT(TLI.getPointerTy(DL))); 7227 } 7228 7229 Args.push_back(Entry); 7230 7231 // If we have an explicit sret argument that is an Instruction, (i.e., it 7232 // might point to function-local memory), we can't meaningfully tail-call. 7233 if (Entry.IsSRet && isa<Instruction>(V)) 7234 isTailCall = false; 7235 } 7236 7237 // If call site has a cfguardtarget operand bundle, create and add an 7238 // additional ArgListEntry. 7239 if (auto Bundle = CS.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7240 TargetLowering::ArgListEntry Entry; 7241 Value *V = Bundle->Inputs[0]; 7242 SDValue ArgNode = getValue(V); 7243 Entry.Node = ArgNode; 7244 Entry.Ty = V->getType(); 7245 Entry.IsCFGuardTarget = true; 7246 Args.push_back(Entry); 7247 } 7248 7249 // Check if target-independent constraints permit a tail call here. 7250 // Target-dependent constraints are checked within TLI->LowerCallTo. 7251 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget())) 7252 isTailCall = false; 7253 7254 // Disable tail calls if there is an swifterror argument. Targets have not 7255 // been updated to support tail calls. 7256 if (TLI.supportSwiftError() && SwiftErrorVal) 7257 isTailCall = false; 7258 7259 TargetLowering::CallLoweringInfo CLI(DAG); 7260 CLI.setDebugLoc(getCurSDLoc()) 7261 .setChain(getRoot()) 7262 .setCallee(RetTy, FTy, Callee, std::move(Args), CS) 7263 .setTailCall(isTailCall) 7264 .setConvergent(CS.isConvergent()); 7265 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7266 7267 if (Result.first.getNode()) { 7268 const Instruction *Inst = CS.getInstruction(); 7269 Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first); 7270 setValue(Inst, Result.first); 7271 } 7272 7273 // The last element of CLI.InVals has the SDValue for swifterror return. 7274 // Here we copy it to a virtual register and update SwiftErrorMap for 7275 // book-keeping. 7276 if (SwiftErrorVal && TLI.supportSwiftError()) { 7277 // Get the last element of InVals. 7278 SDValue Src = CLI.InVals.back(); 7279 Register VReg = SwiftError.getOrCreateVRegDefAt( 7280 CS.getInstruction(), FuncInfo.MBB, SwiftErrorVal); 7281 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7282 DAG.setRoot(CopyNode); 7283 } 7284 } 7285 7286 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7287 SelectionDAGBuilder &Builder) { 7288 // Check to see if this load can be trivially constant folded, e.g. if the 7289 // input is from a string literal. 7290 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7291 // Cast pointer to the type we really want to load. 7292 Type *LoadTy = 7293 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7294 if (LoadVT.isVector()) 7295 LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7296 7297 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7298 PointerType::getUnqual(LoadTy)); 7299 7300 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 7301 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 7302 return Builder.getValue(LoadCst); 7303 } 7304 7305 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7306 // still constant memory, the input chain can be the entry node. 7307 SDValue Root; 7308 bool ConstantMemory = false; 7309 7310 // Do not serialize (non-volatile) loads of constant memory with anything. 7311 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7312 Root = Builder.DAG.getEntryNode(); 7313 ConstantMemory = true; 7314 } else { 7315 // Do not serialize non-volatile loads against each other. 7316 Root = Builder.DAG.getRoot(); 7317 } 7318 7319 SDValue Ptr = Builder.getValue(PtrVal); 7320 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, 7321 Ptr, MachinePointerInfo(PtrVal), 7322 /* Alignment = */ 1); 7323 7324 if (!ConstantMemory) 7325 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7326 return LoadVal; 7327 } 7328 7329 /// Record the value for an instruction that produces an integer result, 7330 /// converting the type where necessary. 7331 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7332 SDValue Value, 7333 bool IsSigned) { 7334 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7335 I.getType(), true); 7336 if (IsSigned) 7337 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7338 else 7339 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7340 setValue(&I, Value); 7341 } 7342 7343 /// See if we can lower a memcmp call into an optimized form. If so, return 7344 /// true and lower it. Otherwise return false, and it will be lowered like a 7345 /// normal call. 7346 /// The caller already checked that \p I calls the appropriate LibFunc with a 7347 /// correct prototype. 7348 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 7349 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 7350 const Value *Size = I.getArgOperand(2); 7351 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 7352 if (CSize && CSize->getZExtValue() == 0) { 7353 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7354 I.getType(), true); 7355 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 7356 return true; 7357 } 7358 7359 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7360 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 7361 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 7362 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 7363 if (Res.first.getNode()) { 7364 processIntegerCallValue(I, Res.first, true); 7365 PendingLoads.push_back(Res.second); 7366 return true; 7367 } 7368 7369 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 7370 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 7371 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 7372 return false; 7373 7374 // If the target has a fast compare for the given size, it will return a 7375 // preferred load type for that size. Require that the load VT is legal and 7376 // that the target supports unaligned loads of that type. Otherwise, return 7377 // INVALID. 7378 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 7379 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7380 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 7381 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 7382 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 7383 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 7384 // TODO: Check alignment of src and dest ptrs. 7385 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 7386 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 7387 if (!TLI.isTypeLegal(LVT) || 7388 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 7389 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 7390 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 7391 } 7392 7393 return LVT; 7394 }; 7395 7396 // This turns into unaligned loads. We only do this if the target natively 7397 // supports the MVT we'll be loading or if it is small enough (<= 4) that 7398 // we'll only produce a small number of byte loads. 7399 MVT LoadVT; 7400 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 7401 switch (NumBitsToCompare) { 7402 default: 7403 return false; 7404 case 16: 7405 LoadVT = MVT::i16; 7406 break; 7407 case 32: 7408 LoadVT = MVT::i32; 7409 break; 7410 case 64: 7411 case 128: 7412 case 256: 7413 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 7414 break; 7415 } 7416 7417 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 7418 return false; 7419 7420 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 7421 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 7422 7423 // Bitcast to a wide integer type if the loads are vectors. 7424 if (LoadVT.isVector()) { 7425 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 7426 LoadL = DAG.getBitcast(CmpVT, LoadL); 7427 LoadR = DAG.getBitcast(CmpVT, LoadR); 7428 } 7429 7430 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 7431 processIntegerCallValue(I, Cmp, false); 7432 return true; 7433 } 7434 7435 /// See if we can lower a memchr call into an optimized form. If so, return 7436 /// true and lower it. Otherwise return false, and it will be lowered like a 7437 /// normal call. 7438 /// The caller already checked that \p I calls the appropriate LibFunc with a 7439 /// correct prototype. 7440 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 7441 const Value *Src = I.getArgOperand(0); 7442 const Value *Char = I.getArgOperand(1); 7443 const Value *Length = I.getArgOperand(2); 7444 7445 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7446 std::pair<SDValue, SDValue> Res = 7447 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 7448 getValue(Src), getValue(Char), getValue(Length), 7449 MachinePointerInfo(Src)); 7450 if (Res.first.getNode()) { 7451 setValue(&I, Res.first); 7452 PendingLoads.push_back(Res.second); 7453 return true; 7454 } 7455 7456 return false; 7457 } 7458 7459 /// See if we can lower a mempcpy call into an optimized form. If so, return 7460 /// true and lower it. Otherwise return false, and it will be lowered like a 7461 /// normal call. 7462 /// The caller already checked that \p I calls the appropriate LibFunc with a 7463 /// correct prototype. 7464 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 7465 SDValue Dst = getValue(I.getArgOperand(0)); 7466 SDValue Src = getValue(I.getArgOperand(1)); 7467 SDValue Size = getValue(I.getArgOperand(2)); 7468 7469 unsigned DstAlign = DAG.InferPtrAlignment(Dst); 7470 unsigned SrcAlign = DAG.InferPtrAlignment(Src); 7471 unsigned Align = std::min(DstAlign, SrcAlign); 7472 if (Align == 0) // Alignment of one or both could not be inferred. 7473 Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved. 7474 7475 bool isVol = false; 7476 SDLoc sdl = getCurSDLoc(); 7477 7478 // In the mempcpy context we need to pass in a false value for isTailCall 7479 // because the return pointer needs to be adjusted by the size of 7480 // the copied memory. 7481 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 7482 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Align, isVol, 7483 false, /*isTailCall=*/false, 7484 MachinePointerInfo(I.getArgOperand(0)), 7485 MachinePointerInfo(I.getArgOperand(1))); 7486 assert(MC.getNode() != nullptr && 7487 "** memcpy should not be lowered as TailCall in mempcpy context **"); 7488 DAG.setRoot(MC); 7489 7490 // Check if Size needs to be truncated or extended. 7491 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 7492 7493 // Adjust return pointer to point just past the last dst byte. 7494 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 7495 Dst, Size); 7496 setValue(&I, DstPlusSize); 7497 return true; 7498 } 7499 7500 /// See if we can lower a strcpy call into an optimized form. If so, return 7501 /// true and lower it, otherwise return false and it will be lowered like a 7502 /// normal call. 7503 /// The caller already checked that \p I calls the appropriate LibFunc with a 7504 /// correct prototype. 7505 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 7506 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7507 7508 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7509 std::pair<SDValue, SDValue> Res = 7510 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 7511 getValue(Arg0), getValue(Arg1), 7512 MachinePointerInfo(Arg0), 7513 MachinePointerInfo(Arg1), isStpcpy); 7514 if (Res.first.getNode()) { 7515 setValue(&I, Res.first); 7516 DAG.setRoot(Res.second); 7517 return true; 7518 } 7519 7520 return false; 7521 } 7522 7523 /// See if we can lower a strcmp call into an optimized form. If so, return 7524 /// true and lower it, otherwise return false and it will be lowered like a 7525 /// normal call. 7526 /// The caller already checked that \p I calls the appropriate LibFunc with a 7527 /// correct prototype. 7528 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 7529 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7530 7531 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7532 std::pair<SDValue, SDValue> Res = 7533 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 7534 getValue(Arg0), getValue(Arg1), 7535 MachinePointerInfo(Arg0), 7536 MachinePointerInfo(Arg1)); 7537 if (Res.first.getNode()) { 7538 processIntegerCallValue(I, Res.first, true); 7539 PendingLoads.push_back(Res.second); 7540 return true; 7541 } 7542 7543 return false; 7544 } 7545 7546 /// See if we can lower a strlen call into an optimized form. If so, return 7547 /// true and lower it, otherwise return false and it will be lowered like a 7548 /// normal call. 7549 /// The caller already checked that \p I calls the appropriate LibFunc with a 7550 /// correct prototype. 7551 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 7552 const Value *Arg0 = I.getArgOperand(0); 7553 7554 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7555 std::pair<SDValue, SDValue> Res = 7556 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 7557 getValue(Arg0), MachinePointerInfo(Arg0)); 7558 if (Res.first.getNode()) { 7559 processIntegerCallValue(I, Res.first, false); 7560 PendingLoads.push_back(Res.second); 7561 return true; 7562 } 7563 7564 return false; 7565 } 7566 7567 /// See if we can lower a strnlen call into an optimized form. If so, return 7568 /// true and lower it, otherwise return false and it will be lowered like a 7569 /// normal call. 7570 /// The caller already checked that \p I calls the appropriate LibFunc with a 7571 /// correct prototype. 7572 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 7573 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7574 7575 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7576 std::pair<SDValue, SDValue> Res = 7577 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 7578 getValue(Arg0), getValue(Arg1), 7579 MachinePointerInfo(Arg0)); 7580 if (Res.first.getNode()) { 7581 processIntegerCallValue(I, Res.first, false); 7582 PendingLoads.push_back(Res.second); 7583 return true; 7584 } 7585 7586 return false; 7587 } 7588 7589 /// See if we can lower a unary floating-point operation into an SDNode with 7590 /// the specified Opcode. If so, return true and lower it, otherwise return 7591 /// false and it will be lowered like a normal call. 7592 /// The caller already checked that \p I calls the appropriate LibFunc with a 7593 /// correct prototype. 7594 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 7595 unsigned Opcode) { 7596 // We already checked this call's prototype; verify it doesn't modify errno. 7597 if (!I.onlyReadsMemory()) 7598 return false; 7599 7600 SDValue Tmp = getValue(I.getArgOperand(0)); 7601 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); 7602 return true; 7603 } 7604 7605 /// See if we can lower a binary floating-point operation into an SDNode with 7606 /// the specified Opcode. If so, return true and lower it. Otherwise return 7607 /// false, and it will be lowered like a normal call. 7608 /// The caller already checked that \p I calls the appropriate LibFunc with a 7609 /// correct prototype. 7610 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 7611 unsigned Opcode) { 7612 // We already checked this call's prototype; verify it doesn't modify errno. 7613 if (!I.onlyReadsMemory()) 7614 return false; 7615 7616 SDValue Tmp0 = getValue(I.getArgOperand(0)); 7617 SDValue Tmp1 = getValue(I.getArgOperand(1)); 7618 EVT VT = Tmp0.getValueType(); 7619 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1)); 7620 return true; 7621 } 7622 7623 void SelectionDAGBuilder::visitCall(const CallInst &I) { 7624 // Handle inline assembly differently. 7625 if (isa<InlineAsm>(I.getCalledValue())) { 7626 visitInlineAsm(&I); 7627 return; 7628 } 7629 7630 if (Function *F = I.getCalledFunction()) { 7631 if (F->isDeclaration()) { 7632 // Is this an LLVM intrinsic or a target-specific intrinsic? 7633 unsigned IID = F->getIntrinsicID(); 7634 if (!IID) 7635 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7636 IID = II->getIntrinsicID(F); 7637 7638 if (IID) { 7639 visitIntrinsicCall(I, IID); 7640 return; 7641 } 7642 } 7643 7644 // Check for well-known libc/libm calls. If the function is internal, it 7645 // can't be a library call. Don't do the check if marked as nobuiltin for 7646 // some reason or the call site requires strict floating point semantics. 7647 LibFunc Func; 7648 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7649 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7650 LibInfo->hasOptimizedCodeGen(Func)) { 7651 switch (Func) { 7652 default: break; 7653 case LibFunc_copysign: 7654 case LibFunc_copysignf: 7655 case LibFunc_copysignl: 7656 // We already checked this call's prototype; verify it doesn't modify 7657 // errno. 7658 if (I.onlyReadsMemory()) { 7659 SDValue LHS = getValue(I.getArgOperand(0)); 7660 SDValue RHS = getValue(I.getArgOperand(1)); 7661 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7662 LHS.getValueType(), LHS, RHS)); 7663 return; 7664 } 7665 break; 7666 case LibFunc_fabs: 7667 case LibFunc_fabsf: 7668 case LibFunc_fabsl: 7669 if (visitUnaryFloatCall(I, ISD::FABS)) 7670 return; 7671 break; 7672 case LibFunc_fmin: 7673 case LibFunc_fminf: 7674 case LibFunc_fminl: 7675 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7676 return; 7677 break; 7678 case LibFunc_fmax: 7679 case LibFunc_fmaxf: 7680 case LibFunc_fmaxl: 7681 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7682 return; 7683 break; 7684 case LibFunc_sin: 7685 case LibFunc_sinf: 7686 case LibFunc_sinl: 7687 if (visitUnaryFloatCall(I, ISD::FSIN)) 7688 return; 7689 break; 7690 case LibFunc_cos: 7691 case LibFunc_cosf: 7692 case LibFunc_cosl: 7693 if (visitUnaryFloatCall(I, ISD::FCOS)) 7694 return; 7695 break; 7696 case LibFunc_sqrt: 7697 case LibFunc_sqrtf: 7698 case LibFunc_sqrtl: 7699 case LibFunc_sqrt_finite: 7700 case LibFunc_sqrtf_finite: 7701 case LibFunc_sqrtl_finite: 7702 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7703 return; 7704 break; 7705 case LibFunc_floor: 7706 case LibFunc_floorf: 7707 case LibFunc_floorl: 7708 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7709 return; 7710 break; 7711 case LibFunc_nearbyint: 7712 case LibFunc_nearbyintf: 7713 case LibFunc_nearbyintl: 7714 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7715 return; 7716 break; 7717 case LibFunc_ceil: 7718 case LibFunc_ceilf: 7719 case LibFunc_ceill: 7720 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7721 return; 7722 break; 7723 case LibFunc_rint: 7724 case LibFunc_rintf: 7725 case LibFunc_rintl: 7726 if (visitUnaryFloatCall(I, ISD::FRINT)) 7727 return; 7728 break; 7729 case LibFunc_round: 7730 case LibFunc_roundf: 7731 case LibFunc_roundl: 7732 if (visitUnaryFloatCall(I, ISD::FROUND)) 7733 return; 7734 break; 7735 case LibFunc_trunc: 7736 case LibFunc_truncf: 7737 case LibFunc_truncl: 7738 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7739 return; 7740 break; 7741 case LibFunc_log2: 7742 case LibFunc_log2f: 7743 case LibFunc_log2l: 7744 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7745 return; 7746 break; 7747 case LibFunc_exp2: 7748 case LibFunc_exp2f: 7749 case LibFunc_exp2l: 7750 if (visitUnaryFloatCall(I, ISD::FEXP2)) 7751 return; 7752 break; 7753 case LibFunc_memcmp: 7754 if (visitMemCmpCall(I)) 7755 return; 7756 break; 7757 case LibFunc_mempcpy: 7758 if (visitMemPCpyCall(I)) 7759 return; 7760 break; 7761 case LibFunc_memchr: 7762 if (visitMemChrCall(I)) 7763 return; 7764 break; 7765 case LibFunc_strcpy: 7766 if (visitStrCpyCall(I, false)) 7767 return; 7768 break; 7769 case LibFunc_stpcpy: 7770 if (visitStrCpyCall(I, true)) 7771 return; 7772 break; 7773 case LibFunc_strcmp: 7774 if (visitStrCmpCall(I)) 7775 return; 7776 break; 7777 case LibFunc_strlen: 7778 if (visitStrLenCall(I)) 7779 return; 7780 break; 7781 case LibFunc_strnlen: 7782 if (visitStrNLenCall(I)) 7783 return; 7784 break; 7785 } 7786 } 7787 } 7788 7789 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 7790 // have to do anything here to lower funclet bundles. 7791 // CFGuardTarget bundles are lowered in LowerCallTo. 7792 assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt, 7793 LLVMContext::OB_funclet, 7794 LLVMContext::OB_cfguardtarget}) && 7795 "Cannot lower calls with arbitrary operand bundles!"); 7796 7797 SDValue Callee = getValue(I.getCalledValue()); 7798 7799 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 7800 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 7801 else 7802 // Check if we can potentially perform a tail call. More detailed checking 7803 // is be done within LowerCallTo, after more information about the call is 7804 // known. 7805 LowerCallTo(&I, Callee, I.isTailCall()); 7806 } 7807 7808 namespace { 7809 7810 /// AsmOperandInfo - This contains information for each constraint that we are 7811 /// lowering. 7812 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 7813 public: 7814 /// CallOperand - If this is the result output operand or a clobber 7815 /// this is null, otherwise it is the incoming operand to the CallInst. 7816 /// This gets modified as the asm is processed. 7817 SDValue CallOperand; 7818 7819 /// AssignedRegs - If this is a register or register class operand, this 7820 /// contains the set of register corresponding to the operand. 7821 RegsForValue AssignedRegs; 7822 7823 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 7824 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 7825 } 7826 7827 /// Whether or not this operand accesses memory 7828 bool hasMemory(const TargetLowering &TLI) const { 7829 // Indirect operand accesses access memory. 7830 if (isIndirect) 7831 return true; 7832 7833 for (const auto &Code : Codes) 7834 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 7835 return true; 7836 7837 return false; 7838 } 7839 7840 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 7841 /// corresponds to. If there is no Value* for this operand, it returns 7842 /// MVT::Other. 7843 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 7844 const DataLayout &DL) const { 7845 if (!CallOperandVal) return MVT::Other; 7846 7847 if (isa<BasicBlock>(CallOperandVal)) 7848 return TLI.getPointerTy(DL); 7849 7850 llvm::Type *OpTy = CallOperandVal->getType(); 7851 7852 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 7853 // If this is an indirect operand, the operand is a pointer to the 7854 // accessed type. 7855 if (isIndirect) { 7856 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 7857 if (!PtrTy) 7858 report_fatal_error("Indirect operand for inline asm not a pointer!"); 7859 OpTy = PtrTy->getElementType(); 7860 } 7861 7862 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 7863 if (StructType *STy = dyn_cast<StructType>(OpTy)) 7864 if (STy->getNumElements() == 1) 7865 OpTy = STy->getElementType(0); 7866 7867 // If OpTy is not a single value, it may be a struct/union that we 7868 // can tile with integers. 7869 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 7870 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 7871 switch (BitSize) { 7872 default: break; 7873 case 1: 7874 case 8: 7875 case 16: 7876 case 32: 7877 case 64: 7878 case 128: 7879 OpTy = IntegerType::get(Context, BitSize); 7880 break; 7881 } 7882 } 7883 7884 return TLI.getValueType(DL, OpTy, true); 7885 } 7886 }; 7887 7888 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>; 7889 7890 } // end anonymous namespace 7891 7892 /// Make sure that the output operand \p OpInfo and its corresponding input 7893 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 7894 /// out). 7895 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 7896 SDISelAsmOperandInfo &MatchingOpInfo, 7897 SelectionDAG &DAG) { 7898 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 7899 return; 7900 7901 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 7902 const auto &TLI = DAG.getTargetLoweringInfo(); 7903 7904 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 7905 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 7906 OpInfo.ConstraintVT); 7907 std::pair<unsigned, const TargetRegisterClass *> InputRC = 7908 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 7909 MatchingOpInfo.ConstraintVT); 7910 if ((OpInfo.ConstraintVT.isInteger() != 7911 MatchingOpInfo.ConstraintVT.isInteger()) || 7912 (MatchRC.second != InputRC.second)) { 7913 // FIXME: error out in a more elegant fashion 7914 report_fatal_error("Unsupported asm: input constraint" 7915 " with a matching output constraint of" 7916 " incompatible type!"); 7917 } 7918 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 7919 } 7920 7921 /// Get a direct memory input to behave well as an indirect operand. 7922 /// This may introduce stores, hence the need for a \p Chain. 7923 /// \return The (possibly updated) chain. 7924 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 7925 SDISelAsmOperandInfo &OpInfo, 7926 SelectionDAG &DAG) { 7927 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7928 7929 // If we don't have an indirect input, put it in the constpool if we can, 7930 // otherwise spill it to a stack slot. 7931 // TODO: This isn't quite right. We need to handle these according to 7932 // the addressing mode that the constraint wants. Also, this may take 7933 // an additional register for the computation and we don't want that 7934 // either. 7935 7936 // If the operand is a float, integer, or vector constant, spill to a 7937 // constant pool entry to get its address. 7938 const Value *OpVal = OpInfo.CallOperandVal; 7939 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 7940 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 7941 OpInfo.CallOperand = DAG.getConstantPool( 7942 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 7943 return Chain; 7944 } 7945 7946 // Otherwise, create a stack slot and emit a store to it before the asm. 7947 Type *Ty = OpVal->getType(); 7948 auto &DL = DAG.getDataLayout(); 7949 uint64_t TySize = DL.getTypeAllocSize(Ty); 7950 unsigned Align = DL.getPrefTypeAlignment(Ty); 7951 MachineFunction &MF = DAG.getMachineFunction(); 7952 int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 7953 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 7954 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 7955 MachinePointerInfo::getFixedStack(MF, SSFI), 7956 TLI.getMemValueType(DL, Ty)); 7957 OpInfo.CallOperand = StackSlot; 7958 7959 return Chain; 7960 } 7961 7962 /// GetRegistersForValue - Assign registers (virtual or physical) for the 7963 /// specified operand. We prefer to assign virtual registers, to allow the 7964 /// register allocator to handle the assignment process. However, if the asm 7965 /// uses features that we can't model on machineinstrs, we have SDISel do the 7966 /// allocation. This produces generally horrible, but correct, code. 7967 /// 7968 /// OpInfo describes the operand 7969 /// RefOpInfo describes the matching operand if any, the operand otherwise 7970 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 7971 SDISelAsmOperandInfo &OpInfo, 7972 SDISelAsmOperandInfo &RefOpInfo) { 7973 LLVMContext &Context = *DAG.getContext(); 7974 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7975 7976 MachineFunction &MF = DAG.getMachineFunction(); 7977 SmallVector<unsigned, 4> Regs; 7978 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 7979 7980 // No work to do for memory operations. 7981 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 7982 return; 7983 7984 // If this is a constraint for a single physreg, or a constraint for a 7985 // register class, find it. 7986 unsigned AssignedReg; 7987 const TargetRegisterClass *RC; 7988 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 7989 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 7990 // RC is unset only on failure. Return immediately. 7991 if (!RC) 7992 return; 7993 7994 // Get the actual register value type. This is important, because the user 7995 // may have asked for (e.g.) the AX register in i32 type. We need to 7996 // remember that AX is actually i16 to get the right extension. 7997 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 7998 7999 if (OpInfo.ConstraintVT != MVT::Other) { 8000 // If this is an FP operand in an integer register (or visa versa), or more 8001 // generally if the operand value disagrees with the register class we plan 8002 // to stick it in, fix the operand type. 8003 // 8004 // If this is an input value, the bitcast to the new type is done now. 8005 // Bitcast for output value is done at the end of visitInlineAsm(). 8006 if ((OpInfo.Type == InlineAsm::isOutput || 8007 OpInfo.Type == InlineAsm::isInput) && 8008 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 8009 // Try to convert to the first EVT that the reg class contains. If the 8010 // types are identical size, use a bitcast to convert (e.g. two differing 8011 // vector types). Note: output bitcast is done at the end of 8012 // visitInlineAsm(). 8013 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 8014 // Exclude indirect inputs while they are unsupported because the code 8015 // to perform the load is missing and thus OpInfo.CallOperand still 8016 // refers to the input address rather than the pointed-to value. 8017 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 8018 OpInfo.CallOperand = 8019 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 8020 OpInfo.ConstraintVT = RegVT; 8021 // If the operand is an FP value and we want it in integer registers, 8022 // use the corresponding integer type. This turns an f64 value into 8023 // i64, which can be passed with two i32 values on a 32-bit machine. 8024 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 8025 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 8026 if (OpInfo.Type == InlineAsm::isInput) 8027 OpInfo.CallOperand = 8028 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 8029 OpInfo.ConstraintVT = VT; 8030 } 8031 } 8032 } 8033 8034 // No need to allocate a matching input constraint since the constraint it's 8035 // matching to has already been allocated. 8036 if (OpInfo.isMatchingInputConstraint()) 8037 return; 8038 8039 EVT ValueVT = OpInfo.ConstraintVT; 8040 if (OpInfo.ConstraintVT == MVT::Other) 8041 ValueVT = RegVT; 8042 8043 // Initialize NumRegs. 8044 unsigned NumRegs = 1; 8045 if (OpInfo.ConstraintVT != MVT::Other) 8046 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 8047 8048 // If this is a constraint for a specific physical register, like {r17}, 8049 // assign it now. 8050 8051 // If this associated to a specific register, initialize iterator to correct 8052 // place. If virtual, make sure we have enough registers 8053 8054 // Initialize iterator if necessary 8055 TargetRegisterClass::iterator I = RC->begin(); 8056 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8057 8058 // Do not check for single registers. 8059 if (AssignedReg) { 8060 for (; *I != AssignedReg; ++I) 8061 assert(I != RC->end() && "AssignedReg should be member of RC"); 8062 } 8063 8064 for (; NumRegs; --NumRegs, ++I) { 8065 assert(I != RC->end() && "Ran out of registers to allocate!"); 8066 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8067 Regs.push_back(R); 8068 } 8069 8070 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8071 } 8072 8073 static unsigned 8074 findMatchingInlineAsmOperand(unsigned OperandNo, 8075 const std::vector<SDValue> &AsmNodeOperands) { 8076 // Scan until we find the definition we already emitted of this operand. 8077 unsigned CurOp = InlineAsm::Op_FirstOperand; 8078 for (; OperandNo; --OperandNo) { 8079 // Advance to the next operand. 8080 unsigned OpFlag = 8081 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8082 assert((InlineAsm::isRegDefKind(OpFlag) || 8083 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8084 InlineAsm::isMemKind(OpFlag)) && 8085 "Skipped past definitions?"); 8086 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8087 } 8088 return CurOp; 8089 } 8090 8091 namespace { 8092 8093 class ExtraFlags { 8094 unsigned Flags = 0; 8095 8096 public: 8097 explicit ExtraFlags(ImmutableCallSite CS) { 8098 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 8099 if (IA->hasSideEffects()) 8100 Flags |= InlineAsm::Extra_HasSideEffects; 8101 if (IA->isAlignStack()) 8102 Flags |= InlineAsm::Extra_IsAlignStack; 8103 if (CS.isConvergent()) 8104 Flags |= InlineAsm::Extra_IsConvergent; 8105 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8106 } 8107 8108 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8109 // Ideally, we would only check against memory constraints. However, the 8110 // meaning of an Other constraint can be target-specific and we can't easily 8111 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8112 // for Other constraints as well. 8113 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8114 OpInfo.ConstraintType == TargetLowering::C_Other) { 8115 if (OpInfo.Type == InlineAsm::isInput) 8116 Flags |= InlineAsm::Extra_MayLoad; 8117 else if (OpInfo.Type == InlineAsm::isOutput) 8118 Flags |= InlineAsm::Extra_MayStore; 8119 else if (OpInfo.Type == InlineAsm::isClobber) 8120 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8121 } 8122 } 8123 8124 unsigned get() const { return Flags; } 8125 }; 8126 8127 } // end anonymous namespace 8128 8129 /// visitInlineAsm - Handle a call to an InlineAsm object. 8130 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) { 8131 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 8132 8133 /// ConstraintOperands - Information about all of the constraints. 8134 SDISelAsmOperandInfoVector ConstraintOperands; 8135 8136 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8137 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8138 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS); 8139 8140 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8141 // AsmDialect, MayLoad, MayStore). 8142 bool HasSideEffect = IA->hasSideEffects(); 8143 ExtraFlags ExtraInfo(CS); 8144 8145 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 8146 unsigned ResNo = 0; // ResNo - The result number of the next output. 8147 for (auto &T : TargetConstraints) { 8148 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8149 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8150 8151 // Compute the value type for each operand. 8152 if (OpInfo.Type == InlineAsm::isInput || 8153 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 8154 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 8155 8156 // Process the call argument. BasicBlocks are labels, currently appearing 8157 // only in asm's. 8158 const Instruction *I = CS.getInstruction(); 8159 if (isa<CallBrInst>(I) && 8160 (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() - 8161 cast<CallBrInst>(I)->getNumIndirectDests())) { 8162 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal); 8163 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true); 8164 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT); 8165 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 8166 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 8167 } else { 8168 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8169 } 8170 8171 OpInfo.ConstraintVT = 8172 OpInfo 8173 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout()) 8174 .getSimpleVT(); 8175 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 8176 // The return value of the call is this value. As such, there is no 8177 // corresponding argument. 8178 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 8179 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 8180 OpInfo.ConstraintVT = TLI.getSimpleValueType( 8181 DAG.getDataLayout(), STy->getElementType(ResNo)); 8182 } else { 8183 assert(ResNo == 0 && "Asm only has one result!"); 8184 OpInfo.ConstraintVT = 8185 TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType()); 8186 } 8187 ++ResNo; 8188 } else { 8189 OpInfo.ConstraintVT = MVT::Other; 8190 } 8191 8192 if (!HasSideEffect) 8193 HasSideEffect = OpInfo.hasMemory(TLI); 8194 8195 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8196 // FIXME: Could we compute this on OpInfo rather than T? 8197 8198 // Compute the constraint code and ConstraintType to use. 8199 TLI.ComputeConstraintToUse(T, SDValue()); 8200 8201 if (T.ConstraintType == TargetLowering::C_Immediate && 8202 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8203 // We've delayed emitting a diagnostic like the "n" constraint because 8204 // inlining could cause an integer showing up. 8205 return emitInlineAsmError( 8206 CS, "constraint '" + Twine(T.ConstraintCode) + "' expects an " 8207 "integer constant expression"); 8208 8209 ExtraInfo.update(T); 8210 } 8211 8212 8213 // We won't need to flush pending loads if this asm doesn't touch 8214 // memory and is nonvolatile. 8215 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8216 8217 bool IsCallBr = isa<CallBrInst>(CS.getInstruction()); 8218 if (IsCallBr) { 8219 // If this is a callbr we need to flush pending exports since inlineasm_br 8220 // is a terminator. We need to do this before nodes are glued to 8221 // the inlineasm_br node. 8222 Chain = getControlRoot(); 8223 } 8224 8225 // Second pass over the constraints: compute which constraint option to use. 8226 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8227 // If this is an output operand with a matching input operand, look up the 8228 // matching input. If their types mismatch, e.g. one is an integer, the 8229 // other is floating point, or their sizes are different, flag it as an 8230 // error. 8231 if (OpInfo.hasMatchingInput()) { 8232 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8233 patchMatchingInput(OpInfo, Input, DAG); 8234 } 8235 8236 // Compute the constraint code and ConstraintType to use. 8237 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8238 8239 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8240 OpInfo.Type == InlineAsm::isClobber) 8241 continue; 8242 8243 // If this is a memory input, and if the operand is not indirect, do what we 8244 // need to provide an address for the memory input. 8245 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8246 !OpInfo.isIndirect) { 8247 assert((OpInfo.isMultipleAlternative || 8248 (OpInfo.Type == InlineAsm::isInput)) && 8249 "Can only indirectify direct input operands!"); 8250 8251 // Memory operands really want the address of the value. 8252 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8253 8254 // There is no longer a Value* corresponding to this operand. 8255 OpInfo.CallOperandVal = nullptr; 8256 8257 // It is now an indirect operand. 8258 OpInfo.isIndirect = true; 8259 } 8260 8261 } 8262 8263 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8264 std::vector<SDValue> AsmNodeOperands; 8265 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8266 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8267 IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout()))); 8268 8269 // If we have a !srcloc metadata node associated with it, we want to attach 8270 // this to the ultimately generated inline asm machineinstr. To do this, we 8271 // pass in the third operand as this (potentially null) inline asm MDNode. 8272 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc"); 8273 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8274 8275 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8276 // bits as operand 3. 8277 AsmNodeOperands.push_back(DAG.getTargetConstant( 8278 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8279 8280 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8281 // this, assign virtual and physical registers for inputs and otput. 8282 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8283 // Assign Registers. 8284 SDISelAsmOperandInfo &RefOpInfo = 8285 OpInfo.isMatchingInputConstraint() 8286 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8287 : OpInfo; 8288 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8289 8290 switch (OpInfo.Type) { 8291 case InlineAsm::isOutput: 8292 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8293 unsigned ConstraintID = 8294 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8295 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8296 "Failed to convert memory constraint code to constraint id."); 8297 8298 // Add information to the INLINEASM node to know about this output. 8299 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8300 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8301 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8302 MVT::i32)); 8303 AsmNodeOperands.push_back(OpInfo.CallOperand); 8304 } else { 8305 // Otherwise, this outputs to a register (directly for C_Register / 8306 // C_RegisterClass, and a target-defined fashion for 8307 // C_Immediate/C_Other). Find a register that we can use. 8308 if (OpInfo.AssignedRegs.Regs.empty()) { 8309 emitInlineAsmError( 8310 CS, "couldn't allocate output register for constraint '" + 8311 Twine(OpInfo.ConstraintCode) + "'"); 8312 return; 8313 } 8314 8315 // Add information to the INLINEASM node to know that this register is 8316 // set. 8317 OpInfo.AssignedRegs.AddInlineAsmOperands( 8318 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8319 : InlineAsm::Kind_RegDef, 8320 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8321 } 8322 break; 8323 8324 case InlineAsm::isInput: { 8325 SDValue InOperandVal = OpInfo.CallOperand; 8326 8327 if (OpInfo.isMatchingInputConstraint()) { 8328 // If this is required to match an output register we have already set, 8329 // just use its register. 8330 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8331 AsmNodeOperands); 8332 unsigned OpFlag = 8333 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8334 if (InlineAsm::isRegDefKind(OpFlag) || 8335 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8336 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8337 if (OpInfo.isIndirect) { 8338 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8339 emitInlineAsmError(CS, "inline asm not supported yet:" 8340 " don't know how to handle tied " 8341 "indirect register inputs"); 8342 return; 8343 } 8344 8345 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 8346 SmallVector<unsigned, 4> Regs; 8347 8348 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { 8349 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8350 MachineRegisterInfo &RegInfo = 8351 DAG.getMachineFunction().getRegInfo(); 8352 for (unsigned i = 0; i != NumRegs; ++i) 8353 Regs.push_back(RegInfo.createVirtualRegister(RC)); 8354 } else { 8355 emitInlineAsmError(CS, "inline asm error: This value type register " 8356 "class is not natively supported!"); 8357 return; 8358 } 8359 8360 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8361 8362 SDLoc dl = getCurSDLoc(); 8363 // Use the produced MatchedRegs object to 8364 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 8365 CS.getInstruction()); 8366 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8367 true, OpInfo.getMatchedOperand(), dl, 8368 DAG, AsmNodeOperands); 8369 break; 8370 } 8371 8372 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8373 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8374 "Unexpected number of operands"); 8375 // Add information to the INLINEASM node to know about this input. 8376 // See InlineAsm.h isUseOperandTiedToDef. 8377 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8378 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8379 OpInfo.getMatchedOperand()); 8380 AsmNodeOperands.push_back(DAG.getTargetConstant( 8381 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8382 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8383 break; 8384 } 8385 8386 // Treat indirect 'X' constraint as memory. 8387 if (OpInfo.ConstraintType == TargetLowering::C_Other && 8388 OpInfo.isIndirect) 8389 OpInfo.ConstraintType = TargetLowering::C_Memory; 8390 8391 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 8392 OpInfo.ConstraintType == TargetLowering::C_Other) { 8393 std::vector<SDValue> Ops; 8394 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 8395 Ops, DAG); 8396 if (Ops.empty()) { 8397 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 8398 if (isa<ConstantSDNode>(InOperandVal)) { 8399 emitInlineAsmError(CS, "value out of range for constraint '" + 8400 Twine(OpInfo.ConstraintCode) + "'"); 8401 return; 8402 } 8403 8404 emitInlineAsmError(CS, "invalid operand for inline asm constraint '" + 8405 Twine(OpInfo.ConstraintCode) + "'"); 8406 return; 8407 } 8408 8409 // Add information to the INLINEASM node to know about this input. 8410 unsigned ResOpType = 8411 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 8412 AsmNodeOperands.push_back(DAG.getTargetConstant( 8413 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8414 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 8415 break; 8416 } 8417 8418 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8419 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 8420 assert(InOperandVal.getValueType() == 8421 TLI.getPointerTy(DAG.getDataLayout()) && 8422 "Memory operands expect pointer values"); 8423 8424 unsigned ConstraintID = 8425 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8426 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8427 "Failed to convert memory constraint code to constraint id."); 8428 8429 // Add information to the INLINEASM node to know about this input. 8430 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8431 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 8432 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 8433 getCurSDLoc(), 8434 MVT::i32)); 8435 AsmNodeOperands.push_back(InOperandVal); 8436 break; 8437 } 8438 8439 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 8440 OpInfo.ConstraintType == TargetLowering::C_Register) && 8441 "Unknown constraint type!"); 8442 8443 // TODO: Support this. 8444 if (OpInfo.isIndirect) { 8445 emitInlineAsmError( 8446 CS, "Don't know how to handle indirect register inputs yet " 8447 "for constraint '" + 8448 Twine(OpInfo.ConstraintCode) + "'"); 8449 return; 8450 } 8451 8452 // Copy the input into the appropriate registers. 8453 if (OpInfo.AssignedRegs.Regs.empty()) { 8454 emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" + 8455 Twine(OpInfo.ConstraintCode) + "'"); 8456 return; 8457 } 8458 8459 SDLoc dl = getCurSDLoc(); 8460 8461 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, 8462 Chain, &Flag, CS.getInstruction()); 8463 8464 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 8465 dl, DAG, AsmNodeOperands); 8466 break; 8467 } 8468 case InlineAsm::isClobber: 8469 // Add the clobbered value to the operand list, so that the register 8470 // allocator is aware that the physreg got clobbered. 8471 if (!OpInfo.AssignedRegs.Regs.empty()) 8472 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 8473 false, 0, getCurSDLoc(), DAG, 8474 AsmNodeOperands); 8475 break; 8476 } 8477 } 8478 8479 // Finish up input operands. Set the input chain and add the flag last. 8480 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 8481 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 8482 8483 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 8484 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 8485 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 8486 Flag = Chain.getValue(1); 8487 8488 // Do additional work to generate outputs. 8489 8490 SmallVector<EVT, 1> ResultVTs; 8491 SmallVector<SDValue, 1> ResultValues; 8492 SmallVector<SDValue, 8> OutChains; 8493 8494 llvm::Type *CSResultType = CS.getType(); 8495 ArrayRef<Type *> ResultTypes; 8496 if (StructType *StructResult = dyn_cast<StructType>(CSResultType)) 8497 ResultTypes = StructResult->elements(); 8498 else if (!CSResultType->isVoidTy()) 8499 ResultTypes = makeArrayRef(CSResultType); 8500 8501 auto CurResultType = ResultTypes.begin(); 8502 auto handleRegAssign = [&](SDValue V) { 8503 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 8504 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 8505 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 8506 ++CurResultType; 8507 // If the type of the inline asm call site return value is different but has 8508 // same size as the type of the asm output bitcast it. One example of this 8509 // is for vectors with different width / number of elements. This can 8510 // happen for register classes that can contain multiple different value 8511 // types. The preg or vreg allocated may not have the same VT as was 8512 // expected. 8513 // 8514 // This can also happen for a return value that disagrees with the register 8515 // class it is put in, eg. a double in a general-purpose register on a 8516 // 32-bit machine. 8517 if (ResultVT != V.getValueType() && 8518 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 8519 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 8520 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 8521 V.getValueType().isInteger()) { 8522 // If a result value was tied to an input value, the computed result 8523 // may have a wider width than the expected result. Extract the 8524 // relevant portion. 8525 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 8526 } 8527 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 8528 ResultVTs.push_back(ResultVT); 8529 ResultValues.push_back(V); 8530 }; 8531 8532 // Deal with output operands. 8533 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8534 if (OpInfo.Type == InlineAsm::isOutput) { 8535 SDValue Val; 8536 // Skip trivial output operands. 8537 if (OpInfo.AssignedRegs.Regs.empty()) 8538 continue; 8539 8540 switch (OpInfo.ConstraintType) { 8541 case TargetLowering::C_Register: 8542 case TargetLowering::C_RegisterClass: 8543 Val = OpInfo.AssignedRegs.getCopyFromRegs( 8544 DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction()); 8545 break; 8546 case TargetLowering::C_Immediate: 8547 case TargetLowering::C_Other: 8548 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 8549 OpInfo, DAG); 8550 break; 8551 case TargetLowering::C_Memory: 8552 break; // Already handled. 8553 case TargetLowering::C_Unknown: 8554 assert(false && "Unexpected unknown constraint"); 8555 } 8556 8557 // Indirect output manifest as stores. Record output chains. 8558 if (OpInfo.isIndirect) { 8559 const Value *Ptr = OpInfo.CallOperandVal; 8560 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 8561 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 8562 MachinePointerInfo(Ptr)); 8563 OutChains.push_back(Store); 8564 } else { 8565 // generate CopyFromRegs to associated registers. 8566 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 8567 if (Val.getOpcode() == ISD::MERGE_VALUES) { 8568 for (const SDValue &V : Val->op_values()) 8569 handleRegAssign(V); 8570 } else 8571 handleRegAssign(Val); 8572 } 8573 } 8574 } 8575 8576 // Set results. 8577 if (!ResultValues.empty()) { 8578 assert(CurResultType == ResultTypes.end() && 8579 "Mismatch in number of ResultTypes"); 8580 assert(ResultValues.size() == ResultTypes.size() && 8581 "Mismatch in number of output operands in asm result"); 8582 8583 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 8584 DAG.getVTList(ResultVTs), ResultValues); 8585 setValue(CS.getInstruction(), V); 8586 } 8587 8588 // Collect store chains. 8589 if (!OutChains.empty()) 8590 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 8591 8592 // Only Update Root if inline assembly has a memory effect. 8593 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr) 8594 DAG.setRoot(Chain); 8595 } 8596 8597 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS, 8598 const Twine &Message) { 8599 LLVMContext &Ctx = *DAG.getContext(); 8600 Ctx.emitError(CS.getInstruction(), Message); 8601 8602 // Make sure we leave the DAG in a valid state 8603 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8604 SmallVector<EVT, 1> ValueVTs; 8605 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8606 8607 if (ValueVTs.empty()) 8608 return; 8609 8610 SmallVector<SDValue, 1> Ops; 8611 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 8612 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 8613 8614 setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc())); 8615 } 8616 8617 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 8618 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 8619 MVT::Other, getRoot(), 8620 getValue(I.getArgOperand(0)), 8621 DAG.getSrcValue(I.getArgOperand(0)))); 8622 } 8623 8624 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 8625 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8626 const DataLayout &DL = DAG.getDataLayout(); 8627 SDValue V = DAG.getVAArg( 8628 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 8629 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 8630 DL.getABITypeAlignment(I.getType())); 8631 DAG.setRoot(V.getValue(1)); 8632 8633 if (I.getType()->isPointerTy()) 8634 V = DAG.getPtrExtOrTrunc( 8635 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 8636 setValue(&I, V); 8637 } 8638 8639 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 8640 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 8641 MVT::Other, getRoot(), 8642 getValue(I.getArgOperand(0)), 8643 DAG.getSrcValue(I.getArgOperand(0)))); 8644 } 8645 8646 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 8647 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 8648 MVT::Other, getRoot(), 8649 getValue(I.getArgOperand(0)), 8650 getValue(I.getArgOperand(1)), 8651 DAG.getSrcValue(I.getArgOperand(0)), 8652 DAG.getSrcValue(I.getArgOperand(1)))); 8653 } 8654 8655 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 8656 const Instruction &I, 8657 SDValue Op) { 8658 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 8659 if (!Range) 8660 return Op; 8661 8662 ConstantRange CR = getConstantRangeFromMetadata(*Range); 8663 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 8664 return Op; 8665 8666 APInt Lo = CR.getUnsignedMin(); 8667 if (!Lo.isMinValue()) 8668 return Op; 8669 8670 APInt Hi = CR.getUnsignedMax(); 8671 unsigned Bits = std::max(Hi.getActiveBits(), 8672 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 8673 8674 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8675 8676 SDLoc SL = getCurSDLoc(); 8677 8678 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8679 DAG.getValueType(SmallVT)); 8680 unsigned NumVals = Op.getNode()->getNumValues(); 8681 if (NumVals == 1) 8682 return ZExt; 8683 8684 SmallVector<SDValue, 4> Ops; 8685 8686 Ops.push_back(ZExt); 8687 for (unsigned I = 1; I != NumVals; ++I) 8688 Ops.push_back(Op.getValue(I)); 8689 8690 return DAG.getMergeValues(Ops, SL); 8691 } 8692 8693 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8694 /// the call being lowered. 8695 /// 8696 /// This is a helper for lowering intrinsics that follow a target calling 8697 /// convention or require stack pointer adjustment. Only a subset of the 8698 /// intrinsic's operands need to participate in the calling convention. 8699 void SelectionDAGBuilder::populateCallLoweringInfo( 8700 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 8701 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8702 bool IsPatchPoint) { 8703 TargetLowering::ArgListTy Args; 8704 Args.reserve(NumArgs); 8705 8706 // Populate the argument list. 8707 // Attributes for args start at offset 1, after the return attribute. 8708 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8709 ArgI != ArgE; ++ArgI) { 8710 const Value *V = Call->getOperand(ArgI); 8711 8712 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 8713 8714 TargetLowering::ArgListEntry Entry; 8715 Entry.Node = getValue(V); 8716 Entry.Ty = V->getType(); 8717 Entry.setAttributes(Call, ArgI); 8718 Args.push_back(Entry); 8719 } 8720 8721 CLI.setDebugLoc(getCurSDLoc()) 8722 .setChain(getRoot()) 8723 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 8724 .setDiscardResult(Call->use_empty()) 8725 .setIsPatchPoint(IsPatchPoint); 8726 } 8727 8728 /// Add a stack map intrinsic call's live variable operands to a stackmap 8729 /// or patchpoint target node's operand list. 8730 /// 8731 /// Constants are converted to TargetConstants purely as an optimization to 8732 /// avoid constant materialization and register allocation. 8733 /// 8734 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 8735 /// generate addess computation nodes, and so FinalizeISel can convert the 8736 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 8737 /// address materialization and register allocation, but may also be required 8738 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 8739 /// alloca in the entry block, then the runtime may assume that the alloca's 8740 /// StackMap location can be read immediately after compilation and that the 8741 /// location is valid at any point during execution (this is similar to the 8742 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 8743 /// only available in a register, then the runtime would need to trap when 8744 /// execution reaches the StackMap in order to read the alloca's location. 8745 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx, 8746 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 8747 SelectionDAGBuilder &Builder) { 8748 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) { 8749 SDValue OpVal = Builder.getValue(CS.getArgument(i)); 8750 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 8751 Ops.push_back( 8752 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 8753 Ops.push_back( 8754 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 8755 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 8756 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 8757 Ops.push_back(Builder.DAG.getTargetFrameIndex( 8758 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 8759 } else 8760 Ops.push_back(OpVal); 8761 } 8762 } 8763 8764 /// Lower llvm.experimental.stackmap directly to its target opcode. 8765 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 8766 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 8767 // [live variables...]) 8768 8769 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 8770 8771 SDValue Chain, InFlag, Callee, NullPtr; 8772 SmallVector<SDValue, 32> Ops; 8773 8774 SDLoc DL = getCurSDLoc(); 8775 Callee = getValue(CI.getCalledValue()); 8776 NullPtr = DAG.getIntPtrConstant(0, DL, true); 8777 8778 // The stackmap intrinsic only records the live variables (the arguments 8779 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 8780 // intrinsic, this won't be lowered to a function call. This means we don't 8781 // have to worry about calling conventions and target specific lowering code. 8782 // Instead we perform the call lowering right here. 8783 // 8784 // chain, flag = CALLSEQ_START(chain, 0, 0) 8785 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 8786 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 8787 // 8788 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 8789 InFlag = Chain.getValue(1); 8790 8791 // Add the <id> and <numBytes> constants. 8792 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 8793 Ops.push_back(DAG.getTargetConstant( 8794 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 8795 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 8796 Ops.push_back(DAG.getTargetConstant( 8797 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 8798 MVT::i32)); 8799 8800 // Push live variables for the stack map. 8801 addStackMapLiveVars(&CI, 2, DL, Ops, *this); 8802 8803 // We are not pushing any register mask info here on the operands list, 8804 // because the stackmap doesn't clobber anything. 8805 8806 // Push the chain and the glue flag. 8807 Ops.push_back(Chain); 8808 Ops.push_back(InFlag); 8809 8810 // Create the STACKMAP node. 8811 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8812 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 8813 Chain = SDValue(SM, 0); 8814 InFlag = Chain.getValue(1); 8815 8816 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 8817 8818 // Stackmaps don't generate values, so nothing goes into the NodeMap. 8819 8820 // Set the root to the target-lowered call chain. 8821 DAG.setRoot(Chain); 8822 8823 // Inform the Frame Information that we have a stackmap in this function. 8824 FuncInfo.MF->getFrameInfo().setHasStackMap(); 8825 } 8826 8827 /// Lower llvm.experimental.patchpoint directly to its target opcode. 8828 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS, 8829 const BasicBlock *EHPadBB) { 8830 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 8831 // i32 <numBytes>, 8832 // i8* <target>, 8833 // i32 <numArgs>, 8834 // [Args...], 8835 // [live variables...]) 8836 8837 CallingConv::ID CC = CS.getCallingConv(); 8838 bool IsAnyRegCC = CC == CallingConv::AnyReg; 8839 bool HasDef = !CS->getType()->isVoidTy(); 8840 SDLoc dl = getCurSDLoc(); 8841 SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos)); 8842 8843 // Handle immediate and symbolic callees. 8844 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 8845 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 8846 /*isTarget=*/true); 8847 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 8848 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 8849 SDLoc(SymbolicCallee), 8850 SymbolicCallee->getValueType(0)); 8851 8852 // Get the real number of arguments participating in the call <numArgs> 8853 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos)); 8854 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 8855 8856 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 8857 // Intrinsics include all meta-operands up to but not including CC. 8858 unsigned NumMetaOpers = PatchPointOpers::CCPos; 8859 assert(CS.arg_size() >= NumMetaOpers + NumArgs && 8860 "Not enough arguments provided to the patchpoint intrinsic"); 8861 8862 // For AnyRegCC the arguments are lowered later on manually. 8863 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 8864 Type *ReturnTy = 8865 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType(); 8866 8867 TargetLowering::CallLoweringInfo CLI(DAG); 8868 populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()), 8869 NumMetaOpers, NumCallArgs, Callee, ReturnTy, true); 8870 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8871 8872 SDNode *CallEnd = Result.second.getNode(); 8873 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 8874 CallEnd = CallEnd->getOperand(0).getNode(); 8875 8876 /// Get a call instruction from the call sequence chain. 8877 /// Tail calls are not allowed. 8878 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 8879 "Expected a callseq node."); 8880 SDNode *Call = CallEnd->getOperand(0).getNode(); 8881 bool HasGlue = Call->getGluedNode(); 8882 8883 // Replace the target specific call node with the patchable intrinsic. 8884 SmallVector<SDValue, 8> Ops; 8885 8886 // Add the <id> and <numBytes> constants. 8887 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos)); 8888 Ops.push_back(DAG.getTargetConstant( 8889 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 8890 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos)); 8891 Ops.push_back(DAG.getTargetConstant( 8892 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 8893 MVT::i32)); 8894 8895 // Add the callee. 8896 Ops.push_back(Callee); 8897 8898 // Adjust <numArgs> to account for any arguments that have been passed on the 8899 // stack instead. 8900 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 8901 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 8902 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 8903 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 8904 8905 // Add the calling convention 8906 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 8907 8908 // Add the arguments we omitted previously. The register allocator should 8909 // place these in any free register. 8910 if (IsAnyRegCC) 8911 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 8912 Ops.push_back(getValue(CS.getArgument(i))); 8913 8914 // Push the arguments from the call instruction up to the register mask. 8915 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 8916 Ops.append(Call->op_begin() + 2, e); 8917 8918 // Push live variables for the stack map. 8919 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this); 8920 8921 // Push the register mask info. 8922 if (HasGlue) 8923 Ops.push_back(*(Call->op_end()-2)); 8924 else 8925 Ops.push_back(*(Call->op_end()-1)); 8926 8927 // Push the chain (this is originally the first operand of the call, but 8928 // becomes now the last or second to last operand). 8929 Ops.push_back(*(Call->op_begin())); 8930 8931 // Push the glue flag (last operand). 8932 if (HasGlue) 8933 Ops.push_back(*(Call->op_end()-1)); 8934 8935 SDVTList NodeTys; 8936 if (IsAnyRegCC && HasDef) { 8937 // Create the return types based on the intrinsic definition 8938 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8939 SmallVector<EVT, 3> ValueVTs; 8940 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8941 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 8942 8943 // There is always a chain and a glue type at the end 8944 ValueVTs.push_back(MVT::Other); 8945 ValueVTs.push_back(MVT::Glue); 8946 NodeTys = DAG.getVTList(ValueVTs); 8947 } else 8948 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8949 8950 // Replace the target specific call node with a PATCHPOINT node. 8951 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 8952 dl, NodeTys, Ops); 8953 8954 // Update the NodeMap. 8955 if (HasDef) { 8956 if (IsAnyRegCC) 8957 setValue(CS.getInstruction(), SDValue(MN, 0)); 8958 else 8959 setValue(CS.getInstruction(), Result.first); 8960 } 8961 8962 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 8963 // call sequence. Furthermore the location of the chain and glue can change 8964 // when the AnyReg calling convention is used and the intrinsic returns a 8965 // value. 8966 if (IsAnyRegCC && HasDef) { 8967 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 8968 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 8969 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 8970 } else 8971 DAG.ReplaceAllUsesWith(Call, MN); 8972 DAG.DeleteNode(Call); 8973 8974 // Inform the Frame Information that we have a patchpoint in this function. 8975 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 8976 } 8977 8978 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 8979 unsigned Intrinsic) { 8980 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8981 SDValue Op1 = getValue(I.getArgOperand(0)); 8982 SDValue Op2; 8983 if (I.getNumArgOperands() > 1) 8984 Op2 = getValue(I.getArgOperand(1)); 8985 SDLoc dl = getCurSDLoc(); 8986 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8987 SDValue Res; 8988 FastMathFlags FMF; 8989 if (isa<FPMathOperator>(I)) 8990 FMF = I.getFastMathFlags(); 8991 8992 switch (Intrinsic) { 8993 case Intrinsic::experimental_vector_reduce_v2_fadd: 8994 if (FMF.allowReassoc()) 8995 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 8996 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2)); 8997 else 8998 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2); 8999 break; 9000 case Intrinsic::experimental_vector_reduce_v2_fmul: 9001 if (FMF.allowReassoc()) 9002 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 9003 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2)); 9004 else 9005 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2); 9006 break; 9007 case Intrinsic::experimental_vector_reduce_add: 9008 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 9009 break; 9010 case Intrinsic::experimental_vector_reduce_mul: 9011 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 9012 break; 9013 case Intrinsic::experimental_vector_reduce_and: 9014 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 9015 break; 9016 case Intrinsic::experimental_vector_reduce_or: 9017 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 9018 break; 9019 case Intrinsic::experimental_vector_reduce_xor: 9020 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 9021 break; 9022 case Intrinsic::experimental_vector_reduce_smax: 9023 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 9024 break; 9025 case Intrinsic::experimental_vector_reduce_smin: 9026 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 9027 break; 9028 case Intrinsic::experimental_vector_reduce_umax: 9029 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 9030 break; 9031 case Intrinsic::experimental_vector_reduce_umin: 9032 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 9033 break; 9034 case Intrinsic::experimental_vector_reduce_fmax: 9035 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1); 9036 break; 9037 case Intrinsic::experimental_vector_reduce_fmin: 9038 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1); 9039 break; 9040 default: 9041 llvm_unreachable("Unhandled vector reduce intrinsic"); 9042 } 9043 setValue(&I, Res); 9044 } 9045 9046 /// Returns an AttributeList representing the attributes applied to the return 9047 /// value of the given call. 9048 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9049 SmallVector<Attribute::AttrKind, 2> Attrs; 9050 if (CLI.RetSExt) 9051 Attrs.push_back(Attribute::SExt); 9052 if (CLI.RetZExt) 9053 Attrs.push_back(Attribute::ZExt); 9054 if (CLI.IsInReg) 9055 Attrs.push_back(Attribute::InReg); 9056 9057 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9058 Attrs); 9059 } 9060 9061 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9062 /// implementation, which just calls LowerCall. 9063 /// FIXME: When all targets are 9064 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9065 std::pair<SDValue, SDValue> 9066 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9067 // Handle the incoming return values from the call. 9068 CLI.Ins.clear(); 9069 Type *OrigRetTy = CLI.RetTy; 9070 SmallVector<EVT, 4> RetTys; 9071 SmallVector<uint64_t, 4> Offsets; 9072 auto &DL = CLI.DAG.getDataLayout(); 9073 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 9074 9075 if (CLI.IsPostTypeLegalization) { 9076 // If we are lowering a libcall after legalization, split the return type. 9077 SmallVector<EVT, 4> OldRetTys; 9078 SmallVector<uint64_t, 4> OldOffsets; 9079 RetTys.swap(OldRetTys); 9080 Offsets.swap(OldOffsets); 9081 9082 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9083 EVT RetVT = OldRetTys[i]; 9084 uint64_t Offset = OldOffsets[i]; 9085 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9086 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9087 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9088 RetTys.append(NumRegs, RegisterVT); 9089 for (unsigned j = 0; j != NumRegs; ++j) 9090 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9091 } 9092 } 9093 9094 SmallVector<ISD::OutputArg, 4> Outs; 9095 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9096 9097 bool CanLowerReturn = 9098 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9099 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9100 9101 SDValue DemoteStackSlot; 9102 int DemoteStackIdx = -100; 9103 if (!CanLowerReturn) { 9104 // FIXME: equivalent assert? 9105 // assert(!CS.hasInAllocaArgument() && 9106 // "sret demotion is incompatible with inalloca"); 9107 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9108 unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy); 9109 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9110 DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 9111 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9112 DL.getAllocaAddrSpace()); 9113 9114 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9115 ArgListEntry Entry; 9116 Entry.Node = DemoteStackSlot; 9117 Entry.Ty = StackSlotPtrType; 9118 Entry.IsSExt = false; 9119 Entry.IsZExt = false; 9120 Entry.IsInReg = false; 9121 Entry.IsSRet = true; 9122 Entry.IsNest = false; 9123 Entry.IsByVal = false; 9124 Entry.IsReturned = false; 9125 Entry.IsSwiftSelf = false; 9126 Entry.IsSwiftError = false; 9127 Entry.IsCFGuardTarget = false; 9128 Entry.Alignment = Align; 9129 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9130 CLI.NumFixedArgs += 1; 9131 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9132 9133 // sret demotion isn't compatible with tail-calls, since the sret argument 9134 // points into the callers stack frame. 9135 CLI.IsTailCall = false; 9136 } else { 9137 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9138 CLI.RetTy, CLI.CallConv, CLI.IsVarArg); 9139 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9140 ISD::ArgFlagsTy Flags; 9141 if (NeedsRegBlock) { 9142 Flags.setInConsecutiveRegs(); 9143 if (I == RetTys.size() - 1) 9144 Flags.setInConsecutiveRegsLast(); 9145 } 9146 EVT VT = RetTys[I]; 9147 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9148 CLI.CallConv, VT); 9149 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9150 CLI.CallConv, VT); 9151 for (unsigned i = 0; i != NumRegs; ++i) { 9152 ISD::InputArg MyFlags; 9153 MyFlags.Flags = Flags; 9154 MyFlags.VT = RegisterVT; 9155 MyFlags.ArgVT = VT; 9156 MyFlags.Used = CLI.IsReturnValueUsed; 9157 if (CLI.RetTy->isPointerTy()) { 9158 MyFlags.Flags.setPointer(); 9159 MyFlags.Flags.setPointerAddrSpace( 9160 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9161 } 9162 if (CLI.RetSExt) 9163 MyFlags.Flags.setSExt(); 9164 if (CLI.RetZExt) 9165 MyFlags.Flags.setZExt(); 9166 if (CLI.IsInReg) 9167 MyFlags.Flags.setInReg(); 9168 CLI.Ins.push_back(MyFlags); 9169 } 9170 } 9171 } 9172 9173 // We push in swifterror return as the last element of CLI.Ins. 9174 ArgListTy &Args = CLI.getArgs(); 9175 if (supportSwiftError()) { 9176 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9177 if (Args[i].IsSwiftError) { 9178 ISD::InputArg MyFlags; 9179 MyFlags.VT = getPointerTy(DL); 9180 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9181 MyFlags.Flags.setSwiftError(); 9182 CLI.Ins.push_back(MyFlags); 9183 } 9184 } 9185 } 9186 9187 // Handle all of the outgoing arguments. 9188 CLI.Outs.clear(); 9189 CLI.OutVals.clear(); 9190 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9191 SmallVector<EVT, 4> ValueVTs; 9192 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9193 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9194 Type *FinalType = Args[i].Ty; 9195 if (Args[i].IsByVal) 9196 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 9197 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9198 FinalType, CLI.CallConv, CLI.IsVarArg); 9199 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9200 ++Value) { 9201 EVT VT = ValueVTs[Value]; 9202 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9203 SDValue Op = SDValue(Args[i].Node.getNode(), 9204 Args[i].Node.getResNo() + Value); 9205 ISD::ArgFlagsTy Flags; 9206 9207 // Certain targets (such as MIPS), may have a different ABI alignment 9208 // for a type depending on the context. Give the target a chance to 9209 // specify the alignment it wants. 9210 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 9211 9212 if (Args[i].Ty->isPointerTy()) { 9213 Flags.setPointer(); 9214 Flags.setPointerAddrSpace( 9215 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9216 } 9217 if (Args[i].IsZExt) 9218 Flags.setZExt(); 9219 if (Args[i].IsSExt) 9220 Flags.setSExt(); 9221 if (Args[i].IsInReg) { 9222 // If we are using vectorcall calling convention, a structure that is 9223 // passed InReg - is surely an HVA 9224 if (CLI.CallConv == CallingConv::X86_VectorCall && 9225 isa<StructType>(FinalType)) { 9226 // The first value of a structure is marked 9227 if (0 == Value) 9228 Flags.setHvaStart(); 9229 Flags.setHva(); 9230 } 9231 // Set InReg Flag 9232 Flags.setInReg(); 9233 } 9234 if (Args[i].IsSRet) 9235 Flags.setSRet(); 9236 if (Args[i].IsSwiftSelf) 9237 Flags.setSwiftSelf(); 9238 if (Args[i].IsSwiftError) 9239 Flags.setSwiftError(); 9240 if (Args[i].IsCFGuardTarget) 9241 Flags.setCFGuardTarget(); 9242 if (Args[i].IsByVal) 9243 Flags.setByVal(); 9244 if (Args[i].IsInAlloca) { 9245 Flags.setInAlloca(); 9246 // Set the byval flag for CCAssignFn callbacks that don't know about 9247 // inalloca. This way we can know how many bytes we should've allocated 9248 // and how many bytes a callee cleanup function will pop. If we port 9249 // inalloca to more targets, we'll have to add custom inalloca handling 9250 // in the various CC lowering callbacks. 9251 Flags.setByVal(); 9252 } 9253 if (Args[i].IsByVal || Args[i].IsInAlloca) { 9254 PointerType *Ty = cast<PointerType>(Args[i].Ty); 9255 Type *ElementTy = Ty->getElementType(); 9256 9257 unsigned FrameSize = DL.getTypeAllocSize( 9258 Args[i].ByValType ? Args[i].ByValType : ElementTy); 9259 Flags.setByValSize(FrameSize); 9260 9261 // info is not there but there are cases it cannot get right. 9262 unsigned FrameAlign; 9263 if (Args[i].Alignment) 9264 FrameAlign = Args[i].Alignment; 9265 else 9266 FrameAlign = getByValTypeAlignment(ElementTy, DL); 9267 Flags.setByValAlign(Align(FrameAlign)); 9268 } 9269 if (Args[i].IsNest) 9270 Flags.setNest(); 9271 if (NeedsRegBlock) 9272 Flags.setInConsecutiveRegs(); 9273 Flags.setOrigAlign(OriginalAlignment); 9274 9275 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9276 CLI.CallConv, VT); 9277 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9278 CLI.CallConv, VT); 9279 SmallVector<SDValue, 4> Parts(NumParts); 9280 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9281 9282 if (Args[i].IsSExt) 9283 ExtendKind = ISD::SIGN_EXTEND; 9284 else if (Args[i].IsZExt) 9285 ExtendKind = ISD::ZERO_EXTEND; 9286 9287 // Conservatively only handle 'returned' on non-vectors that can be lowered, 9288 // for now. 9289 if (Args[i].IsReturned && !Op.getValueType().isVector() && 9290 CanLowerReturn) { 9291 assert((CLI.RetTy == Args[i].Ty || 9292 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 9293 CLI.RetTy->getPointerAddressSpace() == 9294 Args[i].Ty->getPointerAddressSpace())) && 9295 RetTys.size() == NumValues && "unexpected use of 'returned'"); 9296 // Before passing 'returned' to the target lowering code, ensure that 9297 // either the register MVT and the actual EVT are the same size or that 9298 // the return value and argument are extended in the same way; in these 9299 // cases it's safe to pass the argument register value unchanged as the 9300 // return register value (although it's at the target's option whether 9301 // to do so) 9302 // TODO: allow code generation to take advantage of partially preserved 9303 // registers rather than clobbering the entire register when the 9304 // parameter extension method is not compatible with the return 9305 // extension method 9306 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9307 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9308 CLI.RetZExt == Args[i].IsZExt)) 9309 Flags.setReturned(); 9310 } 9311 9312 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, 9313 CLI.CS.getInstruction(), CLI.CallConv, ExtendKind); 9314 9315 for (unsigned j = 0; j != NumParts; ++j) { 9316 // if it isn't first piece, alignment must be 1 9317 // For scalable vectors the scalable part is currently handled 9318 // by individual targets, so we just use the known minimum size here. 9319 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 9320 i < CLI.NumFixedArgs, i, 9321 j*Parts[j].getValueType().getStoreSize().getKnownMinSize()); 9322 if (NumParts > 1 && j == 0) 9323 MyFlags.Flags.setSplit(); 9324 else if (j != 0) { 9325 MyFlags.Flags.setOrigAlign(Align(1)); 9326 if (j == NumParts - 1) 9327 MyFlags.Flags.setSplitEnd(); 9328 } 9329 9330 CLI.Outs.push_back(MyFlags); 9331 CLI.OutVals.push_back(Parts[j]); 9332 } 9333 9334 if (NeedsRegBlock && Value == NumValues - 1) 9335 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 9336 } 9337 } 9338 9339 SmallVector<SDValue, 4> InVals; 9340 CLI.Chain = LowerCall(CLI, InVals); 9341 9342 // Update CLI.InVals to use outside of this function. 9343 CLI.InVals = InVals; 9344 9345 // Verify that the target's LowerCall behaved as expected. 9346 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 9347 "LowerCall didn't return a valid chain!"); 9348 assert((!CLI.IsTailCall || InVals.empty()) && 9349 "LowerCall emitted a return value for a tail call!"); 9350 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9351 "LowerCall didn't emit the correct number of values!"); 9352 9353 // For a tail call, the return value is merely live-out and there aren't 9354 // any nodes in the DAG representing it. Return a special value to 9355 // indicate that a tail call has been emitted and no more Instructions 9356 // should be processed in the current block. 9357 if (CLI.IsTailCall) { 9358 CLI.DAG.setRoot(CLI.Chain); 9359 return std::make_pair(SDValue(), SDValue()); 9360 } 9361 9362 #ifndef NDEBUG 9363 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 9364 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 9365 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 9366 "LowerCall emitted a value with the wrong type!"); 9367 } 9368 #endif 9369 9370 SmallVector<SDValue, 4> ReturnValues; 9371 if (!CanLowerReturn) { 9372 // The instruction result is the result of loading from the 9373 // hidden sret parameter. 9374 SmallVector<EVT, 1> PVTs; 9375 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 9376 9377 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 9378 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 9379 EVT PtrVT = PVTs[0]; 9380 9381 unsigned NumValues = RetTys.size(); 9382 ReturnValues.resize(NumValues); 9383 SmallVector<SDValue, 4> Chains(NumValues); 9384 9385 // An aggregate return value cannot wrap around the address space, so 9386 // offsets to its parts don't wrap either. 9387 SDNodeFlags Flags; 9388 Flags.setNoUnsignedWrap(true); 9389 9390 for (unsigned i = 0; i < NumValues; ++i) { 9391 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 9392 CLI.DAG.getConstant(Offsets[i], CLI.DL, 9393 PtrVT), Flags); 9394 SDValue L = CLI.DAG.getLoad( 9395 RetTys[i], CLI.DL, CLI.Chain, Add, 9396 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 9397 DemoteStackIdx, Offsets[i]), 9398 /* Alignment = */ 1); 9399 ReturnValues[i] = L; 9400 Chains[i] = L.getValue(1); 9401 } 9402 9403 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 9404 } else { 9405 // Collect the legal value parts into potentially illegal values 9406 // that correspond to the original function's return values. 9407 Optional<ISD::NodeType> AssertOp; 9408 if (CLI.RetSExt) 9409 AssertOp = ISD::AssertSext; 9410 else if (CLI.RetZExt) 9411 AssertOp = ISD::AssertZext; 9412 unsigned CurReg = 0; 9413 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9414 EVT VT = RetTys[I]; 9415 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9416 CLI.CallConv, VT); 9417 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9418 CLI.CallConv, VT); 9419 9420 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 9421 NumRegs, RegisterVT, VT, nullptr, 9422 CLI.CallConv, AssertOp)); 9423 CurReg += NumRegs; 9424 } 9425 9426 // For a function returning void, there is no return value. We can't create 9427 // such a node, so we just return a null return value in that case. In 9428 // that case, nothing will actually look at the value. 9429 if (ReturnValues.empty()) 9430 return std::make_pair(SDValue(), CLI.Chain); 9431 } 9432 9433 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 9434 CLI.DAG.getVTList(RetTys), ReturnValues); 9435 return std::make_pair(Res, CLI.Chain); 9436 } 9437 9438 void TargetLowering::LowerOperationWrapper(SDNode *N, 9439 SmallVectorImpl<SDValue> &Results, 9440 SelectionDAG &DAG) const { 9441 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG)) 9442 Results.push_back(Res); 9443 } 9444 9445 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9446 llvm_unreachable("LowerOperation not implemented for this target!"); 9447 } 9448 9449 void 9450 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 9451 SDValue Op = getNonRegisterValue(V); 9452 assert((Op.getOpcode() != ISD::CopyFromReg || 9453 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 9454 "Copy from a reg to the same reg!"); 9455 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 9456 9457 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9458 // If this is an InlineAsm we have to match the registers required, not the 9459 // notional registers required by the type. 9460 9461 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 9462 None); // This is not an ABI copy. 9463 SDValue Chain = DAG.getEntryNode(); 9464 9465 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 9466 FuncInfo.PreferredExtendType.end()) 9467 ? ISD::ANY_EXTEND 9468 : FuncInfo.PreferredExtendType[V]; 9469 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 9470 PendingExports.push_back(Chain); 9471 } 9472 9473 #include "llvm/CodeGen/SelectionDAGISel.h" 9474 9475 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 9476 /// entry block, return true. This includes arguments used by switches, since 9477 /// the switch may expand into multiple basic blocks. 9478 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 9479 // With FastISel active, we may be splitting blocks, so force creation 9480 // of virtual registers for all non-dead arguments. 9481 if (FastISel) 9482 return A->use_empty(); 9483 9484 const BasicBlock &Entry = A->getParent()->front(); 9485 for (const User *U : A->users()) 9486 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 9487 return false; // Use not in entry block. 9488 9489 return true; 9490 } 9491 9492 using ArgCopyElisionMapTy = 9493 DenseMap<const Argument *, 9494 std::pair<const AllocaInst *, const StoreInst *>>; 9495 9496 /// Scan the entry block of the function in FuncInfo for arguments that look 9497 /// like copies into a local alloca. Record any copied arguments in 9498 /// ArgCopyElisionCandidates. 9499 static void 9500 findArgumentCopyElisionCandidates(const DataLayout &DL, 9501 FunctionLoweringInfo *FuncInfo, 9502 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 9503 // Record the state of every static alloca used in the entry block. Argument 9504 // allocas are all used in the entry block, so we need approximately as many 9505 // entries as we have arguments. 9506 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 9507 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 9508 unsigned NumArgs = FuncInfo->Fn->arg_size(); 9509 StaticAllocas.reserve(NumArgs * 2); 9510 9511 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 9512 if (!V) 9513 return nullptr; 9514 V = V->stripPointerCasts(); 9515 const auto *AI = dyn_cast<AllocaInst>(V); 9516 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 9517 return nullptr; 9518 auto Iter = StaticAllocas.insert({AI, Unknown}); 9519 return &Iter.first->second; 9520 }; 9521 9522 // Look for stores of arguments to static allocas. Look through bitcasts and 9523 // GEPs to handle type coercions, as long as the alloca is fully initialized 9524 // by the store. Any non-store use of an alloca escapes it and any subsequent 9525 // unanalyzed store might write it. 9526 // FIXME: Handle structs initialized with multiple stores. 9527 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 9528 // Look for stores, and handle non-store uses conservatively. 9529 const auto *SI = dyn_cast<StoreInst>(&I); 9530 if (!SI) { 9531 // We will look through cast uses, so ignore them completely. 9532 if (I.isCast()) 9533 continue; 9534 // Ignore debug info intrinsics, they don't escape or store to allocas. 9535 if (isa<DbgInfoIntrinsic>(I)) 9536 continue; 9537 // This is an unknown instruction. Assume it escapes or writes to all 9538 // static alloca operands. 9539 for (const Use &U : I.operands()) { 9540 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 9541 *Info = StaticAllocaInfo::Clobbered; 9542 } 9543 continue; 9544 } 9545 9546 // If the stored value is a static alloca, mark it as escaped. 9547 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 9548 *Info = StaticAllocaInfo::Clobbered; 9549 9550 // Check if the destination is a static alloca. 9551 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 9552 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 9553 if (!Info) 9554 continue; 9555 const AllocaInst *AI = cast<AllocaInst>(Dst); 9556 9557 // Skip allocas that have been initialized or clobbered. 9558 if (*Info != StaticAllocaInfo::Unknown) 9559 continue; 9560 9561 // Check if the stored value is an argument, and that this store fully 9562 // initializes the alloca. Don't elide copies from the same argument twice. 9563 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 9564 const auto *Arg = dyn_cast<Argument>(Val); 9565 if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() || 9566 Arg->getType()->isEmptyTy() || 9567 DL.getTypeStoreSize(Arg->getType()) != 9568 DL.getTypeAllocSize(AI->getAllocatedType()) || 9569 ArgCopyElisionCandidates.count(Arg)) { 9570 *Info = StaticAllocaInfo::Clobbered; 9571 continue; 9572 } 9573 9574 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 9575 << '\n'); 9576 9577 // Mark this alloca and store for argument copy elision. 9578 *Info = StaticAllocaInfo::Elidable; 9579 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 9580 9581 // Stop scanning if we've seen all arguments. This will happen early in -O0 9582 // builds, which is useful, because -O0 builds have large entry blocks and 9583 // many allocas. 9584 if (ArgCopyElisionCandidates.size() == NumArgs) 9585 break; 9586 } 9587 } 9588 9589 /// Try to elide argument copies from memory into a local alloca. Succeeds if 9590 /// ArgVal is a load from a suitable fixed stack object. 9591 static void tryToElideArgumentCopy( 9592 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 9593 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 9594 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 9595 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 9596 SDValue ArgVal, bool &ArgHasUses) { 9597 // Check if this is a load from a fixed stack object. 9598 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 9599 if (!LNode) 9600 return; 9601 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 9602 if (!FINode) 9603 return; 9604 9605 // Check that the fixed stack object is the right size and alignment. 9606 // Look at the alignment that the user wrote on the alloca instead of looking 9607 // at the stack object. 9608 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 9609 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 9610 const AllocaInst *AI = ArgCopyIter->second.first; 9611 int FixedIndex = FINode->getIndex(); 9612 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 9613 int OldIndex = AllocaIndex; 9614 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 9615 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 9616 LLVM_DEBUG( 9617 dbgs() << " argument copy elision failed due to bad fixed stack " 9618 "object size\n"); 9619 return; 9620 } 9621 unsigned RequiredAlignment = AI->getAlignment(); 9622 if (!RequiredAlignment) { 9623 RequiredAlignment = FuncInfo.MF->getDataLayout().getABITypeAlignment( 9624 AI->getAllocatedType()); 9625 } 9626 if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) { 9627 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 9628 "greater than stack argument alignment (" 9629 << RequiredAlignment << " vs " 9630 << MFI.getObjectAlignment(FixedIndex) << ")\n"); 9631 return; 9632 } 9633 9634 // Perform the elision. Delete the old stack object and replace its only use 9635 // in the variable info map. Mark the stack object as mutable. 9636 LLVM_DEBUG({ 9637 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 9638 << " Replacing frame index " << OldIndex << " with " << FixedIndex 9639 << '\n'; 9640 }); 9641 MFI.RemoveStackObject(OldIndex); 9642 MFI.setIsImmutableObjectIndex(FixedIndex, false); 9643 AllocaIndex = FixedIndex; 9644 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 9645 Chains.push_back(ArgVal.getValue(1)); 9646 9647 // Avoid emitting code for the store implementing the copy. 9648 const StoreInst *SI = ArgCopyIter->second.second; 9649 ElidedArgCopyInstrs.insert(SI); 9650 9651 // Check for uses of the argument again so that we can avoid exporting ArgVal 9652 // if it is't used by anything other than the store. 9653 for (const Value *U : Arg.users()) { 9654 if (U != SI) { 9655 ArgHasUses = true; 9656 break; 9657 } 9658 } 9659 } 9660 9661 void SelectionDAGISel::LowerArguments(const Function &F) { 9662 SelectionDAG &DAG = SDB->DAG; 9663 SDLoc dl = SDB->getCurSDLoc(); 9664 const DataLayout &DL = DAG.getDataLayout(); 9665 SmallVector<ISD::InputArg, 16> Ins; 9666 9667 if (!FuncInfo->CanLowerReturn) { 9668 // Put in an sret pointer parameter before all the other parameters. 9669 SmallVector<EVT, 1> ValueVTs; 9670 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9671 F.getReturnType()->getPointerTo( 9672 DAG.getDataLayout().getAllocaAddrSpace()), 9673 ValueVTs); 9674 9675 // NOTE: Assuming that a pointer will never break down to more than one VT 9676 // or one register. 9677 ISD::ArgFlagsTy Flags; 9678 Flags.setSRet(); 9679 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 9680 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 9681 ISD::InputArg::NoArgIndex, 0); 9682 Ins.push_back(RetArg); 9683 } 9684 9685 // Look for stores of arguments to static allocas. Mark such arguments with a 9686 // flag to ask the target to give us the memory location of that argument if 9687 // available. 9688 ArgCopyElisionMapTy ArgCopyElisionCandidates; 9689 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 9690 ArgCopyElisionCandidates); 9691 9692 // Set up the incoming argument description vector. 9693 for (const Argument &Arg : F.args()) { 9694 unsigned ArgNo = Arg.getArgNo(); 9695 SmallVector<EVT, 4> ValueVTs; 9696 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9697 bool isArgValueUsed = !Arg.use_empty(); 9698 unsigned PartBase = 0; 9699 Type *FinalType = Arg.getType(); 9700 if (Arg.hasAttribute(Attribute::ByVal)) 9701 FinalType = Arg.getParamByValType(); 9702 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 9703 FinalType, F.getCallingConv(), F.isVarArg()); 9704 for (unsigned Value = 0, NumValues = ValueVTs.size(); 9705 Value != NumValues; ++Value) { 9706 EVT VT = ValueVTs[Value]; 9707 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 9708 ISD::ArgFlagsTy Flags; 9709 9710 // Certain targets (such as MIPS), may have a different ABI alignment 9711 // for a type depending on the context. Give the target a chance to 9712 // specify the alignment it wants. 9713 const Align OriginalAlignment( 9714 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 9715 9716 if (Arg.getType()->isPointerTy()) { 9717 Flags.setPointer(); 9718 Flags.setPointerAddrSpace( 9719 cast<PointerType>(Arg.getType())->getAddressSpace()); 9720 } 9721 if (Arg.hasAttribute(Attribute::ZExt)) 9722 Flags.setZExt(); 9723 if (Arg.hasAttribute(Attribute::SExt)) 9724 Flags.setSExt(); 9725 if (Arg.hasAttribute(Attribute::InReg)) { 9726 // If we are using vectorcall calling convention, a structure that is 9727 // passed InReg - is surely an HVA 9728 if (F.getCallingConv() == CallingConv::X86_VectorCall && 9729 isa<StructType>(Arg.getType())) { 9730 // The first value of a structure is marked 9731 if (0 == Value) 9732 Flags.setHvaStart(); 9733 Flags.setHva(); 9734 } 9735 // Set InReg Flag 9736 Flags.setInReg(); 9737 } 9738 if (Arg.hasAttribute(Attribute::StructRet)) 9739 Flags.setSRet(); 9740 if (Arg.hasAttribute(Attribute::SwiftSelf)) 9741 Flags.setSwiftSelf(); 9742 if (Arg.hasAttribute(Attribute::SwiftError)) 9743 Flags.setSwiftError(); 9744 if (Arg.hasAttribute(Attribute::ByVal)) 9745 Flags.setByVal(); 9746 if (Arg.hasAttribute(Attribute::InAlloca)) { 9747 Flags.setInAlloca(); 9748 // Set the byval flag for CCAssignFn callbacks that don't know about 9749 // inalloca. This way we can know how many bytes we should've allocated 9750 // and how many bytes a callee cleanup function will pop. If we port 9751 // inalloca to more targets, we'll have to add custom inalloca handling 9752 // in the various CC lowering callbacks. 9753 Flags.setByVal(); 9754 } 9755 if (F.getCallingConv() == CallingConv::X86_INTR) { 9756 // IA Interrupt passes frame (1st parameter) by value in the stack. 9757 if (ArgNo == 0) 9758 Flags.setByVal(); 9759 } 9760 if (Flags.isByVal() || Flags.isInAlloca()) { 9761 Type *ElementTy = Arg.getParamByValType(); 9762 9763 // For ByVal, size and alignment should be passed from FE. BE will 9764 // guess if this info is not there but there are cases it cannot get 9765 // right. 9766 unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType()); 9767 Flags.setByValSize(FrameSize); 9768 9769 unsigned FrameAlign; 9770 if (Arg.getParamAlignment()) 9771 FrameAlign = Arg.getParamAlignment(); 9772 else 9773 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL); 9774 Flags.setByValAlign(Align(FrameAlign)); 9775 } 9776 if (Arg.hasAttribute(Attribute::Nest)) 9777 Flags.setNest(); 9778 if (NeedsRegBlock) 9779 Flags.setInConsecutiveRegs(); 9780 Flags.setOrigAlign(OriginalAlignment); 9781 if (ArgCopyElisionCandidates.count(&Arg)) 9782 Flags.setCopyElisionCandidate(); 9783 if (Arg.hasAttribute(Attribute::Returned)) 9784 Flags.setReturned(); 9785 9786 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 9787 *CurDAG->getContext(), F.getCallingConv(), VT); 9788 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 9789 *CurDAG->getContext(), F.getCallingConv(), VT); 9790 for (unsigned i = 0; i != NumRegs; ++i) { 9791 // For scalable vectors, use the minimum size; individual targets 9792 // are responsible for handling scalable vector arguments and 9793 // return values. 9794 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 9795 ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize()); 9796 if (NumRegs > 1 && i == 0) 9797 MyFlags.Flags.setSplit(); 9798 // if it isn't first piece, alignment must be 1 9799 else if (i > 0) { 9800 MyFlags.Flags.setOrigAlign(Align(1)); 9801 if (i == NumRegs - 1) 9802 MyFlags.Flags.setSplitEnd(); 9803 } 9804 Ins.push_back(MyFlags); 9805 } 9806 if (NeedsRegBlock && Value == NumValues - 1) 9807 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 9808 PartBase += VT.getStoreSize().getKnownMinSize(); 9809 } 9810 } 9811 9812 // Call the target to set up the argument values. 9813 SmallVector<SDValue, 8> InVals; 9814 SDValue NewRoot = TLI->LowerFormalArguments( 9815 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 9816 9817 // Verify that the target's LowerFormalArguments behaved as expected. 9818 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 9819 "LowerFormalArguments didn't return a valid chain!"); 9820 assert(InVals.size() == Ins.size() && 9821 "LowerFormalArguments didn't emit the correct number of values!"); 9822 LLVM_DEBUG({ 9823 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 9824 assert(InVals[i].getNode() && 9825 "LowerFormalArguments emitted a null value!"); 9826 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 9827 "LowerFormalArguments emitted a value with the wrong type!"); 9828 } 9829 }); 9830 9831 // Update the DAG with the new chain value resulting from argument lowering. 9832 DAG.setRoot(NewRoot); 9833 9834 // Set up the argument values. 9835 unsigned i = 0; 9836 if (!FuncInfo->CanLowerReturn) { 9837 // Create a virtual register for the sret pointer, and put in a copy 9838 // from the sret argument into it. 9839 SmallVector<EVT, 1> ValueVTs; 9840 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9841 F.getReturnType()->getPointerTo( 9842 DAG.getDataLayout().getAllocaAddrSpace()), 9843 ValueVTs); 9844 MVT VT = ValueVTs[0].getSimpleVT(); 9845 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 9846 Optional<ISD::NodeType> AssertOp = None; 9847 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 9848 nullptr, F.getCallingConv(), AssertOp); 9849 9850 MachineFunction& MF = SDB->DAG.getMachineFunction(); 9851 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 9852 Register SRetReg = 9853 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 9854 FuncInfo->DemoteRegister = SRetReg; 9855 NewRoot = 9856 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 9857 DAG.setRoot(NewRoot); 9858 9859 // i indexes lowered arguments. Bump it past the hidden sret argument. 9860 ++i; 9861 } 9862 9863 SmallVector<SDValue, 4> Chains; 9864 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 9865 for (const Argument &Arg : F.args()) { 9866 SmallVector<SDValue, 4> ArgValues; 9867 SmallVector<EVT, 4> ValueVTs; 9868 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9869 unsigned NumValues = ValueVTs.size(); 9870 if (NumValues == 0) 9871 continue; 9872 9873 bool ArgHasUses = !Arg.use_empty(); 9874 9875 // Elide the copying store if the target loaded this argument from a 9876 // suitable fixed stack object. 9877 if (Ins[i].Flags.isCopyElisionCandidate()) { 9878 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 9879 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 9880 InVals[i], ArgHasUses); 9881 } 9882 9883 // If this argument is unused then remember its value. It is used to generate 9884 // debugging information. 9885 bool isSwiftErrorArg = 9886 TLI->supportSwiftError() && 9887 Arg.hasAttribute(Attribute::SwiftError); 9888 if (!ArgHasUses && !isSwiftErrorArg) { 9889 SDB->setUnusedArgValue(&Arg, InVals[i]); 9890 9891 // Also remember any frame index for use in FastISel. 9892 if (FrameIndexSDNode *FI = 9893 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 9894 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9895 } 9896 9897 for (unsigned Val = 0; Val != NumValues; ++Val) { 9898 EVT VT = ValueVTs[Val]; 9899 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 9900 F.getCallingConv(), VT); 9901 unsigned NumParts = TLI->getNumRegistersForCallingConv( 9902 *CurDAG->getContext(), F.getCallingConv(), VT); 9903 9904 // Even an apparent 'unused' swifterror argument needs to be returned. So 9905 // we do generate a copy for it that can be used on return from the 9906 // function. 9907 if (ArgHasUses || isSwiftErrorArg) { 9908 Optional<ISD::NodeType> AssertOp; 9909 if (Arg.hasAttribute(Attribute::SExt)) 9910 AssertOp = ISD::AssertSext; 9911 else if (Arg.hasAttribute(Attribute::ZExt)) 9912 AssertOp = ISD::AssertZext; 9913 9914 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 9915 PartVT, VT, nullptr, 9916 F.getCallingConv(), AssertOp)); 9917 } 9918 9919 i += NumParts; 9920 } 9921 9922 // We don't need to do anything else for unused arguments. 9923 if (ArgValues.empty()) 9924 continue; 9925 9926 // Note down frame index. 9927 if (FrameIndexSDNode *FI = 9928 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 9929 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9930 9931 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 9932 SDB->getCurSDLoc()); 9933 9934 SDB->setValue(&Arg, Res); 9935 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 9936 // We want to associate the argument with the frame index, among 9937 // involved operands, that correspond to the lowest address. The 9938 // getCopyFromParts function, called earlier, is swapping the order of 9939 // the operands to BUILD_PAIR depending on endianness. The result of 9940 // that swapping is that the least significant bits of the argument will 9941 // be in the first operand of the BUILD_PAIR node, and the most 9942 // significant bits will be in the second operand. 9943 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 9944 if (LoadSDNode *LNode = 9945 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 9946 if (FrameIndexSDNode *FI = 9947 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 9948 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9949 } 9950 9951 // Analyses past this point are naive and don't expect an assertion. 9952 if (Res.getOpcode() == ISD::AssertZext) 9953 Res = Res.getOperand(0); 9954 9955 // Update the SwiftErrorVRegDefMap. 9956 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 9957 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9958 if (Register::isVirtualRegister(Reg)) 9959 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 9960 Reg); 9961 } 9962 9963 // If this argument is live outside of the entry block, insert a copy from 9964 // wherever we got it to the vreg that other BB's will reference it as. 9965 if (Res.getOpcode() == ISD::CopyFromReg) { 9966 // If we can, though, try to skip creating an unnecessary vreg. 9967 // FIXME: This isn't very clean... it would be nice to make this more 9968 // general. 9969 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9970 if (Register::isVirtualRegister(Reg)) { 9971 FuncInfo->ValueMap[&Arg] = Reg; 9972 continue; 9973 } 9974 } 9975 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 9976 FuncInfo->InitializeRegForValue(&Arg); 9977 SDB->CopyToExportRegsIfNeeded(&Arg); 9978 } 9979 } 9980 9981 if (!Chains.empty()) { 9982 Chains.push_back(NewRoot); 9983 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 9984 } 9985 9986 DAG.setRoot(NewRoot); 9987 9988 assert(i == InVals.size() && "Argument register count mismatch!"); 9989 9990 // If any argument copy elisions occurred and we have debug info, update the 9991 // stale frame indices used in the dbg.declare variable info table. 9992 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 9993 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 9994 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 9995 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 9996 if (I != ArgCopyElisionFrameIndexMap.end()) 9997 VI.Slot = I->second; 9998 } 9999 } 10000 10001 // Finally, if the target has anything special to do, allow it to do so. 10002 EmitFunctionEntryCode(); 10003 } 10004 10005 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 10006 /// ensure constants are generated when needed. Remember the virtual registers 10007 /// that need to be added to the Machine PHI nodes as input. We cannot just 10008 /// directly add them, because expansion might result in multiple MBB's for one 10009 /// BB. As such, the start of the BB might correspond to a different MBB than 10010 /// the end. 10011 void 10012 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 10013 const Instruction *TI = LLVMBB->getTerminator(); 10014 10015 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 10016 10017 // Check PHI nodes in successors that expect a value to be available from this 10018 // block. 10019 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 10020 const BasicBlock *SuccBB = TI->getSuccessor(succ); 10021 if (!isa<PHINode>(SuccBB->begin())) continue; 10022 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 10023 10024 // If this terminator has multiple identical successors (common for 10025 // switches), only handle each succ once. 10026 if (!SuccsHandled.insert(SuccMBB).second) 10027 continue; 10028 10029 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 10030 10031 // At this point we know that there is a 1-1 correspondence between LLVM PHI 10032 // nodes and Machine PHI nodes, but the incoming operands have not been 10033 // emitted yet. 10034 for (const PHINode &PN : SuccBB->phis()) { 10035 // Ignore dead phi's. 10036 if (PN.use_empty()) 10037 continue; 10038 10039 // Skip empty types 10040 if (PN.getType()->isEmptyTy()) 10041 continue; 10042 10043 unsigned Reg; 10044 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 10045 10046 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 10047 unsigned &RegOut = ConstantsOut[C]; 10048 if (RegOut == 0) { 10049 RegOut = FuncInfo.CreateRegs(C); 10050 CopyValueToVirtualRegister(C, RegOut); 10051 } 10052 Reg = RegOut; 10053 } else { 10054 DenseMap<const Value *, unsigned>::iterator I = 10055 FuncInfo.ValueMap.find(PHIOp); 10056 if (I != FuncInfo.ValueMap.end()) 10057 Reg = I->second; 10058 else { 10059 assert(isa<AllocaInst>(PHIOp) && 10060 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 10061 "Didn't codegen value into a register!??"); 10062 Reg = FuncInfo.CreateRegs(PHIOp); 10063 CopyValueToVirtualRegister(PHIOp, Reg); 10064 } 10065 } 10066 10067 // Remember that this register needs to added to the machine PHI node as 10068 // the input for this MBB. 10069 SmallVector<EVT, 4> ValueVTs; 10070 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10071 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 10072 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 10073 EVT VT = ValueVTs[vti]; 10074 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 10075 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 10076 FuncInfo.PHINodesToUpdate.push_back( 10077 std::make_pair(&*MBBI++, Reg + i)); 10078 Reg += NumRegisters; 10079 } 10080 } 10081 } 10082 10083 ConstantsOut.clear(); 10084 } 10085 10086 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 10087 /// is 0. 10088 MachineBasicBlock * 10089 SelectionDAGBuilder::StackProtectorDescriptor:: 10090 AddSuccessorMBB(const BasicBlock *BB, 10091 MachineBasicBlock *ParentMBB, 10092 bool IsLikely, 10093 MachineBasicBlock *SuccMBB) { 10094 // If SuccBB has not been created yet, create it. 10095 if (!SuccMBB) { 10096 MachineFunction *MF = ParentMBB->getParent(); 10097 MachineFunction::iterator BBI(ParentMBB); 10098 SuccMBB = MF->CreateMachineBasicBlock(BB); 10099 MF->insert(++BBI, SuccMBB); 10100 } 10101 // Add it as a successor of ParentMBB. 10102 ParentMBB->addSuccessor( 10103 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 10104 return SuccMBB; 10105 } 10106 10107 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 10108 MachineFunction::iterator I(MBB); 10109 if (++I == FuncInfo.MF->end()) 10110 return nullptr; 10111 return &*I; 10112 } 10113 10114 /// During lowering new call nodes can be created (such as memset, etc.). 10115 /// Those will become new roots of the current DAG, but complications arise 10116 /// when they are tail calls. In such cases, the call lowering will update 10117 /// the root, but the builder still needs to know that a tail call has been 10118 /// lowered in order to avoid generating an additional return. 10119 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 10120 // If the node is null, we do have a tail call. 10121 if (MaybeTC.getNode() != nullptr) 10122 DAG.setRoot(MaybeTC); 10123 else 10124 HasTailCall = true; 10125 } 10126 10127 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10128 MachineBasicBlock *SwitchMBB, 10129 MachineBasicBlock *DefaultMBB) { 10130 MachineFunction *CurMF = FuncInfo.MF; 10131 MachineBasicBlock *NextMBB = nullptr; 10132 MachineFunction::iterator BBI(W.MBB); 10133 if (++BBI != FuncInfo.MF->end()) 10134 NextMBB = &*BBI; 10135 10136 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10137 10138 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10139 10140 if (Size == 2 && W.MBB == SwitchMBB) { 10141 // If any two of the cases has the same destination, and if one value 10142 // is the same as the other, but has one bit unset that the other has set, 10143 // use bit manipulation to do two compares at once. For example: 10144 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10145 // TODO: This could be extended to merge any 2 cases in switches with 3 10146 // cases. 10147 // TODO: Handle cases where W.CaseBB != SwitchBB. 10148 CaseCluster &Small = *W.FirstCluster; 10149 CaseCluster &Big = *W.LastCluster; 10150 10151 if (Small.Low == Small.High && Big.Low == Big.High && 10152 Small.MBB == Big.MBB) { 10153 const APInt &SmallValue = Small.Low->getValue(); 10154 const APInt &BigValue = Big.Low->getValue(); 10155 10156 // Check that there is only one bit different. 10157 APInt CommonBit = BigValue ^ SmallValue; 10158 if (CommonBit.isPowerOf2()) { 10159 SDValue CondLHS = getValue(Cond); 10160 EVT VT = CondLHS.getValueType(); 10161 SDLoc DL = getCurSDLoc(); 10162 10163 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10164 DAG.getConstant(CommonBit, DL, VT)); 10165 SDValue Cond = DAG.getSetCC( 10166 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10167 ISD::SETEQ); 10168 10169 // Update successor info. 10170 // Both Small and Big will jump to Small.BB, so we sum up the 10171 // probabilities. 10172 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10173 if (BPI) 10174 addSuccessorWithProb( 10175 SwitchMBB, DefaultMBB, 10176 // The default destination is the first successor in IR. 10177 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10178 else 10179 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10180 10181 // Insert the true branch. 10182 SDValue BrCond = 10183 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10184 DAG.getBasicBlock(Small.MBB)); 10185 // Insert the false branch. 10186 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10187 DAG.getBasicBlock(DefaultMBB)); 10188 10189 DAG.setRoot(BrCond); 10190 return; 10191 } 10192 } 10193 } 10194 10195 if (TM.getOptLevel() != CodeGenOpt::None) { 10196 // Here, we order cases by probability so the most likely case will be 10197 // checked first. However, two clusters can have the same probability in 10198 // which case their relative ordering is non-deterministic. So we use Low 10199 // as a tie-breaker as clusters are guaranteed to never overlap. 10200 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10201 [](const CaseCluster &a, const CaseCluster &b) { 10202 return a.Prob != b.Prob ? 10203 a.Prob > b.Prob : 10204 a.Low->getValue().slt(b.Low->getValue()); 10205 }); 10206 10207 // Rearrange the case blocks so that the last one falls through if possible 10208 // without changing the order of probabilities. 10209 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10210 --I; 10211 if (I->Prob > W.LastCluster->Prob) 10212 break; 10213 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10214 std::swap(*I, *W.LastCluster); 10215 break; 10216 } 10217 } 10218 } 10219 10220 // Compute total probability. 10221 BranchProbability DefaultProb = W.DefaultProb; 10222 BranchProbability UnhandledProbs = DefaultProb; 10223 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10224 UnhandledProbs += I->Prob; 10225 10226 MachineBasicBlock *CurMBB = W.MBB; 10227 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10228 bool FallthroughUnreachable = false; 10229 MachineBasicBlock *Fallthrough; 10230 if (I == W.LastCluster) { 10231 // For the last cluster, fall through to the default destination. 10232 Fallthrough = DefaultMBB; 10233 FallthroughUnreachable = isa<UnreachableInst>( 10234 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10235 } else { 10236 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10237 CurMF->insert(BBI, Fallthrough); 10238 // Put Cond in a virtual register to make it available from the new blocks. 10239 ExportFromCurrentBlock(Cond); 10240 } 10241 UnhandledProbs -= I->Prob; 10242 10243 switch (I->Kind) { 10244 case CC_JumpTable: { 10245 // FIXME: Optimize away range check based on pivot comparisons. 10246 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 10247 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 10248 10249 // The jump block hasn't been inserted yet; insert it here. 10250 MachineBasicBlock *JumpMBB = JT->MBB; 10251 CurMF->insert(BBI, JumpMBB); 10252 10253 auto JumpProb = I->Prob; 10254 auto FallthroughProb = UnhandledProbs; 10255 10256 // If the default statement is a target of the jump table, we evenly 10257 // distribute the default probability to successors of CurMBB. Also 10258 // update the probability on the edge from JumpMBB to Fallthrough. 10259 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10260 SE = JumpMBB->succ_end(); 10261 SI != SE; ++SI) { 10262 if (*SI == DefaultMBB) { 10263 JumpProb += DefaultProb / 2; 10264 FallthroughProb -= DefaultProb / 2; 10265 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10266 JumpMBB->normalizeSuccProbs(); 10267 break; 10268 } 10269 } 10270 10271 if (FallthroughUnreachable) { 10272 // Skip the range check if the fallthrough block is unreachable. 10273 JTH->OmitRangeCheck = true; 10274 } 10275 10276 if (!JTH->OmitRangeCheck) 10277 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10278 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10279 CurMBB->normalizeSuccProbs(); 10280 10281 // The jump table header will be inserted in our current block, do the 10282 // range check, and fall through to our fallthrough block. 10283 JTH->HeaderBB = CurMBB; 10284 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10285 10286 // If we're in the right place, emit the jump table header right now. 10287 if (CurMBB == SwitchMBB) { 10288 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10289 JTH->Emitted = true; 10290 } 10291 break; 10292 } 10293 case CC_BitTests: { 10294 // FIXME: Optimize away range check based on pivot comparisons. 10295 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 10296 10297 // The bit test blocks haven't been inserted yet; insert them here. 10298 for (BitTestCase &BTC : BTB->Cases) 10299 CurMF->insert(BBI, BTC.ThisBB); 10300 10301 // Fill in fields of the BitTestBlock. 10302 BTB->Parent = CurMBB; 10303 BTB->Default = Fallthrough; 10304 10305 BTB->DefaultProb = UnhandledProbs; 10306 // If the cases in bit test don't form a contiguous range, we evenly 10307 // distribute the probability on the edge to Fallthrough to two 10308 // successors of CurMBB. 10309 if (!BTB->ContiguousRange) { 10310 BTB->Prob += DefaultProb / 2; 10311 BTB->DefaultProb -= DefaultProb / 2; 10312 } 10313 10314 if (FallthroughUnreachable) { 10315 // Skip the range check if the fallthrough block is unreachable. 10316 BTB->OmitRangeCheck = true; 10317 } 10318 10319 // If we're in the right place, emit the bit test header right now. 10320 if (CurMBB == SwitchMBB) { 10321 visitBitTestHeader(*BTB, SwitchMBB); 10322 BTB->Emitted = true; 10323 } 10324 break; 10325 } 10326 case CC_Range: { 10327 const Value *RHS, *LHS, *MHS; 10328 ISD::CondCode CC; 10329 if (I->Low == I->High) { 10330 // Check Cond == I->Low. 10331 CC = ISD::SETEQ; 10332 LHS = Cond; 10333 RHS=I->Low; 10334 MHS = nullptr; 10335 } else { 10336 // Check I->Low <= Cond <= I->High. 10337 CC = ISD::SETLE; 10338 LHS = I->Low; 10339 MHS = Cond; 10340 RHS = I->High; 10341 } 10342 10343 // If Fallthrough is unreachable, fold away the comparison. 10344 if (FallthroughUnreachable) 10345 CC = ISD::SETTRUE; 10346 10347 // The false probability is the sum of all unhandled cases. 10348 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10349 getCurSDLoc(), I->Prob, UnhandledProbs); 10350 10351 if (CurMBB == SwitchMBB) 10352 visitSwitchCase(CB, SwitchMBB); 10353 else 10354 SL->SwitchCases.push_back(CB); 10355 10356 break; 10357 } 10358 } 10359 CurMBB = Fallthrough; 10360 } 10361 } 10362 10363 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10364 CaseClusterIt First, 10365 CaseClusterIt Last) { 10366 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10367 if (X.Prob != CC.Prob) 10368 return X.Prob > CC.Prob; 10369 10370 // Ties are broken by comparing the case value. 10371 return X.Low->getValue().slt(CC.Low->getValue()); 10372 }); 10373 } 10374 10375 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10376 const SwitchWorkListItem &W, 10377 Value *Cond, 10378 MachineBasicBlock *SwitchMBB) { 10379 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10380 "Clusters not sorted?"); 10381 10382 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10383 10384 // Balance the tree based on branch probabilities to create a near-optimal (in 10385 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10386 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10387 CaseClusterIt LastLeft = W.FirstCluster; 10388 CaseClusterIt FirstRight = W.LastCluster; 10389 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10390 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10391 10392 // Move LastLeft and FirstRight towards each other from opposite directions to 10393 // find a partitioning of the clusters which balances the probability on both 10394 // sides. If LeftProb and RightProb are equal, alternate which side is 10395 // taken to ensure 0-probability nodes are distributed evenly. 10396 unsigned I = 0; 10397 while (LastLeft + 1 < FirstRight) { 10398 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10399 LeftProb += (++LastLeft)->Prob; 10400 else 10401 RightProb += (--FirstRight)->Prob; 10402 I++; 10403 } 10404 10405 while (true) { 10406 // Our binary search tree differs from a typical BST in that ours can have up 10407 // to three values in each leaf. The pivot selection above doesn't take that 10408 // into account, which means the tree might require more nodes and be less 10409 // efficient. We compensate for this here. 10410 10411 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10412 unsigned NumRight = W.LastCluster - FirstRight + 1; 10413 10414 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10415 // If one side has less than 3 clusters, and the other has more than 3, 10416 // consider taking a cluster from the other side. 10417 10418 if (NumLeft < NumRight) { 10419 // Consider moving the first cluster on the right to the left side. 10420 CaseCluster &CC = *FirstRight; 10421 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10422 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10423 if (LeftSideRank <= RightSideRank) { 10424 // Moving the cluster to the left does not demote it. 10425 ++LastLeft; 10426 ++FirstRight; 10427 continue; 10428 } 10429 } else { 10430 assert(NumRight < NumLeft); 10431 // Consider moving the last element on the left to the right side. 10432 CaseCluster &CC = *LastLeft; 10433 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10434 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10435 if (RightSideRank <= LeftSideRank) { 10436 // Moving the cluster to the right does not demot it. 10437 --LastLeft; 10438 --FirstRight; 10439 continue; 10440 } 10441 } 10442 } 10443 break; 10444 } 10445 10446 assert(LastLeft + 1 == FirstRight); 10447 assert(LastLeft >= W.FirstCluster); 10448 assert(FirstRight <= W.LastCluster); 10449 10450 // Use the first element on the right as pivot since we will make less-than 10451 // comparisons against it. 10452 CaseClusterIt PivotCluster = FirstRight; 10453 assert(PivotCluster > W.FirstCluster); 10454 assert(PivotCluster <= W.LastCluster); 10455 10456 CaseClusterIt FirstLeft = W.FirstCluster; 10457 CaseClusterIt LastRight = W.LastCluster; 10458 10459 const ConstantInt *Pivot = PivotCluster->Low; 10460 10461 // New blocks will be inserted immediately after the current one. 10462 MachineFunction::iterator BBI(W.MBB); 10463 ++BBI; 10464 10465 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10466 // we can branch to its destination directly if it's squeezed exactly in 10467 // between the known lower bound and Pivot - 1. 10468 MachineBasicBlock *LeftMBB; 10469 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10470 FirstLeft->Low == W.GE && 10471 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10472 LeftMBB = FirstLeft->MBB; 10473 } else { 10474 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10475 FuncInfo.MF->insert(BBI, LeftMBB); 10476 WorkList.push_back( 10477 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10478 // Put Cond in a virtual register to make it available from the new blocks. 10479 ExportFromCurrentBlock(Cond); 10480 } 10481 10482 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10483 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10484 // directly if RHS.High equals the current upper bound. 10485 MachineBasicBlock *RightMBB; 10486 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10487 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10488 RightMBB = FirstRight->MBB; 10489 } else { 10490 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10491 FuncInfo.MF->insert(BBI, RightMBB); 10492 WorkList.push_back( 10493 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10494 // Put Cond in a virtual register to make it available from the new blocks. 10495 ExportFromCurrentBlock(Cond); 10496 } 10497 10498 // Create the CaseBlock record that will be used to lower the branch. 10499 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10500 getCurSDLoc(), LeftProb, RightProb); 10501 10502 if (W.MBB == SwitchMBB) 10503 visitSwitchCase(CB, SwitchMBB); 10504 else 10505 SL->SwitchCases.push_back(CB); 10506 } 10507 10508 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10509 // from the swith statement. 10510 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10511 BranchProbability PeeledCaseProb) { 10512 if (PeeledCaseProb == BranchProbability::getOne()) 10513 return BranchProbability::getZero(); 10514 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10515 10516 uint32_t Numerator = CaseProb.getNumerator(); 10517 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10518 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10519 } 10520 10521 // Try to peel the top probability case if it exceeds the threshold. 10522 // Return current MachineBasicBlock for the switch statement if the peeling 10523 // does not occur. 10524 // If the peeling is performed, return the newly created MachineBasicBlock 10525 // for the peeled switch statement. Also update Clusters to remove the peeled 10526 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10527 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10528 const SwitchInst &SI, CaseClusterVector &Clusters, 10529 BranchProbability &PeeledCaseProb) { 10530 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10531 // Don't perform if there is only one cluster or optimizing for size. 10532 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10533 TM.getOptLevel() == CodeGenOpt::None || 10534 SwitchMBB->getParent()->getFunction().hasMinSize()) 10535 return SwitchMBB; 10536 10537 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10538 unsigned PeeledCaseIndex = 0; 10539 bool SwitchPeeled = false; 10540 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10541 CaseCluster &CC = Clusters[Index]; 10542 if (CC.Prob < TopCaseProb) 10543 continue; 10544 TopCaseProb = CC.Prob; 10545 PeeledCaseIndex = Index; 10546 SwitchPeeled = true; 10547 } 10548 if (!SwitchPeeled) 10549 return SwitchMBB; 10550 10551 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10552 << TopCaseProb << "\n"); 10553 10554 // Record the MBB for the peeled switch statement. 10555 MachineFunction::iterator BBI(SwitchMBB); 10556 ++BBI; 10557 MachineBasicBlock *PeeledSwitchMBB = 10558 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10559 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10560 10561 ExportFromCurrentBlock(SI.getCondition()); 10562 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10563 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10564 nullptr, nullptr, TopCaseProb.getCompl()}; 10565 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10566 10567 Clusters.erase(PeeledCaseIt); 10568 for (CaseCluster &CC : Clusters) { 10569 LLVM_DEBUG( 10570 dbgs() << "Scale the probablity for one cluster, before scaling: " 10571 << CC.Prob << "\n"); 10572 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10573 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10574 } 10575 PeeledCaseProb = TopCaseProb; 10576 return PeeledSwitchMBB; 10577 } 10578 10579 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10580 // Extract cases from the switch. 10581 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10582 CaseClusterVector Clusters; 10583 Clusters.reserve(SI.getNumCases()); 10584 for (auto I : SI.cases()) { 10585 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10586 const ConstantInt *CaseVal = I.getCaseValue(); 10587 BranchProbability Prob = 10588 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10589 : BranchProbability(1, SI.getNumCases() + 1); 10590 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10591 } 10592 10593 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10594 10595 // Cluster adjacent cases with the same destination. We do this at all 10596 // optimization levels because it's cheap to do and will make codegen faster 10597 // if there are many clusters. 10598 sortAndRangeify(Clusters); 10599 10600 // The branch probablity of the peeled case. 10601 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10602 MachineBasicBlock *PeeledSwitchMBB = 10603 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10604 10605 // If there is only the default destination, jump there directly. 10606 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10607 if (Clusters.empty()) { 10608 assert(PeeledSwitchMBB == SwitchMBB); 10609 SwitchMBB->addSuccessor(DefaultMBB); 10610 if (DefaultMBB != NextBlock(SwitchMBB)) { 10611 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10612 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10613 } 10614 return; 10615 } 10616 10617 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 10618 SL->findBitTestClusters(Clusters, &SI); 10619 10620 LLVM_DEBUG({ 10621 dbgs() << "Case clusters: "; 10622 for (const CaseCluster &C : Clusters) { 10623 if (C.Kind == CC_JumpTable) 10624 dbgs() << "JT:"; 10625 if (C.Kind == CC_BitTests) 10626 dbgs() << "BT:"; 10627 10628 C.Low->getValue().print(dbgs(), true); 10629 if (C.Low != C.High) { 10630 dbgs() << '-'; 10631 C.High->getValue().print(dbgs(), true); 10632 } 10633 dbgs() << ' '; 10634 } 10635 dbgs() << '\n'; 10636 }); 10637 10638 assert(!Clusters.empty()); 10639 SwitchWorkList WorkList; 10640 CaseClusterIt First = Clusters.begin(); 10641 CaseClusterIt Last = Clusters.end() - 1; 10642 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10643 // Scale the branchprobability for DefaultMBB if the peel occurs and 10644 // DefaultMBB is not replaced. 10645 if (PeeledCaseProb != BranchProbability::getZero() && 10646 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10647 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10648 WorkList.push_back( 10649 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10650 10651 while (!WorkList.empty()) { 10652 SwitchWorkListItem W = WorkList.back(); 10653 WorkList.pop_back(); 10654 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10655 10656 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10657 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 10658 // For optimized builds, lower large range as a balanced binary tree. 10659 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10660 continue; 10661 } 10662 10663 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10664 } 10665 } 10666 10667 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 10668 SDValue N = getValue(I.getOperand(0)); 10669 setValue(&I, N); 10670 } 10671