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/CallingConv.h" 73 #include "llvm/IR/Constant.h" 74 #include "llvm/IR/ConstantRange.h" 75 #include "llvm/IR/Constants.h" 76 #include "llvm/IR/DataLayout.h" 77 #include "llvm/IR/DebugInfoMetadata.h" 78 #include "llvm/IR/DebugLoc.h" 79 #include "llvm/IR/DerivedTypes.h" 80 #include "llvm/IR/Function.h" 81 #include "llvm/IR/GetElementPtrTypeIterator.h" 82 #include "llvm/IR/InlineAsm.h" 83 #include "llvm/IR/InstrTypes.h" 84 #include "llvm/IR/Instruction.h" 85 #include "llvm/IR/Instructions.h" 86 #include "llvm/IR/IntrinsicInst.h" 87 #include "llvm/IR/Intrinsics.h" 88 #include "llvm/IR/IntrinsicsAArch64.h" 89 #include "llvm/IR/IntrinsicsWebAssembly.h" 90 #include "llvm/IR/LLVMContext.h" 91 #include "llvm/IR/Metadata.h" 92 #include "llvm/IR/Module.h" 93 #include "llvm/IR/Operator.h" 94 #include "llvm/IR/PatternMatch.h" 95 #include "llvm/IR/Statepoint.h" 96 #include "llvm/IR/Type.h" 97 #include "llvm/IR/User.h" 98 #include "llvm/IR/Value.h" 99 #include "llvm/MC/MCContext.h" 100 #include "llvm/MC/MCSymbol.h" 101 #include "llvm/Support/AtomicOrdering.h" 102 #include "llvm/Support/BranchProbability.h" 103 #include "llvm/Support/Casting.h" 104 #include "llvm/Support/CodeGen.h" 105 #include "llvm/Support/CommandLine.h" 106 #include "llvm/Support/Compiler.h" 107 #include "llvm/Support/Debug.h" 108 #include "llvm/Support/ErrorHandling.h" 109 #include "llvm/Support/MachineValueType.h" 110 #include "llvm/Support/MathExtras.h" 111 #include "llvm/Support/raw_ostream.h" 112 #include "llvm/Target/TargetIntrinsicInfo.h" 113 #include "llvm/Target/TargetMachine.h" 114 #include "llvm/Target/TargetOptions.h" 115 #include "llvm/Transforms/Utils/Local.h" 116 #include <algorithm> 117 #include <cassert> 118 #include <cstddef> 119 #include <cstdint> 120 #include <cstring> 121 #include <iterator> 122 #include <limits> 123 #include <numeric> 124 #include <tuple> 125 #include <utility> 126 #include <vector> 127 128 using namespace llvm; 129 using namespace PatternMatch; 130 using namespace SwitchCG; 131 132 #define DEBUG_TYPE "isel" 133 134 /// LimitFloatPrecision - Generate low-precision inline sequences for 135 /// some float libcalls (6, 8 or 12 bits). 136 static unsigned LimitFloatPrecision; 137 138 static cl::opt<bool> 139 InsertAssertAlign("insert-assert-align", cl::init(true), 140 cl::desc("Insert the experimental `assertalign` node."), 141 cl::ReallyHidden); 142 143 static cl::opt<unsigned, true> 144 LimitFPPrecision("limit-float-precision", 145 cl::desc("Generate low-precision inline sequences " 146 "for some float libcalls"), 147 cl::location(LimitFloatPrecision), cl::Hidden, 148 cl::init(0)); 149 150 static cl::opt<unsigned> SwitchPeelThreshold( 151 "switch-peel-threshold", cl::Hidden, cl::init(66), 152 cl::desc("Set the case probability threshold for peeling the case from a " 153 "switch statement. A value greater than 100 will void this " 154 "optimization")); 155 156 // Limit the width of DAG chains. This is important in general to prevent 157 // DAG-based analysis from blowing up. For example, alias analysis and 158 // load clustering may not complete in reasonable time. It is difficult to 159 // recognize and avoid this situation within each individual analysis, and 160 // future analyses are likely to have the same behavior. Limiting DAG width is 161 // the safe approach and will be especially important with global DAGs. 162 // 163 // MaxParallelChains default is arbitrarily high to avoid affecting 164 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 165 // sequence over this should have been converted to llvm.memcpy by the 166 // frontend. It is easy to induce this behavior with .ll code such as: 167 // %buffer = alloca [4096 x i8] 168 // %data = load [4096 x i8]* %argPtr 169 // store [4096 x i8] %data, [4096 x i8]* %buffer 170 static const unsigned MaxParallelChains = 64; 171 172 // Return the calling convention if the Value passed requires ABI mangling as it 173 // is a parameter to a function or a return value from a function which is not 174 // an intrinsic. 175 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) { 176 if (auto *R = dyn_cast<ReturnInst>(V)) 177 return R->getParent()->getParent()->getCallingConv(); 178 179 if (auto *CI = dyn_cast<CallInst>(V)) { 180 const bool IsInlineAsm = CI->isInlineAsm(); 181 const bool IsIndirectFunctionCall = 182 !IsInlineAsm && !CI->getCalledFunction(); 183 184 // It is possible that the call instruction is an inline asm statement or an 185 // indirect function call in which case the return value of 186 // getCalledFunction() would be nullptr. 187 const bool IsInstrinsicCall = 188 !IsInlineAsm && !IsIndirectFunctionCall && 189 CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic; 190 191 if (!IsInlineAsm && !IsInstrinsicCall) 192 return CI->getCallingConv(); 193 } 194 195 return None; 196 } 197 198 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 199 const SDValue *Parts, unsigned NumParts, 200 MVT PartVT, EVT ValueVT, const Value *V, 201 Optional<CallingConv::ID> CC); 202 203 /// getCopyFromParts - Create a value that contains the specified legal parts 204 /// combined into the value they represent. If the parts combine to a type 205 /// larger than ValueVT then AssertOp can be used to specify whether the extra 206 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 207 /// (ISD::AssertSext). 208 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 209 const SDValue *Parts, unsigned NumParts, 210 MVT PartVT, EVT ValueVT, const Value *V, 211 Optional<CallingConv::ID> CC = None, 212 Optional<ISD::NodeType> AssertOp = None) { 213 // Let the target assemble the parts if it wants to 214 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 215 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts, 216 PartVT, ValueVT, CC)) 217 return Val; 218 219 if (ValueVT.isVector()) 220 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 221 CC); 222 223 assert(NumParts > 0 && "No parts to assemble!"); 224 SDValue Val = Parts[0]; 225 226 if (NumParts > 1) { 227 // Assemble the value from multiple parts. 228 if (ValueVT.isInteger()) { 229 unsigned PartBits = PartVT.getSizeInBits(); 230 unsigned ValueBits = ValueVT.getSizeInBits(); 231 232 // Assemble the power of 2 part. 233 unsigned RoundParts = 234 (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts; 235 unsigned RoundBits = PartBits * RoundParts; 236 EVT RoundVT = RoundBits == ValueBits ? 237 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 238 SDValue Lo, Hi; 239 240 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 241 242 if (RoundParts > 2) { 243 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 244 PartVT, HalfVT, V); 245 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 246 RoundParts / 2, PartVT, HalfVT, V); 247 } else { 248 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 249 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 250 } 251 252 if (DAG.getDataLayout().isBigEndian()) 253 std::swap(Lo, Hi); 254 255 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 256 257 if (RoundParts < NumParts) { 258 // Assemble the trailing non-power-of-2 part. 259 unsigned OddParts = NumParts - RoundParts; 260 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 261 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 262 OddVT, V, CC); 263 264 // Combine the round and odd parts. 265 Lo = Val; 266 if (DAG.getDataLayout().isBigEndian()) 267 std::swap(Lo, Hi); 268 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 269 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 270 Hi = 271 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 272 DAG.getConstant(Lo.getValueSizeInBits(), DL, 273 TLI.getPointerTy(DAG.getDataLayout()))); 274 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 275 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 276 } 277 } else if (PartVT.isFloatingPoint()) { 278 // FP split into multiple FP parts (for ppcf128) 279 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 280 "Unexpected split"); 281 SDValue Lo, Hi; 282 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 283 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 284 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 285 std::swap(Lo, Hi); 286 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 287 } else { 288 // FP split into integer parts (soft fp) 289 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 290 !PartVT.isVector() && "Unexpected split"); 291 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 292 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 293 } 294 } 295 296 // There is now one part, held in Val. Correct it to match ValueVT. 297 // PartEVT is the type of the register class that holds the value. 298 // ValueVT is the type of the inline asm operation. 299 EVT PartEVT = Val.getValueType(); 300 301 if (PartEVT == ValueVT) 302 return Val; 303 304 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 305 ValueVT.bitsLT(PartEVT)) { 306 // For an FP value in an integer part, we need to truncate to the right 307 // width first. 308 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 309 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 310 } 311 312 // Handle types that have the same size. 313 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 314 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 315 316 // Handle types with different sizes. 317 if (PartEVT.isInteger() && ValueVT.isInteger()) { 318 if (ValueVT.bitsLT(PartEVT)) { 319 // For a truncate, see if we have any information to 320 // indicate whether the truncated bits will always be 321 // zero or sign-extension. 322 if (AssertOp.hasValue()) 323 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 324 DAG.getValueType(ValueVT)); 325 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 326 } 327 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 328 } 329 330 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 331 // FP_ROUND's are always exact here. 332 if (ValueVT.bitsLT(Val.getValueType())) 333 return DAG.getNode( 334 ISD::FP_ROUND, DL, ValueVT, Val, 335 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 336 337 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 338 } 339 340 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 341 // then truncating. 342 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 343 ValueVT.bitsLT(PartEVT)) { 344 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 345 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 346 } 347 348 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 349 } 350 351 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 352 const Twine &ErrMsg) { 353 const Instruction *I = dyn_cast_or_null<Instruction>(V); 354 if (!V) 355 return Ctx.emitError(ErrMsg); 356 357 const char *AsmError = ", possible invalid constraint for vector type"; 358 if (const CallInst *CI = dyn_cast<CallInst>(I)) 359 if (CI->isInlineAsm()) 360 return Ctx.emitError(I, ErrMsg + AsmError); 361 362 return Ctx.emitError(I, ErrMsg); 363 } 364 365 /// getCopyFromPartsVector - Create a value that contains the specified legal 366 /// parts combined into the value they represent. If the parts combine to a 367 /// type larger than ValueVT then AssertOp can be used to specify whether the 368 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 369 /// ValueVT (ISD::AssertSext). 370 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 371 const SDValue *Parts, unsigned NumParts, 372 MVT PartVT, EVT ValueVT, const Value *V, 373 Optional<CallingConv::ID> CallConv) { 374 assert(ValueVT.isVector() && "Not a vector value"); 375 assert(NumParts > 0 && "No parts to assemble!"); 376 const bool IsABIRegCopy = CallConv.hasValue(); 377 378 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 379 SDValue Val = Parts[0]; 380 381 // Handle a multi-element vector. 382 if (NumParts > 1) { 383 EVT IntermediateVT; 384 MVT RegisterVT; 385 unsigned NumIntermediates; 386 unsigned NumRegs; 387 388 if (IsABIRegCopy) { 389 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 390 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 391 NumIntermediates, RegisterVT); 392 } else { 393 NumRegs = 394 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 395 NumIntermediates, RegisterVT); 396 } 397 398 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 399 NumParts = NumRegs; // Silence a compiler warning. 400 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 401 assert(RegisterVT.getSizeInBits() == 402 Parts[0].getSimpleValueType().getSizeInBits() && 403 "Part type sizes don't match!"); 404 405 // Assemble the parts into intermediate operands. 406 SmallVector<SDValue, 8> Ops(NumIntermediates); 407 if (NumIntermediates == NumParts) { 408 // If the register was not expanded, truncate or copy the value, 409 // as appropriate. 410 for (unsigned i = 0; i != NumParts; ++i) 411 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 412 PartVT, IntermediateVT, V); 413 } else if (NumParts > 0) { 414 // If the intermediate type was expanded, build the intermediate 415 // operands from the parts. 416 assert(NumParts % NumIntermediates == 0 && 417 "Must expand into a divisible number of parts!"); 418 unsigned Factor = NumParts / NumIntermediates; 419 for (unsigned i = 0; i != NumIntermediates; ++i) 420 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 421 PartVT, IntermediateVT, V); 422 } 423 424 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 425 // intermediate operands. 426 EVT BuiltVectorTy = 427 IntermediateVT.isVector() 428 ? EVT::getVectorVT( 429 *DAG.getContext(), IntermediateVT.getScalarType(), 430 IntermediateVT.getVectorElementCount() * NumParts) 431 : EVT::getVectorVT(*DAG.getContext(), 432 IntermediateVT.getScalarType(), 433 NumIntermediates); 434 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 435 : ISD::BUILD_VECTOR, 436 DL, BuiltVectorTy, Ops); 437 } 438 439 // There is now one part, held in Val. Correct it to match ValueVT. 440 EVT PartEVT = Val.getValueType(); 441 442 if (PartEVT == ValueVT) 443 return Val; 444 445 if (PartEVT.isVector()) { 446 // If the element type of the source/dest vectors are the same, but the 447 // parts vector has more elements than the value vector, then we have a 448 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 449 // elements we want. 450 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { 451 assert((PartEVT.getVectorElementCount().Min > 452 ValueVT.getVectorElementCount().Min) && 453 (PartEVT.getVectorElementCount().Scalable == 454 ValueVT.getVectorElementCount().Scalable) && 455 "Cannot narrow, it would be a lossy transformation"); 456 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 457 DAG.getVectorIdxConstant(0, DL)); 458 } 459 460 // Vector/Vector bitcast. 461 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 462 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 463 464 assert(PartEVT.getVectorElementCount() == ValueVT.getVectorElementCount() && 465 "Cannot handle this kind of promotion"); 466 // Promoted vector extract 467 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 468 469 } 470 471 // Trivial bitcast if the types are the same size and the destination 472 // vector type is legal. 473 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 474 TLI.isTypeLegal(ValueVT)) 475 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 476 477 if (ValueVT.getVectorNumElements() != 1) { 478 // Certain ABIs require that vectors are passed as integers. For vectors 479 // are the same size, this is an obvious bitcast. 480 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 481 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 482 } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) { 483 // Bitcast Val back the original type and extract the corresponding 484 // vector we want. 485 unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits(); 486 EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(), 487 ValueVT.getVectorElementType(), Elts); 488 Val = DAG.getBitcast(WiderVecType, Val); 489 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 490 DAG.getVectorIdxConstant(0, DL)); 491 } 492 493 diagnosePossiblyInvalidConstraint( 494 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 495 return DAG.getUNDEF(ValueVT); 496 } 497 498 // Handle cases such as i8 -> <1 x i1> 499 EVT ValueSVT = ValueVT.getVectorElementType(); 500 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 501 if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits()) 502 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 503 else 504 Val = ValueVT.isFloatingPoint() 505 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 506 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 507 } 508 509 return DAG.getBuildVector(ValueVT, DL, Val); 510 } 511 512 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 513 SDValue Val, SDValue *Parts, unsigned NumParts, 514 MVT PartVT, const Value *V, 515 Optional<CallingConv::ID> CallConv); 516 517 /// getCopyToParts - Create a series of nodes that contain the specified value 518 /// split into legal parts. If the parts contain more bits than Val, then, for 519 /// integers, ExtendKind can be used to specify how to generate the extra bits. 520 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 521 SDValue *Parts, unsigned NumParts, MVT PartVT, 522 const Value *V, 523 Optional<CallingConv::ID> CallConv = None, 524 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 525 // Let the target split the parts if it wants to 526 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 527 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 528 CallConv)) 529 return; 530 EVT ValueVT = Val.getValueType(); 531 532 // Handle the vector case separately. 533 if (ValueVT.isVector()) 534 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 535 CallConv); 536 537 unsigned PartBits = PartVT.getSizeInBits(); 538 unsigned OrigNumParts = NumParts; 539 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 540 "Copying to an illegal type!"); 541 542 if (NumParts == 0) 543 return; 544 545 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 546 EVT PartEVT = PartVT; 547 if (PartEVT == ValueVT) { 548 assert(NumParts == 1 && "No-op copy with multiple parts!"); 549 Parts[0] = Val; 550 return; 551 } 552 553 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 554 // If the parts cover more bits than the value has, promote the value. 555 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 556 assert(NumParts == 1 && "Do not know what to promote to!"); 557 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 558 } else { 559 if (ValueVT.isFloatingPoint()) { 560 // FP values need to be bitcast, then extended if they are being put 561 // into a larger container. 562 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 563 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 564 } 565 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 566 ValueVT.isInteger() && 567 "Unknown mismatch!"); 568 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 569 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 570 if (PartVT == MVT::x86mmx) 571 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 572 } 573 } else if (PartBits == ValueVT.getSizeInBits()) { 574 // Different types of the same size. 575 assert(NumParts == 1 && PartEVT != ValueVT); 576 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 577 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 578 // If the parts cover less bits than value has, truncate the value. 579 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 580 ValueVT.isInteger() && 581 "Unknown mismatch!"); 582 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 583 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 584 if (PartVT == MVT::x86mmx) 585 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 586 } 587 588 // The value may have changed - recompute ValueVT. 589 ValueVT = Val.getValueType(); 590 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 591 "Failed to tile the value with PartVT!"); 592 593 if (NumParts == 1) { 594 if (PartEVT != ValueVT) { 595 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 596 "scalar-to-vector conversion failed"); 597 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 598 } 599 600 Parts[0] = Val; 601 return; 602 } 603 604 // Expand the value into multiple parts. 605 if (NumParts & (NumParts - 1)) { 606 // The number of parts is not a power of 2. Split off and copy the tail. 607 assert(PartVT.isInteger() && ValueVT.isInteger() && 608 "Do not know what to expand to!"); 609 unsigned RoundParts = 1 << Log2_32(NumParts); 610 unsigned RoundBits = RoundParts * PartBits; 611 unsigned OddParts = NumParts - RoundParts; 612 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 613 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false)); 614 615 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 616 CallConv); 617 618 if (DAG.getDataLayout().isBigEndian()) 619 // The odd parts were reversed by getCopyToParts - unreverse them. 620 std::reverse(Parts + RoundParts, Parts + NumParts); 621 622 NumParts = RoundParts; 623 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 624 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 625 } 626 627 // The number of parts is a power of 2. Repeatedly bisect the value using 628 // EXTRACT_ELEMENT. 629 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 630 EVT::getIntegerVT(*DAG.getContext(), 631 ValueVT.getSizeInBits()), 632 Val); 633 634 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 635 for (unsigned i = 0; i < NumParts; i += StepSize) { 636 unsigned ThisBits = StepSize * PartBits / 2; 637 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 638 SDValue &Part0 = Parts[i]; 639 SDValue &Part1 = Parts[i+StepSize/2]; 640 641 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 642 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 643 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 644 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 645 646 if (ThisBits == PartBits && ThisVT != PartVT) { 647 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 648 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 649 } 650 } 651 } 652 653 if (DAG.getDataLayout().isBigEndian()) 654 std::reverse(Parts, Parts + OrigNumParts); 655 } 656 657 static SDValue widenVectorToPartType(SelectionDAG &DAG, 658 SDValue Val, const SDLoc &DL, EVT PartVT) { 659 if (!PartVT.isVector()) 660 return SDValue(); 661 662 EVT ValueVT = Val.getValueType(); 663 unsigned PartNumElts = PartVT.getVectorNumElements(); 664 unsigned ValueNumElts = ValueVT.getVectorNumElements(); 665 if (PartNumElts > ValueNumElts && 666 PartVT.getVectorElementType() == ValueVT.getVectorElementType()) { 667 EVT ElementVT = PartVT.getVectorElementType(); 668 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 669 // undef elements. 670 SmallVector<SDValue, 16> Ops; 671 DAG.ExtractVectorElements(Val, Ops); 672 SDValue EltUndef = DAG.getUNDEF(ElementVT); 673 for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i) 674 Ops.push_back(EltUndef); 675 676 // FIXME: Use CONCAT for 2x -> 4x. 677 return DAG.getBuildVector(PartVT, DL, Ops); 678 } 679 680 return SDValue(); 681 } 682 683 /// getCopyToPartsVector - Create a series of nodes that contain the specified 684 /// value split into legal parts. 685 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 686 SDValue Val, SDValue *Parts, unsigned NumParts, 687 MVT PartVT, const Value *V, 688 Optional<CallingConv::ID> CallConv) { 689 EVT ValueVT = Val.getValueType(); 690 assert(ValueVT.isVector() && "Not a vector"); 691 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 692 const bool IsABIRegCopy = CallConv.hasValue(); 693 694 if (NumParts == 1) { 695 EVT PartEVT = PartVT; 696 if (PartEVT == ValueVT) { 697 // Nothing to do. 698 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 699 // Bitconvert vector->vector case. 700 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 701 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 702 Val = Widened; 703 } else if (PartVT.isVector() && 704 PartEVT.getVectorElementType().bitsGE( 705 ValueVT.getVectorElementType()) && 706 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) { 707 708 // Promoted vector extract 709 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 710 } else { 711 if (ValueVT.getVectorNumElements() == 1) { 712 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 713 DAG.getVectorIdxConstant(0, DL)); 714 } else { 715 assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() && 716 "lossy conversion of vector to scalar type"); 717 EVT IntermediateType = 718 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 719 Val = DAG.getBitcast(IntermediateType, Val); 720 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 721 } 722 } 723 724 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 725 Parts[0] = Val; 726 return; 727 } 728 729 // Handle a multi-element vector. 730 EVT IntermediateVT; 731 MVT RegisterVT; 732 unsigned NumIntermediates; 733 unsigned NumRegs; 734 if (IsABIRegCopy) { 735 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 736 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 737 NumIntermediates, RegisterVT); 738 } else { 739 NumRegs = 740 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 741 NumIntermediates, RegisterVT); 742 } 743 744 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 745 NumParts = NumRegs; // Silence a compiler warning. 746 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 747 748 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 749 "Mixing scalable and fixed vectors when copying in parts"); 750 751 ElementCount DestEltCnt; 752 753 if (IntermediateVT.isVector()) 754 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 755 else 756 DestEltCnt = ElementCount(NumIntermediates, false); 757 758 EVT BuiltVectorTy = EVT::getVectorVT( 759 *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt); 760 if (ValueVT != BuiltVectorTy) { 761 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) 762 Val = Widened; 763 764 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 765 } 766 767 // Split the vector into intermediate operands. 768 SmallVector<SDValue, 8> Ops(NumIntermediates); 769 for (unsigned i = 0; i != NumIntermediates; ++i) { 770 if (IntermediateVT.isVector()) { 771 // This does something sensible for scalable vectors - see the 772 // definition of EXTRACT_SUBVECTOR for further details. 773 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 774 Ops[i] = 775 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 776 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 777 } else { 778 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 779 DAG.getVectorIdxConstant(i, DL)); 780 } 781 } 782 783 // Split the intermediate operands into legal parts. 784 if (NumParts == NumIntermediates) { 785 // If the register was not expanded, promote or copy the value, 786 // as appropriate. 787 for (unsigned i = 0; i != NumParts; ++i) 788 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 789 } else if (NumParts > 0) { 790 // If the intermediate type was expanded, split each the value into 791 // legal parts. 792 assert(NumIntermediates != 0 && "division by zero"); 793 assert(NumParts % NumIntermediates == 0 && 794 "Must expand into a divisible number of parts!"); 795 unsigned Factor = NumParts / NumIntermediates; 796 for (unsigned i = 0; i != NumIntermediates; ++i) 797 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 798 CallConv); 799 } 800 } 801 802 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 803 EVT valuevt, Optional<CallingConv::ID> CC) 804 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 805 RegCount(1, regs.size()), CallConv(CC) {} 806 807 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 808 const DataLayout &DL, unsigned Reg, Type *Ty, 809 Optional<CallingConv::ID> CC) { 810 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 811 812 CallConv = CC; 813 814 for (EVT ValueVT : ValueVTs) { 815 unsigned NumRegs = 816 isABIMangled() 817 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) 818 : TLI.getNumRegisters(Context, ValueVT); 819 MVT RegisterVT = 820 isABIMangled() 821 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) 822 : TLI.getRegisterType(Context, ValueVT); 823 for (unsigned i = 0; i != NumRegs; ++i) 824 Regs.push_back(Reg + i); 825 RegVTs.push_back(RegisterVT); 826 RegCount.push_back(NumRegs); 827 Reg += NumRegs; 828 } 829 } 830 831 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 832 FunctionLoweringInfo &FuncInfo, 833 const SDLoc &dl, SDValue &Chain, 834 SDValue *Flag, const Value *V) const { 835 // A Value with type {} or [0 x %t] needs no registers. 836 if (ValueVTs.empty()) 837 return SDValue(); 838 839 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 840 841 // Assemble the legal parts into the final values. 842 SmallVector<SDValue, 4> Values(ValueVTs.size()); 843 SmallVector<SDValue, 8> Parts; 844 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 845 // Copy the legal parts from the registers. 846 EVT ValueVT = ValueVTs[Value]; 847 unsigned NumRegs = RegCount[Value]; 848 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 849 *DAG.getContext(), 850 CallConv.getValue(), RegVTs[Value]) 851 : RegVTs[Value]; 852 853 Parts.resize(NumRegs); 854 for (unsigned i = 0; i != NumRegs; ++i) { 855 SDValue P; 856 if (!Flag) { 857 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 858 } else { 859 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 860 *Flag = P.getValue(2); 861 } 862 863 Chain = P.getValue(1); 864 Parts[i] = P; 865 866 // If the source register was virtual and if we know something about it, 867 // add an assert node. 868 if (!Register::isVirtualRegister(Regs[Part + i]) || 869 !RegisterVT.isInteger()) 870 continue; 871 872 const FunctionLoweringInfo::LiveOutInfo *LOI = 873 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 874 if (!LOI) 875 continue; 876 877 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 878 unsigned NumSignBits = LOI->NumSignBits; 879 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 880 881 if (NumZeroBits == RegSize) { 882 // The current value is a zero. 883 // Explicitly express that as it would be easier for 884 // optimizations to kick in. 885 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 886 continue; 887 } 888 889 // FIXME: We capture more information than the dag can represent. For 890 // now, just use the tightest assertzext/assertsext possible. 891 bool isSExt; 892 EVT FromVT(MVT::Other); 893 if (NumZeroBits) { 894 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 895 isSExt = false; 896 } else if (NumSignBits > 1) { 897 FromVT = 898 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 899 isSExt = true; 900 } else { 901 continue; 902 } 903 // Add an assertion node. 904 assert(FromVT != MVT::Other); 905 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 906 RegisterVT, P, DAG.getValueType(FromVT)); 907 } 908 909 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 910 RegisterVT, ValueVT, V, CallConv); 911 Part += NumRegs; 912 Parts.clear(); 913 } 914 915 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 916 } 917 918 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 919 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 920 const Value *V, 921 ISD::NodeType PreferredExtendType) const { 922 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 923 ISD::NodeType ExtendKind = PreferredExtendType; 924 925 // Get the list of the values's legal parts. 926 unsigned NumRegs = Regs.size(); 927 SmallVector<SDValue, 8> Parts(NumRegs); 928 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 929 unsigned NumParts = RegCount[Value]; 930 931 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 932 *DAG.getContext(), 933 CallConv.getValue(), RegVTs[Value]) 934 : RegVTs[Value]; 935 936 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 937 ExtendKind = ISD::ZERO_EXTEND; 938 939 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 940 NumParts, RegisterVT, V, CallConv, ExtendKind); 941 Part += NumParts; 942 } 943 944 // Copy the parts into the registers. 945 SmallVector<SDValue, 8> Chains(NumRegs); 946 for (unsigned i = 0; i != NumRegs; ++i) { 947 SDValue Part; 948 if (!Flag) { 949 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 950 } else { 951 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 952 *Flag = Part.getValue(1); 953 } 954 955 Chains[i] = Part.getValue(0); 956 } 957 958 if (NumRegs == 1 || Flag) 959 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 960 // flagged to it. That is the CopyToReg nodes and the user are considered 961 // a single scheduling unit. If we create a TokenFactor and return it as 962 // chain, then the TokenFactor is both a predecessor (operand) of the 963 // user as well as a successor (the TF operands are flagged to the user). 964 // c1, f1 = CopyToReg 965 // c2, f2 = CopyToReg 966 // c3 = TokenFactor c1, c2 967 // ... 968 // = op c3, ..., f2 969 Chain = Chains[NumRegs-1]; 970 else 971 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 972 } 973 974 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 975 unsigned MatchingIdx, const SDLoc &dl, 976 SelectionDAG &DAG, 977 std::vector<SDValue> &Ops) const { 978 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 979 980 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 981 if (HasMatching) 982 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 983 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 984 // Put the register class of the virtual registers in the flag word. That 985 // way, later passes can recompute register class constraints for inline 986 // assembly as well as normal instructions. 987 // Don't do this for tied operands that can use the regclass information 988 // from the def. 989 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 990 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 991 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 992 } 993 994 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 995 Ops.push_back(Res); 996 997 if (Code == InlineAsm::Kind_Clobber) { 998 // Clobbers should always have a 1:1 mapping with registers, and may 999 // reference registers that have illegal (e.g. vector) types. Hence, we 1000 // shouldn't try to apply any sort of splitting logic to them. 1001 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 1002 "No 1:1 mapping from clobbers to regs?"); 1003 unsigned SP = TLI.getStackPointerRegisterToSaveRestore(); 1004 (void)SP; 1005 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 1006 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 1007 assert( 1008 (Regs[I] != SP || 1009 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 1010 "If we clobbered the stack pointer, MFI should know about it."); 1011 } 1012 return; 1013 } 1014 1015 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 1016 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 1017 MVT RegisterVT = RegVTs[Value]; 1018 for (unsigned i = 0; i != NumRegs; ++i) { 1019 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 1020 unsigned TheReg = Regs[Reg++]; 1021 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 1022 } 1023 } 1024 } 1025 1026 SmallVector<std::pair<unsigned, unsigned>, 4> 1027 RegsForValue::getRegsAndSizes() const { 1028 SmallVector<std::pair<unsigned, unsigned>, 4> OutVec; 1029 unsigned I = 0; 1030 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1031 unsigned RegCount = std::get<0>(CountAndVT); 1032 MVT RegisterVT = std::get<1>(CountAndVT); 1033 unsigned RegisterSize = RegisterVT.getSizeInBits(); 1034 for (unsigned E = I + RegCount; I != E; ++I) 1035 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1036 } 1037 return OutVec; 1038 } 1039 1040 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1041 const TargetLibraryInfo *li) { 1042 AA = aa; 1043 GFI = gfi; 1044 LibInfo = li; 1045 DL = &DAG.getDataLayout(); 1046 Context = DAG.getContext(); 1047 LPadToCallSiteMap.clear(); 1048 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1049 } 1050 1051 void SelectionDAGBuilder::clear() { 1052 NodeMap.clear(); 1053 UnusedArgNodeMap.clear(); 1054 PendingLoads.clear(); 1055 PendingExports.clear(); 1056 PendingConstrainedFP.clear(); 1057 PendingConstrainedFPStrict.clear(); 1058 CurInst = nullptr; 1059 HasTailCall = false; 1060 SDNodeOrder = LowestSDNodeOrder; 1061 StatepointLowering.clear(); 1062 } 1063 1064 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1065 DanglingDebugInfoMap.clear(); 1066 } 1067 1068 // Update DAG root to include dependencies on Pending chains. 1069 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1070 SDValue Root = DAG.getRoot(); 1071 1072 if (Pending.empty()) 1073 return Root; 1074 1075 // Add current root to PendingChains, unless we already indirectly 1076 // depend on it. 1077 if (Root.getOpcode() != ISD::EntryToken) { 1078 unsigned i = 0, e = Pending.size(); 1079 for (; i != e; ++i) { 1080 assert(Pending[i].getNode()->getNumOperands() > 1); 1081 if (Pending[i].getNode()->getOperand(0) == Root) 1082 break; // Don't add the root if we already indirectly depend on it. 1083 } 1084 1085 if (i == e) 1086 Pending.push_back(Root); 1087 } 1088 1089 if (Pending.size() == 1) 1090 Root = Pending[0]; 1091 else 1092 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1093 1094 DAG.setRoot(Root); 1095 Pending.clear(); 1096 return Root; 1097 } 1098 1099 SDValue SelectionDAGBuilder::getMemoryRoot() { 1100 return updateRoot(PendingLoads); 1101 } 1102 1103 SDValue SelectionDAGBuilder::getRoot() { 1104 // Chain up all pending constrained intrinsics together with all 1105 // pending loads, by simply appending them to PendingLoads and 1106 // then calling getMemoryRoot(). 1107 PendingLoads.reserve(PendingLoads.size() + 1108 PendingConstrainedFP.size() + 1109 PendingConstrainedFPStrict.size()); 1110 PendingLoads.append(PendingConstrainedFP.begin(), 1111 PendingConstrainedFP.end()); 1112 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1113 PendingConstrainedFPStrict.end()); 1114 PendingConstrainedFP.clear(); 1115 PendingConstrainedFPStrict.clear(); 1116 return getMemoryRoot(); 1117 } 1118 1119 SDValue SelectionDAGBuilder::getControlRoot() { 1120 // We need to emit pending fpexcept.strict constrained intrinsics, 1121 // so append them to the PendingExports list. 1122 PendingExports.append(PendingConstrainedFPStrict.begin(), 1123 PendingConstrainedFPStrict.end()); 1124 PendingConstrainedFPStrict.clear(); 1125 return updateRoot(PendingExports); 1126 } 1127 1128 void SelectionDAGBuilder::visit(const Instruction &I) { 1129 // Set up outgoing PHI node register values before emitting the terminator. 1130 if (I.isTerminator()) { 1131 HandlePHINodesInSuccessorBlocks(I.getParent()); 1132 } 1133 1134 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1135 if (!isa<DbgInfoIntrinsic>(I)) 1136 ++SDNodeOrder; 1137 1138 CurInst = &I; 1139 1140 visit(I.getOpcode(), I); 1141 1142 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) { 1143 // ConstrainedFPIntrinsics handle their own FMF. 1144 if (!isa<ConstrainedFPIntrinsic>(&I)) { 1145 // Propagate the fast-math-flags of this IR instruction to the DAG node that 1146 // maps to this instruction. 1147 // TODO: We could handle all flags (nsw, etc) here. 1148 // TODO: If an IR instruction maps to >1 node, only the final node will have 1149 // flags set. 1150 if (SDNode *Node = getNodeForIRValue(&I)) { 1151 SDNodeFlags IncomingFlags; 1152 IncomingFlags.copyFMF(*FPMO); 1153 if (!Node->getFlags().isDefined()) 1154 Node->setFlags(IncomingFlags); 1155 else 1156 Node->intersectFlagsWith(IncomingFlags); 1157 } 1158 } 1159 } 1160 1161 if (!I.isTerminator() && !HasTailCall && 1162 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1163 CopyToExportRegsIfNeeded(&I); 1164 1165 CurInst = nullptr; 1166 } 1167 1168 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1169 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1170 } 1171 1172 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1173 // Note: this doesn't use InstVisitor, because it has to work with 1174 // ConstantExpr's in addition to instructions. 1175 switch (Opcode) { 1176 default: llvm_unreachable("Unknown instruction type encountered!"); 1177 // Build the switch statement using the Instruction.def file. 1178 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1179 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1180 #include "llvm/IR/Instruction.def" 1181 } 1182 } 1183 1184 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1185 const DIExpression *Expr) { 1186 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1187 const DbgValueInst *DI = DDI.getDI(); 1188 DIVariable *DanglingVariable = DI->getVariable(); 1189 DIExpression *DanglingExpr = DI->getExpression(); 1190 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1191 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1192 return true; 1193 } 1194 return false; 1195 }; 1196 1197 for (auto &DDIMI : DanglingDebugInfoMap) { 1198 DanglingDebugInfoVector &DDIV = DDIMI.second; 1199 1200 // If debug info is to be dropped, run it through final checks to see 1201 // whether it can be salvaged. 1202 for (auto &DDI : DDIV) 1203 if (isMatchingDbgValue(DDI)) 1204 salvageUnresolvedDbgValue(DDI); 1205 1206 DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end()); 1207 } 1208 } 1209 1210 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1211 // generate the debug data structures now that we've seen its definition. 1212 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1213 SDValue Val) { 1214 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1215 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1216 return; 1217 1218 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1219 for (auto &DDI : DDIV) { 1220 const DbgValueInst *DI = DDI.getDI(); 1221 assert(DI && "Ill-formed DanglingDebugInfo"); 1222 DebugLoc dl = DDI.getdl(); 1223 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1224 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1225 DILocalVariable *Variable = DI->getVariable(); 1226 DIExpression *Expr = DI->getExpression(); 1227 assert(Variable->isValidLocationForIntrinsic(dl) && 1228 "Expected inlined-at fields to agree"); 1229 SDDbgValue *SDV; 1230 if (Val.getNode()) { 1231 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1232 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1233 // we couldn't resolve it directly when examining the DbgValue intrinsic 1234 // in the first place we should not be more successful here). Unless we 1235 // have some test case that prove this to be correct we should avoid 1236 // calling EmitFuncArgumentDbgValue here. 1237 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1238 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1239 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1240 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1241 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1242 // inserted after the definition of Val when emitting the instructions 1243 // after ISel. An alternative could be to teach 1244 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1245 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1246 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1247 << ValSDNodeOrder << "\n"); 1248 SDV = getDbgValue(Val, Variable, Expr, dl, 1249 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1250 DAG.AddDbgValue(SDV, Val.getNode(), false); 1251 } else 1252 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1253 << "in EmitFuncArgumentDbgValue\n"); 1254 } else { 1255 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1256 auto Undef = 1257 UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1258 auto SDV = 1259 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); 1260 DAG.AddDbgValue(SDV, nullptr, false); 1261 } 1262 } 1263 DDIV.clear(); 1264 } 1265 1266 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1267 Value *V = DDI.getDI()->getValue(); 1268 DILocalVariable *Var = DDI.getDI()->getVariable(); 1269 DIExpression *Expr = DDI.getDI()->getExpression(); 1270 DebugLoc DL = DDI.getdl(); 1271 DebugLoc InstDL = DDI.getDI()->getDebugLoc(); 1272 unsigned SDOrder = DDI.getSDNodeOrder(); 1273 1274 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1275 // that DW_OP_stack_value is desired. 1276 assert(isa<DbgValueInst>(DDI.getDI())); 1277 bool StackValue = true; 1278 1279 // Can this Value can be encoded without any further work? 1280 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) 1281 return; 1282 1283 // Attempt to salvage back through as many instructions as possible. Bail if 1284 // a non-instruction is seen, such as a constant expression or global 1285 // variable. FIXME: Further work could recover those too. 1286 while (isa<Instruction>(V)) { 1287 Instruction &VAsInst = *cast<Instruction>(V); 1288 DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue); 1289 1290 // If we cannot salvage any further, and haven't yet found a suitable debug 1291 // expression, bail out. 1292 if (!NewExpr) 1293 break; 1294 1295 // New value and expr now represent this debuginfo. 1296 V = VAsInst.getOperand(0); 1297 Expr = NewExpr; 1298 1299 // Some kind of simplification occurred: check whether the operand of the 1300 // salvaged debug expression can be encoded in this DAG. 1301 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) { 1302 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n " 1303 << DDI.getDI() << "\nBy stripping back to:\n " << V); 1304 return; 1305 } 1306 } 1307 1308 // This was the final opportunity to salvage this debug information, and it 1309 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1310 // any earlier variable location. 1311 auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1312 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1313 DAG.AddDbgValue(SDV, nullptr, false); 1314 1315 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI() 1316 << "\n"); 1317 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0) 1318 << "\n"); 1319 } 1320 1321 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var, 1322 DIExpression *Expr, DebugLoc dl, 1323 DebugLoc InstDL, unsigned Order) { 1324 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1325 SDDbgValue *SDV; 1326 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1327 isa<ConstantPointerNull>(V)) { 1328 SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder); 1329 DAG.AddDbgValue(SDV, nullptr, false); 1330 return true; 1331 } 1332 1333 // If the Value is a frame index, we can create a FrameIndex debug value 1334 // without relying on the DAG at all. 1335 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1336 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1337 if (SI != FuncInfo.StaticAllocaMap.end()) { 1338 auto SDV = 1339 DAG.getFrameIndexDbgValue(Var, Expr, SI->second, 1340 /*IsIndirect*/ false, dl, SDNodeOrder); 1341 // Do not attach the SDNodeDbgValue to an SDNode: this variable location 1342 // is still available even if the SDNode gets optimized out. 1343 DAG.AddDbgValue(SDV, nullptr, false); 1344 return true; 1345 } 1346 } 1347 1348 // Do not use getValue() in here; we don't want to generate code at 1349 // this point if it hasn't been done yet. 1350 SDValue N = NodeMap[V]; 1351 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1352 N = UnusedArgNodeMap[V]; 1353 if (N.getNode()) { 1354 if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N)) 1355 return true; 1356 SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder); 1357 DAG.AddDbgValue(SDV, N.getNode(), false); 1358 return true; 1359 } 1360 1361 // Special rules apply for the first dbg.values of parameter variables in a 1362 // function. Identify them by the fact they reference Argument Values, that 1363 // they're parameters, and they are parameters of the current function. We 1364 // need to let them dangle until they get an SDNode. 1365 bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() && 1366 !InstDL.getInlinedAt(); 1367 if (!IsParamOfFunc) { 1368 // The value is not used in this block yet (or it would have an SDNode). 1369 // We still want the value to appear for the user if possible -- if it has 1370 // an associated VReg, we can refer to that instead. 1371 auto VMI = FuncInfo.ValueMap.find(V); 1372 if (VMI != FuncInfo.ValueMap.end()) { 1373 unsigned Reg = VMI->second; 1374 // If this is a PHI node, it may be split up into several MI PHI nodes 1375 // (in FunctionLoweringInfo::set). 1376 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1377 V->getType(), None); 1378 if (RFV.occupiesMultipleRegs()) { 1379 unsigned Offset = 0; 1380 unsigned BitsToDescribe = 0; 1381 if (auto VarSize = Var->getSizeInBits()) 1382 BitsToDescribe = *VarSize; 1383 if (auto Fragment = Expr->getFragmentInfo()) 1384 BitsToDescribe = Fragment->SizeInBits; 1385 for (auto RegAndSize : RFV.getRegsAndSizes()) { 1386 unsigned RegisterSize = RegAndSize.second; 1387 // Bail out if all bits are described already. 1388 if (Offset >= BitsToDescribe) 1389 break; 1390 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1391 ? BitsToDescribe - Offset 1392 : RegisterSize; 1393 auto FragmentExpr = DIExpression::createFragmentExpression( 1394 Expr, Offset, FragmentSize); 1395 if (!FragmentExpr) 1396 continue; 1397 SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first, 1398 false, dl, SDNodeOrder); 1399 DAG.AddDbgValue(SDV, nullptr, false); 1400 Offset += RegisterSize; 1401 } 1402 } else { 1403 SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder); 1404 DAG.AddDbgValue(SDV, nullptr, false); 1405 } 1406 return true; 1407 } 1408 } 1409 1410 return false; 1411 } 1412 1413 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1414 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1415 for (auto &Pair : DanglingDebugInfoMap) 1416 for (auto &DDI : Pair.second) 1417 salvageUnresolvedDbgValue(DDI); 1418 clearDanglingDebugInfo(); 1419 } 1420 1421 /// getCopyFromRegs - If there was virtual register allocated for the value V 1422 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1423 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1424 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1425 SDValue Result; 1426 1427 if (It != FuncInfo.ValueMap.end()) { 1428 Register InReg = It->second; 1429 1430 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1431 DAG.getDataLayout(), InReg, Ty, 1432 None); // This is not an ABI copy. 1433 SDValue Chain = DAG.getEntryNode(); 1434 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1435 V); 1436 resolveDanglingDebugInfo(V, Result); 1437 } 1438 1439 return Result; 1440 } 1441 1442 /// getValue - Return an SDValue for the given Value. 1443 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1444 // If we already have an SDValue for this value, use it. It's important 1445 // to do this first, so that we don't create a CopyFromReg if we already 1446 // have a regular SDValue. 1447 SDValue &N = NodeMap[V]; 1448 if (N.getNode()) return N; 1449 1450 // If there's a virtual register allocated and initialized for this 1451 // value, use it. 1452 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1453 return copyFromReg; 1454 1455 // Otherwise create a new SDValue and remember it. 1456 SDValue Val = getValueImpl(V); 1457 NodeMap[V] = Val; 1458 resolveDanglingDebugInfo(V, Val); 1459 return Val; 1460 } 1461 1462 /// getNonRegisterValue - Return an SDValue for the given Value, but 1463 /// don't look in FuncInfo.ValueMap for a virtual register. 1464 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1465 // If we already have an SDValue for this value, use it. 1466 SDValue &N = NodeMap[V]; 1467 if (N.getNode()) { 1468 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1469 // Remove the debug location from the node as the node is about to be used 1470 // in a location which may differ from the original debug location. This 1471 // is relevant to Constant and ConstantFP nodes because they can appear 1472 // as constant expressions inside PHI nodes. 1473 N->setDebugLoc(DebugLoc()); 1474 } 1475 return N; 1476 } 1477 1478 // Otherwise create a new SDValue and remember it. 1479 SDValue Val = getValueImpl(V); 1480 NodeMap[V] = Val; 1481 resolveDanglingDebugInfo(V, Val); 1482 return Val; 1483 } 1484 1485 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1486 /// Create an SDValue for the given value. 1487 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1488 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1489 1490 if (const Constant *C = dyn_cast<Constant>(V)) { 1491 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1492 1493 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1494 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1495 1496 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1497 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1498 1499 if (isa<ConstantPointerNull>(C)) { 1500 unsigned AS = V->getType()->getPointerAddressSpace(); 1501 return DAG.getConstant(0, getCurSDLoc(), 1502 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1503 } 1504 1505 if (match(C, m_VScale(DAG.getDataLayout()))) 1506 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1507 1508 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1509 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1510 1511 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1512 return DAG.getUNDEF(VT); 1513 1514 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1515 visit(CE->getOpcode(), *CE); 1516 SDValue N1 = NodeMap[V]; 1517 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1518 return N1; 1519 } 1520 1521 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1522 SmallVector<SDValue, 4> Constants; 1523 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 1524 OI != OE; ++OI) { 1525 SDNode *Val = getValue(*OI).getNode(); 1526 // If the operand is an empty aggregate, there are no values. 1527 if (!Val) continue; 1528 // Add each leaf value from the operand to the Constants list 1529 // to form a flattened list of all the values. 1530 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1531 Constants.push_back(SDValue(Val, i)); 1532 } 1533 1534 return DAG.getMergeValues(Constants, getCurSDLoc()); 1535 } 1536 1537 if (const ConstantDataSequential *CDS = 1538 dyn_cast<ConstantDataSequential>(C)) { 1539 SmallVector<SDValue, 4> Ops; 1540 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1541 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1542 // Add each leaf value from the operand to the Constants list 1543 // to form a flattened list of all the values. 1544 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1545 Ops.push_back(SDValue(Val, i)); 1546 } 1547 1548 if (isa<ArrayType>(CDS->getType())) 1549 return DAG.getMergeValues(Ops, getCurSDLoc()); 1550 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1551 } 1552 1553 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1554 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1555 "Unknown struct or array constant!"); 1556 1557 SmallVector<EVT, 4> ValueVTs; 1558 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1559 unsigned NumElts = ValueVTs.size(); 1560 if (NumElts == 0) 1561 return SDValue(); // empty struct 1562 SmallVector<SDValue, 4> Constants(NumElts); 1563 for (unsigned i = 0; i != NumElts; ++i) { 1564 EVT EltVT = ValueVTs[i]; 1565 if (isa<UndefValue>(C)) 1566 Constants[i] = DAG.getUNDEF(EltVT); 1567 else if (EltVT.isFloatingPoint()) 1568 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1569 else 1570 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1571 } 1572 1573 return DAG.getMergeValues(Constants, getCurSDLoc()); 1574 } 1575 1576 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1577 return DAG.getBlockAddress(BA, VT); 1578 1579 VectorType *VecTy = cast<VectorType>(V->getType()); 1580 1581 // Now that we know the number and type of the elements, get that number of 1582 // elements into the Ops array based on what kind of constant it is. 1583 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1584 SmallVector<SDValue, 16> Ops; 1585 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1586 for (unsigned i = 0; i != NumElements; ++i) 1587 Ops.push_back(getValue(CV->getOperand(i))); 1588 1589 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1590 } else if (isa<ConstantAggregateZero>(C)) { 1591 EVT EltVT = 1592 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1593 1594 SDValue Op; 1595 if (EltVT.isFloatingPoint()) 1596 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1597 else 1598 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1599 1600 if (isa<ScalableVectorType>(VecTy)) 1601 return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op); 1602 else { 1603 SmallVector<SDValue, 16> Ops; 1604 Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op); 1605 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1606 } 1607 } 1608 llvm_unreachable("Unknown vector constant"); 1609 } 1610 1611 // If this is a static alloca, generate it as the frameindex instead of 1612 // computation. 1613 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1614 DenseMap<const AllocaInst*, int>::iterator SI = 1615 FuncInfo.StaticAllocaMap.find(AI); 1616 if (SI != FuncInfo.StaticAllocaMap.end()) 1617 return DAG.getFrameIndex(SI->second, 1618 TLI.getFrameIndexTy(DAG.getDataLayout())); 1619 } 1620 1621 // If this is an instruction which fast-isel has deferred, select it now. 1622 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1623 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1624 1625 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1626 Inst->getType(), getABIRegCopyCC(V)); 1627 SDValue Chain = DAG.getEntryNode(); 1628 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1629 } 1630 1631 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) { 1632 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1633 } 1634 llvm_unreachable("Can't get register for value!"); 1635 } 1636 1637 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1638 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1639 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1640 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1641 bool IsSEH = isAsynchronousEHPersonality(Pers); 1642 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1643 if (!IsSEH) 1644 CatchPadMBB->setIsEHScopeEntry(); 1645 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1646 if (IsMSVCCXX || IsCoreCLR) 1647 CatchPadMBB->setIsEHFuncletEntry(); 1648 } 1649 1650 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1651 // Update machine-CFG edge. 1652 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1653 FuncInfo.MBB->addSuccessor(TargetMBB); 1654 1655 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1656 bool IsSEH = isAsynchronousEHPersonality(Pers); 1657 if (IsSEH) { 1658 // If this is not a fall-through branch or optimizations are switched off, 1659 // emit the branch. 1660 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1661 TM.getOptLevel() == CodeGenOpt::None) 1662 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1663 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1664 return; 1665 } 1666 1667 // Figure out the funclet membership for the catchret's successor. 1668 // This will be used by the FuncletLayout pass to determine how to order the 1669 // BB's. 1670 // A 'catchret' returns to the outer scope's color. 1671 Value *ParentPad = I.getCatchSwitchParentPad(); 1672 const BasicBlock *SuccessorColor; 1673 if (isa<ConstantTokenNone>(ParentPad)) 1674 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1675 else 1676 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1677 assert(SuccessorColor && "No parent funclet for catchret!"); 1678 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1679 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1680 1681 // Create the terminator node. 1682 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1683 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1684 DAG.getBasicBlock(SuccessorColorMBB)); 1685 DAG.setRoot(Ret); 1686 } 1687 1688 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1689 // Don't emit any special code for the cleanuppad instruction. It just marks 1690 // the start of an EH scope/funclet. 1691 FuncInfo.MBB->setIsEHScopeEntry(); 1692 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1693 if (Pers != EHPersonality::Wasm_CXX) { 1694 FuncInfo.MBB->setIsEHFuncletEntry(); 1695 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1696 } 1697 } 1698 1699 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and 1700 // the control flow always stops at the single catch pad, as it does for a 1701 // cleanup pad. In case the exception caught is not of the types the catch pad 1702 // catches, it will be rethrown by a rethrow. 1703 static void findWasmUnwindDestinations( 1704 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1705 BranchProbability Prob, 1706 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1707 &UnwindDests) { 1708 while (EHPadBB) { 1709 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1710 if (isa<CleanupPadInst>(Pad)) { 1711 // Stop on cleanup pads. 1712 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1713 UnwindDests.back().first->setIsEHScopeEntry(); 1714 break; 1715 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1716 // Add the catchpad handlers to the possible destinations. We don't 1717 // continue to the unwind destination of the catchswitch for wasm. 1718 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1719 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1720 UnwindDests.back().first->setIsEHScopeEntry(); 1721 } 1722 break; 1723 } else { 1724 continue; 1725 } 1726 } 1727 } 1728 1729 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1730 /// many places it could ultimately go. In the IR, we have a single unwind 1731 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1732 /// This function skips over imaginary basic blocks that hold catchswitch 1733 /// instructions, and finds all the "real" machine 1734 /// basic block destinations. As those destinations may not be successors of 1735 /// EHPadBB, here we also calculate the edge probability to those destinations. 1736 /// The passed-in Prob is the edge probability to EHPadBB. 1737 static void findUnwindDestinations( 1738 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1739 BranchProbability Prob, 1740 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1741 &UnwindDests) { 1742 EHPersonality Personality = 1743 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1744 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1745 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1746 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1747 bool IsSEH = isAsynchronousEHPersonality(Personality); 1748 1749 if (IsWasmCXX) { 1750 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1751 assert(UnwindDests.size() <= 1 && 1752 "There should be at most one unwind destination for wasm"); 1753 return; 1754 } 1755 1756 while (EHPadBB) { 1757 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1758 BasicBlock *NewEHPadBB = nullptr; 1759 if (isa<LandingPadInst>(Pad)) { 1760 // Stop on landingpads. They are not funclets. 1761 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1762 break; 1763 } else if (isa<CleanupPadInst>(Pad)) { 1764 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1765 // personalities. 1766 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1767 UnwindDests.back().first->setIsEHScopeEntry(); 1768 UnwindDests.back().first->setIsEHFuncletEntry(); 1769 break; 1770 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1771 // Add the catchpad handlers to the possible destinations. 1772 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1773 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1774 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1775 if (IsMSVCCXX || IsCoreCLR) 1776 UnwindDests.back().first->setIsEHFuncletEntry(); 1777 if (!IsSEH) 1778 UnwindDests.back().first->setIsEHScopeEntry(); 1779 } 1780 NewEHPadBB = CatchSwitch->getUnwindDest(); 1781 } else { 1782 continue; 1783 } 1784 1785 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1786 if (BPI && NewEHPadBB) 1787 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1788 EHPadBB = NewEHPadBB; 1789 } 1790 } 1791 1792 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1793 // Update successor info. 1794 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1795 auto UnwindDest = I.getUnwindDest(); 1796 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1797 BranchProbability UnwindDestProb = 1798 (BPI && UnwindDest) 1799 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1800 : BranchProbability::getZero(); 1801 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1802 for (auto &UnwindDest : UnwindDests) { 1803 UnwindDest.first->setIsEHPad(); 1804 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1805 } 1806 FuncInfo.MBB->normalizeSuccProbs(); 1807 1808 // Create the terminator node. 1809 SDValue Ret = 1810 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1811 DAG.setRoot(Ret); 1812 } 1813 1814 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1815 report_fatal_error("visitCatchSwitch not yet implemented!"); 1816 } 1817 1818 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1819 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1820 auto &DL = DAG.getDataLayout(); 1821 SDValue Chain = getControlRoot(); 1822 SmallVector<ISD::OutputArg, 8> Outs; 1823 SmallVector<SDValue, 8> OutVals; 1824 1825 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1826 // lower 1827 // 1828 // %val = call <ty> @llvm.experimental.deoptimize() 1829 // ret <ty> %val 1830 // 1831 // differently. 1832 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1833 LowerDeoptimizingReturn(); 1834 return; 1835 } 1836 1837 if (!FuncInfo.CanLowerReturn) { 1838 unsigned DemoteReg = FuncInfo.DemoteRegister; 1839 const Function *F = I.getParent()->getParent(); 1840 1841 // Emit a store of the return value through the virtual register. 1842 // Leave Outs empty so that LowerReturn won't try to load return 1843 // registers the usual way. 1844 SmallVector<EVT, 1> PtrValueVTs; 1845 ComputeValueVTs(TLI, DL, 1846 F->getReturnType()->getPointerTo( 1847 DAG.getDataLayout().getAllocaAddrSpace()), 1848 PtrValueVTs); 1849 1850 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1851 DemoteReg, PtrValueVTs[0]); 1852 SDValue RetOp = getValue(I.getOperand(0)); 1853 1854 SmallVector<EVT, 4> ValueVTs, MemVTs; 1855 SmallVector<uint64_t, 4> Offsets; 1856 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1857 &Offsets); 1858 unsigned NumValues = ValueVTs.size(); 1859 1860 SmallVector<SDValue, 4> Chains(NumValues); 1861 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 1862 for (unsigned i = 0; i != NumValues; ++i) { 1863 // An aggregate return value cannot wrap around the address space, so 1864 // offsets to its parts don't wrap either. 1865 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]); 1866 1867 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 1868 if (MemVTs[i] != ValueVTs[i]) 1869 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 1870 Chains[i] = DAG.getStore( 1871 Chain, getCurSDLoc(), Val, 1872 // FIXME: better loc info would be nice. 1873 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 1874 commonAlignment(BaseAlign, Offsets[i])); 1875 } 1876 1877 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1878 MVT::Other, Chains); 1879 } else if (I.getNumOperands() != 0) { 1880 SmallVector<EVT, 4> ValueVTs; 1881 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1882 unsigned NumValues = ValueVTs.size(); 1883 if (NumValues) { 1884 SDValue RetOp = getValue(I.getOperand(0)); 1885 1886 const Function *F = I.getParent()->getParent(); 1887 1888 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 1889 I.getOperand(0)->getType(), F->getCallingConv(), 1890 /*IsVarArg*/ false); 1891 1892 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1893 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1894 Attribute::SExt)) 1895 ExtendKind = ISD::SIGN_EXTEND; 1896 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1897 Attribute::ZExt)) 1898 ExtendKind = ISD::ZERO_EXTEND; 1899 1900 LLVMContext &Context = F->getContext(); 1901 bool RetInReg = F->getAttributes().hasAttribute( 1902 AttributeList::ReturnIndex, Attribute::InReg); 1903 1904 for (unsigned j = 0; j != NumValues; ++j) { 1905 EVT VT = ValueVTs[j]; 1906 1907 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1908 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1909 1910 CallingConv::ID CC = F->getCallingConv(); 1911 1912 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1913 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1914 SmallVector<SDValue, 4> Parts(NumParts); 1915 getCopyToParts(DAG, getCurSDLoc(), 1916 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1917 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1918 1919 // 'inreg' on function refers to return value 1920 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1921 if (RetInReg) 1922 Flags.setInReg(); 1923 1924 if (I.getOperand(0)->getType()->isPointerTy()) { 1925 Flags.setPointer(); 1926 Flags.setPointerAddrSpace( 1927 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 1928 } 1929 1930 if (NeedsRegBlock) { 1931 Flags.setInConsecutiveRegs(); 1932 if (j == NumValues - 1) 1933 Flags.setInConsecutiveRegsLast(); 1934 } 1935 1936 // Propagate extension type if any 1937 if (ExtendKind == ISD::SIGN_EXTEND) 1938 Flags.setSExt(); 1939 else if (ExtendKind == ISD::ZERO_EXTEND) 1940 Flags.setZExt(); 1941 1942 for (unsigned i = 0; i < NumParts; ++i) { 1943 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1944 VT, /*isfixed=*/true, 0, 0)); 1945 OutVals.push_back(Parts[i]); 1946 } 1947 } 1948 } 1949 } 1950 1951 // Push in swifterror virtual register as the last element of Outs. This makes 1952 // sure swifterror virtual register will be returned in the swifterror 1953 // physical register. 1954 const Function *F = I.getParent()->getParent(); 1955 if (TLI.supportSwiftError() && 1956 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 1957 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 1958 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1959 Flags.setSwiftError(); 1960 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 1961 EVT(TLI.getPointerTy(DL)) /*argvt*/, 1962 true /*isfixed*/, 1 /*origidx*/, 1963 0 /*partOffs*/)); 1964 // Create SDNode for the swifterror virtual register. 1965 OutVals.push_back( 1966 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 1967 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 1968 EVT(TLI.getPointerTy(DL)))); 1969 } 1970 1971 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 1972 CallingConv::ID CallConv = 1973 DAG.getMachineFunction().getFunction().getCallingConv(); 1974 Chain = DAG.getTargetLoweringInfo().LowerReturn( 1975 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 1976 1977 // Verify that the target's LowerReturn behaved as expected. 1978 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 1979 "LowerReturn didn't return a valid chain!"); 1980 1981 // Update the DAG with the new chain value resulting from return lowering. 1982 DAG.setRoot(Chain); 1983 } 1984 1985 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 1986 /// created for it, emit nodes to copy the value into the virtual 1987 /// registers. 1988 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 1989 // Skip empty types 1990 if (V->getType()->isEmptyTy()) 1991 return; 1992 1993 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 1994 if (VMI != FuncInfo.ValueMap.end()) { 1995 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 1996 CopyValueToVirtualRegister(V, VMI->second); 1997 } 1998 } 1999 2000 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2001 /// the current basic block, add it to ValueMap now so that we'll get a 2002 /// CopyTo/FromReg. 2003 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2004 // No need to export constants. 2005 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2006 2007 // Already exported? 2008 if (FuncInfo.isExportedInst(V)) return; 2009 2010 unsigned Reg = FuncInfo.InitializeRegForValue(V); 2011 CopyValueToVirtualRegister(V, Reg); 2012 } 2013 2014 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2015 const BasicBlock *FromBB) { 2016 // The operands of the setcc have to be in this block. We don't know 2017 // how to export them from some other block. 2018 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2019 // Can export from current BB. 2020 if (VI->getParent() == FromBB) 2021 return true; 2022 2023 // Is already exported, noop. 2024 return FuncInfo.isExportedInst(V); 2025 } 2026 2027 // If this is an argument, we can export it if the BB is the entry block or 2028 // if it is already exported. 2029 if (isa<Argument>(V)) { 2030 if (FromBB == &FromBB->getParent()->getEntryBlock()) 2031 return true; 2032 2033 // Otherwise, can only export this if it is already exported. 2034 return FuncInfo.isExportedInst(V); 2035 } 2036 2037 // Otherwise, constants can always be exported. 2038 return true; 2039 } 2040 2041 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2042 BranchProbability 2043 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2044 const MachineBasicBlock *Dst) const { 2045 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2046 const BasicBlock *SrcBB = Src->getBasicBlock(); 2047 const BasicBlock *DstBB = Dst->getBasicBlock(); 2048 if (!BPI) { 2049 // If BPI is not available, set the default probability as 1 / N, where N is 2050 // the number of successors. 2051 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2052 return BranchProbability(1, SuccSize); 2053 } 2054 return BPI->getEdgeProbability(SrcBB, DstBB); 2055 } 2056 2057 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2058 MachineBasicBlock *Dst, 2059 BranchProbability Prob) { 2060 if (!FuncInfo.BPI) 2061 Src->addSuccessorWithoutProb(Dst); 2062 else { 2063 if (Prob.isUnknown()) 2064 Prob = getEdgeProbability(Src, Dst); 2065 Src->addSuccessor(Dst, Prob); 2066 } 2067 } 2068 2069 static bool InBlock(const Value *V, const BasicBlock *BB) { 2070 if (const Instruction *I = dyn_cast<Instruction>(V)) 2071 return I->getParent() == BB; 2072 return true; 2073 } 2074 2075 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2076 /// This function emits a branch and is used at the leaves of an OR or an 2077 /// AND operator tree. 2078 void 2079 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2080 MachineBasicBlock *TBB, 2081 MachineBasicBlock *FBB, 2082 MachineBasicBlock *CurBB, 2083 MachineBasicBlock *SwitchBB, 2084 BranchProbability TProb, 2085 BranchProbability FProb, 2086 bool InvertCond) { 2087 const BasicBlock *BB = CurBB->getBasicBlock(); 2088 2089 // If the leaf of the tree is a comparison, merge the condition into 2090 // the caseblock. 2091 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2092 // The operands of the cmp have to be in this block. We don't know 2093 // how to export them from some other block. If this is the first block 2094 // of the sequence, no exporting is needed. 2095 if (CurBB == SwitchBB || 2096 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2097 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2098 ISD::CondCode Condition; 2099 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2100 ICmpInst::Predicate Pred = 2101 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2102 Condition = getICmpCondCode(Pred); 2103 } else { 2104 const FCmpInst *FC = cast<FCmpInst>(Cond); 2105 FCmpInst::Predicate Pred = 2106 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2107 Condition = getFCmpCondCode(Pred); 2108 if (TM.Options.NoNaNsFPMath) 2109 Condition = getFCmpCodeWithoutNaN(Condition); 2110 } 2111 2112 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2113 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2114 SL->SwitchCases.push_back(CB); 2115 return; 2116 } 2117 } 2118 2119 // Create a CaseBlock record representing this branch. 2120 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2121 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2122 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2123 SL->SwitchCases.push_back(CB); 2124 } 2125 2126 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2127 MachineBasicBlock *TBB, 2128 MachineBasicBlock *FBB, 2129 MachineBasicBlock *CurBB, 2130 MachineBasicBlock *SwitchBB, 2131 Instruction::BinaryOps Opc, 2132 BranchProbability TProb, 2133 BranchProbability FProb, 2134 bool InvertCond) { 2135 // Skip over not part of the tree and remember to invert op and operands at 2136 // next level. 2137 Value *NotCond; 2138 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2139 InBlock(NotCond, CurBB->getBasicBlock())) { 2140 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2141 !InvertCond); 2142 return; 2143 } 2144 2145 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2146 // Compute the effective opcode for Cond, taking into account whether it needs 2147 // to be inverted, e.g. 2148 // and (not (or A, B)), C 2149 // gets lowered as 2150 // and (and (not A, not B), C) 2151 unsigned BOpc = 0; 2152 if (BOp) { 2153 BOpc = BOp->getOpcode(); 2154 if (InvertCond) { 2155 if (BOpc == Instruction::And) 2156 BOpc = Instruction::Or; 2157 else if (BOpc == Instruction::Or) 2158 BOpc = Instruction::And; 2159 } 2160 } 2161 2162 // If this node is not part of the or/and tree, emit it as a branch. 2163 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 2164 BOpc != unsigned(Opc) || !BOp->hasOneUse() || 2165 BOp->getParent() != CurBB->getBasicBlock() || 2166 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 2167 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 2168 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2169 TProb, FProb, InvertCond); 2170 return; 2171 } 2172 2173 // Create TmpBB after CurBB. 2174 MachineFunction::iterator BBI(CurBB); 2175 MachineFunction &MF = DAG.getMachineFunction(); 2176 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2177 CurBB->getParent()->insert(++BBI, TmpBB); 2178 2179 if (Opc == Instruction::Or) { 2180 // Codegen X | Y as: 2181 // BB1: 2182 // jmp_if_X TBB 2183 // jmp TmpBB 2184 // TmpBB: 2185 // jmp_if_Y TBB 2186 // jmp FBB 2187 // 2188 2189 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2190 // The requirement is that 2191 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2192 // = TrueProb for original BB. 2193 // Assuming the original probabilities are A and B, one choice is to set 2194 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2195 // A/(1+B) and 2B/(1+B). This choice assumes that 2196 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2197 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2198 // TmpBB, but the math is more complicated. 2199 2200 auto NewTrueProb = TProb / 2; 2201 auto NewFalseProb = TProb / 2 + FProb; 2202 // Emit the LHS condition. 2203 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc, 2204 NewTrueProb, NewFalseProb, InvertCond); 2205 2206 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2207 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2208 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2209 // Emit the RHS condition into TmpBB. 2210 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2211 Probs[0], Probs[1], InvertCond); 2212 } else { 2213 assert(Opc == Instruction::And && "Unknown merge op!"); 2214 // Codegen X & Y as: 2215 // BB1: 2216 // jmp_if_X TmpBB 2217 // jmp FBB 2218 // TmpBB: 2219 // jmp_if_Y TBB 2220 // jmp FBB 2221 // 2222 // This requires creation of TmpBB after CurBB. 2223 2224 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2225 // The requirement is that 2226 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2227 // = FalseProb for original BB. 2228 // Assuming the original probabilities are A and B, one choice is to set 2229 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2230 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2231 // TrueProb for BB1 * FalseProb for TmpBB. 2232 2233 auto NewTrueProb = TProb + FProb / 2; 2234 auto NewFalseProb = FProb / 2; 2235 // Emit the LHS condition. 2236 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc, 2237 NewTrueProb, NewFalseProb, InvertCond); 2238 2239 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2240 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2241 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2242 // Emit the RHS condition into TmpBB. 2243 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2244 Probs[0], Probs[1], InvertCond); 2245 } 2246 } 2247 2248 /// If the set of cases should be emitted as a series of branches, return true. 2249 /// If we should emit this as a bunch of and/or'd together conditions, return 2250 /// false. 2251 bool 2252 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2253 if (Cases.size() != 2) return true; 2254 2255 // If this is two comparisons of the same values or'd or and'd together, they 2256 // will get folded into a single comparison, so don't emit two blocks. 2257 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2258 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2259 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2260 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2261 return false; 2262 } 2263 2264 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2265 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2266 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2267 Cases[0].CC == Cases[1].CC && 2268 isa<Constant>(Cases[0].CmpRHS) && 2269 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2270 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2271 return false; 2272 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2273 return false; 2274 } 2275 2276 return true; 2277 } 2278 2279 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2280 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2281 2282 // Update machine-CFG edges. 2283 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2284 2285 if (I.isUnconditional()) { 2286 // Update machine-CFG edges. 2287 BrMBB->addSuccessor(Succ0MBB); 2288 2289 // If this is not a fall-through branch or optimizations are switched off, 2290 // emit the branch. 2291 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2292 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2293 MVT::Other, getControlRoot(), 2294 DAG.getBasicBlock(Succ0MBB))); 2295 2296 return; 2297 } 2298 2299 // If this condition is one of the special cases we handle, do special stuff 2300 // now. 2301 const Value *CondVal = I.getCondition(); 2302 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2303 2304 // If this is a series of conditions that are or'd or and'd together, emit 2305 // this as a sequence of branches instead of setcc's with and/or operations. 2306 // As long as jumps are not expensive, this should improve performance. 2307 // For example, instead of something like: 2308 // cmp A, B 2309 // C = seteq 2310 // cmp D, E 2311 // F = setle 2312 // or C, F 2313 // jnz foo 2314 // Emit: 2315 // cmp A, B 2316 // je foo 2317 // cmp D, E 2318 // jle foo 2319 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 2320 Instruction::BinaryOps Opcode = BOp->getOpcode(); 2321 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() && 2322 !I.hasMetadata(LLVMContext::MD_unpredictable) && 2323 (Opcode == Instruction::And || Opcode == Instruction::Or)) { 2324 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, 2325 Opcode, 2326 getEdgeProbability(BrMBB, Succ0MBB), 2327 getEdgeProbability(BrMBB, Succ1MBB), 2328 /*InvertCond=*/false); 2329 // If the compares in later blocks need to use values not currently 2330 // exported from this block, export them now. This block should always 2331 // be the first entry. 2332 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2333 2334 // Allow some cases to be rejected. 2335 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2336 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2337 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2338 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2339 } 2340 2341 // Emit the branch for this block. 2342 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2343 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2344 return; 2345 } 2346 2347 // Okay, we decided not to do this, remove any inserted MBB's and clear 2348 // SwitchCases. 2349 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2350 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2351 2352 SL->SwitchCases.clear(); 2353 } 2354 } 2355 2356 // Create a CaseBlock record representing this branch. 2357 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2358 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2359 2360 // Use visitSwitchCase to actually insert the fast branch sequence for this 2361 // cond branch. 2362 visitSwitchCase(CB, BrMBB); 2363 } 2364 2365 /// visitSwitchCase - Emits the necessary code to represent a single node in 2366 /// the binary search tree resulting from lowering a switch instruction. 2367 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2368 MachineBasicBlock *SwitchBB) { 2369 SDValue Cond; 2370 SDValue CondLHS = getValue(CB.CmpLHS); 2371 SDLoc dl = CB.DL; 2372 2373 if (CB.CC == ISD::SETTRUE) { 2374 // Branch or fall through to TrueBB. 2375 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2376 SwitchBB->normalizeSuccProbs(); 2377 if (CB.TrueBB != NextBlock(SwitchBB)) { 2378 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2379 DAG.getBasicBlock(CB.TrueBB))); 2380 } 2381 return; 2382 } 2383 2384 auto &TLI = DAG.getTargetLoweringInfo(); 2385 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2386 2387 // Build the setcc now. 2388 if (!CB.CmpMHS) { 2389 // Fold "(X == true)" to X and "(X == false)" to !X to 2390 // handle common cases produced by branch lowering. 2391 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2392 CB.CC == ISD::SETEQ) 2393 Cond = CondLHS; 2394 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2395 CB.CC == ISD::SETEQ) { 2396 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2397 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2398 } else { 2399 SDValue CondRHS = getValue(CB.CmpRHS); 2400 2401 // If a pointer's DAG type is larger than its memory type then the DAG 2402 // values are zero-extended. This breaks signed comparisons so truncate 2403 // back to the underlying type before doing the compare. 2404 if (CondLHS.getValueType() != MemVT) { 2405 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2406 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2407 } 2408 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2409 } 2410 } else { 2411 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2412 2413 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2414 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2415 2416 SDValue CmpOp = getValue(CB.CmpMHS); 2417 EVT VT = CmpOp.getValueType(); 2418 2419 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2420 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2421 ISD::SETLE); 2422 } else { 2423 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2424 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2425 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2426 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2427 } 2428 } 2429 2430 // Update successor info 2431 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2432 // TrueBB and FalseBB are always different unless the incoming IR is 2433 // degenerate. This only happens when running llc on weird IR. 2434 if (CB.TrueBB != CB.FalseBB) 2435 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2436 SwitchBB->normalizeSuccProbs(); 2437 2438 // If the lhs block is the next block, invert the condition so that we can 2439 // fall through to the lhs instead of the rhs block. 2440 if (CB.TrueBB == NextBlock(SwitchBB)) { 2441 std::swap(CB.TrueBB, CB.FalseBB); 2442 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2443 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2444 } 2445 2446 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2447 MVT::Other, getControlRoot(), Cond, 2448 DAG.getBasicBlock(CB.TrueBB)); 2449 2450 // Insert the false branch. Do this even if it's a fall through branch, 2451 // this makes it easier to do DAG optimizations which require inverting 2452 // the branch condition. 2453 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2454 DAG.getBasicBlock(CB.FalseBB)); 2455 2456 DAG.setRoot(BrCond); 2457 } 2458 2459 /// visitJumpTable - Emit JumpTable node in the current MBB 2460 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2461 // Emit the code for the jump table 2462 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2463 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2464 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2465 JT.Reg, PTy); 2466 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2467 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2468 MVT::Other, Index.getValue(1), 2469 Table, Index); 2470 DAG.setRoot(BrJumpTable); 2471 } 2472 2473 /// visitJumpTableHeader - This function emits necessary code to produce index 2474 /// in the JumpTable from switch case. 2475 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2476 JumpTableHeader &JTH, 2477 MachineBasicBlock *SwitchBB) { 2478 SDLoc dl = getCurSDLoc(); 2479 2480 // Subtract the lowest switch case value from the value being switched on. 2481 SDValue SwitchOp = getValue(JTH.SValue); 2482 EVT VT = SwitchOp.getValueType(); 2483 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2484 DAG.getConstant(JTH.First, dl, VT)); 2485 2486 // The SDNode we just created, which holds the value being switched on minus 2487 // the smallest case value, needs to be copied to a virtual register so it 2488 // can be used as an index into the jump table in a subsequent basic block. 2489 // This value may be smaller or larger than the target's pointer type, and 2490 // therefore require extension or truncating. 2491 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2492 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2493 2494 unsigned JumpTableReg = 2495 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2496 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2497 JumpTableReg, SwitchOp); 2498 JT.Reg = JumpTableReg; 2499 2500 if (!JTH.OmitRangeCheck) { 2501 // Emit the range check for the jump table, and branch to the default block 2502 // for the switch statement if the value being switched on exceeds the 2503 // largest case in the switch. 2504 SDValue CMP = DAG.getSetCC( 2505 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2506 Sub.getValueType()), 2507 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2508 2509 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2510 MVT::Other, CopyTo, CMP, 2511 DAG.getBasicBlock(JT.Default)); 2512 2513 // Avoid emitting unnecessary branches to the next block. 2514 if (JT.MBB != NextBlock(SwitchBB)) 2515 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2516 DAG.getBasicBlock(JT.MBB)); 2517 2518 DAG.setRoot(BrCond); 2519 } else { 2520 // Avoid emitting unnecessary branches to the next block. 2521 if (JT.MBB != NextBlock(SwitchBB)) 2522 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2523 DAG.getBasicBlock(JT.MBB))); 2524 else 2525 DAG.setRoot(CopyTo); 2526 } 2527 } 2528 2529 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2530 /// variable if there exists one. 2531 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2532 SDValue &Chain) { 2533 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2534 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2535 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2536 MachineFunction &MF = DAG.getMachineFunction(); 2537 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2538 MachineSDNode *Node = 2539 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2540 if (Global) { 2541 MachinePointerInfo MPInfo(Global); 2542 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2543 MachineMemOperand::MODereferenceable; 2544 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2545 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2546 DAG.setNodeMemRefs(Node, {MemRef}); 2547 } 2548 if (PtrTy != PtrMemTy) 2549 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2550 return SDValue(Node, 0); 2551 } 2552 2553 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2554 /// tail spliced into a stack protector check success bb. 2555 /// 2556 /// For a high level explanation of how this fits into the stack protector 2557 /// generation see the comment on the declaration of class 2558 /// StackProtectorDescriptor. 2559 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2560 MachineBasicBlock *ParentBB) { 2561 2562 // First create the loads to the guard/stack slot for the comparison. 2563 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2564 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2565 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2566 2567 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2568 int FI = MFI.getStackProtectorIndex(); 2569 2570 SDValue Guard; 2571 SDLoc dl = getCurSDLoc(); 2572 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2573 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2574 unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext())); 2575 2576 // Generate code to load the content of the guard slot. 2577 SDValue GuardVal = DAG.getLoad( 2578 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2579 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2580 MachineMemOperand::MOVolatile); 2581 2582 if (TLI.useStackGuardXorFP()) 2583 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2584 2585 // Retrieve guard check function, nullptr if instrumentation is inlined. 2586 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2587 // The target provides a guard check function to validate the guard value. 2588 // Generate a call to that function with the content of the guard slot as 2589 // argument. 2590 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2591 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2592 2593 TargetLowering::ArgListTy Args; 2594 TargetLowering::ArgListEntry Entry; 2595 Entry.Node = GuardVal; 2596 Entry.Ty = FnTy->getParamType(0); 2597 if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg)) 2598 Entry.IsInReg = true; 2599 Args.push_back(Entry); 2600 2601 TargetLowering::CallLoweringInfo CLI(DAG); 2602 CLI.setDebugLoc(getCurSDLoc()) 2603 .setChain(DAG.getEntryNode()) 2604 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2605 getValue(GuardCheckFn), std::move(Args)); 2606 2607 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2608 DAG.setRoot(Result.second); 2609 return; 2610 } 2611 2612 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2613 // Otherwise, emit a volatile load to retrieve the stack guard value. 2614 SDValue Chain = DAG.getEntryNode(); 2615 if (TLI.useLoadStackGuardNode()) { 2616 Guard = getLoadStackGuard(DAG, dl, Chain); 2617 } else { 2618 const Value *IRGuard = TLI.getSDagStackGuard(M); 2619 SDValue GuardPtr = getValue(IRGuard); 2620 2621 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2622 MachinePointerInfo(IRGuard, 0), Align, 2623 MachineMemOperand::MOVolatile); 2624 } 2625 2626 // Perform the comparison via a getsetcc. 2627 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2628 *DAG.getContext(), 2629 Guard.getValueType()), 2630 Guard, GuardVal, ISD::SETNE); 2631 2632 // If the guard/stackslot do not equal, branch to failure MBB. 2633 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2634 MVT::Other, GuardVal.getOperand(0), 2635 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2636 // Otherwise branch to success MBB. 2637 SDValue Br = DAG.getNode(ISD::BR, dl, 2638 MVT::Other, BrCond, 2639 DAG.getBasicBlock(SPD.getSuccessMBB())); 2640 2641 DAG.setRoot(Br); 2642 } 2643 2644 /// Codegen the failure basic block for a stack protector check. 2645 /// 2646 /// A failure stack protector machine basic block consists simply of a call to 2647 /// __stack_chk_fail(). 2648 /// 2649 /// For a high level explanation of how this fits into the stack protector 2650 /// generation see the comment on the declaration of class 2651 /// StackProtectorDescriptor. 2652 void 2653 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2654 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2655 TargetLowering::MakeLibCallOptions CallOptions; 2656 CallOptions.setDiscardResult(true); 2657 SDValue Chain = 2658 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2659 None, CallOptions, getCurSDLoc()).second; 2660 // On PS4, the "return address" must still be within the calling function, 2661 // even if it's at the very end, so emit an explicit TRAP here. 2662 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2663 if (TM.getTargetTriple().isPS4CPU()) 2664 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2665 2666 DAG.setRoot(Chain); 2667 } 2668 2669 /// visitBitTestHeader - This function emits necessary code to produce value 2670 /// suitable for "bit tests" 2671 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2672 MachineBasicBlock *SwitchBB) { 2673 SDLoc dl = getCurSDLoc(); 2674 2675 // Subtract the minimum value. 2676 SDValue SwitchOp = getValue(B.SValue); 2677 EVT VT = SwitchOp.getValueType(); 2678 SDValue RangeSub = 2679 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2680 2681 // Determine the type of the test operands. 2682 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2683 bool UsePtrType = false; 2684 if (!TLI.isTypeLegal(VT)) { 2685 UsePtrType = true; 2686 } else { 2687 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2688 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2689 // Switch table case range are encoded into series of masks. 2690 // Just use pointer type, it's guaranteed to fit. 2691 UsePtrType = true; 2692 break; 2693 } 2694 } 2695 SDValue Sub = RangeSub; 2696 if (UsePtrType) { 2697 VT = TLI.getPointerTy(DAG.getDataLayout()); 2698 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2699 } 2700 2701 B.RegVT = VT.getSimpleVT(); 2702 B.Reg = FuncInfo.CreateReg(B.RegVT); 2703 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2704 2705 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2706 2707 if (!B.OmitRangeCheck) 2708 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2709 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2710 SwitchBB->normalizeSuccProbs(); 2711 2712 SDValue Root = CopyTo; 2713 if (!B.OmitRangeCheck) { 2714 // Conditional branch to the default block. 2715 SDValue RangeCmp = DAG.getSetCC(dl, 2716 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2717 RangeSub.getValueType()), 2718 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2719 ISD::SETUGT); 2720 2721 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2722 DAG.getBasicBlock(B.Default)); 2723 } 2724 2725 // Avoid emitting unnecessary branches to the next block. 2726 if (MBB != NextBlock(SwitchBB)) 2727 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2728 2729 DAG.setRoot(Root); 2730 } 2731 2732 /// visitBitTestCase - this function produces one "bit test" 2733 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2734 MachineBasicBlock* NextMBB, 2735 BranchProbability BranchProbToNext, 2736 unsigned Reg, 2737 BitTestCase &B, 2738 MachineBasicBlock *SwitchBB) { 2739 SDLoc dl = getCurSDLoc(); 2740 MVT VT = BB.RegVT; 2741 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2742 SDValue Cmp; 2743 unsigned PopCount = countPopulation(B.Mask); 2744 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2745 if (PopCount == 1) { 2746 // Testing for a single bit; just compare the shift count with what it 2747 // would need to be to shift a 1 bit in that position. 2748 Cmp = DAG.getSetCC( 2749 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2750 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2751 ISD::SETEQ); 2752 } else if (PopCount == BB.Range) { 2753 // There is only one zero bit in the range, test for it directly. 2754 Cmp = DAG.getSetCC( 2755 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2756 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2757 ISD::SETNE); 2758 } else { 2759 // Make desired shift 2760 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2761 DAG.getConstant(1, dl, VT), ShiftOp); 2762 2763 // Emit bit tests and jumps 2764 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2765 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2766 Cmp = DAG.getSetCC( 2767 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2768 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2769 } 2770 2771 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2772 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2773 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2774 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2775 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2776 // one as they are relative probabilities (and thus work more like weights), 2777 // and hence we need to normalize them to let the sum of them become one. 2778 SwitchBB->normalizeSuccProbs(); 2779 2780 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2781 MVT::Other, getControlRoot(), 2782 Cmp, DAG.getBasicBlock(B.TargetBB)); 2783 2784 // Avoid emitting unnecessary branches to the next block. 2785 if (NextMBB != NextBlock(SwitchBB)) 2786 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2787 DAG.getBasicBlock(NextMBB)); 2788 2789 DAG.setRoot(BrAnd); 2790 } 2791 2792 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2793 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2794 2795 // Retrieve successors. Look through artificial IR level blocks like 2796 // catchswitch for successors. 2797 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2798 const BasicBlock *EHPadBB = I.getSuccessor(1); 2799 2800 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2801 // have to do anything here to lower funclet bundles. 2802 assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt, 2803 LLVMContext::OB_gc_transition, 2804 LLVMContext::OB_gc_live, 2805 LLVMContext::OB_funclet, 2806 LLVMContext::OB_cfguardtarget}) && 2807 "Cannot lower invokes with arbitrary operand bundles yet!"); 2808 2809 const Value *Callee(I.getCalledOperand()); 2810 const Function *Fn = dyn_cast<Function>(Callee); 2811 if (isa<InlineAsm>(Callee)) 2812 visitInlineAsm(I); 2813 else if (Fn && Fn->isIntrinsic()) { 2814 switch (Fn->getIntrinsicID()) { 2815 default: 2816 llvm_unreachable("Cannot invoke this intrinsic"); 2817 case Intrinsic::donothing: 2818 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2819 break; 2820 case Intrinsic::experimental_patchpoint_void: 2821 case Intrinsic::experimental_patchpoint_i64: 2822 visitPatchpoint(I, EHPadBB); 2823 break; 2824 case Intrinsic::experimental_gc_statepoint: 2825 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 2826 break; 2827 case Intrinsic::wasm_rethrow_in_catch: { 2828 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2829 // special because it can be invoked, so we manually lower it to a DAG 2830 // node here. 2831 SmallVector<SDValue, 8> Ops; 2832 Ops.push_back(getRoot()); // inchain 2833 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2834 Ops.push_back( 2835 DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(), 2836 TLI.getPointerTy(DAG.getDataLayout()))); 2837 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2838 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2839 break; 2840 } 2841 } 2842 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2843 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2844 // Eventually we will support lowering the @llvm.experimental.deoptimize 2845 // intrinsic, and right now there are no plans to support other intrinsics 2846 // with deopt state. 2847 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2848 } else { 2849 LowerCallTo(I, getValue(Callee), false, EHPadBB); 2850 } 2851 2852 // If the value of the invoke is used outside of its defining block, make it 2853 // available as a virtual register. 2854 // We already took care of the exported value for the statepoint instruction 2855 // during call to the LowerStatepoint. 2856 if (!isa<GCStatepointInst>(I)) { 2857 CopyToExportRegsIfNeeded(&I); 2858 } 2859 2860 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2861 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2862 BranchProbability EHPadBBProb = 2863 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2864 : BranchProbability::getZero(); 2865 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2866 2867 // Update successor info. 2868 addSuccessorWithProb(InvokeMBB, Return); 2869 for (auto &UnwindDest : UnwindDests) { 2870 UnwindDest.first->setIsEHPad(); 2871 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2872 } 2873 InvokeMBB->normalizeSuccProbs(); 2874 2875 // Drop into normal successor. 2876 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 2877 DAG.getBasicBlock(Return))); 2878 } 2879 2880 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 2881 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 2882 2883 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2884 // have to do anything here to lower funclet bundles. 2885 assert(!I.hasOperandBundlesOtherThan( 2886 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2887 "Cannot lower callbrs with arbitrary operand bundles yet!"); 2888 2889 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 2890 visitInlineAsm(I); 2891 CopyToExportRegsIfNeeded(&I); 2892 2893 // Retrieve successors. 2894 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 2895 2896 // Update successor info. 2897 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 2898 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 2899 MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)]; 2900 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 2901 Target->setIsInlineAsmBrIndirectTarget(); 2902 } 2903 CallBrMBB->normalizeSuccProbs(); 2904 2905 // Drop into default successor. 2906 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2907 MVT::Other, getControlRoot(), 2908 DAG.getBasicBlock(Return))); 2909 } 2910 2911 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2912 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2913 } 2914 2915 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2916 assert(FuncInfo.MBB->isEHPad() && 2917 "Call to landingpad not in landing pad!"); 2918 2919 // If there aren't registers to copy the values into (e.g., during SjLj 2920 // exceptions), then don't bother to create these DAG nodes. 2921 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2922 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2923 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2924 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2925 return; 2926 2927 // If landingpad's return type is token type, we don't create DAG nodes 2928 // for its exception pointer and selector value. The extraction of exception 2929 // pointer or selector value from token type landingpads is not currently 2930 // supported. 2931 if (LP.getType()->isTokenTy()) 2932 return; 2933 2934 SmallVector<EVT, 2> ValueVTs; 2935 SDLoc dl = getCurSDLoc(); 2936 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2937 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2938 2939 // Get the two live-in registers as SDValues. The physregs have already been 2940 // copied into virtual registers. 2941 SDValue Ops[2]; 2942 if (FuncInfo.ExceptionPointerVirtReg) { 2943 Ops[0] = DAG.getZExtOrTrunc( 2944 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2945 FuncInfo.ExceptionPointerVirtReg, 2946 TLI.getPointerTy(DAG.getDataLayout())), 2947 dl, ValueVTs[0]); 2948 } else { 2949 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2950 } 2951 Ops[1] = DAG.getZExtOrTrunc( 2952 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2953 FuncInfo.ExceptionSelectorVirtReg, 2954 TLI.getPointerTy(DAG.getDataLayout())), 2955 dl, ValueVTs[1]); 2956 2957 // Merge into one. 2958 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 2959 DAG.getVTList(ValueVTs), Ops); 2960 setValue(&LP, Res); 2961 } 2962 2963 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2964 MachineBasicBlock *Last) { 2965 // Update JTCases. 2966 for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i) 2967 if (SL->JTCases[i].first.HeaderBB == First) 2968 SL->JTCases[i].first.HeaderBB = Last; 2969 2970 // Update BitTestCases. 2971 for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i) 2972 if (SL->BitTestCases[i].Parent == First) 2973 SL->BitTestCases[i].Parent = Last; 2974 } 2975 2976 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2977 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2978 2979 // Update machine-CFG edges with unique successors. 2980 SmallSet<BasicBlock*, 32> Done; 2981 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 2982 BasicBlock *BB = I.getSuccessor(i); 2983 bool Inserted = Done.insert(BB).second; 2984 if (!Inserted) 2985 continue; 2986 2987 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 2988 addSuccessorWithProb(IndirectBrMBB, Succ); 2989 } 2990 IndirectBrMBB->normalizeSuccProbs(); 2991 2992 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 2993 MVT::Other, getControlRoot(), 2994 getValue(I.getAddress()))); 2995 } 2996 2997 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 2998 if (!DAG.getTarget().Options.TrapUnreachable) 2999 return; 3000 3001 // We may be able to ignore unreachable behind a noreturn call. 3002 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3003 const BasicBlock &BB = *I.getParent(); 3004 if (&I != &BB.front()) { 3005 BasicBlock::const_iterator PredI = 3006 std::prev(BasicBlock::const_iterator(&I)); 3007 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 3008 if (Call->doesNotReturn()) 3009 return; 3010 } 3011 } 3012 } 3013 3014 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3015 } 3016 3017 void SelectionDAGBuilder::visitFSub(const User &I) { 3018 // -0.0 - X --> fneg 3019 Type *Ty = I.getType(); 3020 if (isa<Constant>(I.getOperand(0)) && 3021 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) { 3022 SDValue Op2 = getValue(I.getOperand(1)); 3023 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(), 3024 Op2.getValueType(), Op2)); 3025 return; 3026 } 3027 3028 visitBinary(I, ISD::FSUB); 3029 } 3030 3031 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3032 SDNodeFlags Flags; 3033 3034 SDValue Op = getValue(I.getOperand(0)); 3035 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3036 Op, Flags); 3037 setValue(&I, UnNodeValue); 3038 } 3039 3040 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3041 SDNodeFlags Flags; 3042 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3043 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3044 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3045 } 3046 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) { 3047 Flags.setExact(ExactOp->isExact()); 3048 } 3049 3050 SDValue Op1 = getValue(I.getOperand(0)); 3051 SDValue Op2 = getValue(I.getOperand(1)); 3052 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3053 Op1, Op2, Flags); 3054 setValue(&I, BinNodeValue); 3055 } 3056 3057 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3058 SDValue Op1 = getValue(I.getOperand(0)); 3059 SDValue Op2 = getValue(I.getOperand(1)); 3060 3061 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3062 Op1.getValueType(), DAG.getDataLayout()); 3063 3064 // Coerce the shift amount to the right type if we can. 3065 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3066 unsigned ShiftSize = ShiftTy.getSizeInBits(); 3067 unsigned Op2Size = Op2.getValueSizeInBits(); 3068 SDLoc DL = getCurSDLoc(); 3069 3070 // If the operand is smaller than the shift count type, promote it. 3071 if (ShiftSize > Op2Size) 3072 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 3073 3074 // If the operand is larger than the shift count type but the shift 3075 // count type has enough bits to represent any shift value, truncate 3076 // it now. This is a common case and it exposes the truncate to 3077 // optimization early. 3078 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 3079 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 3080 // Otherwise we'll need to temporarily settle for some other convenient 3081 // type. Type legalization will make adjustments once the shiftee is split. 3082 else 3083 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 3084 } 3085 3086 bool nuw = false; 3087 bool nsw = false; 3088 bool exact = false; 3089 3090 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3091 3092 if (const OverflowingBinaryOperator *OFBinOp = 3093 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3094 nuw = OFBinOp->hasNoUnsignedWrap(); 3095 nsw = OFBinOp->hasNoSignedWrap(); 3096 } 3097 if (const PossiblyExactOperator *ExactOp = 3098 dyn_cast<const PossiblyExactOperator>(&I)) 3099 exact = ExactOp->isExact(); 3100 } 3101 SDNodeFlags Flags; 3102 Flags.setExact(exact); 3103 Flags.setNoSignedWrap(nsw); 3104 Flags.setNoUnsignedWrap(nuw); 3105 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3106 Flags); 3107 setValue(&I, Res); 3108 } 3109 3110 void SelectionDAGBuilder::visitSDiv(const User &I) { 3111 SDValue Op1 = getValue(I.getOperand(0)); 3112 SDValue Op2 = getValue(I.getOperand(1)); 3113 3114 SDNodeFlags Flags; 3115 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3116 cast<PossiblyExactOperator>(&I)->isExact()); 3117 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3118 Op2, Flags)); 3119 } 3120 3121 void SelectionDAGBuilder::visitICmp(const User &I) { 3122 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3123 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3124 predicate = IC->getPredicate(); 3125 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3126 predicate = ICmpInst::Predicate(IC->getPredicate()); 3127 SDValue Op1 = getValue(I.getOperand(0)); 3128 SDValue Op2 = getValue(I.getOperand(1)); 3129 ISD::CondCode Opcode = getICmpCondCode(predicate); 3130 3131 auto &TLI = DAG.getTargetLoweringInfo(); 3132 EVT MemVT = 3133 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3134 3135 // If a pointer's DAG type is larger than its memory type then the DAG values 3136 // are zero-extended. This breaks signed comparisons so truncate back to the 3137 // underlying type before doing the compare. 3138 if (Op1.getValueType() != MemVT) { 3139 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3140 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3141 } 3142 3143 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3144 I.getType()); 3145 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3146 } 3147 3148 void SelectionDAGBuilder::visitFCmp(const User &I) { 3149 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3150 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3151 predicate = FC->getPredicate(); 3152 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3153 predicate = FCmpInst::Predicate(FC->getPredicate()); 3154 SDValue Op1 = getValue(I.getOperand(0)); 3155 SDValue Op2 = getValue(I.getOperand(1)); 3156 3157 ISD::CondCode Condition = getFCmpCondCode(predicate); 3158 auto *FPMO = dyn_cast<FPMathOperator>(&I); 3159 if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath) 3160 Condition = getFCmpCodeWithoutNaN(Condition); 3161 3162 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3163 I.getType()); 3164 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3165 } 3166 3167 // Check if the condition of the select has one use or two users that are both 3168 // selects with the same condition. 3169 static bool hasOnlySelectUsers(const Value *Cond) { 3170 return llvm::all_of(Cond->users(), [](const Value *V) { 3171 return isa<SelectInst>(V); 3172 }); 3173 } 3174 3175 void SelectionDAGBuilder::visitSelect(const User &I) { 3176 SmallVector<EVT, 4> ValueVTs; 3177 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3178 ValueVTs); 3179 unsigned NumValues = ValueVTs.size(); 3180 if (NumValues == 0) return; 3181 3182 SmallVector<SDValue, 4> Values(NumValues); 3183 SDValue Cond = getValue(I.getOperand(0)); 3184 SDValue LHSVal = getValue(I.getOperand(1)); 3185 SDValue RHSVal = getValue(I.getOperand(2)); 3186 SmallVector<SDValue, 1> BaseOps(1, Cond); 3187 ISD::NodeType OpCode = 3188 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3189 3190 bool IsUnaryAbs = false; 3191 3192 // Min/max matching is only viable if all output VTs are the same. 3193 if (is_splat(ValueVTs)) { 3194 EVT VT = ValueVTs[0]; 3195 LLVMContext &Ctx = *DAG.getContext(); 3196 auto &TLI = DAG.getTargetLoweringInfo(); 3197 3198 // We care about the legality of the operation after it has been type 3199 // legalized. 3200 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3201 VT = TLI.getTypeToTransformTo(Ctx, VT); 3202 3203 // If the vselect is legal, assume we want to leave this as a vector setcc + 3204 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3205 // min/max is legal on the scalar type. 3206 bool UseScalarMinMax = VT.isVector() && 3207 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3208 3209 Value *LHS, *RHS; 3210 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3211 ISD::NodeType Opc = ISD::DELETED_NODE; 3212 switch (SPR.Flavor) { 3213 case SPF_UMAX: Opc = ISD::UMAX; break; 3214 case SPF_UMIN: Opc = ISD::UMIN; break; 3215 case SPF_SMAX: Opc = ISD::SMAX; break; 3216 case SPF_SMIN: Opc = ISD::SMIN; break; 3217 case SPF_FMINNUM: 3218 switch (SPR.NaNBehavior) { 3219 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3220 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3221 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3222 case SPNB_RETURNS_ANY: { 3223 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3224 Opc = ISD::FMINNUM; 3225 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3226 Opc = ISD::FMINIMUM; 3227 else if (UseScalarMinMax) 3228 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3229 ISD::FMINNUM : ISD::FMINIMUM; 3230 break; 3231 } 3232 } 3233 break; 3234 case SPF_FMAXNUM: 3235 switch (SPR.NaNBehavior) { 3236 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3237 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3238 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3239 case SPNB_RETURNS_ANY: 3240 3241 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3242 Opc = ISD::FMAXNUM; 3243 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3244 Opc = ISD::FMAXIMUM; 3245 else if (UseScalarMinMax) 3246 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3247 ISD::FMAXNUM : ISD::FMAXIMUM; 3248 break; 3249 } 3250 break; 3251 case SPF_ABS: 3252 IsUnaryAbs = true; 3253 Opc = ISD::ABS; 3254 break; 3255 case SPF_NABS: 3256 // TODO: we need to produce sub(0, abs(X)). 3257 default: break; 3258 } 3259 3260 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3261 (TLI.isOperationLegalOrCustom(Opc, VT) || 3262 (UseScalarMinMax && 3263 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3264 // If the underlying comparison instruction is used by any other 3265 // instruction, the consumed instructions won't be destroyed, so it is 3266 // not profitable to convert to a min/max. 3267 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3268 OpCode = Opc; 3269 LHSVal = getValue(LHS); 3270 RHSVal = getValue(RHS); 3271 BaseOps.clear(); 3272 } 3273 3274 if (IsUnaryAbs) { 3275 OpCode = Opc; 3276 LHSVal = getValue(LHS); 3277 BaseOps.clear(); 3278 } 3279 } 3280 3281 if (IsUnaryAbs) { 3282 for (unsigned i = 0; i != NumValues; ++i) { 3283 Values[i] = 3284 DAG.getNode(OpCode, getCurSDLoc(), 3285 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), 3286 SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3287 } 3288 } else { 3289 for (unsigned i = 0; i != NumValues; ++i) { 3290 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3291 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3292 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3293 Values[i] = DAG.getNode( 3294 OpCode, getCurSDLoc(), 3295 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops); 3296 } 3297 } 3298 3299 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3300 DAG.getVTList(ValueVTs), Values)); 3301 } 3302 3303 void SelectionDAGBuilder::visitTrunc(const User &I) { 3304 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3305 SDValue N = getValue(I.getOperand(0)); 3306 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3307 I.getType()); 3308 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3309 } 3310 3311 void SelectionDAGBuilder::visitZExt(const User &I) { 3312 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3313 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3314 SDValue N = getValue(I.getOperand(0)); 3315 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3316 I.getType()); 3317 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3318 } 3319 3320 void SelectionDAGBuilder::visitSExt(const User &I) { 3321 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3322 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3323 SDValue N = getValue(I.getOperand(0)); 3324 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3325 I.getType()); 3326 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3327 } 3328 3329 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3330 // FPTrunc is never a no-op cast, no need to check 3331 SDValue N = getValue(I.getOperand(0)); 3332 SDLoc dl = getCurSDLoc(); 3333 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3334 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3335 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3336 DAG.getTargetConstant( 3337 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3338 } 3339 3340 void SelectionDAGBuilder::visitFPExt(const User &I) { 3341 // FPExt is never a no-op cast, no need to check 3342 SDValue N = getValue(I.getOperand(0)); 3343 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3344 I.getType()); 3345 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3346 } 3347 3348 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3349 // FPToUI is never a no-op cast, no need to check 3350 SDValue N = getValue(I.getOperand(0)); 3351 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3352 I.getType()); 3353 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3354 } 3355 3356 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3357 // FPToSI is never a no-op cast, no need to check 3358 SDValue N = getValue(I.getOperand(0)); 3359 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3360 I.getType()); 3361 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3362 } 3363 3364 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3365 // UIToFP is never a no-op cast, no need to check 3366 SDValue N = getValue(I.getOperand(0)); 3367 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3368 I.getType()); 3369 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3370 } 3371 3372 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3373 // SIToFP is never a no-op cast, no need to check 3374 SDValue N = getValue(I.getOperand(0)); 3375 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3376 I.getType()); 3377 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3378 } 3379 3380 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3381 // What to do depends on the size of the integer and the size of the pointer. 3382 // We can either truncate, zero extend, or no-op, accordingly. 3383 SDValue N = getValue(I.getOperand(0)); 3384 auto &TLI = DAG.getTargetLoweringInfo(); 3385 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3386 I.getType()); 3387 EVT PtrMemVT = 3388 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3389 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3390 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3391 setValue(&I, N); 3392 } 3393 3394 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3395 // What to do depends on the size of the integer and the size of the pointer. 3396 // We can either truncate, zero extend, or no-op, accordingly. 3397 SDValue N = getValue(I.getOperand(0)); 3398 auto &TLI = DAG.getTargetLoweringInfo(); 3399 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3400 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3401 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3402 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3403 setValue(&I, N); 3404 } 3405 3406 void SelectionDAGBuilder::visitBitCast(const User &I) { 3407 SDValue N = getValue(I.getOperand(0)); 3408 SDLoc dl = getCurSDLoc(); 3409 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3410 I.getType()); 3411 3412 // BitCast assures us that source and destination are the same size so this is 3413 // either a BITCAST or a no-op. 3414 if (DestVT != N.getValueType()) 3415 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3416 DestVT, N)); // convert types. 3417 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3418 // might fold any kind of constant expression to an integer constant and that 3419 // is not what we are looking for. Only recognize a bitcast of a genuine 3420 // constant integer as an opaque constant. 3421 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3422 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3423 /*isOpaque*/true)); 3424 else 3425 setValue(&I, N); // noop cast. 3426 } 3427 3428 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3429 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3430 const Value *SV = I.getOperand(0); 3431 SDValue N = getValue(SV); 3432 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3433 3434 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3435 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3436 3437 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) 3438 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3439 3440 setValue(&I, N); 3441 } 3442 3443 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3444 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3445 SDValue InVec = getValue(I.getOperand(0)); 3446 SDValue InVal = getValue(I.getOperand(1)); 3447 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3448 TLI.getVectorIdxTy(DAG.getDataLayout())); 3449 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3450 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3451 InVec, InVal, InIdx)); 3452 } 3453 3454 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3455 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3456 SDValue InVec = getValue(I.getOperand(0)); 3457 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3458 TLI.getVectorIdxTy(DAG.getDataLayout())); 3459 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3460 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3461 InVec, InIdx)); 3462 } 3463 3464 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3465 SDValue Src1 = getValue(I.getOperand(0)); 3466 SDValue Src2 = getValue(I.getOperand(1)); 3467 ArrayRef<int> Mask; 3468 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3469 Mask = SVI->getShuffleMask(); 3470 else 3471 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3472 SDLoc DL = getCurSDLoc(); 3473 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3474 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3475 EVT SrcVT = Src1.getValueType(); 3476 3477 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3478 VT.isScalableVector()) { 3479 // Canonical splat form of first element of first input vector. 3480 SDValue FirstElt = 3481 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3482 DAG.getVectorIdxConstant(0, DL)); 3483 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3484 return; 3485 } 3486 3487 // For now, we only handle splats for scalable vectors. 3488 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3489 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3490 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3491 3492 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3493 unsigned MaskNumElts = Mask.size(); 3494 3495 if (SrcNumElts == MaskNumElts) { 3496 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3497 return; 3498 } 3499 3500 // Normalize the shuffle vector since mask and vector length don't match. 3501 if (SrcNumElts < MaskNumElts) { 3502 // Mask is longer than the source vectors. We can use concatenate vector to 3503 // make the mask and vectors lengths match. 3504 3505 if (MaskNumElts % SrcNumElts == 0) { 3506 // Mask length is a multiple of the source vector length. 3507 // Check if the shuffle is some kind of concatenation of the input 3508 // vectors. 3509 unsigned NumConcat = MaskNumElts / SrcNumElts; 3510 bool IsConcat = true; 3511 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3512 for (unsigned i = 0; i != MaskNumElts; ++i) { 3513 int Idx = Mask[i]; 3514 if (Idx < 0) 3515 continue; 3516 // Ensure the indices in each SrcVT sized piece are sequential and that 3517 // the same source is used for the whole piece. 3518 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3519 (ConcatSrcs[i / SrcNumElts] >= 0 && 3520 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3521 IsConcat = false; 3522 break; 3523 } 3524 // Remember which source this index came from. 3525 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3526 } 3527 3528 // The shuffle is concatenating multiple vectors together. Just emit 3529 // a CONCAT_VECTORS operation. 3530 if (IsConcat) { 3531 SmallVector<SDValue, 8> ConcatOps; 3532 for (auto Src : ConcatSrcs) { 3533 if (Src < 0) 3534 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3535 else if (Src == 0) 3536 ConcatOps.push_back(Src1); 3537 else 3538 ConcatOps.push_back(Src2); 3539 } 3540 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3541 return; 3542 } 3543 } 3544 3545 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3546 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3547 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3548 PaddedMaskNumElts); 3549 3550 // Pad both vectors with undefs to make them the same length as the mask. 3551 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3552 3553 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3554 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3555 MOps1[0] = Src1; 3556 MOps2[0] = Src2; 3557 3558 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3559 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3560 3561 // Readjust mask for new input vector length. 3562 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3563 for (unsigned i = 0; i != MaskNumElts; ++i) { 3564 int Idx = Mask[i]; 3565 if (Idx >= (int)SrcNumElts) 3566 Idx -= SrcNumElts - PaddedMaskNumElts; 3567 MappedOps[i] = Idx; 3568 } 3569 3570 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3571 3572 // If the concatenated vector was padded, extract a subvector with the 3573 // correct number of elements. 3574 if (MaskNumElts != PaddedMaskNumElts) 3575 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3576 DAG.getVectorIdxConstant(0, DL)); 3577 3578 setValue(&I, Result); 3579 return; 3580 } 3581 3582 if (SrcNumElts > MaskNumElts) { 3583 // Analyze the access pattern of the vector to see if we can extract 3584 // two subvectors and do the shuffle. 3585 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3586 bool CanExtract = true; 3587 for (int Idx : Mask) { 3588 unsigned Input = 0; 3589 if (Idx < 0) 3590 continue; 3591 3592 if (Idx >= (int)SrcNumElts) { 3593 Input = 1; 3594 Idx -= SrcNumElts; 3595 } 3596 3597 // If all the indices come from the same MaskNumElts sized portion of 3598 // the sources we can use extract. Also make sure the extract wouldn't 3599 // extract past the end of the source. 3600 int NewStartIdx = alignDown(Idx, MaskNumElts); 3601 if (NewStartIdx + MaskNumElts > SrcNumElts || 3602 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3603 CanExtract = false; 3604 // Make sure we always update StartIdx as we use it to track if all 3605 // elements are undef. 3606 StartIdx[Input] = NewStartIdx; 3607 } 3608 3609 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3610 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3611 return; 3612 } 3613 if (CanExtract) { 3614 // Extract appropriate subvector and generate a vector shuffle 3615 for (unsigned Input = 0; Input < 2; ++Input) { 3616 SDValue &Src = Input == 0 ? Src1 : Src2; 3617 if (StartIdx[Input] < 0) 3618 Src = DAG.getUNDEF(VT); 3619 else { 3620 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3621 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3622 } 3623 } 3624 3625 // Calculate new mask. 3626 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3627 for (int &Idx : MappedOps) { 3628 if (Idx >= (int)SrcNumElts) 3629 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3630 else if (Idx >= 0) 3631 Idx -= StartIdx[0]; 3632 } 3633 3634 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3635 return; 3636 } 3637 } 3638 3639 // We can't use either concat vectors or extract subvectors so fall back to 3640 // replacing the shuffle with extract and build vector. 3641 // to insert and build vector. 3642 EVT EltVT = VT.getVectorElementType(); 3643 SmallVector<SDValue,8> Ops; 3644 for (int Idx : Mask) { 3645 SDValue Res; 3646 3647 if (Idx < 0) { 3648 Res = DAG.getUNDEF(EltVT); 3649 } else { 3650 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3651 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3652 3653 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3654 DAG.getVectorIdxConstant(Idx, DL)); 3655 } 3656 3657 Ops.push_back(Res); 3658 } 3659 3660 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3661 } 3662 3663 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3664 ArrayRef<unsigned> Indices; 3665 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3666 Indices = IV->getIndices(); 3667 else 3668 Indices = cast<ConstantExpr>(&I)->getIndices(); 3669 3670 const Value *Op0 = I.getOperand(0); 3671 const Value *Op1 = I.getOperand(1); 3672 Type *AggTy = I.getType(); 3673 Type *ValTy = Op1->getType(); 3674 bool IntoUndef = isa<UndefValue>(Op0); 3675 bool FromUndef = isa<UndefValue>(Op1); 3676 3677 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3678 3679 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3680 SmallVector<EVT, 4> AggValueVTs; 3681 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3682 SmallVector<EVT, 4> ValValueVTs; 3683 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3684 3685 unsigned NumAggValues = AggValueVTs.size(); 3686 unsigned NumValValues = ValValueVTs.size(); 3687 SmallVector<SDValue, 4> Values(NumAggValues); 3688 3689 // Ignore an insertvalue that produces an empty object 3690 if (!NumAggValues) { 3691 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3692 return; 3693 } 3694 3695 SDValue Agg = getValue(Op0); 3696 unsigned i = 0; 3697 // Copy the beginning value(s) from the original aggregate. 3698 for (; i != LinearIndex; ++i) 3699 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3700 SDValue(Agg.getNode(), Agg.getResNo() + i); 3701 // Copy values from the inserted value(s). 3702 if (NumValValues) { 3703 SDValue Val = getValue(Op1); 3704 for (; i != LinearIndex + NumValValues; ++i) 3705 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3706 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3707 } 3708 // Copy remaining value(s) from the original aggregate. 3709 for (; i != NumAggValues; ++i) 3710 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3711 SDValue(Agg.getNode(), Agg.getResNo() + i); 3712 3713 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3714 DAG.getVTList(AggValueVTs), Values)); 3715 } 3716 3717 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3718 ArrayRef<unsigned> Indices; 3719 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3720 Indices = EV->getIndices(); 3721 else 3722 Indices = cast<ConstantExpr>(&I)->getIndices(); 3723 3724 const Value *Op0 = I.getOperand(0); 3725 Type *AggTy = Op0->getType(); 3726 Type *ValTy = I.getType(); 3727 bool OutOfUndef = isa<UndefValue>(Op0); 3728 3729 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3730 3731 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3732 SmallVector<EVT, 4> ValValueVTs; 3733 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3734 3735 unsigned NumValValues = ValValueVTs.size(); 3736 3737 // Ignore a extractvalue that produces an empty object 3738 if (!NumValValues) { 3739 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3740 return; 3741 } 3742 3743 SmallVector<SDValue, 4> Values(NumValValues); 3744 3745 SDValue Agg = getValue(Op0); 3746 // Copy out the selected value(s). 3747 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3748 Values[i - LinearIndex] = 3749 OutOfUndef ? 3750 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3751 SDValue(Agg.getNode(), Agg.getResNo() + i); 3752 3753 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3754 DAG.getVTList(ValValueVTs), Values)); 3755 } 3756 3757 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3758 Value *Op0 = I.getOperand(0); 3759 // Note that the pointer operand may be a vector of pointers. Take the scalar 3760 // element which holds a pointer. 3761 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3762 SDValue N = getValue(Op0); 3763 SDLoc dl = getCurSDLoc(); 3764 auto &TLI = DAG.getTargetLoweringInfo(); 3765 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 3766 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 3767 3768 // Normalize Vector GEP - all scalar operands should be converted to the 3769 // splat vector. 3770 bool IsVectorGEP = I.getType()->isVectorTy(); 3771 ElementCount VectorElementCount = 3772 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3773 : ElementCount(0, false); 3774 3775 if (IsVectorGEP && !N.getValueType().isVector()) { 3776 LLVMContext &Context = *DAG.getContext(); 3777 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3778 if (VectorElementCount.Scalable) 3779 N = DAG.getSplatVector(VT, dl, N); 3780 else 3781 N = DAG.getSplatBuildVector(VT, dl, N); 3782 } 3783 3784 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3785 GTI != E; ++GTI) { 3786 const Value *Idx = GTI.getOperand(); 3787 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3788 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3789 if (Field) { 3790 // N = N + Offset 3791 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3792 3793 // In an inbounds GEP with an offset that is nonnegative even when 3794 // interpreted as signed, assume there is no unsigned overflow. 3795 SDNodeFlags Flags; 3796 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3797 Flags.setNoUnsignedWrap(true); 3798 3799 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3800 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3801 } 3802 } else { 3803 // IdxSize is the width of the arithmetic according to IR semantics. 3804 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3805 // (and fix up the result later). 3806 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3807 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3808 TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType()); 3809 // We intentionally mask away the high bits here; ElementSize may not 3810 // fit in IdxTy. 3811 APInt ElementMul(IdxSize, ElementSize.getKnownMinSize()); 3812 bool ElementScalable = ElementSize.isScalable(); 3813 3814 // If this is a scalar constant or a splat vector of constants, 3815 // handle it quickly. 3816 const auto *C = dyn_cast<Constant>(Idx); 3817 if (C && isa<VectorType>(C->getType())) 3818 C = C->getSplatValue(); 3819 3820 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 3821 if (CI && CI->isZero()) 3822 continue; 3823 if (CI && !ElementScalable) { 3824 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 3825 LLVMContext &Context = *DAG.getContext(); 3826 SDValue OffsVal; 3827 if (IsVectorGEP) 3828 OffsVal = DAG.getConstant( 3829 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 3830 else 3831 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 3832 3833 // In an inbounds GEP with an offset that is nonnegative even when 3834 // interpreted as signed, assume there is no unsigned overflow. 3835 SDNodeFlags Flags; 3836 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3837 Flags.setNoUnsignedWrap(true); 3838 3839 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3840 3841 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3842 continue; 3843 } 3844 3845 // N = N + Idx * ElementMul; 3846 SDValue IdxN = getValue(Idx); 3847 3848 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 3849 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 3850 VectorElementCount); 3851 if (VectorElementCount.Scalable) 3852 IdxN = DAG.getSplatVector(VT, dl, IdxN); 3853 else 3854 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3855 } 3856 3857 // If the index is smaller or larger than intptr_t, truncate or extend 3858 // it. 3859 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3860 3861 if (ElementScalable) { 3862 EVT VScaleTy = N.getValueType().getScalarType(); 3863 SDValue VScale = DAG.getNode( 3864 ISD::VSCALE, dl, VScaleTy, 3865 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 3866 if (IsVectorGEP) 3867 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 3868 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 3869 } else { 3870 // If this is a multiply by a power of two, turn it into a shl 3871 // immediately. This is a very common case. 3872 if (ElementMul != 1) { 3873 if (ElementMul.isPowerOf2()) { 3874 unsigned Amt = ElementMul.logBase2(); 3875 IdxN = DAG.getNode(ISD::SHL, dl, 3876 N.getValueType(), IdxN, 3877 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3878 } else { 3879 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 3880 IdxN.getValueType()); 3881 IdxN = DAG.getNode(ISD::MUL, dl, 3882 N.getValueType(), IdxN, Scale); 3883 } 3884 } 3885 } 3886 3887 N = DAG.getNode(ISD::ADD, dl, 3888 N.getValueType(), N, IdxN); 3889 } 3890 } 3891 3892 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 3893 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 3894 3895 setValue(&I, N); 3896 } 3897 3898 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3899 // If this is a fixed sized alloca in the entry block of the function, 3900 // allocate it statically on the stack. 3901 if (FuncInfo.StaticAllocaMap.count(&I)) 3902 return; // getValue will auto-populate this. 3903 3904 SDLoc dl = getCurSDLoc(); 3905 Type *Ty = I.getAllocatedType(); 3906 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3907 auto &DL = DAG.getDataLayout(); 3908 uint64_t TySize = DL.getTypeAllocSize(Ty); 3909 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 3910 3911 SDValue AllocSize = getValue(I.getArraySize()); 3912 3913 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3914 if (AllocSize.getValueType() != IntPtr) 3915 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3916 3917 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3918 AllocSize, 3919 DAG.getConstant(TySize, dl, IntPtr)); 3920 3921 // Handle alignment. If the requested alignment is less than or equal to 3922 // the stack alignment, ignore it. If the size is greater than or equal to 3923 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3924 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 3925 if (*Alignment <= StackAlign) 3926 Alignment = None; 3927 3928 const uint64_t StackAlignMask = StackAlign.value() - 1U; 3929 // Round the size of the allocation up to the stack alignment size 3930 // by add SA-1 to the size. This doesn't overflow because we're computing 3931 // an address inside an alloca. 3932 SDNodeFlags Flags; 3933 Flags.setNoUnsignedWrap(true); 3934 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 3935 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 3936 3937 // Mask out the low bits for alignment purposes. 3938 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 3939 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 3940 3941 SDValue Ops[] = { 3942 getRoot(), AllocSize, 3943 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 3944 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 3945 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 3946 setValue(&I, DSA); 3947 DAG.setRoot(DSA.getValue(1)); 3948 3949 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 3950 } 3951 3952 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 3953 if (I.isAtomic()) 3954 return visitAtomicLoad(I); 3955 3956 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3957 const Value *SV = I.getOperand(0); 3958 if (TLI.supportSwiftError()) { 3959 // Swifterror values can come from either a function parameter with 3960 // swifterror attribute or an alloca with swifterror attribute. 3961 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 3962 if (Arg->hasSwiftErrorAttr()) 3963 return visitLoadFromSwiftError(I); 3964 } 3965 3966 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 3967 if (Alloca->isSwiftError()) 3968 return visitLoadFromSwiftError(I); 3969 } 3970 } 3971 3972 SDValue Ptr = getValue(SV); 3973 3974 Type *Ty = I.getType(); 3975 Align Alignment = I.getAlign(); 3976 3977 AAMDNodes AAInfo; 3978 I.getAAMetadata(AAInfo); 3979 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 3980 3981 SmallVector<EVT, 4> ValueVTs, MemVTs; 3982 SmallVector<uint64_t, 4> Offsets; 3983 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 3984 unsigned NumValues = ValueVTs.size(); 3985 if (NumValues == 0) 3986 return; 3987 3988 bool isVolatile = I.isVolatile(); 3989 3990 SDValue Root; 3991 bool ConstantMemory = false; 3992 if (isVolatile) 3993 // Serialize volatile loads with other side effects. 3994 Root = getRoot(); 3995 else if (NumValues > MaxParallelChains) 3996 Root = getMemoryRoot(); 3997 else if (AA && 3998 AA->pointsToConstantMemory(MemoryLocation( 3999 SV, 4000 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4001 AAInfo))) { 4002 // Do not serialize (non-volatile) loads of constant memory with anything. 4003 Root = DAG.getEntryNode(); 4004 ConstantMemory = true; 4005 } else { 4006 // Do not serialize non-volatile loads against each other. 4007 Root = DAG.getRoot(); 4008 } 4009 4010 SDLoc dl = getCurSDLoc(); 4011 4012 if (isVolatile) 4013 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4014 4015 // An aggregate load cannot wrap around the address space, so offsets to its 4016 // parts don't wrap either. 4017 SDNodeFlags Flags; 4018 Flags.setNoUnsignedWrap(true); 4019 4020 SmallVector<SDValue, 4> Values(NumValues); 4021 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4022 EVT PtrVT = Ptr.getValueType(); 4023 4024 MachineMemOperand::Flags MMOFlags 4025 = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4026 4027 unsigned ChainI = 0; 4028 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4029 // Serializing loads here may result in excessive register pressure, and 4030 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4031 // could recover a bit by hoisting nodes upward in the chain by recognizing 4032 // they are side-effect free or do not alias. The optimizer should really 4033 // avoid this case by converting large object/array copies to llvm.memcpy 4034 // (MaxParallelChains should always remain as failsafe). 4035 if (ChainI == MaxParallelChains) { 4036 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4037 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4038 makeArrayRef(Chains.data(), ChainI)); 4039 Root = Chain; 4040 ChainI = 0; 4041 } 4042 SDValue A = DAG.getNode(ISD::ADD, dl, 4043 PtrVT, Ptr, 4044 DAG.getConstant(Offsets[i], dl, PtrVT), 4045 Flags); 4046 4047 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4048 MachinePointerInfo(SV, Offsets[i]), Alignment, 4049 MMOFlags, AAInfo, Ranges); 4050 Chains[ChainI] = L.getValue(1); 4051 4052 if (MemVTs[i] != ValueVTs[i]) 4053 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4054 4055 Values[i] = L; 4056 } 4057 4058 if (!ConstantMemory) { 4059 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4060 makeArrayRef(Chains.data(), ChainI)); 4061 if (isVolatile) 4062 DAG.setRoot(Chain); 4063 else 4064 PendingLoads.push_back(Chain); 4065 } 4066 4067 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4068 DAG.getVTList(ValueVTs), Values)); 4069 } 4070 4071 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4072 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4073 "call visitStoreToSwiftError when backend supports swifterror"); 4074 4075 SmallVector<EVT, 4> ValueVTs; 4076 SmallVector<uint64_t, 4> Offsets; 4077 const Value *SrcV = I.getOperand(0); 4078 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4079 SrcV->getType(), ValueVTs, &Offsets); 4080 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4081 "expect a single EVT for swifterror"); 4082 4083 SDValue Src = getValue(SrcV); 4084 // Create a virtual register, then update the virtual register. 4085 Register VReg = 4086 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4087 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4088 // Chain can be getRoot or getControlRoot. 4089 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4090 SDValue(Src.getNode(), Src.getResNo())); 4091 DAG.setRoot(CopyNode); 4092 } 4093 4094 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4095 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4096 "call visitLoadFromSwiftError when backend supports swifterror"); 4097 4098 assert(!I.isVolatile() && 4099 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4100 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4101 "Support volatile, non temporal, invariant for load_from_swift_error"); 4102 4103 const Value *SV = I.getOperand(0); 4104 Type *Ty = I.getType(); 4105 AAMDNodes AAInfo; 4106 I.getAAMetadata(AAInfo); 4107 assert( 4108 (!AA || 4109 !AA->pointsToConstantMemory(MemoryLocation( 4110 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4111 AAInfo))) && 4112 "load_from_swift_error should not be constant memory"); 4113 4114 SmallVector<EVT, 4> ValueVTs; 4115 SmallVector<uint64_t, 4> Offsets; 4116 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4117 ValueVTs, &Offsets); 4118 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4119 "expect a single EVT for swifterror"); 4120 4121 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4122 SDValue L = DAG.getCopyFromReg( 4123 getRoot(), getCurSDLoc(), 4124 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4125 4126 setValue(&I, L); 4127 } 4128 4129 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4130 if (I.isAtomic()) 4131 return visitAtomicStore(I); 4132 4133 const Value *SrcV = I.getOperand(0); 4134 const Value *PtrV = I.getOperand(1); 4135 4136 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4137 if (TLI.supportSwiftError()) { 4138 // Swifterror values can come from either a function parameter with 4139 // swifterror attribute or an alloca with swifterror attribute. 4140 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4141 if (Arg->hasSwiftErrorAttr()) 4142 return visitStoreToSwiftError(I); 4143 } 4144 4145 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4146 if (Alloca->isSwiftError()) 4147 return visitStoreToSwiftError(I); 4148 } 4149 } 4150 4151 SmallVector<EVT, 4> ValueVTs, MemVTs; 4152 SmallVector<uint64_t, 4> Offsets; 4153 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4154 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4155 unsigned NumValues = ValueVTs.size(); 4156 if (NumValues == 0) 4157 return; 4158 4159 // Get the lowered operands. Note that we do this after 4160 // checking if NumResults is zero, because with zero results 4161 // the operands won't have values in the map. 4162 SDValue Src = getValue(SrcV); 4163 SDValue Ptr = getValue(PtrV); 4164 4165 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4166 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4167 SDLoc dl = getCurSDLoc(); 4168 Align Alignment = I.getAlign(); 4169 AAMDNodes AAInfo; 4170 I.getAAMetadata(AAInfo); 4171 4172 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4173 4174 // An aggregate load cannot wrap around the address space, so offsets to its 4175 // parts don't wrap either. 4176 SDNodeFlags Flags; 4177 Flags.setNoUnsignedWrap(true); 4178 4179 unsigned ChainI = 0; 4180 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4181 // See visitLoad comments. 4182 if (ChainI == MaxParallelChains) { 4183 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4184 makeArrayRef(Chains.data(), ChainI)); 4185 Root = Chain; 4186 ChainI = 0; 4187 } 4188 SDValue Add = DAG.getMemBasePlusOffset(Ptr, Offsets[i], dl, Flags); 4189 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4190 if (MemVTs[i] != ValueVTs[i]) 4191 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4192 SDValue St = 4193 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4194 Alignment, MMOFlags, AAInfo); 4195 Chains[ChainI] = St; 4196 } 4197 4198 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4199 makeArrayRef(Chains.data(), ChainI)); 4200 DAG.setRoot(StoreNode); 4201 } 4202 4203 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4204 bool IsCompressing) { 4205 SDLoc sdl = getCurSDLoc(); 4206 4207 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4208 MaybeAlign &Alignment) { 4209 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4210 Src0 = I.getArgOperand(0); 4211 Ptr = I.getArgOperand(1); 4212 Alignment = 4213 MaybeAlign(cast<ConstantInt>(I.getArgOperand(2))->getZExtValue()); 4214 Mask = I.getArgOperand(3); 4215 }; 4216 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4217 MaybeAlign &Alignment) { 4218 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4219 Src0 = I.getArgOperand(0); 4220 Ptr = I.getArgOperand(1); 4221 Mask = I.getArgOperand(2); 4222 Alignment = None; 4223 }; 4224 4225 Value *PtrOperand, *MaskOperand, *Src0Operand; 4226 MaybeAlign Alignment; 4227 if (IsCompressing) 4228 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4229 else 4230 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4231 4232 SDValue Ptr = getValue(PtrOperand); 4233 SDValue Src0 = getValue(Src0Operand); 4234 SDValue Mask = getValue(MaskOperand); 4235 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4236 4237 EVT VT = Src0.getValueType(); 4238 if (!Alignment) 4239 Alignment = DAG.getEVTAlign(VT); 4240 4241 AAMDNodes AAInfo; 4242 I.getAAMetadata(AAInfo); 4243 4244 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4245 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4246 // TODO: Make MachineMemOperands aware of scalable 4247 // vectors. 4248 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo); 4249 SDValue StoreNode = 4250 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4251 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4252 DAG.setRoot(StoreNode); 4253 setValue(&I, StoreNode); 4254 } 4255 4256 // Get a uniform base for the Gather/Scatter intrinsic. 4257 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4258 // We try to represent it as a base pointer + vector of indices. 4259 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4260 // The first operand of the GEP may be a single pointer or a vector of pointers 4261 // Example: 4262 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4263 // or 4264 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4265 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4266 // 4267 // When the first GEP operand is a single pointer - it is the uniform base we 4268 // are looking for. If first operand of the GEP is a splat vector - we 4269 // extract the splat value and use it as a uniform base. 4270 // In all other cases the function returns 'false'. 4271 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4272 ISD::MemIndexType &IndexType, SDValue &Scale, 4273 SelectionDAGBuilder *SDB, const BasicBlock *CurBB) { 4274 SelectionDAG& DAG = SDB->DAG; 4275 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4276 const DataLayout &DL = DAG.getDataLayout(); 4277 4278 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 4279 4280 // Handle splat constant pointer. 4281 if (auto *C = dyn_cast<Constant>(Ptr)) { 4282 C = C->getSplatValue(); 4283 if (!C) 4284 return false; 4285 4286 Base = SDB->getValue(C); 4287 4288 unsigned NumElts = cast<VectorType>(Ptr->getType())->getNumElements(); 4289 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4290 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4291 IndexType = ISD::SIGNED_SCALED; 4292 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4293 return true; 4294 } 4295 4296 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4297 if (!GEP || GEP->getParent() != CurBB) 4298 return false; 4299 4300 if (GEP->getNumOperands() != 2) 4301 return false; 4302 4303 const Value *BasePtr = GEP->getPointerOperand(); 4304 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4305 4306 // Make sure the base is scalar and the index is a vector. 4307 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4308 return false; 4309 4310 Base = SDB->getValue(BasePtr); 4311 Index = SDB->getValue(IndexVal); 4312 IndexType = ISD::SIGNED_SCALED; 4313 Scale = DAG.getTargetConstant( 4314 DL.getTypeAllocSize(GEP->getResultElementType()), 4315 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4316 return true; 4317 } 4318 4319 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4320 SDLoc sdl = getCurSDLoc(); 4321 4322 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4323 const Value *Ptr = I.getArgOperand(1); 4324 SDValue Src0 = getValue(I.getArgOperand(0)); 4325 SDValue Mask = getValue(I.getArgOperand(3)); 4326 EVT VT = Src0.getValueType(); 4327 MaybeAlign Alignment(cast<ConstantInt>(I.getArgOperand(2))->getZExtValue()); 4328 if (!Alignment) 4329 Alignment = DAG.getEVTAlign(VT); 4330 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4331 4332 AAMDNodes AAInfo; 4333 I.getAAMetadata(AAInfo); 4334 4335 SDValue Base; 4336 SDValue Index; 4337 ISD::MemIndexType IndexType; 4338 SDValue Scale; 4339 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4340 I.getParent()); 4341 4342 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4343 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4344 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4345 // TODO: Make MachineMemOperands aware of scalable 4346 // vectors. 4347 MemoryLocation::UnknownSize, *Alignment, AAInfo); 4348 if (!UniformBase) { 4349 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4350 Index = getValue(Ptr); 4351 IndexType = ISD::SIGNED_SCALED; 4352 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4353 } 4354 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4355 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4356 Ops, MMO, IndexType); 4357 DAG.setRoot(Scatter); 4358 setValue(&I, Scatter); 4359 } 4360 4361 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4362 SDLoc sdl = getCurSDLoc(); 4363 4364 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4365 MaybeAlign &Alignment) { 4366 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4367 Ptr = I.getArgOperand(0); 4368 Alignment = 4369 MaybeAlign(cast<ConstantInt>(I.getArgOperand(1))->getZExtValue()); 4370 Mask = I.getArgOperand(2); 4371 Src0 = I.getArgOperand(3); 4372 }; 4373 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4374 MaybeAlign &Alignment) { 4375 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4376 Ptr = I.getArgOperand(0); 4377 Alignment = None; 4378 Mask = I.getArgOperand(1); 4379 Src0 = I.getArgOperand(2); 4380 }; 4381 4382 Value *PtrOperand, *MaskOperand, *Src0Operand; 4383 MaybeAlign Alignment; 4384 if (IsExpanding) 4385 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4386 else 4387 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4388 4389 SDValue Ptr = getValue(PtrOperand); 4390 SDValue Src0 = getValue(Src0Operand); 4391 SDValue Mask = getValue(MaskOperand); 4392 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4393 4394 EVT VT = Src0.getValueType(); 4395 if (!Alignment) 4396 Alignment = DAG.getEVTAlign(VT); 4397 4398 AAMDNodes AAInfo; 4399 I.getAAMetadata(AAInfo); 4400 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4401 4402 // Do not serialize masked loads of constant memory with anything. 4403 MemoryLocation ML; 4404 if (VT.isScalableVector()) 4405 ML = MemoryLocation(PtrOperand); 4406 else 4407 ML = MemoryLocation(PtrOperand, LocationSize::precise( 4408 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4409 AAInfo); 4410 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4411 4412 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4413 4414 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4415 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4416 // TODO: Make MachineMemOperands aware of scalable 4417 // vectors. 4418 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges); 4419 4420 SDValue Load = 4421 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4422 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4423 if (AddToChain) 4424 PendingLoads.push_back(Load.getValue(1)); 4425 setValue(&I, Load); 4426 } 4427 4428 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4429 SDLoc sdl = getCurSDLoc(); 4430 4431 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4432 const Value *Ptr = I.getArgOperand(0); 4433 SDValue Src0 = getValue(I.getArgOperand(3)); 4434 SDValue Mask = getValue(I.getArgOperand(2)); 4435 4436 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4437 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4438 MaybeAlign Alignment(cast<ConstantInt>(I.getArgOperand(1))->getZExtValue()); 4439 if (!Alignment) 4440 Alignment = DAG.getEVTAlign(VT); 4441 4442 AAMDNodes AAInfo; 4443 I.getAAMetadata(AAInfo); 4444 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4445 4446 SDValue Root = DAG.getRoot(); 4447 SDValue Base; 4448 SDValue Index; 4449 ISD::MemIndexType IndexType; 4450 SDValue Scale; 4451 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4452 I.getParent()); 4453 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4454 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4455 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4456 // TODO: Make MachineMemOperands aware of scalable 4457 // vectors. 4458 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 4459 4460 if (!UniformBase) { 4461 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4462 Index = getValue(Ptr); 4463 IndexType = ISD::SIGNED_SCALED; 4464 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4465 } 4466 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4467 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4468 Ops, MMO, IndexType); 4469 4470 PendingLoads.push_back(Gather.getValue(1)); 4471 setValue(&I, Gather); 4472 } 4473 4474 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4475 SDLoc dl = getCurSDLoc(); 4476 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4477 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4478 SyncScope::ID SSID = I.getSyncScopeID(); 4479 4480 SDValue InChain = getRoot(); 4481 4482 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4483 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4484 4485 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4486 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4487 4488 MachineFunction &MF = DAG.getMachineFunction(); 4489 MachineMemOperand *MMO = MF.getMachineMemOperand( 4490 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4491 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4492 FailureOrdering); 4493 4494 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4495 dl, MemVT, VTs, InChain, 4496 getValue(I.getPointerOperand()), 4497 getValue(I.getCompareOperand()), 4498 getValue(I.getNewValOperand()), MMO); 4499 4500 SDValue OutChain = L.getValue(2); 4501 4502 setValue(&I, L); 4503 DAG.setRoot(OutChain); 4504 } 4505 4506 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4507 SDLoc dl = getCurSDLoc(); 4508 ISD::NodeType NT; 4509 switch (I.getOperation()) { 4510 default: llvm_unreachable("Unknown atomicrmw operation"); 4511 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4512 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4513 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4514 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4515 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4516 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4517 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4518 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4519 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4520 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4521 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4522 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4523 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4524 } 4525 AtomicOrdering Ordering = I.getOrdering(); 4526 SyncScope::ID SSID = I.getSyncScopeID(); 4527 4528 SDValue InChain = getRoot(); 4529 4530 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4531 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4532 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4533 4534 MachineFunction &MF = DAG.getMachineFunction(); 4535 MachineMemOperand *MMO = MF.getMachineMemOperand( 4536 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4537 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4538 4539 SDValue L = 4540 DAG.getAtomic(NT, dl, MemVT, InChain, 4541 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4542 MMO); 4543 4544 SDValue OutChain = L.getValue(1); 4545 4546 setValue(&I, L); 4547 DAG.setRoot(OutChain); 4548 } 4549 4550 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4551 SDLoc dl = getCurSDLoc(); 4552 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4553 SDValue Ops[3]; 4554 Ops[0] = getRoot(); 4555 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4556 TLI.getFenceOperandTy(DAG.getDataLayout())); 4557 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4558 TLI.getFenceOperandTy(DAG.getDataLayout())); 4559 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4560 } 4561 4562 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4563 SDLoc dl = getCurSDLoc(); 4564 AtomicOrdering Order = I.getOrdering(); 4565 SyncScope::ID SSID = I.getSyncScopeID(); 4566 4567 SDValue InChain = getRoot(); 4568 4569 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4570 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4571 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4572 4573 if (!TLI.supportsUnalignedAtomics() && 4574 I.getAlignment() < MemVT.getSizeInBits() / 8) 4575 report_fatal_error("Cannot generate unaligned atomic load"); 4576 4577 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4578 4579 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4580 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4581 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4582 4583 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4584 4585 SDValue Ptr = getValue(I.getPointerOperand()); 4586 4587 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4588 // TODO: Once this is better exercised by tests, it should be merged with 4589 // the normal path for loads to prevent future divergence. 4590 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4591 if (MemVT != VT) 4592 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4593 4594 setValue(&I, L); 4595 SDValue OutChain = L.getValue(1); 4596 if (!I.isUnordered()) 4597 DAG.setRoot(OutChain); 4598 else 4599 PendingLoads.push_back(OutChain); 4600 return; 4601 } 4602 4603 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4604 Ptr, MMO); 4605 4606 SDValue OutChain = L.getValue(1); 4607 if (MemVT != VT) 4608 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4609 4610 setValue(&I, L); 4611 DAG.setRoot(OutChain); 4612 } 4613 4614 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4615 SDLoc dl = getCurSDLoc(); 4616 4617 AtomicOrdering Ordering = I.getOrdering(); 4618 SyncScope::ID SSID = I.getSyncScopeID(); 4619 4620 SDValue InChain = getRoot(); 4621 4622 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4623 EVT MemVT = 4624 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4625 4626 if (I.getAlignment() < MemVT.getSizeInBits() / 8) 4627 report_fatal_error("Cannot generate unaligned atomic store"); 4628 4629 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4630 4631 MachineFunction &MF = DAG.getMachineFunction(); 4632 MachineMemOperand *MMO = MF.getMachineMemOperand( 4633 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4634 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4635 4636 SDValue Val = getValue(I.getValueOperand()); 4637 if (Val.getValueType() != MemVT) 4638 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4639 SDValue Ptr = getValue(I.getPointerOperand()); 4640 4641 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4642 // TODO: Once this is better exercised by tests, it should be merged with 4643 // the normal path for stores to prevent future divergence. 4644 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4645 DAG.setRoot(S); 4646 return; 4647 } 4648 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4649 Ptr, Val, MMO); 4650 4651 4652 DAG.setRoot(OutChain); 4653 } 4654 4655 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4656 /// node. 4657 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4658 unsigned Intrinsic) { 4659 // Ignore the callsite's attributes. A specific call site may be marked with 4660 // readnone, but the lowering code will expect the chain based on the 4661 // definition. 4662 const Function *F = I.getCalledFunction(); 4663 bool HasChain = !F->doesNotAccessMemory(); 4664 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4665 4666 // Build the operand list. 4667 SmallVector<SDValue, 8> Ops; 4668 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4669 if (OnlyLoad) { 4670 // We don't need to serialize loads against other loads. 4671 Ops.push_back(DAG.getRoot()); 4672 } else { 4673 Ops.push_back(getRoot()); 4674 } 4675 } 4676 4677 // Info is set by getTgtMemInstrinsic 4678 TargetLowering::IntrinsicInfo Info; 4679 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4680 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4681 DAG.getMachineFunction(), 4682 Intrinsic); 4683 4684 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4685 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4686 Info.opc == ISD::INTRINSIC_W_CHAIN) 4687 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4688 TLI.getPointerTy(DAG.getDataLayout()))); 4689 4690 // Add all operands of the call to the operand list. 4691 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4692 const Value *Arg = I.getArgOperand(i); 4693 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4694 Ops.push_back(getValue(Arg)); 4695 continue; 4696 } 4697 4698 // Use TargetConstant instead of a regular constant for immarg. 4699 EVT VT = TLI.getValueType(*DL, Arg->getType(), true); 4700 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4701 assert(CI->getBitWidth() <= 64 && 4702 "large intrinsic immediates not handled"); 4703 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4704 } else { 4705 Ops.push_back( 4706 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4707 } 4708 } 4709 4710 SmallVector<EVT, 4> ValueVTs; 4711 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4712 4713 if (HasChain) 4714 ValueVTs.push_back(MVT::Other); 4715 4716 SDVTList VTs = DAG.getVTList(ValueVTs); 4717 4718 // Create the node. 4719 SDValue Result; 4720 if (IsTgtIntrinsic) { 4721 // This is target intrinsic that touches memory 4722 AAMDNodes AAInfo; 4723 I.getAAMetadata(AAInfo); 4724 Result = 4725 DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT, 4726 MachinePointerInfo(Info.ptrVal, Info.offset), 4727 Info.align, Info.flags, Info.size, AAInfo); 4728 } else if (!HasChain) { 4729 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4730 } else if (!I.getType()->isVoidTy()) { 4731 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4732 } else { 4733 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4734 } 4735 4736 if (HasChain) { 4737 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4738 if (OnlyLoad) 4739 PendingLoads.push_back(Chain); 4740 else 4741 DAG.setRoot(Chain); 4742 } 4743 4744 if (!I.getType()->isVoidTy()) { 4745 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4746 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4747 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4748 } else 4749 Result = lowerRangeToAssertZExt(DAG, I, Result); 4750 4751 MaybeAlign Alignment = I.getRetAlign(); 4752 if (!Alignment) 4753 Alignment = F->getAttributes().getRetAlignment(); 4754 // Insert `assertalign` node if there's an alignment. 4755 if (InsertAssertAlign && Alignment) { 4756 Result = 4757 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 4758 } 4759 4760 setValue(&I, Result); 4761 } 4762 } 4763 4764 /// GetSignificand - Get the significand and build it into a floating-point 4765 /// number with exponent of 1: 4766 /// 4767 /// Op = (Op & 0x007fffff) | 0x3f800000; 4768 /// 4769 /// where Op is the hexadecimal representation of floating point value. 4770 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4771 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4772 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4773 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4774 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4775 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4776 } 4777 4778 /// GetExponent - Get the exponent: 4779 /// 4780 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4781 /// 4782 /// where Op is the hexadecimal representation of floating point value. 4783 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4784 const TargetLowering &TLI, const SDLoc &dl) { 4785 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4786 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4787 SDValue t1 = DAG.getNode( 4788 ISD::SRL, dl, MVT::i32, t0, 4789 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4790 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4791 DAG.getConstant(127, dl, MVT::i32)); 4792 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4793 } 4794 4795 /// getF32Constant - Get 32-bit floating point constant. 4796 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4797 const SDLoc &dl) { 4798 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4799 MVT::f32); 4800 } 4801 4802 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4803 SelectionDAG &DAG) { 4804 // TODO: What fast-math-flags should be set on the floating-point nodes? 4805 4806 // IntegerPartOfX = ((int32_t)(t0); 4807 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4808 4809 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4810 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4811 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4812 4813 // IntegerPartOfX <<= 23; 4814 IntegerPartOfX = DAG.getNode( 4815 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4816 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4817 DAG.getDataLayout()))); 4818 4819 SDValue TwoToFractionalPartOfX; 4820 if (LimitFloatPrecision <= 6) { 4821 // For floating-point precision of 6: 4822 // 4823 // TwoToFractionalPartOfX = 4824 // 0.997535578f + 4825 // (0.735607626f + 0.252464424f * x) * x; 4826 // 4827 // error 0.0144103317, which is 6 bits 4828 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4829 getF32Constant(DAG, 0x3e814304, dl)); 4830 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4831 getF32Constant(DAG, 0x3f3c50c8, dl)); 4832 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4833 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4834 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4835 } else if (LimitFloatPrecision <= 12) { 4836 // For floating-point precision of 12: 4837 // 4838 // TwoToFractionalPartOfX = 4839 // 0.999892986f + 4840 // (0.696457318f + 4841 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4842 // 4843 // error 0.000107046256, which is 13 to 14 bits 4844 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4845 getF32Constant(DAG, 0x3da235e3, dl)); 4846 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4847 getF32Constant(DAG, 0x3e65b8f3, dl)); 4848 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4849 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4850 getF32Constant(DAG, 0x3f324b07, dl)); 4851 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4852 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4853 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4854 } else { // LimitFloatPrecision <= 18 4855 // For floating-point precision of 18: 4856 // 4857 // TwoToFractionalPartOfX = 4858 // 0.999999982f + 4859 // (0.693148872f + 4860 // (0.240227044f + 4861 // (0.554906021e-1f + 4862 // (0.961591928e-2f + 4863 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4864 // error 2.47208000*10^(-7), which is better than 18 bits 4865 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4866 getF32Constant(DAG, 0x3924b03e, dl)); 4867 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4868 getF32Constant(DAG, 0x3ab24b87, dl)); 4869 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4870 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4871 getF32Constant(DAG, 0x3c1d8c17, dl)); 4872 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4873 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4874 getF32Constant(DAG, 0x3d634a1d, dl)); 4875 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4876 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4877 getF32Constant(DAG, 0x3e75fe14, dl)); 4878 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4879 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4880 getF32Constant(DAG, 0x3f317234, dl)); 4881 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4882 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4883 getF32Constant(DAG, 0x3f800000, dl)); 4884 } 4885 4886 // Add the exponent into the result in integer domain. 4887 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4888 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4889 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4890 } 4891 4892 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4893 /// limited-precision mode. 4894 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4895 const TargetLowering &TLI) { 4896 if (Op.getValueType() == MVT::f32 && 4897 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4898 4899 // Put the exponent in the right bit position for later addition to the 4900 // final result: 4901 // 4902 // t0 = Op * log2(e) 4903 4904 // TODO: What fast-math-flags should be set here? 4905 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 4906 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 4907 return getLimitedPrecisionExp2(t0, dl, DAG); 4908 } 4909 4910 // No special expansion. 4911 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op); 4912 } 4913 4914 /// expandLog - Lower a log intrinsic. Handles the special sequences for 4915 /// limited-precision mode. 4916 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4917 const TargetLowering &TLI) { 4918 // TODO: What fast-math-flags should be set on the floating-point nodes? 4919 4920 if (Op.getValueType() == MVT::f32 && 4921 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4922 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4923 4924 // Scale the exponent by log(2). 4925 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4926 SDValue LogOfExponent = 4927 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4928 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 4929 4930 // Get the significand and build it into a floating-point number with 4931 // exponent of 1. 4932 SDValue X = GetSignificand(DAG, Op1, dl); 4933 4934 SDValue LogOfMantissa; 4935 if (LimitFloatPrecision <= 6) { 4936 // For floating-point precision of 6: 4937 // 4938 // LogofMantissa = 4939 // -1.1609546f + 4940 // (1.4034025f - 0.23903021f * x) * x; 4941 // 4942 // error 0.0034276066, which is better than 8 bits 4943 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4944 getF32Constant(DAG, 0xbe74c456, dl)); 4945 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4946 getF32Constant(DAG, 0x3fb3a2b1, dl)); 4947 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4948 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4949 getF32Constant(DAG, 0x3f949a29, dl)); 4950 } else if (LimitFloatPrecision <= 12) { 4951 // For floating-point precision of 12: 4952 // 4953 // LogOfMantissa = 4954 // -1.7417939f + 4955 // (2.8212026f + 4956 // (-1.4699568f + 4957 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 4958 // 4959 // error 0.000061011436, which is 14 bits 4960 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4961 getF32Constant(DAG, 0xbd67b6d6, dl)); 4962 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4963 getF32Constant(DAG, 0x3ee4f4b8, dl)); 4964 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4965 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4966 getF32Constant(DAG, 0x3fbc278b, dl)); 4967 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4968 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4969 getF32Constant(DAG, 0x40348e95, dl)); 4970 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4971 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4972 getF32Constant(DAG, 0x3fdef31a, dl)); 4973 } else { // LimitFloatPrecision <= 18 4974 // For floating-point precision of 18: 4975 // 4976 // LogOfMantissa = 4977 // -2.1072184f + 4978 // (4.2372794f + 4979 // (-3.7029485f + 4980 // (2.2781945f + 4981 // (-0.87823314f + 4982 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 4983 // 4984 // error 0.0000023660568, which is better than 18 bits 4985 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4986 getF32Constant(DAG, 0xbc91e5ac, dl)); 4987 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4988 getF32Constant(DAG, 0x3e4350aa, dl)); 4989 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4990 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4991 getF32Constant(DAG, 0x3f60d3e3, dl)); 4992 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4993 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4994 getF32Constant(DAG, 0x4011cdf0, dl)); 4995 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4996 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4997 getF32Constant(DAG, 0x406cfd1c, dl)); 4998 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4999 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5000 getF32Constant(DAG, 0x408797cb, dl)); 5001 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5002 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5003 getF32Constant(DAG, 0x4006dcab, dl)); 5004 } 5005 5006 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5007 } 5008 5009 // No special expansion. 5010 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op); 5011 } 5012 5013 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5014 /// limited-precision mode. 5015 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5016 const TargetLowering &TLI) { 5017 // TODO: What fast-math-flags should be set on the floating-point nodes? 5018 5019 if (Op.getValueType() == MVT::f32 && 5020 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5021 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5022 5023 // Get the exponent. 5024 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5025 5026 // Get the significand and build it into a floating-point number with 5027 // exponent of 1. 5028 SDValue X = GetSignificand(DAG, Op1, dl); 5029 5030 // Different possible minimax approximations of significand in 5031 // floating-point for various degrees of accuracy over [1,2]. 5032 SDValue Log2ofMantissa; 5033 if (LimitFloatPrecision <= 6) { 5034 // For floating-point precision of 6: 5035 // 5036 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5037 // 5038 // error 0.0049451742, which is more than 7 bits 5039 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5040 getF32Constant(DAG, 0xbeb08fe0, dl)); 5041 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5042 getF32Constant(DAG, 0x40019463, dl)); 5043 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5044 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5045 getF32Constant(DAG, 0x3fd6633d, dl)); 5046 } else if (LimitFloatPrecision <= 12) { 5047 // For floating-point precision of 12: 5048 // 5049 // Log2ofMantissa = 5050 // -2.51285454f + 5051 // (4.07009056f + 5052 // (-2.12067489f + 5053 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5054 // 5055 // error 0.0000876136000, which is better than 13 bits 5056 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5057 getF32Constant(DAG, 0xbda7262e, dl)); 5058 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5059 getF32Constant(DAG, 0x3f25280b, dl)); 5060 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5061 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5062 getF32Constant(DAG, 0x4007b923, dl)); 5063 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5064 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5065 getF32Constant(DAG, 0x40823e2f, dl)); 5066 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5067 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5068 getF32Constant(DAG, 0x4020d29c, dl)); 5069 } else { // LimitFloatPrecision <= 18 5070 // For floating-point precision of 18: 5071 // 5072 // Log2ofMantissa = 5073 // -3.0400495f + 5074 // (6.1129976f + 5075 // (-5.3420409f + 5076 // (3.2865683f + 5077 // (-1.2669343f + 5078 // (0.27515199f - 5079 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5080 // 5081 // error 0.0000018516, which is better than 18 bits 5082 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5083 getF32Constant(DAG, 0xbcd2769e, dl)); 5084 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5085 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5086 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5087 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5088 getF32Constant(DAG, 0x3fa22ae7, dl)); 5089 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5090 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5091 getF32Constant(DAG, 0x40525723, dl)); 5092 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5093 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5094 getF32Constant(DAG, 0x40aaf200, dl)); 5095 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5096 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5097 getF32Constant(DAG, 0x40c39dad, dl)); 5098 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5099 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5100 getF32Constant(DAG, 0x4042902c, dl)); 5101 } 5102 5103 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5104 } 5105 5106 // No special expansion. 5107 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op); 5108 } 5109 5110 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5111 /// limited-precision mode. 5112 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5113 const TargetLowering &TLI) { 5114 // TODO: What fast-math-flags should be set on the floating-point nodes? 5115 5116 if (Op.getValueType() == MVT::f32 && 5117 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5118 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5119 5120 // Scale the exponent by log10(2) [0.30102999f]. 5121 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5122 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5123 getF32Constant(DAG, 0x3e9a209a, dl)); 5124 5125 // Get the significand and build it into a floating-point number with 5126 // exponent of 1. 5127 SDValue X = GetSignificand(DAG, Op1, dl); 5128 5129 SDValue Log10ofMantissa; 5130 if (LimitFloatPrecision <= 6) { 5131 // For floating-point precision of 6: 5132 // 5133 // Log10ofMantissa = 5134 // -0.50419619f + 5135 // (0.60948995f - 0.10380950f * x) * x; 5136 // 5137 // error 0.0014886165, which is 6 bits 5138 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5139 getF32Constant(DAG, 0xbdd49a13, dl)); 5140 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5141 getF32Constant(DAG, 0x3f1c0789, dl)); 5142 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5143 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5144 getF32Constant(DAG, 0x3f011300, dl)); 5145 } else if (LimitFloatPrecision <= 12) { 5146 // For floating-point precision of 12: 5147 // 5148 // Log10ofMantissa = 5149 // -0.64831180f + 5150 // (0.91751397f + 5151 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5152 // 5153 // error 0.00019228036, which is better than 12 bits 5154 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5155 getF32Constant(DAG, 0x3d431f31, dl)); 5156 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5157 getF32Constant(DAG, 0x3ea21fb2, dl)); 5158 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5159 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5160 getF32Constant(DAG, 0x3f6ae232, dl)); 5161 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5162 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5163 getF32Constant(DAG, 0x3f25f7c3, dl)); 5164 } else { // LimitFloatPrecision <= 18 5165 // For floating-point precision of 18: 5166 // 5167 // Log10ofMantissa = 5168 // -0.84299375f + 5169 // (1.5327582f + 5170 // (-1.0688956f + 5171 // (0.49102474f + 5172 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5173 // 5174 // error 0.0000037995730, which is better than 18 bits 5175 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5176 getF32Constant(DAG, 0x3c5d51ce, dl)); 5177 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5178 getF32Constant(DAG, 0x3e00685a, dl)); 5179 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5180 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5181 getF32Constant(DAG, 0x3efb6798, dl)); 5182 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5183 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5184 getF32Constant(DAG, 0x3f88d192, dl)); 5185 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5186 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5187 getF32Constant(DAG, 0x3fc4316c, dl)); 5188 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5189 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5190 getF32Constant(DAG, 0x3f57ce70, dl)); 5191 } 5192 5193 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5194 } 5195 5196 // No special expansion. 5197 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op); 5198 } 5199 5200 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5201 /// limited-precision mode. 5202 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5203 const TargetLowering &TLI) { 5204 if (Op.getValueType() == MVT::f32 && 5205 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5206 return getLimitedPrecisionExp2(Op, dl, DAG); 5207 5208 // No special expansion. 5209 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op); 5210 } 5211 5212 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5213 /// limited-precision mode with x == 10.0f. 5214 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5215 SelectionDAG &DAG, const TargetLowering &TLI) { 5216 bool IsExp10 = false; 5217 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5218 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5219 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5220 APFloat Ten(10.0f); 5221 IsExp10 = LHSC->isExactlyValue(Ten); 5222 } 5223 } 5224 5225 // TODO: What fast-math-flags should be set on the FMUL node? 5226 if (IsExp10) { 5227 // Put the exponent in the right bit position for later addition to the 5228 // final result: 5229 // 5230 // #define LOG2OF10 3.3219281f 5231 // t0 = Op * LOG2OF10; 5232 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5233 getF32Constant(DAG, 0x40549a78, dl)); 5234 return getLimitedPrecisionExp2(t0, dl, DAG); 5235 } 5236 5237 // No special expansion. 5238 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS); 5239 } 5240 5241 /// ExpandPowI - Expand a llvm.powi intrinsic. 5242 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5243 SelectionDAG &DAG) { 5244 // If RHS is a constant, we can expand this out to a multiplication tree, 5245 // otherwise we end up lowering to a call to __powidf2 (for example). When 5246 // optimizing for size, we only want to do this if the expansion would produce 5247 // a small number of multiplies, otherwise we do the full expansion. 5248 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5249 // Get the exponent as a positive value. 5250 unsigned Val = RHSC->getSExtValue(); 5251 if ((int)Val < 0) Val = -Val; 5252 5253 // powi(x, 0) -> 1.0 5254 if (Val == 0) 5255 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5256 5257 bool OptForSize = DAG.shouldOptForSize(); 5258 if (!OptForSize || 5259 // If optimizing for size, don't insert too many multiplies. 5260 // This inserts up to 5 multiplies. 5261 countPopulation(Val) + Log2_32(Val) < 7) { 5262 // We use the simple binary decomposition method to generate the multiply 5263 // sequence. There are more optimal ways to do this (for example, 5264 // powi(x,15) generates one more multiply than it should), but this has 5265 // the benefit of being both really simple and much better than a libcall. 5266 SDValue Res; // Logically starts equal to 1.0 5267 SDValue CurSquare = LHS; 5268 // TODO: Intrinsics should have fast-math-flags that propagate to these 5269 // nodes. 5270 while (Val) { 5271 if (Val & 1) { 5272 if (Res.getNode()) 5273 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 5274 else 5275 Res = CurSquare; // 1.0*CurSquare. 5276 } 5277 5278 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5279 CurSquare, CurSquare); 5280 Val >>= 1; 5281 } 5282 5283 // If the original was negative, invert the result, producing 1/(x*x*x). 5284 if (RHSC->getSExtValue() < 0) 5285 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5286 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5287 return Res; 5288 } 5289 } 5290 5291 // Otherwise, expand to a libcall. 5292 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5293 } 5294 5295 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5296 SDValue LHS, SDValue RHS, SDValue Scale, 5297 SelectionDAG &DAG, const TargetLowering &TLI) { 5298 EVT VT = LHS.getValueType(); 5299 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5300 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5301 LLVMContext &Ctx = *DAG.getContext(); 5302 5303 // If the type is legal but the operation isn't, this node might survive all 5304 // the way to operation legalization. If we end up there and we do not have 5305 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5306 // node. 5307 5308 // Coax the legalizer into expanding the node during type legalization instead 5309 // by bumping the size by one bit. This will force it to Promote, enabling the 5310 // early expansion and avoiding the need to expand later. 5311 5312 // We don't have to do this if Scale is 0; that can always be expanded, unless 5313 // it's a saturating signed operation. Those can experience true integer 5314 // division overflow, a case which we must avoid. 5315 5316 // FIXME: We wouldn't have to do this (or any of the early 5317 // expansion/promotion) if it was possible to expand a libcall of an 5318 // illegal type during operation legalization. But it's not, so things 5319 // get a bit hacky. 5320 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5321 if ((ScaleInt > 0 || (Saturating && Signed)) && 5322 (TLI.isTypeLegal(VT) || 5323 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5324 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5325 Opcode, VT, ScaleInt); 5326 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5327 EVT PromVT; 5328 if (VT.isScalarInteger()) 5329 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5330 else if (VT.isVector()) { 5331 PromVT = VT.getVectorElementType(); 5332 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5333 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5334 } else 5335 llvm_unreachable("Wrong VT for DIVFIX?"); 5336 if (Signed) { 5337 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5338 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5339 } else { 5340 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5341 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5342 } 5343 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5344 // For saturating operations, we need to shift up the LHS to get the 5345 // proper saturation width, and then shift down again afterwards. 5346 if (Saturating) 5347 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5348 DAG.getConstant(1, DL, ShiftTy)); 5349 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5350 if (Saturating) 5351 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5352 DAG.getConstant(1, DL, ShiftTy)); 5353 return DAG.getZExtOrTrunc(Res, DL, VT); 5354 } 5355 } 5356 5357 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5358 } 5359 5360 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5361 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5362 static void 5363 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs, 5364 const SDValue &N) { 5365 switch (N.getOpcode()) { 5366 case ISD::CopyFromReg: { 5367 SDValue Op = N.getOperand(1); 5368 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5369 Op.getValueType().getSizeInBits()); 5370 return; 5371 } 5372 case ISD::BITCAST: 5373 case ISD::AssertZext: 5374 case ISD::AssertSext: 5375 case ISD::TRUNCATE: 5376 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5377 return; 5378 case ISD::BUILD_PAIR: 5379 case ISD::BUILD_VECTOR: 5380 case ISD::CONCAT_VECTORS: 5381 for (SDValue Op : N->op_values()) 5382 getUnderlyingArgRegs(Regs, Op); 5383 return; 5384 default: 5385 return; 5386 } 5387 } 5388 5389 /// If the DbgValueInst is a dbg_value of a function argument, create the 5390 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5391 /// instruction selection, they will be inserted to the entry BB. 5392 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5393 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5394 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 5395 const Argument *Arg = dyn_cast<Argument>(V); 5396 if (!Arg) 5397 return false; 5398 5399 if (!IsDbgDeclare) { 5400 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5401 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5402 // the entry block. 5403 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5404 if (!IsInEntryBlock) 5405 return false; 5406 5407 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5408 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5409 // variable that also is a param. 5410 // 5411 // Although, if we are at the top of the entry block already, we can still 5412 // emit using ArgDbgValue. This might catch some situations when the 5413 // dbg.value refers to an argument that isn't used in the entry block, so 5414 // any CopyToReg node would be optimized out and the only way to express 5415 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5416 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5417 // we should only emit as ArgDbgValue if the Variable is an argument to the 5418 // current function, and the dbg.value intrinsic is found in the entry 5419 // block. 5420 bool VariableIsFunctionInputArg = Variable->isParameter() && 5421 !DL->getInlinedAt(); 5422 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5423 if (!IsInPrologue && !VariableIsFunctionInputArg) 5424 return false; 5425 5426 // Here we assume that a function argument on IR level only can be used to 5427 // describe one input parameter on source level. If we for example have 5428 // source code like this 5429 // 5430 // struct A { long x, y; }; 5431 // void foo(struct A a, long b) { 5432 // ... 5433 // b = a.x; 5434 // ... 5435 // } 5436 // 5437 // and IR like this 5438 // 5439 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5440 // entry: 5441 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5442 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5443 // call void @llvm.dbg.value(metadata i32 %b, "b", 5444 // ... 5445 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5446 // ... 5447 // 5448 // then the last dbg.value is describing a parameter "b" using a value that 5449 // is an argument. But since we already has used %a1 to describe a parameter 5450 // we should not handle that last dbg.value here (that would result in an 5451 // incorrect hoisting of the DBG_VALUE to the function entry). 5452 // Notice that we allow one dbg.value per IR level argument, to accommodate 5453 // for the situation with fragments above. 5454 if (VariableIsFunctionInputArg) { 5455 unsigned ArgNo = Arg->getArgNo(); 5456 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5457 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5458 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5459 return false; 5460 FuncInfo.DescribedArgs.set(ArgNo); 5461 } 5462 } 5463 5464 MachineFunction &MF = DAG.getMachineFunction(); 5465 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5466 5467 bool IsIndirect = false; 5468 Optional<MachineOperand> Op; 5469 // Some arguments' frame index is recorded during argument lowering. 5470 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5471 if (FI != std::numeric_limits<int>::max()) 5472 Op = MachineOperand::CreateFI(FI); 5473 5474 SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes; 5475 if (!Op && N.getNode()) { 5476 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5477 Register Reg; 5478 if (ArgRegsAndSizes.size() == 1) 5479 Reg = ArgRegsAndSizes.front().first; 5480 5481 if (Reg && Reg.isVirtual()) { 5482 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5483 Register PR = RegInfo.getLiveInPhysReg(Reg); 5484 if (PR) 5485 Reg = PR; 5486 } 5487 if (Reg) { 5488 Op = MachineOperand::CreateReg(Reg, false); 5489 IsIndirect = IsDbgDeclare; 5490 } 5491 } 5492 5493 if (!Op && N.getNode()) { 5494 // Check if frame index is available. 5495 SDValue LCandidate = peekThroughBitcasts(N); 5496 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5497 if (FrameIndexSDNode *FINode = 5498 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5499 Op = MachineOperand::CreateFI(FINode->getIndex()); 5500 } 5501 5502 if (!Op) { 5503 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5504 auto splitMultiRegDbgValue 5505 = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) { 5506 unsigned Offset = 0; 5507 for (auto RegAndSize : SplitRegs) { 5508 // If the expression is already a fragment, the current register 5509 // offset+size might extend beyond the fragment. In this case, only 5510 // the register bits that are inside the fragment are relevant. 5511 int RegFragmentSizeInBits = RegAndSize.second; 5512 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5513 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5514 // The register is entirely outside the expression fragment, 5515 // so is irrelevant for debug info. 5516 if (Offset >= ExprFragmentSizeInBits) 5517 break; 5518 // The register is partially outside the expression fragment, only 5519 // the low bits within the fragment are relevant for debug info. 5520 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5521 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5522 } 5523 } 5524 5525 auto FragmentExpr = DIExpression::createFragmentExpression( 5526 Expr, Offset, RegFragmentSizeInBits); 5527 Offset += RegAndSize.second; 5528 // If a valid fragment expression cannot be created, the variable's 5529 // correct value cannot be determined and so it is set as Undef. 5530 if (!FragmentExpr) { 5531 SDDbgValue *SDV = DAG.getConstantDbgValue( 5532 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5533 DAG.AddDbgValue(SDV, nullptr, false); 5534 continue; 5535 } 5536 assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?"); 5537 FuncInfo.ArgDbgValues.push_back( 5538 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare, 5539 RegAndSize.first, Variable, *FragmentExpr)); 5540 } 5541 }; 5542 5543 // Check if ValueMap has reg number. 5544 DenseMap<const Value *, Register>::const_iterator 5545 VMI = FuncInfo.ValueMap.find(V); 5546 if (VMI != FuncInfo.ValueMap.end()) { 5547 const auto &TLI = DAG.getTargetLoweringInfo(); 5548 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5549 V->getType(), getABIRegCopyCC(V)); 5550 if (RFV.occupiesMultipleRegs()) { 5551 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5552 return true; 5553 } 5554 5555 Op = MachineOperand::CreateReg(VMI->second, false); 5556 IsIndirect = IsDbgDeclare; 5557 } else if (ArgRegsAndSizes.size() > 1) { 5558 // This was split due to the calling convention, and no virtual register 5559 // mapping exists for the value. 5560 splitMultiRegDbgValue(ArgRegsAndSizes); 5561 return true; 5562 } 5563 } 5564 5565 if (!Op) 5566 return false; 5567 5568 assert(Variable->isValidLocationForIntrinsic(DL) && 5569 "Expected inlined-at fields to agree"); 5570 IsIndirect = (Op->isReg()) ? IsIndirect : true; 5571 FuncInfo.ArgDbgValues.push_back( 5572 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 5573 *Op, Variable, Expr)); 5574 5575 return true; 5576 } 5577 5578 /// Return the appropriate SDDbgValue based on N. 5579 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5580 DILocalVariable *Variable, 5581 DIExpression *Expr, 5582 const DebugLoc &dl, 5583 unsigned DbgSDNodeOrder) { 5584 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5585 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5586 // stack slot locations. 5587 // 5588 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5589 // debug values here after optimization: 5590 // 5591 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5592 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5593 // 5594 // Both describe the direct values of their associated variables. 5595 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5596 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5597 } 5598 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5599 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5600 } 5601 5602 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5603 switch (Intrinsic) { 5604 case Intrinsic::smul_fix: 5605 return ISD::SMULFIX; 5606 case Intrinsic::umul_fix: 5607 return ISD::UMULFIX; 5608 case Intrinsic::smul_fix_sat: 5609 return ISD::SMULFIXSAT; 5610 case Intrinsic::umul_fix_sat: 5611 return ISD::UMULFIXSAT; 5612 case Intrinsic::sdiv_fix: 5613 return ISD::SDIVFIX; 5614 case Intrinsic::udiv_fix: 5615 return ISD::UDIVFIX; 5616 case Intrinsic::sdiv_fix_sat: 5617 return ISD::SDIVFIXSAT; 5618 case Intrinsic::udiv_fix_sat: 5619 return ISD::UDIVFIXSAT; 5620 default: 5621 llvm_unreachable("Unhandled fixed point intrinsic"); 5622 } 5623 } 5624 5625 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5626 const char *FunctionName) { 5627 assert(FunctionName && "FunctionName must not be nullptr"); 5628 SDValue Callee = DAG.getExternalSymbol( 5629 FunctionName, 5630 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5631 LowerCallTo(I, Callee, I.isTailCall()); 5632 } 5633 5634 /// Given a @llvm.call.preallocated.setup, return the corresponding 5635 /// preallocated call. 5636 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5637 assert(cast<CallBase>(PreallocatedSetup) 5638 ->getCalledFunction() 5639 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5640 "expected call_preallocated_setup Value"); 5641 for (auto *U : PreallocatedSetup->users()) { 5642 auto *UseCall = cast<CallBase>(U); 5643 const Function *Fn = UseCall->getCalledFunction(); 5644 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5645 return UseCall; 5646 } 5647 } 5648 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5649 } 5650 5651 /// Lower the call to the specified intrinsic function. 5652 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5653 unsigned Intrinsic) { 5654 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5655 SDLoc sdl = getCurSDLoc(); 5656 DebugLoc dl = getCurDebugLoc(); 5657 SDValue Res; 5658 5659 switch (Intrinsic) { 5660 default: 5661 // By default, turn this into a target intrinsic node. 5662 visitTargetIntrinsic(I, Intrinsic); 5663 return; 5664 case Intrinsic::vscale: { 5665 match(&I, m_VScale(DAG.getDataLayout())); 5666 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5667 setValue(&I, 5668 DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1))); 5669 return; 5670 } 5671 case Intrinsic::vastart: visitVAStart(I); return; 5672 case Intrinsic::vaend: visitVAEnd(I); return; 5673 case Intrinsic::vacopy: visitVACopy(I); return; 5674 case Intrinsic::returnaddress: 5675 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5676 TLI.getPointerTy(DAG.getDataLayout()), 5677 getValue(I.getArgOperand(0)))); 5678 return; 5679 case Intrinsic::addressofreturnaddress: 5680 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5681 TLI.getPointerTy(DAG.getDataLayout()))); 5682 return; 5683 case Intrinsic::sponentry: 5684 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5685 TLI.getFrameIndexTy(DAG.getDataLayout()))); 5686 return; 5687 case Intrinsic::frameaddress: 5688 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5689 TLI.getFrameIndexTy(DAG.getDataLayout()), 5690 getValue(I.getArgOperand(0)))); 5691 return; 5692 case Intrinsic::read_register: { 5693 Value *Reg = I.getArgOperand(0); 5694 SDValue Chain = getRoot(); 5695 SDValue RegName = 5696 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5697 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5698 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5699 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5700 setValue(&I, Res); 5701 DAG.setRoot(Res.getValue(1)); 5702 return; 5703 } 5704 case Intrinsic::write_register: { 5705 Value *Reg = I.getArgOperand(0); 5706 Value *RegValue = I.getArgOperand(1); 5707 SDValue Chain = getRoot(); 5708 SDValue RegName = 5709 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5710 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5711 RegName, getValue(RegValue))); 5712 return; 5713 } 5714 case Intrinsic::memcpy: { 5715 const auto &MCI = cast<MemCpyInst>(I); 5716 SDValue Op1 = getValue(I.getArgOperand(0)); 5717 SDValue Op2 = getValue(I.getArgOperand(1)); 5718 SDValue Op3 = getValue(I.getArgOperand(2)); 5719 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5720 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5721 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5722 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5723 bool isVol = MCI.isVolatile(); 5724 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5725 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5726 // node. 5727 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5728 SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5729 /* AlwaysInline */ false, isTC, 5730 MachinePointerInfo(I.getArgOperand(0)), 5731 MachinePointerInfo(I.getArgOperand(1))); 5732 updateDAGForMaybeTailCall(MC); 5733 return; 5734 } 5735 case Intrinsic::memcpy_inline: { 5736 const auto &MCI = cast<MemCpyInlineInst>(I); 5737 SDValue Dst = getValue(I.getArgOperand(0)); 5738 SDValue Src = getValue(I.getArgOperand(1)); 5739 SDValue Size = getValue(I.getArgOperand(2)); 5740 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 5741 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 5742 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5743 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5744 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5745 bool isVol = MCI.isVolatile(); 5746 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5747 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5748 // node. 5749 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 5750 /* AlwaysInline */ true, isTC, 5751 MachinePointerInfo(I.getArgOperand(0)), 5752 MachinePointerInfo(I.getArgOperand(1))); 5753 updateDAGForMaybeTailCall(MC); 5754 return; 5755 } 5756 case Intrinsic::memset: { 5757 const auto &MSI = cast<MemSetInst>(I); 5758 SDValue Op1 = getValue(I.getArgOperand(0)); 5759 SDValue Op2 = getValue(I.getArgOperand(1)); 5760 SDValue Op3 = getValue(I.getArgOperand(2)); 5761 // @llvm.memset defines 0 and 1 to both mean no alignment. 5762 Align Alignment = MSI.getDestAlign().valueOrOne(); 5763 bool isVol = MSI.isVolatile(); 5764 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5765 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5766 SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC, 5767 MachinePointerInfo(I.getArgOperand(0))); 5768 updateDAGForMaybeTailCall(MS); 5769 return; 5770 } 5771 case Intrinsic::memmove: { 5772 const auto &MMI = cast<MemMoveInst>(I); 5773 SDValue Op1 = getValue(I.getArgOperand(0)); 5774 SDValue Op2 = getValue(I.getArgOperand(1)); 5775 SDValue Op3 = getValue(I.getArgOperand(2)); 5776 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5777 Align DstAlign = MMI.getDestAlign().valueOrOne(); 5778 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 5779 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5780 bool isVol = MMI.isVolatile(); 5781 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5782 // FIXME: Support passing different dest/src alignments to the memmove DAG 5783 // node. 5784 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5785 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5786 isTC, MachinePointerInfo(I.getArgOperand(0)), 5787 MachinePointerInfo(I.getArgOperand(1))); 5788 updateDAGForMaybeTailCall(MM); 5789 return; 5790 } 5791 case Intrinsic::memcpy_element_unordered_atomic: { 5792 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5793 SDValue Dst = getValue(MI.getRawDest()); 5794 SDValue Src = getValue(MI.getRawSource()); 5795 SDValue Length = getValue(MI.getLength()); 5796 5797 unsigned DstAlign = MI.getDestAlignment(); 5798 unsigned SrcAlign = MI.getSourceAlignment(); 5799 Type *LengthTy = MI.getLength()->getType(); 5800 unsigned ElemSz = MI.getElementSizeInBytes(); 5801 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5802 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5803 SrcAlign, Length, LengthTy, ElemSz, isTC, 5804 MachinePointerInfo(MI.getRawDest()), 5805 MachinePointerInfo(MI.getRawSource())); 5806 updateDAGForMaybeTailCall(MC); 5807 return; 5808 } 5809 case Intrinsic::memmove_element_unordered_atomic: { 5810 auto &MI = cast<AtomicMemMoveInst>(I); 5811 SDValue Dst = getValue(MI.getRawDest()); 5812 SDValue Src = getValue(MI.getRawSource()); 5813 SDValue Length = getValue(MI.getLength()); 5814 5815 unsigned DstAlign = MI.getDestAlignment(); 5816 unsigned SrcAlign = MI.getSourceAlignment(); 5817 Type *LengthTy = MI.getLength()->getType(); 5818 unsigned ElemSz = MI.getElementSizeInBytes(); 5819 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5820 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5821 SrcAlign, Length, LengthTy, ElemSz, isTC, 5822 MachinePointerInfo(MI.getRawDest()), 5823 MachinePointerInfo(MI.getRawSource())); 5824 updateDAGForMaybeTailCall(MC); 5825 return; 5826 } 5827 case Intrinsic::memset_element_unordered_atomic: { 5828 auto &MI = cast<AtomicMemSetInst>(I); 5829 SDValue Dst = getValue(MI.getRawDest()); 5830 SDValue Val = getValue(MI.getValue()); 5831 SDValue Length = getValue(MI.getLength()); 5832 5833 unsigned DstAlign = MI.getDestAlignment(); 5834 Type *LengthTy = MI.getLength()->getType(); 5835 unsigned ElemSz = MI.getElementSizeInBytes(); 5836 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5837 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5838 LengthTy, ElemSz, isTC, 5839 MachinePointerInfo(MI.getRawDest())); 5840 updateDAGForMaybeTailCall(MC); 5841 return; 5842 } 5843 case Intrinsic::call_preallocated_setup: { 5844 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 5845 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 5846 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 5847 getRoot(), SrcValue); 5848 setValue(&I, Res); 5849 DAG.setRoot(Res); 5850 return; 5851 } 5852 case Intrinsic::call_preallocated_arg: { 5853 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 5854 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 5855 SDValue Ops[3]; 5856 Ops[0] = getRoot(); 5857 Ops[1] = SrcValue; 5858 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 5859 MVT::i32); // arg index 5860 SDValue Res = DAG.getNode( 5861 ISD::PREALLOCATED_ARG, sdl, 5862 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 5863 setValue(&I, Res); 5864 DAG.setRoot(Res.getValue(1)); 5865 return; 5866 } 5867 case Intrinsic::dbg_addr: 5868 case Intrinsic::dbg_declare: { 5869 const auto &DI = cast<DbgVariableIntrinsic>(I); 5870 DILocalVariable *Variable = DI.getVariable(); 5871 DIExpression *Expression = DI.getExpression(); 5872 dropDanglingDebugInfo(Variable, Expression); 5873 assert(Variable && "Missing variable"); 5874 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 5875 << "\n"); 5876 // Check if address has undef value. 5877 const Value *Address = DI.getVariableLocation(); 5878 if (!Address || isa<UndefValue>(Address) || 5879 (Address->use_empty() && !isa<Argument>(Address))) { 5880 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 5881 << " (bad/undef/unused-arg address)\n"); 5882 return; 5883 } 5884 5885 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5886 5887 // Check if this variable can be described by a frame index, typically 5888 // either as a static alloca or a byval parameter. 5889 int FI = std::numeric_limits<int>::max(); 5890 if (const auto *AI = 5891 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5892 if (AI->isStaticAlloca()) { 5893 auto I = FuncInfo.StaticAllocaMap.find(AI); 5894 if (I != FuncInfo.StaticAllocaMap.end()) 5895 FI = I->second; 5896 } 5897 } else if (const auto *Arg = dyn_cast<Argument>( 5898 Address->stripInBoundsConstantOffsets())) { 5899 FI = FuncInfo.getArgumentFrameIndex(Arg); 5900 } 5901 5902 // llvm.dbg.addr is control dependent and always generates indirect 5903 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5904 // the MachineFunction variable table. 5905 if (FI != std::numeric_limits<int>::max()) { 5906 if (Intrinsic == Intrinsic::dbg_addr) { 5907 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 5908 Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder); 5909 DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter); 5910 } else { 5911 LLVM_DEBUG(dbgs() << "Skipping " << DI 5912 << " (variable info stashed in MF side table)\n"); 5913 } 5914 return; 5915 } 5916 5917 SDValue &N = NodeMap[Address]; 5918 if (!N.getNode() && isa<Argument>(Address)) 5919 // Check unused arguments map. 5920 N = UnusedArgNodeMap[Address]; 5921 SDDbgValue *SDV; 5922 if (N.getNode()) { 5923 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 5924 Address = BCI->getOperand(0); 5925 // Parameters are handled specially. 5926 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 5927 if (isParameter && FINode) { 5928 // Byval parameter. We have a frame index at this point. 5929 SDV = 5930 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 5931 /*IsIndirect*/ true, dl, SDNodeOrder); 5932 } else if (isa<Argument>(Address)) { 5933 // Address is an argument, so try to emit its dbg value using 5934 // virtual register info from the FuncInfo.ValueMap. 5935 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 5936 return; 5937 } else { 5938 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 5939 true, dl, SDNodeOrder); 5940 } 5941 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 5942 } else { 5943 // If Address is an argument then try to emit its dbg value using 5944 // virtual register info from the FuncInfo.ValueMap. 5945 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 5946 N)) { 5947 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 5948 << " (could not emit func-arg dbg_value)\n"); 5949 } 5950 } 5951 return; 5952 } 5953 case Intrinsic::dbg_label: { 5954 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 5955 DILabel *Label = DI.getLabel(); 5956 assert(Label && "Missing label"); 5957 5958 SDDbgLabel *SDV; 5959 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 5960 DAG.AddDbgLabel(SDV); 5961 return; 5962 } 5963 case Intrinsic::dbg_value: { 5964 const DbgValueInst &DI = cast<DbgValueInst>(I); 5965 assert(DI.getVariable() && "Missing variable"); 5966 5967 DILocalVariable *Variable = DI.getVariable(); 5968 DIExpression *Expression = DI.getExpression(); 5969 dropDanglingDebugInfo(Variable, Expression); 5970 const Value *V = DI.getValue(); 5971 if (!V) 5972 return; 5973 5974 if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(), 5975 SDNodeOrder)) 5976 return; 5977 5978 // TODO: Dangling debug info will eventually either be resolved or produce 5979 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 5980 // between the original dbg.value location and its resolved DBG_VALUE, which 5981 // we should ideally fill with an extra Undef DBG_VALUE. 5982 5983 DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder); 5984 return; 5985 } 5986 5987 case Intrinsic::eh_typeid_for: { 5988 // Find the type id for the given typeinfo. 5989 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 5990 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 5991 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 5992 setValue(&I, Res); 5993 return; 5994 } 5995 5996 case Intrinsic::eh_return_i32: 5997 case Intrinsic::eh_return_i64: 5998 DAG.getMachineFunction().setCallsEHReturn(true); 5999 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6000 MVT::Other, 6001 getControlRoot(), 6002 getValue(I.getArgOperand(0)), 6003 getValue(I.getArgOperand(1)))); 6004 return; 6005 case Intrinsic::eh_unwind_init: 6006 DAG.getMachineFunction().setCallsUnwindInit(true); 6007 return; 6008 case Intrinsic::eh_dwarf_cfa: 6009 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6010 TLI.getPointerTy(DAG.getDataLayout()), 6011 getValue(I.getArgOperand(0)))); 6012 return; 6013 case Intrinsic::eh_sjlj_callsite: { 6014 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6015 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 6016 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 6017 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6018 6019 MMI.setCurrentCallSite(CI->getZExtValue()); 6020 return; 6021 } 6022 case Intrinsic::eh_sjlj_functioncontext: { 6023 // Get and store the index of the function context. 6024 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6025 AllocaInst *FnCtx = 6026 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6027 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6028 MFI.setFunctionContextIndex(FI); 6029 return; 6030 } 6031 case Intrinsic::eh_sjlj_setjmp: { 6032 SDValue Ops[2]; 6033 Ops[0] = getRoot(); 6034 Ops[1] = getValue(I.getArgOperand(0)); 6035 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6036 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6037 setValue(&I, Op.getValue(0)); 6038 DAG.setRoot(Op.getValue(1)); 6039 return; 6040 } 6041 case Intrinsic::eh_sjlj_longjmp: 6042 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6043 getRoot(), getValue(I.getArgOperand(0)))); 6044 return; 6045 case Intrinsic::eh_sjlj_setup_dispatch: 6046 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6047 getRoot())); 6048 return; 6049 case Intrinsic::masked_gather: 6050 visitMaskedGather(I); 6051 return; 6052 case Intrinsic::masked_load: 6053 visitMaskedLoad(I); 6054 return; 6055 case Intrinsic::masked_scatter: 6056 visitMaskedScatter(I); 6057 return; 6058 case Intrinsic::masked_store: 6059 visitMaskedStore(I); 6060 return; 6061 case Intrinsic::masked_expandload: 6062 visitMaskedLoad(I, true /* IsExpanding */); 6063 return; 6064 case Intrinsic::masked_compressstore: 6065 visitMaskedStore(I, true /* IsCompressing */); 6066 return; 6067 case Intrinsic::powi: 6068 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6069 getValue(I.getArgOperand(1)), DAG)); 6070 return; 6071 case Intrinsic::log: 6072 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6073 return; 6074 case Intrinsic::log2: 6075 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6076 return; 6077 case Intrinsic::log10: 6078 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6079 return; 6080 case Intrinsic::exp: 6081 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6082 return; 6083 case Intrinsic::exp2: 6084 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6085 return; 6086 case Intrinsic::pow: 6087 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6088 getValue(I.getArgOperand(1)), DAG, TLI)); 6089 return; 6090 case Intrinsic::sqrt: 6091 case Intrinsic::fabs: 6092 case Intrinsic::sin: 6093 case Intrinsic::cos: 6094 case Intrinsic::floor: 6095 case Intrinsic::ceil: 6096 case Intrinsic::trunc: 6097 case Intrinsic::rint: 6098 case Intrinsic::nearbyint: 6099 case Intrinsic::round: 6100 case Intrinsic::roundeven: 6101 case Intrinsic::canonicalize: { 6102 unsigned Opcode; 6103 switch (Intrinsic) { 6104 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6105 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6106 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6107 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6108 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6109 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6110 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6111 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6112 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6113 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6114 case Intrinsic::round: Opcode = ISD::FROUND; break; 6115 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6116 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6117 } 6118 6119 setValue(&I, DAG.getNode(Opcode, sdl, 6120 getValue(I.getArgOperand(0)).getValueType(), 6121 getValue(I.getArgOperand(0)))); 6122 return; 6123 } 6124 case Intrinsic::lround: 6125 case Intrinsic::llround: 6126 case Intrinsic::lrint: 6127 case Intrinsic::llrint: { 6128 unsigned Opcode; 6129 switch (Intrinsic) { 6130 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6131 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6132 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6133 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6134 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6135 } 6136 6137 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6138 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6139 getValue(I.getArgOperand(0)))); 6140 return; 6141 } 6142 case Intrinsic::minnum: 6143 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6144 getValue(I.getArgOperand(0)).getValueType(), 6145 getValue(I.getArgOperand(0)), 6146 getValue(I.getArgOperand(1)))); 6147 return; 6148 case Intrinsic::maxnum: 6149 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6150 getValue(I.getArgOperand(0)).getValueType(), 6151 getValue(I.getArgOperand(0)), 6152 getValue(I.getArgOperand(1)))); 6153 return; 6154 case Intrinsic::minimum: 6155 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6156 getValue(I.getArgOperand(0)).getValueType(), 6157 getValue(I.getArgOperand(0)), 6158 getValue(I.getArgOperand(1)))); 6159 return; 6160 case Intrinsic::maximum: 6161 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6162 getValue(I.getArgOperand(0)).getValueType(), 6163 getValue(I.getArgOperand(0)), 6164 getValue(I.getArgOperand(1)))); 6165 return; 6166 case Intrinsic::copysign: 6167 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6168 getValue(I.getArgOperand(0)).getValueType(), 6169 getValue(I.getArgOperand(0)), 6170 getValue(I.getArgOperand(1)))); 6171 return; 6172 case Intrinsic::fma: 6173 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6174 getValue(I.getArgOperand(0)).getValueType(), 6175 getValue(I.getArgOperand(0)), 6176 getValue(I.getArgOperand(1)), 6177 getValue(I.getArgOperand(2)))); 6178 return; 6179 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6180 case Intrinsic::INTRINSIC: 6181 #include "llvm/IR/ConstrainedOps.def" 6182 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6183 return; 6184 case Intrinsic::fmuladd: { 6185 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6186 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6187 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6188 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6189 getValue(I.getArgOperand(0)).getValueType(), 6190 getValue(I.getArgOperand(0)), 6191 getValue(I.getArgOperand(1)), 6192 getValue(I.getArgOperand(2)))); 6193 } else { 6194 // TODO: Intrinsic calls should have fast-math-flags. 6195 SDValue Mul = DAG.getNode(ISD::FMUL, sdl, 6196 getValue(I.getArgOperand(0)).getValueType(), 6197 getValue(I.getArgOperand(0)), 6198 getValue(I.getArgOperand(1))); 6199 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6200 getValue(I.getArgOperand(0)).getValueType(), 6201 Mul, 6202 getValue(I.getArgOperand(2))); 6203 setValue(&I, Add); 6204 } 6205 return; 6206 } 6207 case Intrinsic::convert_to_fp16: 6208 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6209 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6210 getValue(I.getArgOperand(0)), 6211 DAG.getTargetConstant(0, sdl, 6212 MVT::i32)))); 6213 return; 6214 case Intrinsic::convert_from_fp16: 6215 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6216 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6217 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6218 getValue(I.getArgOperand(0))))); 6219 return; 6220 case Intrinsic::pcmarker: { 6221 SDValue Tmp = getValue(I.getArgOperand(0)); 6222 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6223 return; 6224 } 6225 case Intrinsic::readcyclecounter: { 6226 SDValue Op = getRoot(); 6227 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6228 DAG.getVTList(MVT::i64, MVT::Other), Op); 6229 setValue(&I, Res); 6230 DAG.setRoot(Res.getValue(1)); 6231 return; 6232 } 6233 case Intrinsic::bitreverse: 6234 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6235 getValue(I.getArgOperand(0)).getValueType(), 6236 getValue(I.getArgOperand(0)))); 6237 return; 6238 case Intrinsic::bswap: 6239 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6240 getValue(I.getArgOperand(0)).getValueType(), 6241 getValue(I.getArgOperand(0)))); 6242 return; 6243 case Intrinsic::cttz: { 6244 SDValue Arg = getValue(I.getArgOperand(0)); 6245 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6246 EVT Ty = Arg.getValueType(); 6247 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6248 sdl, Ty, Arg)); 6249 return; 6250 } 6251 case Intrinsic::ctlz: { 6252 SDValue Arg = getValue(I.getArgOperand(0)); 6253 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6254 EVT Ty = Arg.getValueType(); 6255 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6256 sdl, Ty, Arg)); 6257 return; 6258 } 6259 case Intrinsic::ctpop: { 6260 SDValue Arg = getValue(I.getArgOperand(0)); 6261 EVT Ty = Arg.getValueType(); 6262 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6263 return; 6264 } 6265 case Intrinsic::fshl: 6266 case Intrinsic::fshr: { 6267 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6268 SDValue X = getValue(I.getArgOperand(0)); 6269 SDValue Y = getValue(I.getArgOperand(1)); 6270 SDValue Z = getValue(I.getArgOperand(2)); 6271 EVT VT = X.getValueType(); 6272 SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT); 6273 SDValue Zero = DAG.getConstant(0, sdl, VT); 6274 SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC); 6275 6276 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6277 if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) { 6278 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6279 return; 6280 } 6281 6282 // When X == Y, this is rotate. If the data type has a power-of-2 size, we 6283 // avoid the select that is necessary in the general case to filter out 6284 // the 0-shift possibility that leads to UB. 6285 if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) { 6286 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6287 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 6288 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6289 return; 6290 } 6291 6292 // Some targets only rotate one way. Try the opposite direction. 6293 RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL; 6294 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 6295 // Negate the shift amount because it is safe to ignore the high bits. 6296 SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 6297 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt)); 6298 return; 6299 } 6300 6301 // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW)) 6302 // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW)) 6303 SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 6304 SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC); 6305 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt); 6306 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt); 6307 setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY)); 6308 return; 6309 } 6310 6311 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 6312 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 6313 SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt); 6314 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt); 6315 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt); 6316 SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY); 6317 6318 // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth, 6319 // and that is undefined. We must compare and select to avoid UB. 6320 EVT CCVT = MVT::i1; 6321 if (VT.isVector()) 6322 CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements()); 6323 6324 // For fshl, 0-shift returns the 1st arg (X). 6325 // For fshr, 0-shift returns the 2nd arg (Y). 6326 SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ); 6327 setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or)); 6328 return; 6329 } 6330 case Intrinsic::sadd_sat: { 6331 SDValue Op1 = getValue(I.getArgOperand(0)); 6332 SDValue Op2 = getValue(I.getArgOperand(1)); 6333 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6334 return; 6335 } 6336 case Intrinsic::uadd_sat: { 6337 SDValue Op1 = getValue(I.getArgOperand(0)); 6338 SDValue Op2 = getValue(I.getArgOperand(1)); 6339 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6340 return; 6341 } 6342 case Intrinsic::ssub_sat: { 6343 SDValue Op1 = getValue(I.getArgOperand(0)); 6344 SDValue Op2 = getValue(I.getArgOperand(1)); 6345 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6346 return; 6347 } 6348 case Intrinsic::usub_sat: { 6349 SDValue Op1 = getValue(I.getArgOperand(0)); 6350 SDValue Op2 = getValue(I.getArgOperand(1)); 6351 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6352 return; 6353 } 6354 case Intrinsic::smul_fix: 6355 case Intrinsic::umul_fix: 6356 case Intrinsic::smul_fix_sat: 6357 case Intrinsic::umul_fix_sat: { 6358 SDValue Op1 = getValue(I.getArgOperand(0)); 6359 SDValue Op2 = getValue(I.getArgOperand(1)); 6360 SDValue Op3 = getValue(I.getArgOperand(2)); 6361 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6362 Op1.getValueType(), Op1, Op2, Op3)); 6363 return; 6364 } 6365 case Intrinsic::sdiv_fix: 6366 case Intrinsic::udiv_fix: 6367 case Intrinsic::sdiv_fix_sat: 6368 case Intrinsic::udiv_fix_sat: { 6369 SDValue Op1 = getValue(I.getArgOperand(0)); 6370 SDValue Op2 = getValue(I.getArgOperand(1)); 6371 SDValue Op3 = getValue(I.getArgOperand(2)); 6372 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6373 Op1, Op2, Op3, DAG, TLI)); 6374 return; 6375 } 6376 case Intrinsic::stacksave: { 6377 SDValue Op = getRoot(); 6378 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6379 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6380 setValue(&I, Res); 6381 DAG.setRoot(Res.getValue(1)); 6382 return; 6383 } 6384 case Intrinsic::stackrestore: 6385 Res = getValue(I.getArgOperand(0)); 6386 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6387 return; 6388 case Intrinsic::get_dynamic_area_offset: { 6389 SDValue Op = getRoot(); 6390 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6391 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6392 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6393 // target. 6394 if (PtrTy.getSizeInBits() < ResTy.getSizeInBits()) 6395 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6396 " intrinsic!"); 6397 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6398 Op); 6399 DAG.setRoot(Op); 6400 setValue(&I, Res); 6401 return; 6402 } 6403 case Intrinsic::stackguard: { 6404 MachineFunction &MF = DAG.getMachineFunction(); 6405 const Module &M = *MF.getFunction().getParent(); 6406 SDValue Chain = getRoot(); 6407 if (TLI.useLoadStackGuardNode()) { 6408 Res = getLoadStackGuard(DAG, sdl, Chain); 6409 } else { 6410 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6411 const Value *Global = TLI.getSDagStackGuard(M); 6412 unsigned Align = DL->getPrefTypeAlignment(Global->getType()); 6413 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6414 MachinePointerInfo(Global, 0), Align, 6415 MachineMemOperand::MOVolatile); 6416 } 6417 if (TLI.useStackGuardXorFP()) 6418 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6419 DAG.setRoot(Chain); 6420 setValue(&I, Res); 6421 return; 6422 } 6423 case Intrinsic::stackprotector: { 6424 // Emit code into the DAG to store the stack guard onto the stack. 6425 MachineFunction &MF = DAG.getMachineFunction(); 6426 MachineFrameInfo &MFI = MF.getFrameInfo(); 6427 SDValue Src, Chain = getRoot(); 6428 6429 if (TLI.useLoadStackGuardNode()) 6430 Src = getLoadStackGuard(DAG, sdl, Chain); 6431 else 6432 Src = getValue(I.getArgOperand(0)); // The guard's value. 6433 6434 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6435 6436 int FI = FuncInfo.StaticAllocaMap[Slot]; 6437 MFI.setStackProtectorIndex(FI); 6438 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6439 6440 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6441 6442 // Store the stack protector onto the stack. 6443 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack( 6444 DAG.getMachineFunction(), FI), 6445 /* Alignment = */ 0, MachineMemOperand::MOVolatile); 6446 setValue(&I, Res); 6447 DAG.setRoot(Res); 6448 return; 6449 } 6450 case Intrinsic::objectsize: 6451 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6452 6453 case Intrinsic::is_constant: 6454 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6455 6456 case Intrinsic::annotation: 6457 case Intrinsic::ptr_annotation: 6458 case Intrinsic::launder_invariant_group: 6459 case Intrinsic::strip_invariant_group: 6460 // Drop the intrinsic, but forward the value 6461 setValue(&I, getValue(I.getOperand(0))); 6462 return; 6463 case Intrinsic::assume: 6464 case Intrinsic::var_annotation: 6465 case Intrinsic::sideeffect: 6466 // Discard annotate attributes, assumptions, and artificial side-effects. 6467 return; 6468 6469 case Intrinsic::codeview_annotation: { 6470 // Emit a label associated with this metadata. 6471 MachineFunction &MF = DAG.getMachineFunction(); 6472 MCSymbol *Label = 6473 MF.getMMI().getContext().createTempSymbol("annotation", true); 6474 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6475 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6476 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6477 DAG.setRoot(Res); 6478 return; 6479 } 6480 6481 case Intrinsic::init_trampoline: { 6482 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6483 6484 SDValue Ops[6]; 6485 Ops[0] = getRoot(); 6486 Ops[1] = getValue(I.getArgOperand(0)); 6487 Ops[2] = getValue(I.getArgOperand(1)); 6488 Ops[3] = getValue(I.getArgOperand(2)); 6489 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6490 Ops[5] = DAG.getSrcValue(F); 6491 6492 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6493 6494 DAG.setRoot(Res); 6495 return; 6496 } 6497 case Intrinsic::adjust_trampoline: 6498 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6499 TLI.getPointerTy(DAG.getDataLayout()), 6500 getValue(I.getArgOperand(0)))); 6501 return; 6502 case Intrinsic::gcroot: { 6503 assert(DAG.getMachineFunction().getFunction().hasGC() && 6504 "only valid in functions with gc specified, enforced by Verifier"); 6505 assert(GFI && "implied by previous"); 6506 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6507 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6508 6509 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6510 GFI->addStackRoot(FI->getIndex(), TypeMap); 6511 return; 6512 } 6513 case Intrinsic::gcread: 6514 case Intrinsic::gcwrite: 6515 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6516 case Intrinsic::flt_rounds: 6517 Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot()); 6518 setValue(&I, Res); 6519 DAG.setRoot(Res.getValue(1)); 6520 return; 6521 6522 case Intrinsic::expect: 6523 // Just replace __builtin_expect(exp, c) with EXP. 6524 setValue(&I, getValue(I.getArgOperand(0))); 6525 return; 6526 6527 case Intrinsic::debugtrap: 6528 case Intrinsic::trap: { 6529 StringRef TrapFuncName = 6530 I.getAttributes() 6531 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6532 .getValueAsString(); 6533 if (TrapFuncName.empty()) { 6534 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 6535 ISD::TRAP : ISD::DEBUGTRAP; 6536 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 6537 return; 6538 } 6539 TargetLowering::ArgListTy Args; 6540 6541 TargetLowering::CallLoweringInfo CLI(DAG); 6542 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6543 CallingConv::C, I.getType(), 6544 DAG.getExternalSymbol(TrapFuncName.data(), 6545 TLI.getPointerTy(DAG.getDataLayout())), 6546 std::move(Args)); 6547 6548 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6549 DAG.setRoot(Result.second); 6550 return; 6551 } 6552 6553 case Intrinsic::uadd_with_overflow: 6554 case Intrinsic::sadd_with_overflow: 6555 case Intrinsic::usub_with_overflow: 6556 case Intrinsic::ssub_with_overflow: 6557 case Intrinsic::umul_with_overflow: 6558 case Intrinsic::smul_with_overflow: { 6559 ISD::NodeType Op; 6560 switch (Intrinsic) { 6561 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6562 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6563 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6564 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6565 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6566 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6567 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6568 } 6569 SDValue Op1 = getValue(I.getArgOperand(0)); 6570 SDValue Op2 = getValue(I.getArgOperand(1)); 6571 6572 EVT ResultVT = Op1.getValueType(); 6573 EVT OverflowVT = MVT::i1; 6574 if (ResultVT.isVector()) 6575 OverflowVT = EVT::getVectorVT( 6576 *Context, OverflowVT, ResultVT.getVectorNumElements()); 6577 6578 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6579 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6580 return; 6581 } 6582 case Intrinsic::prefetch: { 6583 SDValue Ops[5]; 6584 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6585 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6586 Ops[0] = DAG.getRoot(); 6587 Ops[1] = getValue(I.getArgOperand(0)); 6588 Ops[2] = getValue(I.getArgOperand(1)); 6589 Ops[3] = getValue(I.getArgOperand(2)); 6590 Ops[4] = getValue(I.getArgOperand(3)); 6591 SDValue Result = DAG.getMemIntrinsicNode( 6592 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 6593 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 6594 /* align */ None, Flags); 6595 6596 // Chain the prefetch in parallell with any pending loads, to stay out of 6597 // the way of later optimizations. 6598 PendingLoads.push_back(Result); 6599 Result = getRoot(); 6600 DAG.setRoot(Result); 6601 return; 6602 } 6603 case Intrinsic::lifetime_start: 6604 case Intrinsic::lifetime_end: { 6605 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6606 // Stack coloring is not enabled in O0, discard region information. 6607 if (TM.getOptLevel() == CodeGenOpt::None) 6608 return; 6609 6610 const int64_t ObjectSize = 6611 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6612 Value *const ObjectPtr = I.getArgOperand(1); 6613 SmallVector<const Value *, 4> Allocas; 6614 GetUnderlyingObjects(ObjectPtr, Allocas, *DL); 6615 6616 for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(), 6617 E = Allocas.end(); Object != E; ++Object) { 6618 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 6619 6620 // Could not find an Alloca. 6621 if (!LifetimeObject) 6622 continue; 6623 6624 // First check that the Alloca is static, otherwise it won't have a 6625 // valid frame index. 6626 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6627 if (SI == FuncInfo.StaticAllocaMap.end()) 6628 return; 6629 6630 const int FrameIndex = SI->second; 6631 int64_t Offset; 6632 if (GetPointerBaseWithConstantOffset( 6633 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6634 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6635 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6636 Offset); 6637 DAG.setRoot(Res); 6638 } 6639 return; 6640 } 6641 case Intrinsic::invariant_start: 6642 // Discard region information. 6643 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6644 return; 6645 case Intrinsic::invariant_end: 6646 // Discard region information. 6647 return; 6648 case Intrinsic::clear_cache: 6649 /// FunctionName may be null. 6650 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6651 lowerCallToExternalSymbol(I, FunctionName); 6652 return; 6653 case Intrinsic::donothing: 6654 // ignore 6655 return; 6656 case Intrinsic::experimental_stackmap: 6657 visitStackmap(I); 6658 return; 6659 case Intrinsic::experimental_patchpoint_void: 6660 case Intrinsic::experimental_patchpoint_i64: 6661 visitPatchpoint(I); 6662 return; 6663 case Intrinsic::experimental_gc_statepoint: 6664 LowerStatepoint(cast<GCStatepointInst>(I)); 6665 return; 6666 case Intrinsic::experimental_gc_result: 6667 visitGCResult(cast<GCResultInst>(I)); 6668 return; 6669 case Intrinsic::experimental_gc_relocate: 6670 visitGCRelocate(cast<GCRelocateInst>(I)); 6671 return; 6672 case Intrinsic::instrprof_increment: 6673 llvm_unreachable("instrprof failed to lower an increment"); 6674 case Intrinsic::instrprof_value_profile: 6675 llvm_unreachable("instrprof failed to lower a value profiling call"); 6676 case Intrinsic::localescape: { 6677 MachineFunction &MF = DAG.getMachineFunction(); 6678 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6679 6680 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6681 // is the same on all targets. 6682 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6683 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6684 if (isa<ConstantPointerNull>(Arg)) 6685 continue; // Skip null pointers. They represent a hole in index space. 6686 AllocaInst *Slot = cast<AllocaInst>(Arg); 6687 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6688 "can only escape static allocas"); 6689 int FI = FuncInfo.StaticAllocaMap[Slot]; 6690 MCSymbol *FrameAllocSym = 6691 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6692 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6693 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6694 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6695 .addSym(FrameAllocSym) 6696 .addFrameIndex(FI); 6697 } 6698 6699 return; 6700 } 6701 6702 case Intrinsic::localrecover: { 6703 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6704 MachineFunction &MF = DAG.getMachineFunction(); 6705 6706 // Get the symbol that defines the frame offset. 6707 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6708 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6709 unsigned IdxVal = 6710 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6711 MCSymbol *FrameAllocSym = 6712 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6713 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6714 6715 Value *FP = I.getArgOperand(1); 6716 SDValue FPVal = getValue(FP); 6717 EVT PtrVT = FPVal.getValueType(); 6718 6719 // Create a MCSymbol for the label to avoid any target lowering 6720 // that would make this PC relative. 6721 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6722 SDValue OffsetVal = 6723 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6724 6725 // Add the offset to the FP. 6726 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 6727 setValue(&I, Add); 6728 6729 return; 6730 } 6731 6732 case Intrinsic::eh_exceptionpointer: 6733 case Intrinsic::eh_exceptioncode: { 6734 // Get the exception pointer vreg, copy from it, and resize it to fit. 6735 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6736 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6737 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6738 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6739 SDValue N = 6740 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6741 if (Intrinsic == Intrinsic::eh_exceptioncode) 6742 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6743 setValue(&I, N); 6744 return; 6745 } 6746 case Intrinsic::xray_customevent: { 6747 // Here we want to make sure that the intrinsic behaves as if it has a 6748 // specific calling convention, and only for x86_64. 6749 // FIXME: Support other platforms later. 6750 const auto &Triple = DAG.getTarget().getTargetTriple(); 6751 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6752 return; 6753 6754 SDLoc DL = getCurSDLoc(); 6755 SmallVector<SDValue, 8> Ops; 6756 6757 // We want to say that we always want the arguments in registers. 6758 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6759 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6760 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6761 SDValue Chain = getRoot(); 6762 Ops.push_back(LogEntryVal); 6763 Ops.push_back(StrSizeVal); 6764 Ops.push_back(Chain); 6765 6766 // We need to enforce the calling convention for the callsite, so that 6767 // argument ordering is enforced correctly, and that register allocation can 6768 // see that some registers may be assumed clobbered and have to preserve 6769 // them across calls to the intrinsic. 6770 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6771 DL, NodeTys, Ops); 6772 SDValue patchableNode = SDValue(MN, 0); 6773 DAG.setRoot(patchableNode); 6774 setValue(&I, patchableNode); 6775 return; 6776 } 6777 case Intrinsic::xray_typedevent: { 6778 // Here we want to make sure that the intrinsic behaves as if it has a 6779 // specific calling convention, and only for x86_64. 6780 // FIXME: Support other platforms later. 6781 const auto &Triple = DAG.getTarget().getTargetTriple(); 6782 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6783 return; 6784 6785 SDLoc DL = getCurSDLoc(); 6786 SmallVector<SDValue, 8> Ops; 6787 6788 // We want to say that we always want the arguments in registers. 6789 // It's unclear to me how manipulating the selection DAG here forces callers 6790 // to provide arguments in registers instead of on the stack. 6791 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6792 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6793 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6794 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6795 SDValue Chain = getRoot(); 6796 Ops.push_back(LogTypeId); 6797 Ops.push_back(LogEntryVal); 6798 Ops.push_back(StrSizeVal); 6799 Ops.push_back(Chain); 6800 6801 // We need to enforce the calling convention for the callsite, so that 6802 // argument ordering is enforced correctly, and that register allocation can 6803 // see that some registers may be assumed clobbered and have to preserve 6804 // them across calls to the intrinsic. 6805 MachineSDNode *MN = DAG.getMachineNode( 6806 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6807 SDValue patchableNode = SDValue(MN, 0); 6808 DAG.setRoot(patchableNode); 6809 setValue(&I, patchableNode); 6810 return; 6811 } 6812 case Intrinsic::experimental_deoptimize: 6813 LowerDeoptimizeCall(&I); 6814 return; 6815 6816 case Intrinsic::experimental_vector_reduce_v2_fadd: 6817 case Intrinsic::experimental_vector_reduce_v2_fmul: 6818 case Intrinsic::experimental_vector_reduce_add: 6819 case Intrinsic::experimental_vector_reduce_mul: 6820 case Intrinsic::experimental_vector_reduce_and: 6821 case Intrinsic::experimental_vector_reduce_or: 6822 case Intrinsic::experimental_vector_reduce_xor: 6823 case Intrinsic::experimental_vector_reduce_smax: 6824 case Intrinsic::experimental_vector_reduce_smin: 6825 case Intrinsic::experimental_vector_reduce_umax: 6826 case Intrinsic::experimental_vector_reduce_umin: 6827 case Intrinsic::experimental_vector_reduce_fmax: 6828 case Intrinsic::experimental_vector_reduce_fmin: 6829 visitVectorReduce(I, Intrinsic); 6830 return; 6831 6832 case Intrinsic::icall_branch_funnel: { 6833 SmallVector<SDValue, 16> Ops; 6834 Ops.push_back(getValue(I.getArgOperand(0))); 6835 6836 int64_t Offset; 6837 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6838 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6839 if (!Base) 6840 report_fatal_error( 6841 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6842 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6843 6844 struct BranchFunnelTarget { 6845 int64_t Offset; 6846 SDValue Target; 6847 }; 6848 SmallVector<BranchFunnelTarget, 8> Targets; 6849 6850 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6851 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6852 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6853 if (ElemBase != Base) 6854 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6855 "to the same GlobalValue"); 6856 6857 SDValue Val = getValue(I.getArgOperand(Op + 1)); 6858 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 6859 if (!GA) 6860 report_fatal_error( 6861 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6862 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 6863 GA->getGlobal(), getCurSDLoc(), 6864 Val.getValueType(), GA->getOffset())}); 6865 } 6866 llvm::sort(Targets, 6867 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 6868 return T1.Offset < T2.Offset; 6869 }); 6870 6871 for (auto &T : Targets) { 6872 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 6873 Ops.push_back(T.Target); 6874 } 6875 6876 Ops.push_back(DAG.getRoot()); // Chain 6877 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 6878 getCurSDLoc(), MVT::Other, Ops), 6879 0); 6880 DAG.setRoot(N); 6881 setValue(&I, N); 6882 HasTailCall = true; 6883 return; 6884 } 6885 6886 case Intrinsic::wasm_landingpad_index: 6887 // Information this intrinsic contained has been transferred to 6888 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 6889 // delete it now. 6890 return; 6891 6892 case Intrinsic::aarch64_settag: 6893 case Intrinsic::aarch64_settag_zero: { 6894 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6895 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 6896 SDValue Val = TSI.EmitTargetCodeForSetTag( 6897 DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)), 6898 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 6899 ZeroMemory); 6900 DAG.setRoot(Val); 6901 setValue(&I, Val); 6902 return; 6903 } 6904 case Intrinsic::ptrmask: { 6905 SDValue Ptr = getValue(I.getOperand(0)); 6906 SDValue Const = getValue(I.getOperand(1)); 6907 6908 EVT PtrVT = Ptr.getValueType(); 6909 setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), PtrVT, Ptr, 6910 DAG.getZExtOrTrunc(Const, getCurSDLoc(), PtrVT))); 6911 return; 6912 } 6913 case Intrinsic::get_active_lane_mask: { 6914 auto DL = getCurSDLoc(); 6915 SDValue Index = getValue(I.getOperand(0)); 6916 SDValue BTC = getValue(I.getOperand(1)); 6917 Type *ElementTy = I.getOperand(0)->getType(); 6918 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6919 unsigned VecWidth = VT.getVectorNumElements(); 6920 6921 SmallVector<SDValue, 16> OpsBTC; 6922 SmallVector<SDValue, 16> OpsIndex; 6923 SmallVector<SDValue, 16> OpsStepConstants; 6924 for (unsigned i = 0; i < VecWidth; i++) { 6925 OpsBTC.push_back(BTC); 6926 OpsIndex.push_back(Index); 6927 OpsStepConstants.push_back(DAG.getConstant(i, DL, MVT::getVT(ElementTy))); 6928 } 6929 6930 EVT CCVT = MVT::i1; 6931 CCVT = EVT::getVectorVT(I.getContext(), CCVT, VecWidth); 6932 6933 auto VecTy = MVT::getVT(FixedVectorType::get(ElementTy, VecWidth)); 6934 SDValue VectorIndex = DAG.getBuildVector(VecTy, DL, OpsIndex); 6935 SDValue VectorStep = DAG.getBuildVector(VecTy, DL, OpsStepConstants); 6936 SDValue VectorInduction = DAG.getNode( 6937 ISD::UADDO, DL, DAG.getVTList(VecTy, CCVT), VectorIndex, VectorStep); 6938 SDValue VectorBTC = DAG.getBuildVector(VecTy, DL, OpsBTC); 6939 SDValue SetCC = DAG.getSetCC(DL, CCVT, VectorInduction.getValue(0), 6940 VectorBTC, ISD::CondCode::SETULE); 6941 setValue(&I, DAG.getNode(ISD::AND, DL, CCVT, 6942 DAG.getNOT(DL, VectorInduction.getValue(1), CCVT), 6943 SetCC)); 6944 return; 6945 } 6946 } 6947 } 6948 6949 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 6950 const ConstrainedFPIntrinsic &FPI) { 6951 SDLoc sdl = getCurSDLoc(); 6952 6953 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6954 SmallVector<EVT, 4> ValueVTs; 6955 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 6956 ValueVTs.push_back(MVT::Other); // Out chain 6957 6958 // We do not need to serialize constrained FP intrinsics against 6959 // each other or against (nonvolatile) loads, so they can be 6960 // chained like loads. 6961 SDValue Chain = DAG.getRoot(); 6962 SmallVector<SDValue, 4> Opers; 6963 Opers.push_back(Chain); 6964 if (FPI.isUnaryOp()) { 6965 Opers.push_back(getValue(FPI.getArgOperand(0))); 6966 } else if (FPI.isTernaryOp()) { 6967 Opers.push_back(getValue(FPI.getArgOperand(0))); 6968 Opers.push_back(getValue(FPI.getArgOperand(1))); 6969 Opers.push_back(getValue(FPI.getArgOperand(2))); 6970 } else { 6971 Opers.push_back(getValue(FPI.getArgOperand(0))); 6972 Opers.push_back(getValue(FPI.getArgOperand(1))); 6973 } 6974 6975 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 6976 assert(Result.getNode()->getNumValues() == 2); 6977 6978 // Push node to the appropriate list so that future instructions can be 6979 // chained up correctly. 6980 SDValue OutChain = Result.getValue(1); 6981 switch (EB) { 6982 case fp::ExceptionBehavior::ebIgnore: 6983 // The only reason why ebIgnore nodes still need to be chained is that 6984 // they might depend on the current rounding mode, and therefore must 6985 // not be moved across instruction that may change that mode. 6986 LLVM_FALLTHROUGH; 6987 case fp::ExceptionBehavior::ebMayTrap: 6988 // These must not be moved across calls or instructions that may change 6989 // floating-point exception masks. 6990 PendingConstrainedFP.push_back(OutChain); 6991 break; 6992 case fp::ExceptionBehavior::ebStrict: 6993 // These must not be moved across calls or instructions that may change 6994 // floating-point exception masks or read floating-point exception flags. 6995 // In addition, they cannot be optimized out even if unused. 6996 PendingConstrainedFPStrict.push_back(OutChain); 6997 break; 6998 } 6999 }; 7000 7001 SDVTList VTs = DAG.getVTList(ValueVTs); 7002 fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue(); 7003 7004 SDNodeFlags Flags; 7005 if (EB == fp::ExceptionBehavior::ebIgnore) 7006 Flags.setNoFPExcept(true); 7007 7008 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7009 Flags.copyFMF(*FPOp); 7010 7011 unsigned Opcode; 7012 switch (FPI.getIntrinsicID()) { 7013 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7014 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7015 case Intrinsic::INTRINSIC: \ 7016 Opcode = ISD::STRICT_##DAGN; \ 7017 break; 7018 #include "llvm/IR/ConstrainedOps.def" 7019 case Intrinsic::experimental_constrained_fmuladd: { 7020 Opcode = ISD::STRICT_FMA; 7021 // Break fmuladd into fmul and fadd. 7022 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7023 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), 7024 ValueVTs[0])) { 7025 Opers.pop_back(); 7026 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7027 pushOutChain(Mul, EB); 7028 Opcode = ISD::STRICT_FADD; 7029 Opers.clear(); 7030 Opers.push_back(Mul.getValue(1)); 7031 Opers.push_back(Mul.getValue(0)); 7032 Opers.push_back(getValue(FPI.getArgOperand(2))); 7033 } 7034 break; 7035 } 7036 } 7037 7038 // A few strict DAG nodes carry additional operands that are not 7039 // set up by the default code above. 7040 switch (Opcode) { 7041 default: break; 7042 case ISD::STRICT_FP_ROUND: 7043 Opers.push_back( 7044 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7045 break; 7046 case ISD::STRICT_FSETCC: 7047 case ISD::STRICT_FSETCCS: { 7048 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7049 Opers.push_back(DAG.getCondCode(getFCmpCondCode(FPCmp->getPredicate()))); 7050 break; 7051 } 7052 } 7053 7054 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7055 pushOutChain(Result, EB); 7056 7057 SDValue FPResult = Result.getValue(0); 7058 setValue(&FPI, FPResult); 7059 } 7060 7061 std::pair<SDValue, SDValue> 7062 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7063 const BasicBlock *EHPadBB) { 7064 MachineFunction &MF = DAG.getMachineFunction(); 7065 MachineModuleInfo &MMI = MF.getMMI(); 7066 MCSymbol *BeginLabel = nullptr; 7067 7068 if (EHPadBB) { 7069 // Insert a label before the invoke call to mark the try range. This can be 7070 // used to detect deletion of the invoke via the MachineModuleInfo. 7071 BeginLabel = MMI.getContext().createTempSymbol(); 7072 7073 // For SjLj, keep track of which landing pads go with which invokes 7074 // so as to maintain the ordering of pads in the LSDA. 7075 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7076 if (CallSiteIndex) { 7077 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7078 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7079 7080 // Now that the call site is handled, stop tracking it. 7081 MMI.setCurrentCallSite(0); 7082 } 7083 7084 // Both PendingLoads and PendingExports must be flushed here; 7085 // this call might not return. 7086 (void)getRoot(); 7087 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 7088 7089 CLI.setChain(getRoot()); 7090 } 7091 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7092 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7093 7094 assert((CLI.IsTailCall || Result.second.getNode()) && 7095 "Non-null chain expected with non-tail call!"); 7096 assert((Result.second.getNode() || !Result.first.getNode()) && 7097 "Null value expected with tail call!"); 7098 7099 if (!Result.second.getNode()) { 7100 // As a special case, a null chain means that a tail call has been emitted 7101 // and the DAG root is already updated. 7102 HasTailCall = true; 7103 7104 // Since there's no actual continuation from this block, nothing can be 7105 // relying on us setting vregs for them. 7106 PendingExports.clear(); 7107 } else { 7108 DAG.setRoot(Result.second); 7109 } 7110 7111 if (EHPadBB) { 7112 // Insert a label at the end of the invoke call to mark the try range. This 7113 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7114 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7115 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 7116 7117 // Inform MachineModuleInfo of range. 7118 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7119 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7120 // actually use outlined funclets and their LSDA info style. 7121 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7122 assert(CLI.CB); 7123 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 7124 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CB), BeginLabel, EndLabel); 7125 } else if (!isScopedEHPersonality(Pers)) { 7126 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7127 } 7128 } 7129 7130 return Result; 7131 } 7132 7133 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 7134 bool isTailCall, 7135 const BasicBlock *EHPadBB) { 7136 auto &DL = DAG.getDataLayout(); 7137 FunctionType *FTy = CB.getFunctionType(); 7138 Type *RetTy = CB.getType(); 7139 7140 TargetLowering::ArgListTy Args; 7141 Args.reserve(CB.arg_size()); 7142 7143 const Value *SwiftErrorVal = nullptr; 7144 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7145 7146 if (isTailCall) { 7147 // Avoid emitting tail calls in functions with the disable-tail-calls 7148 // attribute. 7149 auto *Caller = CB.getParent()->getParent(); 7150 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7151 "true") 7152 isTailCall = false; 7153 7154 // We can't tail call inside a function with a swifterror argument. Lowering 7155 // does not support this yet. It would have to move into the swifterror 7156 // register before the call. 7157 if (TLI.supportSwiftError() && 7158 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7159 isTailCall = false; 7160 } 7161 7162 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 7163 TargetLowering::ArgListEntry Entry; 7164 const Value *V = *I; 7165 7166 // Skip empty types 7167 if (V->getType()->isEmptyTy()) 7168 continue; 7169 7170 SDValue ArgNode = getValue(V); 7171 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7172 7173 Entry.setAttributes(&CB, I - CB.arg_begin()); 7174 7175 // Use swifterror virtual register as input to the call. 7176 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7177 SwiftErrorVal = V; 7178 // We find the virtual register for the actual swifterror argument. 7179 // Instead of using the Value, we use the virtual register instead. 7180 Entry.Node = 7181 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 7182 EVT(TLI.getPointerTy(DL))); 7183 } 7184 7185 Args.push_back(Entry); 7186 7187 // If we have an explicit sret argument that is an Instruction, (i.e., it 7188 // might point to function-local memory), we can't meaningfully tail-call. 7189 if (Entry.IsSRet && isa<Instruction>(V)) 7190 isTailCall = false; 7191 } 7192 7193 // If call site has a cfguardtarget operand bundle, create and add an 7194 // additional ArgListEntry. 7195 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7196 TargetLowering::ArgListEntry Entry; 7197 Value *V = Bundle->Inputs[0]; 7198 SDValue ArgNode = getValue(V); 7199 Entry.Node = ArgNode; 7200 Entry.Ty = V->getType(); 7201 Entry.IsCFGuardTarget = true; 7202 Args.push_back(Entry); 7203 } 7204 7205 // Check if target-independent constraints permit a tail call here. 7206 // Target-dependent constraints are checked within TLI->LowerCallTo. 7207 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 7208 isTailCall = false; 7209 7210 // Disable tail calls if there is an swifterror argument. Targets have not 7211 // been updated to support tail calls. 7212 if (TLI.supportSwiftError() && SwiftErrorVal) 7213 isTailCall = false; 7214 7215 TargetLowering::CallLoweringInfo CLI(DAG); 7216 CLI.setDebugLoc(getCurSDLoc()) 7217 .setChain(getRoot()) 7218 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 7219 .setTailCall(isTailCall) 7220 .setConvergent(CB.isConvergent()) 7221 .setIsPreallocated( 7222 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 7223 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7224 7225 if (Result.first.getNode()) { 7226 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 7227 setValue(&CB, Result.first); 7228 } 7229 7230 // The last element of CLI.InVals has the SDValue for swifterror return. 7231 // Here we copy it to a virtual register and update SwiftErrorMap for 7232 // book-keeping. 7233 if (SwiftErrorVal && TLI.supportSwiftError()) { 7234 // Get the last element of InVals. 7235 SDValue Src = CLI.InVals.back(); 7236 Register VReg = 7237 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 7238 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7239 DAG.setRoot(CopyNode); 7240 } 7241 } 7242 7243 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7244 SelectionDAGBuilder &Builder) { 7245 // Check to see if this load can be trivially constant folded, e.g. if the 7246 // input is from a string literal. 7247 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7248 // Cast pointer to the type we really want to load. 7249 Type *LoadTy = 7250 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7251 if (LoadVT.isVector()) 7252 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7253 7254 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7255 PointerType::getUnqual(LoadTy)); 7256 7257 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 7258 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 7259 return Builder.getValue(LoadCst); 7260 } 7261 7262 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7263 // still constant memory, the input chain can be the entry node. 7264 SDValue Root; 7265 bool ConstantMemory = false; 7266 7267 // Do not serialize (non-volatile) loads of constant memory with anything. 7268 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7269 Root = Builder.DAG.getEntryNode(); 7270 ConstantMemory = true; 7271 } else { 7272 // Do not serialize non-volatile loads against each other. 7273 Root = Builder.DAG.getRoot(); 7274 } 7275 7276 SDValue Ptr = Builder.getValue(PtrVal); 7277 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, 7278 Ptr, MachinePointerInfo(PtrVal), 7279 /* Alignment = */ 1); 7280 7281 if (!ConstantMemory) 7282 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7283 return LoadVal; 7284 } 7285 7286 /// Record the value for an instruction that produces an integer result, 7287 /// converting the type where necessary. 7288 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7289 SDValue Value, 7290 bool IsSigned) { 7291 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7292 I.getType(), true); 7293 if (IsSigned) 7294 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7295 else 7296 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7297 setValue(&I, Value); 7298 } 7299 7300 /// See if we can lower a memcmp call into an optimized form. If so, return 7301 /// true and lower it. Otherwise return false, and it will be lowered like a 7302 /// normal call. 7303 /// The caller already checked that \p I calls the appropriate LibFunc with a 7304 /// correct prototype. 7305 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 7306 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 7307 const Value *Size = I.getArgOperand(2); 7308 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 7309 if (CSize && CSize->getZExtValue() == 0) { 7310 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7311 I.getType(), true); 7312 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 7313 return true; 7314 } 7315 7316 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7317 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 7318 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 7319 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 7320 if (Res.first.getNode()) { 7321 processIntegerCallValue(I, Res.first, true); 7322 PendingLoads.push_back(Res.second); 7323 return true; 7324 } 7325 7326 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 7327 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 7328 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 7329 return false; 7330 7331 // If the target has a fast compare for the given size, it will return a 7332 // preferred load type for that size. Require that the load VT is legal and 7333 // that the target supports unaligned loads of that type. Otherwise, return 7334 // INVALID. 7335 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 7336 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7337 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 7338 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 7339 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 7340 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 7341 // TODO: Check alignment of src and dest ptrs. 7342 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 7343 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 7344 if (!TLI.isTypeLegal(LVT) || 7345 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 7346 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 7347 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 7348 } 7349 7350 return LVT; 7351 }; 7352 7353 // This turns into unaligned loads. We only do this if the target natively 7354 // supports the MVT we'll be loading or if it is small enough (<= 4) that 7355 // we'll only produce a small number of byte loads. 7356 MVT LoadVT; 7357 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 7358 switch (NumBitsToCompare) { 7359 default: 7360 return false; 7361 case 16: 7362 LoadVT = MVT::i16; 7363 break; 7364 case 32: 7365 LoadVT = MVT::i32; 7366 break; 7367 case 64: 7368 case 128: 7369 case 256: 7370 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 7371 break; 7372 } 7373 7374 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 7375 return false; 7376 7377 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 7378 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 7379 7380 // Bitcast to a wide integer type if the loads are vectors. 7381 if (LoadVT.isVector()) { 7382 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 7383 LoadL = DAG.getBitcast(CmpVT, LoadL); 7384 LoadR = DAG.getBitcast(CmpVT, LoadR); 7385 } 7386 7387 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 7388 processIntegerCallValue(I, Cmp, false); 7389 return true; 7390 } 7391 7392 /// See if we can lower a memchr call into an optimized form. If so, return 7393 /// true and lower it. Otherwise return false, and it will be lowered like a 7394 /// normal call. 7395 /// The caller already checked that \p I calls the appropriate LibFunc with a 7396 /// correct prototype. 7397 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 7398 const Value *Src = I.getArgOperand(0); 7399 const Value *Char = I.getArgOperand(1); 7400 const Value *Length = I.getArgOperand(2); 7401 7402 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7403 std::pair<SDValue, SDValue> Res = 7404 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 7405 getValue(Src), getValue(Char), getValue(Length), 7406 MachinePointerInfo(Src)); 7407 if (Res.first.getNode()) { 7408 setValue(&I, Res.first); 7409 PendingLoads.push_back(Res.second); 7410 return true; 7411 } 7412 7413 return false; 7414 } 7415 7416 /// See if we can lower a mempcpy call into an optimized form. If so, return 7417 /// true and lower it. Otherwise return false, and it will be lowered like a 7418 /// normal call. 7419 /// The caller already checked that \p I calls the appropriate LibFunc with a 7420 /// correct prototype. 7421 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 7422 SDValue Dst = getValue(I.getArgOperand(0)); 7423 SDValue Src = getValue(I.getArgOperand(1)); 7424 SDValue Size = getValue(I.getArgOperand(2)); 7425 7426 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 7427 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 7428 // DAG::getMemcpy needs Alignment to be defined. 7429 Align Alignment = std::min(DstAlign, SrcAlign); 7430 7431 bool isVol = false; 7432 SDLoc sdl = getCurSDLoc(); 7433 7434 // In the mempcpy context we need to pass in a false value for isTailCall 7435 // because the return pointer needs to be adjusted by the size of 7436 // the copied memory. 7437 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 7438 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false, 7439 /*isTailCall=*/false, 7440 MachinePointerInfo(I.getArgOperand(0)), 7441 MachinePointerInfo(I.getArgOperand(1))); 7442 assert(MC.getNode() != nullptr && 7443 "** memcpy should not be lowered as TailCall in mempcpy context **"); 7444 DAG.setRoot(MC); 7445 7446 // Check if Size needs to be truncated or extended. 7447 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 7448 7449 // Adjust return pointer to point just past the last dst byte. 7450 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 7451 Dst, Size); 7452 setValue(&I, DstPlusSize); 7453 return true; 7454 } 7455 7456 /// See if we can lower a strcpy call into an optimized form. If so, return 7457 /// true and lower it, otherwise return false and it will be lowered like a 7458 /// normal call. 7459 /// The caller already checked that \p I calls the appropriate LibFunc with a 7460 /// correct prototype. 7461 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 7462 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7463 7464 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7465 std::pair<SDValue, SDValue> Res = 7466 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 7467 getValue(Arg0), getValue(Arg1), 7468 MachinePointerInfo(Arg0), 7469 MachinePointerInfo(Arg1), isStpcpy); 7470 if (Res.first.getNode()) { 7471 setValue(&I, Res.first); 7472 DAG.setRoot(Res.second); 7473 return true; 7474 } 7475 7476 return false; 7477 } 7478 7479 /// See if we can lower a strcmp call into an optimized form. If so, return 7480 /// true and lower it, otherwise return false and it will be lowered like a 7481 /// normal call. 7482 /// The caller already checked that \p I calls the appropriate LibFunc with a 7483 /// correct prototype. 7484 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 7485 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7486 7487 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7488 std::pair<SDValue, SDValue> Res = 7489 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 7490 getValue(Arg0), getValue(Arg1), 7491 MachinePointerInfo(Arg0), 7492 MachinePointerInfo(Arg1)); 7493 if (Res.first.getNode()) { 7494 processIntegerCallValue(I, Res.first, true); 7495 PendingLoads.push_back(Res.second); 7496 return true; 7497 } 7498 7499 return false; 7500 } 7501 7502 /// See if we can lower a strlen call into an optimized form. If so, return 7503 /// true and lower it, otherwise return false and it will be lowered like a 7504 /// normal call. 7505 /// The caller already checked that \p I calls the appropriate LibFunc with a 7506 /// correct prototype. 7507 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 7508 const Value *Arg0 = I.getArgOperand(0); 7509 7510 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7511 std::pair<SDValue, SDValue> Res = 7512 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 7513 getValue(Arg0), MachinePointerInfo(Arg0)); 7514 if (Res.first.getNode()) { 7515 processIntegerCallValue(I, Res.first, false); 7516 PendingLoads.push_back(Res.second); 7517 return true; 7518 } 7519 7520 return false; 7521 } 7522 7523 /// See if we can lower a strnlen 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::visitStrNLenCall(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.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 7534 getValue(Arg0), getValue(Arg1), 7535 MachinePointerInfo(Arg0)); 7536 if (Res.first.getNode()) { 7537 processIntegerCallValue(I, Res.first, false); 7538 PendingLoads.push_back(Res.second); 7539 return true; 7540 } 7541 7542 return false; 7543 } 7544 7545 /// See if we can lower a unary floating-point operation into an SDNode with 7546 /// the specified Opcode. If so, return true and lower it, otherwise return 7547 /// false and it will be lowered like a normal call. 7548 /// The caller already checked that \p I calls the appropriate LibFunc with a 7549 /// correct prototype. 7550 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 7551 unsigned Opcode) { 7552 // We already checked this call's prototype; verify it doesn't modify errno. 7553 if (!I.onlyReadsMemory()) 7554 return false; 7555 7556 SDValue Tmp = getValue(I.getArgOperand(0)); 7557 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); 7558 return true; 7559 } 7560 7561 /// See if we can lower a binary floating-point operation into an SDNode with 7562 /// the specified Opcode. If so, return true and lower it. Otherwise return 7563 /// false, and it will be lowered like a normal call. 7564 /// The caller already checked that \p I calls the appropriate LibFunc with a 7565 /// correct prototype. 7566 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 7567 unsigned Opcode) { 7568 // We already checked this call's prototype; verify it doesn't modify errno. 7569 if (!I.onlyReadsMemory()) 7570 return false; 7571 7572 SDValue Tmp0 = getValue(I.getArgOperand(0)); 7573 SDValue Tmp1 = getValue(I.getArgOperand(1)); 7574 EVT VT = Tmp0.getValueType(); 7575 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1)); 7576 return true; 7577 } 7578 7579 void SelectionDAGBuilder::visitCall(const CallInst &I) { 7580 // Handle inline assembly differently. 7581 if (I.isInlineAsm()) { 7582 visitInlineAsm(I); 7583 return; 7584 } 7585 7586 if (Function *F = I.getCalledFunction()) { 7587 if (F->isDeclaration()) { 7588 // Is this an LLVM intrinsic or a target-specific intrinsic? 7589 unsigned IID = F->getIntrinsicID(); 7590 if (!IID) 7591 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7592 IID = II->getIntrinsicID(F); 7593 7594 if (IID) { 7595 visitIntrinsicCall(I, IID); 7596 return; 7597 } 7598 } 7599 7600 // Check for well-known libc/libm calls. If the function is internal, it 7601 // can't be a library call. Don't do the check if marked as nobuiltin for 7602 // some reason or the call site requires strict floating point semantics. 7603 LibFunc Func; 7604 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7605 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7606 LibInfo->hasOptimizedCodeGen(Func)) { 7607 switch (Func) { 7608 default: break; 7609 case LibFunc_copysign: 7610 case LibFunc_copysignf: 7611 case LibFunc_copysignl: 7612 // We already checked this call's prototype; verify it doesn't modify 7613 // errno. 7614 if (I.onlyReadsMemory()) { 7615 SDValue LHS = getValue(I.getArgOperand(0)); 7616 SDValue RHS = getValue(I.getArgOperand(1)); 7617 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7618 LHS.getValueType(), LHS, RHS)); 7619 return; 7620 } 7621 break; 7622 case LibFunc_fabs: 7623 case LibFunc_fabsf: 7624 case LibFunc_fabsl: 7625 if (visitUnaryFloatCall(I, ISD::FABS)) 7626 return; 7627 break; 7628 case LibFunc_fmin: 7629 case LibFunc_fminf: 7630 case LibFunc_fminl: 7631 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7632 return; 7633 break; 7634 case LibFunc_fmax: 7635 case LibFunc_fmaxf: 7636 case LibFunc_fmaxl: 7637 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7638 return; 7639 break; 7640 case LibFunc_sin: 7641 case LibFunc_sinf: 7642 case LibFunc_sinl: 7643 if (visitUnaryFloatCall(I, ISD::FSIN)) 7644 return; 7645 break; 7646 case LibFunc_cos: 7647 case LibFunc_cosf: 7648 case LibFunc_cosl: 7649 if (visitUnaryFloatCall(I, ISD::FCOS)) 7650 return; 7651 break; 7652 case LibFunc_sqrt: 7653 case LibFunc_sqrtf: 7654 case LibFunc_sqrtl: 7655 case LibFunc_sqrt_finite: 7656 case LibFunc_sqrtf_finite: 7657 case LibFunc_sqrtl_finite: 7658 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7659 return; 7660 break; 7661 case LibFunc_floor: 7662 case LibFunc_floorf: 7663 case LibFunc_floorl: 7664 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7665 return; 7666 break; 7667 case LibFunc_nearbyint: 7668 case LibFunc_nearbyintf: 7669 case LibFunc_nearbyintl: 7670 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7671 return; 7672 break; 7673 case LibFunc_ceil: 7674 case LibFunc_ceilf: 7675 case LibFunc_ceill: 7676 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7677 return; 7678 break; 7679 case LibFunc_rint: 7680 case LibFunc_rintf: 7681 case LibFunc_rintl: 7682 if (visitUnaryFloatCall(I, ISD::FRINT)) 7683 return; 7684 break; 7685 case LibFunc_round: 7686 case LibFunc_roundf: 7687 case LibFunc_roundl: 7688 if (visitUnaryFloatCall(I, ISD::FROUND)) 7689 return; 7690 break; 7691 case LibFunc_trunc: 7692 case LibFunc_truncf: 7693 case LibFunc_truncl: 7694 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7695 return; 7696 break; 7697 case LibFunc_log2: 7698 case LibFunc_log2f: 7699 case LibFunc_log2l: 7700 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7701 return; 7702 break; 7703 case LibFunc_exp2: 7704 case LibFunc_exp2f: 7705 case LibFunc_exp2l: 7706 if (visitUnaryFloatCall(I, ISD::FEXP2)) 7707 return; 7708 break; 7709 case LibFunc_memcmp: 7710 if (visitMemCmpCall(I)) 7711 return; 7712 break; 7713 case LibFunc_mempcpy: 7714 if (visitMemPCpyCall(I)) 7715 return; 7716 break; 7717 case LibFunc_memchr: 7718 if (visitMemChrCall(I)) 7719 return; 7720 break; 7721 case LibFunc_strcpy: 7722 if (visitStrCpyCall(I, false)) 7723 return; 7724 break; 7725 case LibFunc_stpcpy: 7726 if (visitStrCpyCall(I, true)) 7727 return; 7728 break; 7729 case LibFunc_strcmp: 7730 if (visitStrCmpCall(I)) 7731 return; 7732 break; 7733 case LibFunc_strlen: 7734 if (visitStrLenCall(I)) 7735 return; 7736 break; 7737 case LibFunc_strnlen: 7738 if (visitStrNLenCall(I)) 7739 return; 7740 break; 7741 } 7742 } 7743 } 7744 7745 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 7746 // have to do anything here to lower funclet bundles. 7747 // CFGuardTarget bundles are lowered in LowerCallTo. 7748 assert(!I.hasOperandBundlesOtherThan( 7749 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 7750 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated}) && 7751 "Cannot lower calls with arbitrary operand bundles!"); 7752 7753 SDValue Callee = getValue(I.getCalledOperand()); 7754 7755 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 7756 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 7757 else 7758 // Check if we can potentially perform a tail call. More detailed checking 7759 // is be done within LowerCallTo, after more information about the call is 7760 // known. 7761 LowerCallTo(I, Callee, I.isTailCall()); 7762 } 7763 7764 namespace { 7765 7766 /// AsmOperandInfo - This contains information for each constraint that we are 7767 /// lowering. 7768 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 7769 public: 7770 /// CallOperand - If this is the result output operand or a clobber 7771 /// this is null, otherwise it is the incoming operand to the CallInst. 7772 /// This gets modified as the asm is processed. 7773 SDValue CallOperand; 7774 7775 /// AssignedRegs - If this is a register or register class operand, this 7776 /// contains the set of register corresponding to the operand. 7777 RegsForValue AssignedRegs; 7778 7779 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 7780 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 7781 } 7782 7783 /// Whether or not this operand accesses memory 7784 bool hasMemory(const TargetLowering &TLI) const { 7785 // Indirect operand accesses access memory. 7786 if (isIndirect) 7787 return true; 7788 7789 for (const auto &Code : Codes) 7790 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 7791 return true; 7792 7793 return false; 7794 } 7795 7796 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 7797 /// corresponds to. If there is no Value* for this operand, it returns 7798 /// MVT::Other. 7799 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 7800 const DataLayout &DL) const { 7801 if (!CallOperandVal) return MVT::Other; 7802 7803 if (isa<BasicBlock>(CallOperandVal)) 7804 return TLI.getProgramPointerTy(DL); 7805 7806 llvm::Type *OpTy = CallOperandVal->getType(); 7807 7808 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 7809 // If this is an indirect operand, the operand is a pointer to the 7810 // accessed type. 7811 if (isIndirect) { 7812 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 7813 if (!PtrTy) 7814 report_fatal_error("Indirect operand for inline asm not a pointer!"); 7815 OpTy = PtrTy->getElementType(); 7816 } 7817 7818 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 7819 if (StructType *STy = dyn_cast<StructType>(OpTy)) 7820 if (STy->getNumElements() == 1) 7821 OpTy = STy->getElementType(0); 7822 7823 // If OpTy is not a single value, it may be a struct/union that we 7824 // can tile with integers. 7825 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 7826 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 7827 switch (BitSize) { 7828 default: break; 7829 case 1: 7830 case 8: 7831 case 16: 7832 case 32: 7833 case 64: 7834 case 128: 7835 OpTy = IntegerType::get(Context, BitSize); 7836 break; 7837 } 7838 } 7839 7840 return TLI.getValueType(DL, OpTy, true); 7841 } 7842 }; 7843 7844 7845 } // end anonymous namespace 7846 7847 /// Make sure that the output operand \p OpInfo and its corresponding input 7848 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 7849 /// out). 7850 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 7851 SDISelAsmOperandInfo &MatchingOpInfo, 7852 SelectionDAG &DAG) { 7853 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 7854 return; 7855 7856 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 7857 const auto &TLI = DAG.getTargetLoweringInfo(); 7858 7859 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 7860 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 7861 OpInfo.ConstraintVT); 7862 std::pair<unsigned, const TargetRegisterClass *> InputRC = 7863 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 7864 MatchingOpInfo.ConstraintVT); 7865 if ((OpInfo.ConstraintVT.isInteger() != 7866 MatchingOpInfo.ConstraintVT.isInteger()) || 7867 (MatchRC.second != InputRC.second)) { 7868 // FIXME: error out in a more elegant fashion 7869 report_fatal_error("Unsupported asm: input constraint" 7870 " with a matching output constraint of" 7871 " incompatible type!"); 7872 } 7873 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 7874 } 7875 7876 /// Get a direct memory input to behave well as an indirect operand. 7877 /// This may introduce stores, hence the need for a \p Chain. 7878 /// \return The (possibly updated) chain. 7879 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 7880 SDISelAsmOperandInfo &OpInfo, 7881 SelectionDAG &DAG) { 7882 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7883 7884 // If we don't have an indirect input, put it in the constpool if we can, 7885 // otherwise spill it to a stack slot. 7886 // TODO: This isn't quite right. We need to handle these according to 7887 // the addressing mode that the constraint wants. Also, this may take 7888 // an additional register for the computation and we don't want that 7889 // either. 7890 7891 // If the operand is a float, integer, or vector constant, spill to a 7892 // constant pool entry to get its address. 7893 const Value *OpVal = OpInfo.CallOperandVal; 7894 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 7895 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 7896 OpInfo.CallOperand = DAG.getConstantPool( 7897 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 7898 return Chain; 7899 } 7900 7901 // Otherwise, create a stack slot and emit a store to it before the asm. 7902 Type *Ty = OpVal->getType(); 7903 auto &DL = DAG.getDataLayout(); 7904 uint64_t TySize = DL.getTypeAllocSize(Ty); 7905 MachineFunction &MF = DAG.getMachineFunction(); 7906 int SSFI = MF.getFrameInfo().CreateStackObject( 7907 TySize, DL.getPrefTypeAlign(Ty), false); 7908 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 7909 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 7910 MachinePointerInfo::getFixedStack(MF, SSFI), 7911 TLI.getMemValueType(DL, Ty)); 7912 OpInfo.CallOperand = StackSlot; 7913 7914 return Chain; 7915 } 7916 7917 /// GetRegistersForValue - Assign registers (virtual or physical) for the 7918 /// specified operand. We prefer to assign virtual registers, to allow the 7919 /// register allocator to handle the assignment process. However, if the asm 7920 /// uses features that we can't model on machineinstrs, we have SDISel do the 7921 /// allocation. This produces generally horrible, but correct, code. 7922 /// 7923 /// OpInfo describes the operand 7924 /// RefOpInfo describes the matching operand if any, the operand otherwise 7925 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 7926 SDISelAsmOperandInfo &OpInfo, 7927 SDISelAsmOperandInfo &RefOpInfo) { 7928 LLVMContext &Context = *DAG.getContext(); 7929 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7930 7931 MachineFunction &MF = DAG.getMachineFunction(); 7932 SmallVector<unsigned, 4> Regs; 7933 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 7934 7935 // No work to do for memory operations. 7936 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 7937 return; 7938 7939 // If this is a constraint for a single physreg, or a constraint for a 7940 // register class, find it. 7941 unsigned AssignedReg; 7942 const TargetRegisterClass *RC; 7943 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 7944 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 7945 // RC is unset only on failure. Return immediately. 7946 if (!RC) 7947 return; 7948 7949 // Get the actual register value type. This is important, because the user 7950 // may have asked for (e.g.) the AX register in i32 type. We need to 7951 // remember that AX is actually i16 to get the right extension. 7952 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 7953 7954 if (OpInfo.ConstraintVT != MVT::Other) { 7955 // If this is an FP operand in an integer register (or visa versa), or more 7956 // generally if the operand value disagrees with the register class we plan 7957 // to stick it in, fix the operand type. 7958 // 7959 // If this is an input value, the bitcast to the new type is done now. 7960 // Bitcast for output value is done at the end of visitInlineAsm(). 7961 if ((OpInfo.Type == InlineAsm::isOutput || 7962 OpInfo.Type == InlineAsm::isInput) && 7963 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 7964 // Try to convert to the first EVT that the reg class contains. If the 7965 // types are identical size, use a bitcast to convert (e.g. two differing 7966 // vector types). Note: output bitcast is done at the end of 7967 // visitInlineAsm(). 7968 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 7969 // Exclude indirect inputs while they are unsupported because the code 7970 // to perform the load is missing and thus OpInfo.CallOperand still 7971 // refers to the input address rather than the pointed-to value. 7972 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 7973 OpInfo.CallOperand = 7974 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 7975 OpInfo.ConstraintVT = RegVT; 7976 // If the operand is an FP value and we want it in integer registers, 7977 // use the corresponding integer type. This turns an f64 value into 7978 // i64, which can be passed with two i32 values on a 32-bit machine. 7979 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 7980 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 7981 if (OpInfo.Type == InlineAsm::isInput) 7982 OpInfo.CallOperand = 7983 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 7984 OpInfo.ConstraintVT = VT; 7985 } 7986 } 7987 } 7988 7989 // No need to allocate a matching input constraint since the constraint it's 7990 // matching to has already been allocated. 7991 if (OpInfo.isMatchingInputConstraint()) 7992 return; 7993 7994 EVT ValueVT = OpInfo.ConstraintVT; 7995 if (OpInfo.ConstraintVT == MVT::Other) 7996 ValueVT = RegVT; 7997 7998 // Initialize NumRegs. 7999 unsigned NumRegs = 1; 8000 if (OpInfo.ConstraintVT != MVT::Other) 8001 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 8002 8003 // If this is a constraint for a specific physical register, like {r17}, 8004 // assign it now. 8005 8006 // If this associated to a specific register, initialize iterator to correct 8007 // place. If virtual, make sure we have enough registers 8008 8009 // Initialize iterator if necessary 8010 TargetRegisterClass::iterator I = RC->begin(); 8011 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8012 8013 // Do not check for single registers. 8014 if (AssignedReg) { 8015 for (; *I != AssignedReg; ++I) 8016 assert(I != RC->end() && "AssignedReg should be member of RC"); 8017 } 8018 8019 for (; NumRegs; --NumRegs, ++I) { 8020 assert(I != RC->end() && "Ran out of registers to allocate!"); 8021 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8022 Regs.push_back(R); 8023 } 8024 8025 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8026 } 8027 8028 static unsigned 8029 findMatchingInlineAsmOperand(unsigned OperandNo, 8030 const std::vector<SDValue> &AsmNodeOperands) { 8031 // Scan until we find the definition we already emitted of this operand. 8032 unsigned CurOp = InlineAsm::Op_FirstOperand; 8033 for (; OperandNo; --OperandNo) { 8034 // Advance to the next operand. 8035 unsigned OpFlag = 8036 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8037 assert((InlineAsm::isRegDefKind(OpFlag) || 8038 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8039 InlineAsm::isMemKind(OpFlag)) && 8040 "Skipped past definitions?"); 8041 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8042 } 8043 return CurOp; 8044 } 8045 8046 namespace { 8047 8048 class ExtraFlags { 8049 unsigned Flags = 0; 8050 8051 public: 8052 explicit ExtraFlags(const CallBase &Call) { 8053 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8054 if (IA->hasSideEffects()) 8055 Flags |= InlineAsm::Extra_HasSideEffects; 8056 if (IA->isAlignStack()) 8057 Flags |= InlineAsm::Extra_IsAlignStack; 8058 if (Call.isConvergent()) 8059 Flags |= InlineAsm::Extra_IsConvergent; 8060 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8061 } 8062 8063 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8064 // Ideally, we would only check against memory constraints. However, the 8065 // meaning of an Other constraint can be target-specific and we can't easily 8066 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8067 // for Other constraints as well. 8068 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8069 OpInfo.ConstraintType == TargetLowering::C_Other) { 8070 if (OpInfo.Type == InlineAsm::isInput) 8071 Flags |= InlineAsm::Extra_MayLoad; 8072 else if (OpInfo.Type == InlineAsm::isOutput) 8073 Flags |= InlineAsm::Extra_MayStore; 8074 else if (OpInfo.Type == InlineAsm::isClobber) 8075 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8076 } 8077 } 8078 8079 unsigned get() const { return Flags; } 8080 }; 8081 8082 } // end anonymous namespace 8083 8084 /// visitInlineAsm - Handle a call to an InlineAsm object. 8085 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call) { 8086 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8087 8088 /// ConstraintOperands - Information about all of the constraints. 8089 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 8090 8091 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8092 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8093 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 8094 8095 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8096 // AsmDialect, MayLoad, MayStore). 8097 bool HasSideEffect = IA->hasSideEffects(); 8098 ExtraFlags ExtraInfo(Call); 8099 8100 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 8101 unsigned ResNo = 0; // ResNo - The result number of the next output. 8102 unsigned NumMatchingOps = 0; 8103 for (auto &T : TargetConstraints) { 8104 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8105 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8106 8107 // Compute the value type for each operand. 8108 if (OpInfo.Type == InlineAsm::isInput || 8109 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 8110 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++); 8111 8112 // Process the call argument. BasicBlocks are labels, currently appearing 8113 // only in asm's. 8114 if (isa<CallBrInst>(Call) && 8115 ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() - 8116 cast<CallBrInst>(&Call)->getNumIndirectDests() - 8117 NumMatchingOps) && 8118 (NumMatchingOps == 0 || 8119 ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() - 8120 NumMatchingOps))) { 8121 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal); 8122 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true); 8123 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT); 8124 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 8125 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 8126 } else { 8127 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8128 } 8129 8130 OpInfo.ConstraintVT = 8131 OpInfo 8132 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout()) 8133 .getSimpleVT(); 8134 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 8135 // The return value of the call is this value. As such, there is no 8136 // corresponding argument. 8137 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8138 if (StructType *STy = dyn_cast<StructType>(Call.getType())) { 8139 OpInfo.ConstraintVT = TLI.getSimpleValueType( 8140 DAG.getDataLayout(), STy->getElementType(ResNo)); 8141 } else { 8142 assert(ResNo == 0 && "Asm only has one result!"); 8143 OpInfo.ConstraintVT = 8144 TLI.getSimpleValueType(DAG.getDataLayout(), Call.getType()); 8145 } 8146 ++ResNo; 8147 } else { 8148 OpInfo.ConstraintVT = MVT::Other; 8149 } 8150 8151 if (OpInfo.hasMatchingInput()) 8152 ++NumMatchingOps; 8153 8154 if (!HasSideEffect) 8155 HasSideEffect = OpInfo.hasMemory(TLI); 8156 8157 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8158 // FIXME: Could we compute this on OpInfo rather than T? 8159 8160 // Compute the constraint code and ConstraintType to use. 8161 TLI.ComputeConstraintToUse(T, SDValue()); 8162 8163 if (T.ConstraintType == TargetLowering::C_Immediate && 8164 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8165 // We've delayed emitting a diagnostic like the "n" constraint because 8166 // inlining could cause an integer showing up. 8167 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 8168 "' expects an integer constant " 8169 "expression"); 8170 8171 ExtraInfo.update(T); 8172 } 8173 8174 8175 // We won't need to flush pending loads if this asm doesn't touch 8176 // memory and is nonvolatile. 8177 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8178 8179 bool IsCallBr = isa<CallBrInst>(Call); 8180 if (IsCallBr) { 8181 // If this is a callbr we need to flush pending exports since inlineasm_br 8182 // is a terminator. We need to do this before nodes are glued to 8183 // the inlineasm_br node. 8184 Chain = getControlRoot(); 8185 } 8186 8187 // Second pass over the constraints: compute which constraint option to use. 8188 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8189 // If this is an output operand with a matching input operand, look up the 8190 // matching input. If their types mismatch, e.g. one is an integer, the 8191 // other is floating point, or their sizes are different, flag it as an 8192 // error. 8193 if (OpInfo.hasMatchingInput()) { 8194 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8195 patchMatchingInput(OpInfo, Input, DAG); 8196 } 8197 8198 // Compute the constraint code and ConstraintType to use. 8199 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8200 8201 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8202 OpInfo.Type == InlineAsm::isClobber) 8203 continue; 8204 8205 // If this is a memory input, and if the operand is not indirect, do what we 8206 // need to provide an address for the memory input. 8207 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8208 !OpInfo.isIndirect) { 8209 assert((OpInfo.isMultipleAlternative || 8210 (OpInfo.Type == InlineAsm::isInput)) && 8211 "Can only indirectify direct input operands!"); 8212 8213 // Memory operands really want the address of the value. 8214 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8215 8216 // There is no longer a Value* corresponding to this operand. 8217 OpInfo.CallOperandVal = nullptr; 8218 8219 // It is now an indirect operand. 8220 OpInfo.isIndirect = true; 8221 } 8222 8223 } 8224 8225 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8226 std::vector<SDValue> AsmNodeOperands; 8227 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8228 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8229 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 8230 8231 // If we have a !srcloc metadata node associated with it, we want to attach 8232 // this to the ultimately generated inline asm machineinstr. To do this, we 8233 // pass in the third operand as this (potentially null) inline asm MDNode. 8234 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 8235 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8236 8237 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8238 // bits as operand 3. 8239 AsmNodeOperands.push_back(DAG.getTargetConstant( 8240 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8241 8242 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8243 // this, assign virtual and physical registers for inputs and otput. 8244 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8245 // Assign Registers. 8246 SDISelAsmOperandInfo &RefOpInfo = 8247 OpInfo.isMatchingInputConstraint() 8248 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8249 : OpInfo; 8250 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8251 8252 auto DetectWriteToReservedRegister = [&]() { 8253 const MachineFunction &MF = DAG.getMachineFunction(); 8254 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8255 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 8256 if (Register::isPhysicalRegister(Reg) && 8257 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 8258 const char *RegName = TRI.getName(Reg); 8259 emitInlineAsmError(Call, "write to reserved register '" + 8260 Twine(RegName) + "'"); 8261 return true; 8262 } 8263 } 8264 return false; 8265 }; 8266 8267 switch (OpInfo.Type) { 8268 case InlineAsm::isOutput: 8269 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8270 unsigned ConstraintID = 8271 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8272 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8273 "Failed to convert memory constraint code to constraint id."); 8274 8275 // Add information to the INLINEASM node to know about this output. 8276 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8277 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8278 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8279 MVT::i32)); 8280 AsmNodeOperands.push_back(OpInfo.CallOperand); 8281 } else { 8282 // Otherwise, this outputs to a register (directly for C_Register / 8283 // C_RegisterClass, and a target-defined fashion for 8284 // C_Immediate/C_Other). Find a register that we can use. 8285 if (OpInfo.AssignedRegs.Regs.empty()) { 8286 emitInlineAsmError( 8287 Call, "couldn't allocate output register for constraint '" + 8288 Twine(OpInfo.ConstraintCode) + "'"); 8289 return; 8290 } 8291 8292 if (DetectWriteToReservedRegister()) 8293 return; 8294 8295 // Add information to the INLINEASM node to know that this register is 8296 // set. 8297 OpInfo.AssignedRegs.AddInlineAsmOperands( 8298 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8299 : InlineAsm::Kind_RegDef, 8300 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8301 } 8302 break; 8303 8304 case InlineAsm::isInput: { 8305 SDValue InOperandVal = OpInfo.CallOperand; 8306 8307 if (OpInfo.isMatchingInputConstraint()) { 8308 // If this is required to match an output register we have already set, 8309 // just use its register. 8310 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8311 AsmNodeOperands); 8312 unsigned OpFlag = 8313 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8314 if (InlineAsm::isRegDefKind(OpFlag) || 8315 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8316 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8317 if (OpInfo.isIndirect) { 8318 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8319 emitInlineAsmError(Call, "inline asm not supported yet: " 8320 "don't know how to handle tied " 8321 "indirect register inputs"); 8322 return; 8323 } 8324 8325 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 8326 SmallVector<unsigned, 4> Regs; 8327 8328 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { 8329 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8330 MachineRegisterInfo &RegInfo = 8331 DAG.getMachineFunction().getRegInfo(); 8332 for (unsigned i = 0; i != NumRegs; ++i) 8333 Regs.push_back(RegInfo.createVirtualRegister(RC)); 8334 } else { 8335 emitInlineAsmError(Call, 8336 "inline asm error: This value type register " 8337 "class is not natively supported!"); 8338 return; 8339 } 8340 8341 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8342 8343 SDLoc dl = getCurSDLoc(); 8344 // Use the produced MatchedRegs object to 8345 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call); 8346 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8347 true, OpInfo.getMatchedOperand(), dl, 8348 DAG, AsmNodeOperands); 8349 break; 8350 } 8351 8352 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8353 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8354 "Unexpected number of operands"); 8355 // Add information to the INLINEASM node to know about this input. 8356 // See InlineAsm.h isUseOperandTiedToDef. 8357 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8358 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8359 OpInfo.getMatchedOperand()); 8360 AsmNodeOperands.push_back(DAG.getTargetConstant( 8361 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8362 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8363 break; 8364 } 8365 8366 // Treat indirect 'X' constraint as memory. 8367 if (OpInfo.ConstraintType == TargetLowering::C_Other && 8368 OpInfo.isIndirect) 8369 OpInfo.ConstraintType = TargetLowering::C_Memory; 8370 8371 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 8372 OpInfo.ConstraintType == TargetLowering::C_Other) { 8373 std::vector<SDValue> Ops; 8374 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 8375 Ops, DAG); 8376 if (Ops.empty()) { 8377 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 8378 if (isa<ConstantSDNode>(InOperandVal)) { 8379 emitInlineAsmError(Call, "value out of range for constraint '" + 8380 Twine(OpInfo.ConstraintCode) + "'"); 8381 return; 8382 } 8383 8384 emitInlineAsmError(Call, 8385 "invalid operand for inline asm constraint '" + 8386 Twine(OpInfo.ConstraintCode) + "'"); 8387 return; 8388 } 8389 8390 // Add information to the INLINEASM node to know about this input. 8391 unsigned ResOpType = 8392 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 8393 AsmNodeOperands.push_back(DAG.getTargetConstant( 8394 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8395 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 8396 break; 8397 } 8398 8399 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8400 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 8401 assert(InOperandVal.getValueType() == 8402 TLI.getPointerTy(DAG.getDataLayout()) && 8403 "Memory operands expect pointer values"); 8404 8405 unsigned ConstraintID = 8406 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8407 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8408 "Failed to convert memory constraint code to constraint id."); 8409 8410 // Add information to the INLINEASM node to know about this input. 8411 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8412 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 8413 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 8414 getCurSDLoc(), 8415 MVT::i32)); 8416 AsmNodeOperands.push_back(InOperandVal); 8417 break; 8418 } 8419 8420 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 8421 OpInfo.ConstraintType == TargetLowering::C_Register) && 8422 "Unknown constraint type!"); 8423 8424 // TODO: Support this. 8425 if (OpInfo.isIndirect) { 8426 emitInlineAsmError( 8427 Call, "Don't know how to handle indirect register inputs yet " 8428 "for constraint '" + 8429 Twine(OpInfo.ConstraintCode) + "'"); 8430 return; 8431 } 8432 8433 // Copy the input into the appropriate registers. 8434 if (OpInfo.AssignedRegs.Regs.empty()) { 8435 emitInlineAsmError(Call, 8436 "couldn't allocate input reg for constraint '" + 8437 Twine(OpInfo.ConstraintCode) + "'"); 8438 return; 8439 } 8440 8441 if (DetectWriteToReservedRegister()) 8442 return; 8443 8444 SDLoc dl = getCurSDLoc(); 8445 8446 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 8447 &Call); 8448 8449 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 8450 dl, DAG, AsmNodeOperands); 8451 break; 8452 } 8453 case InlineAsm::isClobber: 8454 // Add the clobbered value to the operand list, so that the register 8455 // allocator is aware that the physreg got clobbered. 8456 if (!OpInfo.AssignedRegs.Regs.empty()) 8457 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 8458 false, 0, getCurSDLoc(), DAG, 8459 AsmNodeOperands); 8460 break; 8461 } 8462 } 8463 8464 // Finish up input operands. Set the input chain and add the flag last. 8465 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 8466 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 8467 8468 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 8469 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 8470 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 8471 Flag = Chain.getValue(1); 8472 8473 // Do additional work to generate outputs. 8474 8475 SmallVector<EVT, 1> ResultVTs; 8476 SmallVector<SDValue, 1> ResultValues; 8477 SmallVector<SDValue, 8> OutChains; 8478 8479 llvm::Type *CallResultType = Call.getType(); 8480 ArrayRef<Type *> ResultTypes; 8481 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 8482 ResultTypes = StructResult->elements(); 8483 else if (!CallResultType->isVoidTy()) 8484 ResultTypes = makeArrayRef(CallResultType); 8485 8486 auto CurResultType = ResultTypes.begin(); 8487 auto handleRegAssign = [&](SDValue V) { 8488 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 8489 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 8490 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 8491 ++CurResultType; 8492 // If the type of the inline asm call site return value is different but has 8493 // same size as the type of the asm output bitcast it. One example of this 8494 // is for vectors with different width / number of elements. This can 8495 // happen for register classes that can contain multiple different value 8496 // types. The preg or vreg allocated may not have the same VT as was 8497 // expected. 8498 // 8499 // This can also happen for a return value that disagrees with the register 8500 // class it is put in, eg. a double in a general-purpose register on a 8501 // 32-bit machine. 8502 if (ResultVT != V.getValueType() && 8503 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 8504 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 8505 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 8506 V.getValueType().isInteger()) { 8507 // If a result value was tied to an input value, the computed result 8508 // may have a wider width than the expected result. Extract the 8509 // relevant portion. 8510 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 8511 } 8512 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 8513 ResultVTs.push_back(ResultVT); 8514 ResultValues.push_back(V); 8515 }; 8516 8517 // Deal with output operands. 8518 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8519 if (OpInfo.Type == InlineAsm::isOutput) { 8520 SDValue Val; 8521 // Skip trivial output operands. 8522 if (OpInfo.AssignedRegs.Regs.empty()) 8523 continue; 8524 8525 switch (OpInfo.ConstraintType) { 8526 case TargetLowering::C_Register: 8527 case TargetLowering::C_RegisterClass: 8528 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 8529 Chain, &Flag, &Call); 8530 break; 8531 case TargetLowering::C_Immediate: 8532 case TargetLowering::C_Other: 8533 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 8534 OpInfo, DAG); 8535 break; 8536 case TargetLowering::C_Memory: 8537 break; // Already handled. 8538 case TargetLowering::C_Unknown: 8539 assert(false && "Unexpected unknown constraint"); 8540 } 8541 8542 // Indirect output manifest as stores. Record output chains. 8543 if (OpInfo.isIndirect) { 8544 const Value *Ptr = OpInfo.CallOperandVal; 8545 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 8546 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 8547 MachinePointerInfo(Ptr)); 8548 OutChains.push_back(Store); 8549 } else { 8550 // generate CopyFromRegs to associated registers. 8551 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8552 if (Val.getOpcode() == ISD::MERGE_VALUES) { 8553 for (const SDValue &V : Val->op_values()) 8554 handleRegAssign(V); 8555 } else 8556 handleRegAssign(Val); 8557 } 8558 } 8559 } 8560 8561 // Set results. 8562 if (!ResultValues.empty()) { 8563 assert(CurResultType == ResultTypes.end() && 8564 "Mismatch in number of ResultTypes"); 8565 assert(ResultValues.size() == ResultTypes.size() && 8566 "Mismatch in number of output operands in asm result"); 8567 8568 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 8569 DAG.getVTList(ResultVTs), ResultValues); 8570 setValue(&Call, V); 8571 } 8572 8573 // Collect store chains. 8574 if (!OutChains.empty()) 8575 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 8576 8577 // Only Update Root if inline assembly has a memory effect. 8578 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr) 8579 DAG.setRoot(Chain); 8580 } 8581 8582 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 8583 const Twine &Message) { 8584 LLVMContext &Ctx = *DAG.getContext(); 8585 Ctx.emitError(&Call, Message); 8586 8587 // Make sure we leave the DAG in a valid state 8588 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8589 SmallVector<EVT, 1> ValueVTs; 8590 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 8591 8592 if (ValueVTs.empty()) 8593 return; 8594 8595 SmallVector<SDValue, 1> Ops; 8596 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 8597 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 8598 8599 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 8600 } 8601 8602 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 8603 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 8604 MVT::Other, getRoot(), 8605 getValue(I.getArgOperand(0)), 8606 DAG.getSrcValue(I.getArgOperand(0)))); 8607 } 8608 8609 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 8610 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8611 const DataLayout &DL = DAG.getDataLayout(); 8612 SDValue V = DAG.getVAArg( 8613 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 8614 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 8615 DL.getABITypeAlign(I.getType()).value()); 8616 DAG.setRoot(V.getValue(1)); 8617 8618 if (I.getType()->isPointerTy()) 8619 V = DAG.getPtrExtOrTrunc( 8620 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 8621 setValue(&I, V); 8622 } 8623 8624 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 8625 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 8626 MVT::Other, getRoot(), 8627 getValue(I.getArgOperand(0)), 8628 DAG.getSrcValue(I.getArgOperand(0)))); 8629 } 8630 8631 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 8632 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 8633 MVT::Other, getRoot(), 8634 getValue(I.getArgOperand(0)), 8635 getValue(I.getArgOperand(1)), 8636 DAG.getSrcValue(I.getArgOperand(0)), 8637 DAG.getSrcValue(I.getArgOperand(1)))); 8638 } 8639 8640 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 8641 const Instruction &I, 8642 SDValue Op) { 8643 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 8644 if (!Range) 8645 return Op; 8646 8647 ConstantRange CR = getConstantRangeFromMetadata(*Range); 8648 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 8649 return Op; 8650 8651 APInt Lo = CR.getUnsignedMin(); 8652 if (!Lo.isMinValue()) 8653 return Op; 8654 8655 APInt Hi = CR.getUnsignedMax(); 8656 unsigned Bits = std::max(Hi.getActiveBits(), 8657 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 8658 8659 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8660 8661 SDLoc SL = getCurSDLoc(); 8662 8663 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8664 DAG.getValueType(SmallVT)); 8665 unsigned NumVals = Op.getNode()->getNumValues(); 8666 if (NumVals == 1) 8667 return ZExt; 8668 8669 SmallVector<SDValue, 4> Ops; 8670 8671 Ops.push_back(ZExt); 8672 for (unsigned I = 1; I != NumVals; ++I) 8673 Ops.push_back(Op.getValue(I)); 8674 8675 return DAG.getMergeValues(Ops, SL); 8676 } 8677 8678 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8679 /// the call being lowered. 8680 /// 8681 /// This is a helper for lowering intrinsics that follow a target calling 8682 /// convention or require stack pointer adjustment. Only a subset of the 8683 /// intrinsic's operands need to participate in the calling convention. 8684 void SelectionDAGBuilder::populateCallLoweringInfo( 8685 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 8686 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8687 bool IsPatchPoint) { 8688 TargetLowering::ArgListTy Args; 8689 Args.reserve(NumArgs); 8690 8691 // Populate the argument list. 8692 // Attributes for args start at offset 1, after the return attribute. 8693 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8694 ArgI != ArgE; ++ArgI) { 8695 const Value *V = Call->getOperand(ArgI); 8696 8697 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 8698 8699 TargetLowering::ArgListEntry Entry; 8700 Entry.Node = getValue(V); 8701 Entry.Ty = V->getType(); 8702 Entry.setAttributes(Call, ArgI); 8703 Args.push_back(Entry); 8704 } 8705 8706 CLI.setDebugLoc(getCurSDLoc()) 8707 .setChain(getRoot()) 8708 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 8709 .setDiscardResult(Call->use_empty()) 8710 .setIsPatchPoint(IsPatchPoint) 8711 .setIsPreallocated( 8712 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 8713 } 8714 8715 /// Add a stack map intrinsic call's live variable operands to a stackmap 8716 /// or patchpoint target node's operand list. 8717 /// 8718 /// Constants are converted to TargetConstants purely as an optimization to 8719 /// avoid constant materialization and register allocation. 8720 /// 8721 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 8722 /// generate addess computation nodes, and so FinalizeISel can convert the 8723 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 8724 /// address materialization and register allocation, but may also be required 8725 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 8726 /// alloca in the entry block, then the runtime may assume that the alloca's 8727 /// StackMap location can be read immediately after compilation and that the 8728 /// location is valid at any point during execution (this is similar to the 8729 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 8730 /// only available in a register, then the runtime would need to trap when 8731 /// execution reaches the StackMap in order to read the alloca's location. 8732 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 8733 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 8734 SelectionDAGBuilder &Builder) { 8735 for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) { 8736 SDValue OpVal = Builder.getValue(Call.getArgOperand(i)); 8737 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 8738 Ops.push_back( 8739 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 8740 Ops.push_back( 8741 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 8742 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 8743 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 8744 Ops.push_back(Builder.DAG.getTargetFrameIndex( 8745 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 8746 } else 8747 Ops.push_back(OpVal); 8748 } 8749 } 8750 8751 /// Lower llvm.experimental.stackmap directly to its target opcode. 8752 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 8753 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 8754 // [live variables...]) 8755 8756 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 8757 8758 SDValue Chain, InFlag, Callee, NullPtr; 8759 SmallVector<SDValue, 32> Ops; 8760 8761 SDLoc DL = getCurSDLoc(); 8762 Callee = getValue(CI.getCalledOperand()); 8763 NullPtr = DAG.getIntPtrConstant(0, DL, true); 8764 8765 // The stackmap intrinsic only records the live variables (the arguments 8766 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 8767 // intrinsic, this won't be lowered to a function call. This means we don't 8768 // have to worry about calling conventions and target specific lowering code. 8769 // Instead we perform the call lowering right here. 8770 // 8771 // chain, flag = CALLSEQ_START(chain, 0, 0) 8772 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 8773 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 8774 // 8775 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 8776 InFlag = Chain.getValue(1); 8777 8778 // Add the <id> and <numBytes> constants. 8779 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 8780 Ops.push_back(DAG.getTargetConstant( 8781 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 8782 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 8783 Ops.push_back(DAG.getTargetConstant( 8784 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 8785 MVT::i32)); 8786 8787 // Push live variables for the stack map. 8788 addStackMapLiveVars(CI, 2, DL, Ops, *this); 8789 8790 // We are not pushing any register mask info here on the operands list, 8791 // because the stackmap doesn't clobber anything. 8792 8793 // Push the chain and the glue flag. 8794 Ops.push_back(Chain); 8795 Ops.push_back(InFlag); 8796 8797 // Create the STACKMAP node. 8798 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8799 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 8800 Chain = SDValue(SM, 0); 8801 InFlag = Chain.getValue(1); 8802 8803 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 8804 8805 // Stackmaps don't generate values, so nothing goes into the NodeMap. 8806 8807 // Set the root to the target-lowered call chain. 8808 DAG.setRoot(Chain); 8809 8810 // Inform the Frame Information that we have a stackmap in this function. 8811 FuncInfo.MF->getFrameInfo().setHasStackMap(); 8812 } 8813 8814 /// Lower llvm.experimental.patchpoint directly to its target opcode. 8815 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 8816 const BasicBlock *EHPadBB) { 8817 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 8818 // i32 <numBytes>, 8819 // i8* <target>, 8820 // i32 <numArgs>, 8821 // [Args...], 8822 // [live variables...]) 8823 8824 CallingConv::ID CC = CB.getCallingConv(); 8825 bool IsAnyRegCC = CC == CallingConv::AnyReg; 8826 bool HasDef = !CB.getType()->isVoidTy(); 8827 SDLoc dl = getCurSDLoc(); 8828 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 8829 8830 // Handle immediate and symbolic callees. 8831 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 8832 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 8833 /*isTarget=*/true); 8834 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 8835 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 8836 SDLoc(SymbolicCallee), 8837 SymbolicCallee->getValueType(0)); 8838 8839 // Get the real number of arguments participating in the call <numArgs> 8840 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 8841 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 8842 8843 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 8844 // Intrinsics include all meta-operands up to but not including CC. 8845 unsigned NumMetaOpers = PatchPointOpers::CCPos; 8846 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 8847 "Not enough arguments provided to the patchpoint intrinsic"); 8848 8849 // For AnyRegCC the arguments are lowered later on manually. 8850 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 8851 Type *ReturnTy = 8852 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 8853 8854 TargetLowering::CallLoweringInfo CLI(DAG); 8855 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 8856 ReturnTy, true); 8857 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8858 8859 SDNode *CallEnd = Result.second.getNode(); 8860 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 8861 CallEnd = CallEnd->getOperand(0).getNode(); 8862 8863 /// Get a call instruction from the call sequence chain. 8864 /// Tail calls are not allowed. 8865 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 8866 "Expected a callseq node."); 8867 SDNode *Call = CallEnd->getOperand(0).getNode(); 8868 bool HasGlue = Call->getGluedNode(); 8869 8870 // Replace the target specific call node with the patchable intrinsic. 8871 SmallVector<SDValue, 8> Ops; 8872 8873 // Add the <id> and <numBytes> constants. 8874 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 8875 Ops.push_back(DAG.getTargetConstant( 8876 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 8877 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 8878 Ops.push_back(DAG.getTargetConstant( 8879 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 8880 MVT::i32)); 8881 8882 // Add the callee. 8883 Ops.push_back(Callee); 8884 8885 // Adjust <numArgs> to account for any arguments that have been passed on the 8886 // stack instead. 8887 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 8888 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 8889 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 8890 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 8891 8892 // Add the calling convention 8893 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 8894 8895 // Add the arguments we omitted previously. The register allocator should 8896 // place these in any free register. 8897 if (IsAnyRegCC) 8898 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 8899 Ops.push_back(getValue(CB.getArgOperand(i))); 8900 8901 // Push the arguments from the call instruction up to the register mask. 8902 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 8903 Ops.append(Call->op_begin() + 2, e); 8904 8905 // Push live variables for the stack map. 8906 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 8907 8908 // Push the register mask info. 8909 if (HasGlue) 8910 Ops.push_back(*(Call->op_end()-2)); 8911 else 8912 Ops.push_back(*(Call->op_end()-1)); 8913 8914 // Push the chain (this is originally the first operand of the call, but 8915 // becomes now the last or second to last operand). 8916 Ops.push_back(*(Call->op_begin())); 8917 8918 // Push the glue flag (last operand). 8919 if (HasGlue) 8920 Ops.push_back(*(Call->op_end()-1)); 8921 8922 SDVTList NodeTys; 8923 if (IsAnyRegCC && HasDef) { 8924 // Create the return types based on the intrinsic definition 8925 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8926 SmallVector<EVT, 3> ValueVTs; 8927 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 8928 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 8929 8930 // There is always a chain and a glue type at the end 8931 ValueVTs.push_back(MVT::Other); 8932 ValueVTs.push_back(MVT::Glue); 8933 NodeTys = DAG.getVTList(ValueVTs); 8934 } else 8935 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8936 8937 // Replace the target specific call node with a PATCHPOINT node. 8938 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 8939 dl, NodeTys, Ops); 8940 8941 // Update the NodeMap. 8942 if (HasDef) { 8943 if (IsAnyRegCC) 8944 setValue(&CB, SDValue(MN, 0)); 8945 else 8946 setValue(&CB, Result.first); 8947 } 8948 8949 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 8950 // call sequence. Furthermore the location of the chain and glue can change 8951 // when the AnyReg calling convention is used and the intrinsic returns a 8952 // value. 8953 if (IsAnyRegCC && HasDef) { 8954 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 8955 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 8956 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 8957 } else 8958 DAG.ReplaceAllUsesWith(Call, MN); 8959 DAG.DeleteNode(Call); 8960 8961 // Inform the Frame Information that we have a patchpoint in this function. 8962 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 8963 } 8964 8965 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 8966 unsigned Intrinsic) { 8967 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8968 SDValue Op1 = getValue(I.getArgOperand(0)); 8969 SDValue Op2; 8970 if (I.getNumArgOperands() > 1) 8971 Op2 = getValue(I.getArgOperand(1)); 8972 SDLoc dl = getCurSDLoc(); 8973 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8974 SDValue Res; 8975 FastMathFlags FMF; 8976 if (isa<FPMathOperator>(I)) 8977 FMF = I.getFastMathFlags(); 8978 8979 switch (Intrinsic) { 8980 case Intrinsic::experimental_vector_reduce_v2_fadd: 8981 if (FMF.allowReassoc()) 8982 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 8983 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2)); 8984 else 8985 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2); 8986 break; 8987 case Intrinsic::experimental_vector_reduce_v2_fmul: 8988 if (FMF.allowReassoc()) 8989 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 8990 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2)); 8991 else 8992 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2); 8993 break; 8994 case Intrinsic::experimental_vector_reduce_add: 8995 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 8996 break; 8997 case Intrinsic::experimental_vector_reduce_mul: 8998 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 8999 break; 9000 case Intrinsic::experimental_vector_reduce_and: 9001 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 9002 break; 9003 case Intrinsic::experimental_vector_reduce_or: 9004 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 9005 break; 9006 case Intrinsic::experimental_vector_reduce_xor: 9007 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 9008 break; 9009 case Intrinsic::experimental_vector_reduce_smax: 9010 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 9011 break; 9012 case Intrinsic::experimental_vector_reduce_smin: 9013 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 9014 break; 9015 case Intrinsic::experimental_vector_reduce_umax: 9016 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 9017 break; 9018 case Intrinsic::experimental_vector_reduce_umin: 9019 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 9020 break; 9021 case Intrinsic::experimental_vector_reduce_fmax: 9022 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1); 9023 break; 9024 case Intrinsic::experimental_vector_reduce_fmin: 9025 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1); 9026 break; 9027 default: 9028 llvm_unreachable("Unhandled vector reduce intrinsic"); 9029 } 9030 setValue(&I, Res); 9031 } 9032 9033 /// Returns an AttributeList representing the attributes applied to the return 9034 /// value of the given call. 9035 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9036 SmallVector<Attribute::AttrKind, 2> Attrs; 9037 if (CLI.RetSExt) 9038 Attrs.push_back(Attribute::SExt); 9039 if (CLI.RetZExt) 9040 Attrs.push_back(Attribute::ZExt); 9041 if (CLI.IsInReg) 9042 Attrs.push_back(Attribute::InReg); 9043 9044 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9045 Attrs); 9046 } 9047 9048 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9049 /// implementation, which just calls LowerCall. 9050 /// FIXME: When all targets are 9051 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9052 std::pair<SDValue, SDValue> 9053 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9054 // Handle the incoming return values from the call. 9055 CLI.Ins.clear(); 9056 Type *OrigRetTy = CLI.RetTy; 9057 SmallVector<EVT, 4> RetTys; 9058 SmallVector<uint64_t, 4> Offsets; 9059 auto &DL = CLI.DAG.getDataLayout(); 9060 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 9061 9062 if (CLI.IsPostTypeLegalization) { 9063 // If we are lowering a libcall after legalization, split the return type. 9064 SmallVector<EVT, 4> OldRetTys; 9065 SmallVector<uint64_t, 4> OldOffsets; 9066 RetTys.swap(OldRetTys); 9067 Offsets.swap(OldOffsets); 9068 9069 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9070 EVT RetVT = OldRetTys[i]; 9071 uint64_t Offset = OldOffsets[i]; 9072 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9073 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9074 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9075 RetTys.append(NumRegs, RegisterVT); 9076 for (unsigned j = 0; j != NumRegs; ++j) 9077 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9078 } 9079 } 9080 9081 SmallVector<ISD::OutputArg, 4> Outs; 9082 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9083 9084 bool CanLowerReturn = 9085 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9086 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9087 9088 SDValue DemoteStackSlot; 9089 int DemoteStackIdx = -100; 9090 if (!CanLowerReturn) { 9091 // FIXME: equivalent assert? 9092 // assert(!CS.hasInAllocaArgument() && 9093 // "sret demotion is incompatible with inalloca"); 9094 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9095 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 9096 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9097 DemoteStackIdx = 9098 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 9099 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9100 DL.getAllocaAddrSpace()); 9101 9102 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9103 ArgListEntry Entry; 9104 Entry.Node = DemoteStackSlot; 9105 Entry.Ty = StackSlotPtrType; 9106 Entry.IsSExt = false; 9107 Entry.IsZExt = false; 9108 Entry.IsInReg = false; 9109 Entry.IsSRet = true; 9110 Entry.IsNest = false; 9111 Entry.IsByVal = false; 9112 Entry.IsReturned = false; 9113 Entry.IsSwiftSelf = false; 9114 Entry.IsSwiftError = false; 9115 Entry.IsCFGuardTarget = false; 9116 Entry.Alignment = Alignment; 9117 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9118 CLI.NumFixedArgs += 1; 9119 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9120 9121 // sret demotion isn't compatible with tail-calls, since the sret argument 9122 // points into the callers stack frame. 9123 CLI.IsTailCall = false; 9124 } else { 9125 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9126 CLI.RetTy, CLI.CallConv, CLI.IsVarArg); 9127 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9128 ISD::ArgFlagsTy Flags; 9129 if (NeedsRegBlock) { 9130 Flags.setInConsecutiveRegs(); 9131 if (I == RetTys.size() - 1) 9132 Flags.setInConsecutiveRegsLast(); 9133 } 9134 EVT VT = RetTys[I]; 9135 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9136 CLI.CallConv, VT); 9137 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9138 CLI.CallConv, VT); 9139 for (unsigned i = 0; i != NumRegs; ++i) { 9140 ISD::InputArg MyFlags; 9141 MyFlags.Flags = Flags; 9142 MyFlags.VT = RegisterVT; 9143 MyFlags.ArgVT = VT; 9144 MyFlags.Used = CLI.IsReturnValueUsed; 9145 if (CLI.RetTy->isPointerTy()) { 9146 MyFlags.Flags.setPointer(); 9147 MyFlags.Flags.setPointerAddrSpace( 9148 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9149 } 9150 if (CLI.RetSExt) 9151 MyFlags.Flags.setSExt(); 9152 if (CLI.RetZExt) 9153 MyFlags.Flags.setZExt(); 9154 if (CLI.IsInReg) 9155 MyFlags.Flags.setInReg(); 9156 CLI.Ins.push_back(MyFlags); 9157 } 9158 } 9159 } 9160 9161 // We push in swifterror return as the last element of CLI.Ins. 9162 ArgListTy &Args = CLI.getArgs(); 9163 if (supportSwiftError()) { 9164 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9165 if (Args[i].IsSwiftError) { 9166 ISD::InputArg MyFlags; 9167 MyFlags.VT = getPointerTy(DL); 9168 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9169 MyFlags.Flags.setSwiftError(); 9170 CLI.Ins.push_back(MyFlags); 9171 } 9172 } 9173 } 9174 9175 // Handle all of the outgoing arguments. 9176 CLI.Outs.clear(); 9177 CLI.OutVals.clear(); 9178 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9179 SmallVector<EVT, 4> ValueVTs; 9180 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9181 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9182 Type *FinalType = Args[i].Ty; 9183 if (Args[i].IsByVal) 9184 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 9185 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9186 FinalType, CLI.CallConv, CLI.IsVarArg); 9187 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9188 ++Value) { 9189 EVT VT = ValueVTs[Value]; 9190 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9191 SDValue Op = SDValue(Args[i].Node.getNode(), 9192 Args[i].Node.getResNo() + Value); 9193 ISD::ArgFlagsTy Flags; 9194 9195 // Certain targets (such as MIPS), may have a different ABI alignment 9196 // for a type depending on the context. Give the target a chance to 9197 // specify the alignment it wants. 9198 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 9199 9200 if (Args[i].Ty->isPointerTy()) { 9201 Flags.setPointer(); 9202 Flags.setPointerAddrSpace( 9203 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9204 } 9205 if (Args[i].IsZExt) 9206 Flags.setZExt(); 9207 if (Args[i].IsSExt) 9208 Flags.setSExt(); 9209 if (Args[i].IsInReg) { 9210 // If we are using vectorcall calling convention, a structure that is 9211 // passed InReg - is surely an HVA 9212 if (CLI.CallConv == CallingConv::X86_VectorCall && 9213 isa<StructType>(FinalType)) { 9214 // The first value of a structure is marked 9215 if (0 == Value) 9216 Flags.setHvaStart(); 9217 Flags.setHva(); 9218 } 9219 // Set InReg Flag 9220 Flags.setInReg(); 9221 } 9222 if (Args[i].IsSRet) 9223 Flags.setSRet(); 9224 if (Args[i].IsSwiftSelf) 9225 Flags.setSwiftSelf(); 9226 if (Args[i].IsSwiftError) 9227 Flags.setSwiftError(); 9228 if (Args[i].IsCFGuardTarget) 9229 Flags.setCFGuardTarget(); 9230 if (Args[i].IsByVal) 9231 Flags.setByVal(); 9232 if (Args[i].IsPreallocated) { 9233 Flags.setPreallocated(); 9234 // Set the byval flag for CCAssignFn callbacks that don't know about 9235 // preallocated. This way we can know how many bytes we should've 9236 // allocated and how many bytes a callee cleanup function will pop. If 9237 // we port preallocated to more targets, we'll have to add custom 9238 // preallocated handling in the various CC lowering callbacks. 9239 Flags.setByVal(); 9240 } 9241 if (Args[i].IsInAlloca) { 9242 Flags.setInAlloca(); 9243 // Set the byval flag for CCAssignFn callbacks that don't know about 9244 // inalloca. This way we can know how many bytes we should've allocated 9245 // and how many bytes a callee cleanup function will pop. If we port 9246 // inalloca to more targets, we'll have to add custom inalloca handling 9247 // in the various CC lowering callbacks. 9248 Flags.setByVal(); 9249 } 9250 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 9251 PointerType *Ty = cast<PointerType>(Args[i].Ty); 9252 Type *ElementTy = Ty->getElementType(); 9253 9254 unsigned FrameSize = DL.getTypeAllocSize( 9255 Args[i].ByValType ? Args[i].ByValType : ElementTy); 9256 Flags.setByValSize(FrameSize); 9257 9258 // info is not there but there are cases it cannot get right. 9259 Align FrameAlign; 9260 if (auto MA = Args[i].Alignment) 9261 FrameAlign = *MA; 9262 else 9263 FrameAlign = Align(getByValTypeAlignment(ElementTy, DL)); 9264 Flags.setByValAlign(FrameAlign); 9265 } 9266 if (Args[i].IsNest) 9267 Flags.setNest(); 9268 if (NeedsRegBlock) 9269 Flags.setInConsecutiveRegs(); 9270 Flags.setOrigAlign(OriginalAlignment); 9271 9272 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9273 CLI.CallConv, VT); 9274 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9275 CLI.CallConv, VT); 9276 SmallVector<SDValue, 4> Parts(NumParts); 9277 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9278 9279 if (Args[i].IsSExt) 9280 ExtendKind = ISD::SIGN_EXTEND; 9281 else if (Args[i].IsZExt) 9282 ExtendKind = ISD::ZERO_EXTEND; 9283 9284 // Conservatively only handle 'returned' on non-vectors that can be lowered, 9285 // for now. 9286 if (Args[i].IsReturned && !Op.getValueType().isVector() && 9287 CanLowerReturn) { 9288 assert((CLI.RetTy == Args[i].Ty || 9289 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 9290 CLI.RetTy->getPointerAddressSpace() == 9291 Args[i].Ty->getPointerAddressSpace())) && 9292 RetTys.size() == NumValues && "unexpected use of 'returned'"); 9293 // Before passing 'returned' to the target lowering code, ensure that 9294 // either the register MVT and the actual EVT are the same size or that 9295 // the return value and argument are extended in the same way; in these 9296 // cases it's safe to pass the argument register value unchanged as the 9297 // return register value (although it's at the target's option whether 9298 // to do so) 9299 // TODO: allow code generation to take advantage of partially preserved 9300 // registers rather than clobbering the entire register when the 9301 // parameter extension method is not compatible with the return 9302 // extension method 9303 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9304 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9305 CLI.RetZExt == Args[i].IsZExt)) 9306 Flags.setReturned(); 9307 } 9308 9309 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 9310 CLI.CallConv, ExtendKind); 9311 9312 for (unsigned j = 0; j != NumParts; ++j) { 9313 // if it isn't first piece, alignment must be 1 9314 // For scalable vectors the scalable part is currently handled 9315 // by individual targets, so we just use the known minimum size here. 9316 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 9317 i < CLI.NumFixedArgs, i, 9318 j*Parts[j].getValueType().getStoreSize().getKnownMinSize()); 9319 if (NumParts > 1 && j == 0) 9320 MyFlags.Flags.setSplit(); 9321 else if (j != 0) { 9322 MyFlags.Flags.setOrigAlign(Align(1)); 9323 if (j == NumParts - 1) 9324 MyFlags.Flags.setSplitEnd(); 9325 } 9326 9327 CLI.Outs.push_back(MyFlags); 9328 CLI.OutVals.push_back(Parts[j]); 9329 } 9330 9331 if (NeedsRegBlock && Value == NumValues - 1) 9332 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 9333 } 9334 } 9335 9336 SmallVector<SDValue, 4> InVals; 9337 CLI.Chain = LowerCall(CLI, InVals); 9338 9339 // Update CLI.InVals to use outside of this function. 9340 CLI.InVals = InVals; 9341 9342 // Verify that the target's LowerCall behaved as expected. 9343 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 9344 "LowerCall didn't return a valid chain!"); 9345 assert((!CLI.IsTailCall || InVals.empty()) && 9346 "LowerCall emitted a return value for a tail call!"); 9347 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9348 "LowerCall didn't emit the correct number of values!"); 9349 9350 // For a tail call, the return value is merely live-out and there aren't 9351 // any nodes in the DAG representing it. Return a special value to 9352 // indicate that a tail call has been emitted and no more Instructions 9353 // should be processed in the current block. 9354 if (CLI.IsTailCall) { 9355 CLI.DAG.setRoot(CLI.Chain); 9356 return std::make_pair(SDValue(), SDValue()); 9357 } 9358 9359 #ifndef NDEBUG 9360 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 9361 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 9362 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 9363 "LowerCall emitted a value with the wrong type!"); 9364 } 9365 #endif 9366 9367 SmallVector<SDValue, 4> ReturnValues; 9368 if (!CanLowerReturn) { 9369 // The instruction result is the result of loading from the 9370 // hidden sret parameter. 9371 SmallVector<EVT, 1> PVTs; 9372 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 9373 9374 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 9375 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 9376 EVT PtrVT = PVTs[0]; 9377 9378 unsigned NumValues = RetTys.size(); 9379 ReturnValues.resize(NumValues); 9380 SmallVector<SDValue, 4> Chains(NumValues); 9381 9382 // An aggregate return value cannot wrap around the address space, so 9383 // offsets to its parts don't wrap either. 9384 SDNodeFlags Flags; 9385 Flags.setNoUnsignedWrap(true); 9386 9387 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9388 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 9389 for (unsigned i = 0; i < NumValues; ++i) { 9390 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 9391 CLI.DAG.getConstant(Offsets[i], CLI.DL, 9392 PtrVT), Flags); 9393 SDValue L = CLI.DAG.getLoad( 9394 RetTys[i], CLI.DL, CLI.Chain, Add, 9395 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 9396 DemoteStackIdx, Offsets[i]), 9397 HiddenSRetAlign); 9398 ReturnValues[i] = L; 9399 Chains[i] = L.getValue(1); 9400 } 9401 9402 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 9403 } else { 9404 // Collect the legal value parts into potentially illegal values 9405 // that correspond to the original function's return values. 9406 Optional<ISD::NodeType> AssertOp; 9407 if (CLI.RetSExt) 9408 AssertOp = ISD::AssertSext; 9409 else if (CLI.RetZExt) 9410 AssertOp = ISD::AssertZext; 9411 unsigned CurReg = 0; 9412 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9413 EVT VT = RetTys[I]; 9414 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9415 CLI.CallConv, VT); 9416 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9417 CLI.CallConv, VT); 9418 9419 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 9420 NumRegs, RegisterVT, VT, nullptr, 9421 CLI.CallConv, AssertOp)); 9422 CurReg += NumRegs; 9423 } 9424 9425 // For a function returning void, there is no return value. We can't create 9426 // such a node, so we just return a null return value in that case. In 9427 // that case, nothing will actually look at the value. 9428 if (ReturnValues.empty()) 9429 return std::make_pair(SDValue(), CLI.Chain); 9430 } 9431 9432 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 9433 CLI.DAG.getVTList(RetTys), ReturnValues); 9434 return std::make_pair(Res, CLI.Chain); 9435 } 9436 9437 void TargetLowering::LowerOperationWrapper(SDNode *N, 9438 SmallVectorImpl<SDValue> &Results, 9439 SelectionDAG &DAG) const { 9440 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG)) 9441 Results.push_back(Res); 9442 } 9443 9444 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9445 llvm_unreachable("LowerOperation not implemented for this target!"); 9446 } 9447 9448 void 9449 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 9450 SDValue Op = getNonRegisterValue(V); 9451 assert((Op.getOpcode() != ISD::CopyFromReg || 9452 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 9453 "Copy from a reg to the same reg!"); 9454 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 9455 9456 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9457 // If this is an InlineAsm we have to match the registers required, not the 9458 // notional registers required by the type. 9459 9460 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 9461 None); // This is not an ABI copy. 9462 SDValue Chain = DAG.getEntryNode(); 9463 9464 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 9465 FuncInfo.PreferredExtendType.end()) 9466 ? ISD::ANY_EXTEND 9467 : FuncInfo.PreferredExtendType[V]; 9468 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 9469 PendingExports.push_back(Chain); 9470 } 9471 9472 #include "llvm/CodeGen/SelectionDAGISel.h" 9473 9474 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 9475 /// entry block, return true. This includes arguments used by switches, since 9476 /// the switch may expand into multiple basic blocks. 9477 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 9478 // With FastISel active, we may be splitting blocks, so force creation 9479 // of virtual registers for all non-dead arguments. 9480 if (FastISel) 9481 return A->use_empty(); 9482 9483 const BasicBlock &Entry = A->getParent()->front(); 9484 for (const User *U : A->users()) 9485 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 9486 return false; // Use not in entry block. 9487 9488 return true; 9489 } 9490 9491 using ArgCopyElisionMapTy = 9492 DenseMap<const Argument *, 9493 std::pair<const AllocaInst *, const StoreInst *>>; 9494 9495 /// Scan the entry block of the function in FuncInfo for arguments that look 9496 /// like copies into a local alloca. Record any copied arguments in 9497 /// ArgCopyElisionCandidates. 9498 static void 9499 findArgumentCopyElisionCandidates(const DataLayout &DL, 9500 FunctionLoweringInfo *FuncInfo, 9501 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 9502 // Record the state of every static alloca used in the entry block. Argument 9503 // allocas are all used in the entry block, so we need approximately as many 9504 // entries as we have arguments. 9505 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 9506 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 9507 unsigned NumArgs = FuncInfo->Fn->arg_size(); 9508 StaticAllocas.reserve(NumArgs * 2); 9509 9510 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 9511 if (!V) 9512 return nullptr; 9513 V = V->stripPointerCasts(); 9514 const auto *AI = dyn_cast<AllocaInst>(V); 9515 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 9516 return nullptr; 9517 auto Iter = StaticAllocas.insert({AI, Unknown}); 9518 return &Iter.first->second; 9519 }; 9520 9521 // Look for stores of arguments to static allocas. Look through bitcasts and 9522 // GEPs to handle type coercions, as long as the alloca is fully initialized 9523 // by the store. Any non-store use of an alloca escapes it and any subsequent 9524 // unanalyzed store might write it. 9525 // FIXME: Handle structs initialized with multiple stores. 9526 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 9527 // Look for stores, and handle non-store uses conservatively. 9528 const auto *SI = dyn_cast<StoreInst>(&I); 9529 if (!SI) { 9530 // We will look through cast uses, so ignore them completely. 9531 if (I.isCast()) 9532 continue; 9533 // Ignore debug info intrinsics, they don't escape or store to allocas. 9534 if (isa<DbgInfoIntrinsic>(I)) 9535 continue; 9536 // This is an unknown instruction. Assume it escapes or writes to all 9537 // static alloca operands. 9538 for (const Use &U : I.operands()) { 9539 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 9540 *Info = StaticAllocaInfo::Clobbered; 9541 } 9542 continue; 9543 } 9544 9545 // If the stored value is a static alloca, mark it as escaped. 9546 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 9547 *Info = StaticAllocaInfo::Clobbered; 9548 9549 // Check if the destination is a static alloca. 9550 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 9551 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 9552 if (!Info) 9553 continue; 9554 const AllocaInst *AI = cast<AllocaInst>(Dst); 9555 9556 // Skip allocas that have been initialized or clobbered. 9557 if (*Info != StaticAllocaInfo::Unknown) 9558 continue; 9559 9560 // Check if the stored value is an argument, and that this store fully 9561 // initializes the alloca. Don't elide copies from the same argument twice. 9562 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 9563 const auto *Arg = dyn_cast<Argument>(Val); 9564 if (!Arg || Arg->hasPassPointeeByValueAttr() || 9565 Arg->getType()->isEmptyTy() || 9566 DL.getTypeStoreSize(Arg->getType()) != 9567 DL.getTypeAllocSize(AI->getAllocatedType()) || 9568 ArgCopyElisionCandidates.count(Arg)) { 9569 *Info = StaticAllocaInfo::Clobbered; 9570 continue; 9571 } 9572 9573 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 9574 << '\n'); 9575 9576 // Mark this alloca and store for argument copy elision. 9577 *Info = StaticAllocaInfo::Elidable; 9578 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 9579 9580 // Stop scanning if we've seen all arguments. This will happen early in -O0 9581 // builds, which is useful, because -O0 builds have large entry blocks and 9582 // many allocas. 9583 if (ArgCopyElisionCandidates.size() == NumArgs) 9584 break; 9585 } 9586 } 9587 9588 /// Try to elide argument copies from memory into a local alloca. Succeeds if 9589 /// ArgVal is a load from a suitable fixed stack object. 9590 static void tryToElideArgumentCopy( 9591 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 9592 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 9593 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 9594 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 9595 SDValue ArgVal, bool &ArgHasUses) { 9596 // Check if this is a load from a fixed stack object. 9597 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 9598 if (!LNode) 9599 return; 9600 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 9601 if (!FINode) 9602 return; 9603 9604 // Check that the fixed stack object is the right size and alignment. 9605 // Look at the alignment that the user wrote on the alloca instead of looking 9606 // at the stack object. 9607 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 9608 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 9609 const AllocaInst *AI = ArgCopyIter->second.first; 9610 int FixedIndex = FINode->getIndex(); 9611 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 9612 int OldIndex = AllocaIndex; 9613 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 9614 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 9615 LLVM_DEBUG( 9616 dbgs() << " argument copy elision failed due to bad fixed stack " 9617 "object size\n"); 9618 return; 9619 } 9620 Align RequiredAlignment = AI->getAlign(); 9621 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 9622 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 9623 "greater than stack argument alignment (" 9624 << DebugStr(RequiredAlignment) << " vs " 9625 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 9626 return; 9627 } 9628 9629 // Perform the elision. Delete the old stack object and replace its only use 9630 // in the variable info map. Mark the stack object as mutable. 9631 LLVM_DEBUG({ 9632 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 9633 << " Replacing frame index " << OldIndex << " with " << FixedIndex 9634 << '\n'; 9635 }); 9636 MFI.RemoveStackObject(OldIndex); 9637 MFI.setIsImmutableObjectIndex(FixedIndex, false); 9638 AllocaIndex = FixedIndex; 9639 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 9640 Chains.push_back(ArgVal.getValue(1)); 9641 9642 // Avoid emitting code for the store implementing the copy. 9643 const StoreInst *SI = ArgCopyIter->second.second; 9644 ElidedArgCopyInstrs.insert(SI); 9645 9646 // Check for uses of the argument again so that we can avoid exporting ArgVal 9647 // if it is't used by anything other than the store. 9648 for (const Value *U : Arg.users()) { 9649 if (U != SI) { 9650 ArgHasUses = true; 9651 break; 9652 } 9653 } 9654 } 9655 9656 void SelectionDAGISel::LowerArguments(const Function &F) { 9657 SelectionDAG &DAG = SDB->DAG; 9658 SDLoc dl = SDB->getCurSDLoc(); 9659 const DataLayout &DL = DAG.getDataLayout(); 9660 SmallVector<ISD::InputArg, 16> Ins; 9661 9662 // In Naked functions we aren't going to save any registers. 9663 if (F.hasFnAttribute(Attribute::Naked)) 9664 return; 9665 9666 if (!FuncInfo->CanLowerReturn) { 9667 // Put in an sret pointer parameter before all the other parameters. 9668 SmallVector<EVT, 1> ValueVTs; 9669 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9670 F.getReturnType()->getPointerTo( 9671 DAG.getDataLayout().getAllocaAddrSpace()), 9672 ValueVTs); 9673 9674 // NOTE: Assuming that a pointer will never break down to more than one VT 9675 // or one register. 9676 ISD::ArgFlagsTy Flags; 9677 Flags.setSRet(); 9678 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 9679 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 9680 ISD::InputArg::NoArgIndex, 0); 9681 Ins.push_back(RetArg); 9682 } 9683 9684 // Look for stores of arguments to static allocas. Mark such arguments with a 9685 // flag to ask the target to give us the memory location of that argument if 9686 // available. 9687 ArgCopyElisionMapTy ArgCopyElisionCandidates; 9688 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 9689 ArgCopyElisionCandidates); 9690 9691 // Set up the incoming argument description vector. 9692 for (const Argument &Arg : F.args()) { 9693 unsigned ArgNo = Arg.getArgNo(); 9694 SmallVector<EVT, 4> ValueVTs; 9695 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9696 bool isArgValueUsed = !Arg.use_empty(); 9697 unsigned PartBase = 0; 9698 Type *FinalType = Arg.getType(); 9699 if (Arg.hasAttribute(Attribute::ByVal)) 9700 FinalType = Arg.getParamByValType(); 9701 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 9702 FinalType, F.getCallingConv(), F.isVarArg()); 9703 for (unsigned Value = 0, NumValues = ValueVTs.size(); 9704 Value != NumValues; ++Value) { 9705 EVT VT = ValueVTs[Value]; 9706 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 9707 ISD::ArgFlagsTy Flags; 9708 9709 // Certain targets (such as MIPS), may have a different ABI alignment 9710 // for a type depending on the context. Give the target a chance to 9711 // specify the alignment it wants. 9712 const Align OriginalAlignment( 9713 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 9714 9715 if (Arg.getType()->isPointerTy()) { 9716 Flags.setPointer(); 9717 Flags.setPointerAddrSpace( 9718 cast<PointerType>(Arg.getType())->getAddressSpace()); 9719 } 9720 if (Arg.hasAttribute(Attribute::ZExt)) 9721 Flags.setZExt(); 9722 if (Arg.hasAttribute(Attribute::SExt)) 9723 Flags.setSExt(); 9724 if (Arg.hasAttribute(Attribute::InReg)) { 9725 // If we are using vectorcall calling convention, a structure that is 9726 // passed InReg - is surely an HVA 9727 if (F.getCallingConv() == CallingConv::X86_VectorCall && 9728 isa<StructType>(Arg.getType())) { 9729 // The first value of a structure is marked 9730 if (0 == Value) 9731 Flags.setHvaStart(); 9732 Flags.setHva(); 9733 } 9734 // Set InReg Flag 9735 Flags.setInReg(); 9736 } 9737 if (Arg.hasAttribute(Attribute::StructRet)) 9738 Flags.setSRet(); 9739 if (Arg.hasAttribute(Attribute::SwiftSelf)) 9740 Flags.setSwiftSelf(); 9741 if (Arg.hasAttribute(Attribute::SwiftError)) 9742 Flags.setSwiftError(); 9743 if (Arg.hasAttribute(Attribute::ByVal)) 9744 Flags.setByVal(); 9745 if (Arg.hasAttribute(Attribute::InAlloca)) { 9746 Flags.setInAlloca(); 9747 // Set the byval flag for CCAssignFn callbacks that don't know about 9748 // inalloca. This way we can know how many bytes we should've allocated 9749 // and how many bytes a callee cleanup function will pop. If we port 9750 // inalloca to more targets, we'll have to add custom inalloca handling 9751 // in the various CC lowering callbacks. 9752 Flags.setByVal(); 9753 } 9754 if (Arg.hasAttribute(Attribute::Preallocated)) { 9755 Flags.setPreallocated(); 9756 // Set the byval flag for CCAssignFn callbacks that don't know about 9757 // preallocated. This way we can know how many bytes we should've 9758 // allocated and how many bytes a callee cleanup function will pop. If 9759 // we port preallocated to more targets, we'll have to add custom 9760 // preallocated handling in the various CC lowering callbacks. 9761 Flags.setByVal(); 9762 } 9763 if (F.getCallingConv() == CallingConv::X86_INTR) { 9764 // IA Interrupt passes frame (1st parameter) by value in the stack. 9765 if (ArgNo == 0) 9766 Flags.setByVal(); 9767 } 9768 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated()) { 9769 Type *ElementTy = Arg.getParamByValType(); 9770 9771 // For ByVal, size and alignment should be passed from FE. BE will 9772 // guess if this info is not there but there are cases it cannot get 9773 // right. 9774 unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType()); 9775 Flags.setByValSize(FrameSize); 9776 9777 unsigned FrameAlign; 9778 if (Arg.getParamAlignment()) 9779 FrameAlign = Arg.getParamAlignment(); 9780 else 9781 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL); 9782 Flags.setByValAlign(Align(FrameAlign)); 9783 } 9784 if (Arg.hasAttribute(Attribute::Nest)) 9785 Flags.setNest(); 9786 if (NeedsRegBlock) 9787 Flags.setInConsecutiveRegs(); 9788 Flags.setOrigAlign(OriginalAlignment); 9789 if (ArgCopyElisionCandidates.count(&Arg)) 9790 Flags.setCopyElisionCandidate(); 9791 if (Arg.hasAttribute(Attribute::Returned)) 9792 Flags.setReturned(); 9793 9794 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 9795 *CurDAG->getContext(), F.getCallingConv(), VT); 9796 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 9797 *CurDAG->getContext(), F.getCallingConv(), VT); 9798 for (unsigned i = 0; i != NumRegs; ++i) { 9799 // For scalable vectors, use the minimum size; individual targets 9800 // are responsible for handling scalable vector arguments and 9801 // return values. 9802 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 9803 ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize()); 9804 if (NumRegs > 1 && i == 0) 9805 MyFlags.Flags.setSplit(); 9806 // if it isn't first piece, alignment must be 1 9807 else if (i > 0) { 9808 MyFlags.Flags.setOrigAlign(Align(1)); 9809 if (i == NumRegs - 1) 9810 MyFlags.Flags.setSplitEnd(); 9811 } 9812 Ins.push_back(MyFlags); 9813 } 9814 if (NeedsRegBlock && Value == NumValues - 1) 9815 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 9816 PartBase += VT.getStoreSize().getKnownMinSize(); 9817 } 9818 } 9819 9820 // Call the target to set up the argument values. 9821 SmallVector<SDValue, 8> InVals; 9822 SDValue NewRoot = TLI->LowerFormalArguments( 9823 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 9824 9825 // Verify that the target's LowerFormalArguments behaved as expected. 9826 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 9827 "LowerFormalArguments didn't return a valid chain!"); 9828 assert(InVals.size() == Ins.size() && 9829 "LowerFormalArguments didn't emit the correct number of values!"); 9830 LLVM_DEBUG({ 9831 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 9832 assert(InVals[i].getNode() && 9833 "LowerFormalArguments emitted a null value!"); 9834 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 9835 "LowerFormalArguments emitted a value with the wrong type!"); 9836 } 9837 }); 9838 9839 // Update the DAG with the new chain value resulting from argument lowering. 9840 DAG.setRoot(NewRoot); 9841 9842 // Set up the argument values. 9843 unsigned i = 0; 9844 if (!FuncInfo->CanLowerReturn) { 9845 // Create a virtual register for the sret pointer, and put in a copy 9846 // from the sret argument into it. 9847 SmallVector<EVT, 1> ValueVTs; 9848 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9849 F.getReturnType()->getPointerTo( 9850 DAG.getDataLayout().getAllocaAddrSpace()), 9851 ValueVTs); 9852 MVT VT = ValueVTs[0].getSimpleVT(); 9853 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 9854 Optional<ISD::NodeType> AssertOp = None; 9855 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 9856 nullptr, F.getCallingConv(), AssertOp); 9857 9858 MachineFunction& MF = SDB->DAG.getMachineFunction(); 9859 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 9860 Register SRetReg = 9861 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 9862 FuncInfo->DemoteRegister = SRetReg; 9863 NewRoot = 9864 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 9865 DAG.setRoot(NewRoot); 9866 9867 // i indexes lowered arguments. Bump it past the hidden sret argument. 9868 ++i; 9869 } 9870 9871 SmallVector<SDValue, 4> Chains; 9872 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 9873 for (const Argument &Arg : F.args()) { 9874 SmallVector<SDValue, 4> ArgValues; 9875 SmallVector<EVT, 4> ValueVTs; 9876 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9877 unsigned NumValues = ValueVTs.size(); 9878 if (NumValues == 0) 9879 continue; 9880 9881 bool ArgHasUses = !Arg.use_empty(); 9882 9883 // Elide the copying store if the target loaded this argument from a 9884 // suitable fixed stack object. 9885 if (Ins[i].Flags.isCopyElisionCandidate()) { 9886 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 9887 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 9888 InVals[i], ArgHasUses); 9889 } 9890 9891 // If this argument is unused then remember its value. It is used to generate 9892 // debugging information. 9893 bool isSwiftErrorArg = 9894 TLI->supportSwiftError() && 9895 Arg.hasAttribute(Attribute::SwiftError); 9896 if (!ArgHasUses && !isSwiftErrorArg) { 9897 SDB->setUnusedArgValue(&Arg, InVals[i]); 9898 9899 // Also remember any frame index for use in FastISel. 9900 if (FrameIndexSDNode *FI = 9901 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 9902 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9903 } 9904 9905 for (unsigned Val = 0; Val != NumValues; ++Val) { 9906 EVT VT = ValueVTs[Val]; 9907 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 9908 F.getCallingConv(), VT); 9909 unsigned NumParts = TLI->getNumRegistersForCallingConv( 9910 *CurDAG->getContext(), F.getCallingConv(), VT); 9911 9912 // Even an apparent 'unused' swifterror argument needs to be returned. So 9913 // we do generate a copy for it that can be used on return from the 9914 // function. 9915 if (ArgHasUses || isSwiftErrorArg) { 9916 Optional<ISD::NodeType> AssertOp; 9917 if (Arg.hasAttribute(Attribute::SExt)) 9918 AssertOp = ISD::AssertSext; 9919 else if (Arg.hasAttribute(Attribute::ZExt)) 9920 AssertOp = ISD::AssertZext; 9921 9922 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 9923 PartVT, VT, nullptr, 9924 F.getCallingConv(), AssertOp)); 9925 } 9926 9927 i += NumParts; 9928 } 9929 9930 // We don't need to do anything else for unused arguments. 9931 if (ArgValues.empty()) 9932 continue; 9933 9934 // Note down frame index. 9935 if (FrameIndexSDNode *FI = 9936 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 9937 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9938 9939 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 9940 SDB->getCurSDLoc()); 9941 9942 SDB->setValue(&Arg, Res); 9943 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 9944 // We want to associate the argument with the frame index, among 9945 // involved operands, that correspond to the lowest address. The 9946 // getCopyFromParts function, called earlier, is swapping the order of 9947 // the operands to BUILD_PAIR depending on endianness. The result of 9948 // that swapping is that the least significant bits of the argument will 9949 // be in the first operand of the BUILD_PAIR node, and the most 9950 // significant bits will be in the second operand. 9951 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 9952 if (LoadSDNode *LNode = 9953 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 9954 if (FrameIndexSDNode *FI = 9955 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 9956 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9957 } 9958 9959 // Analyses past this point are naive and don't expect an assertion. 9960 if (Res.getOpcode() == ISD::AssertZext) 9961 Res = Res.getOperand(0); 9962 9963 // Update the SwiftErrorVRegDefMap. 9964 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 9965 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9966 if (Register::isVirtualRegister(Reg)) 9967 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 9968 Reg); 9969 } 9970 9971 // If this argument is live outside of the entry block, insert a copy from 9972 // wherever we got it to the vreg that other BB's will reference it as. 9973 if (Res.getOpcode() == ISD::CopyFromReg) { 9974 // If we can, though, try to skip creating an unnecessary vreg. 9975 // FIXME: This isn't very clean... it would be nice to make this more 9976 // general. 9977 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9978 if (Register::isVirtualRegister(Reg)) { 9979 FuncInfo->ValueMap[&Arg] = Reg; 9980 continue; 9981 } 9982 } 9983 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 9984 FuncInfo->InitializeRegForValue(&Arg); 9985 SDB->CopyToExportRegsIfNeeded(&Arg); 9986 } 9987 } 9988 9989 if (!Chains.empty()) { 9990 Chains.push_back(NewRoot); 9991 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 9992 } 9993 9994 DAG.setRoot(NewRoot); 9995 9996 assert(i == InVals.size() && "Argument register count mismatch!"); 9997 9998 // If any argument copy elisions occurred and we have debug info, update the 9999 // stale frame indices used in the dbg.declare variable info table. 10000 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 10001 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 10002 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 10003 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 10004 if (I != ArgCopyElisionFrameIndexMap.end()) 10005 VI.Slot = I->second; 10006 } 10007 } 10008 10009 // Finally, if the target has anything special to do, allow it to do so. 10010 emitFunctionEntryCode(); 10011 } 10012 10013 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 10014 /// ensure constants are generated when needed. Remember the virtual registers 10015 /// that need to be added to the Machine PHI nodes as input. We cannot just 10016 /// directly add them, because expansion might result in multiple MBB's for one 10017 /// BB. As such, the start of the BB might correspond to a different MBB than 10018 /// the end. 10019 void 10020 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 10021 const Instruction *TI = LLVMBB->getTerminator(); 10022 10023 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 10024 10025 // Check PHI nodes in successors that expect a value to be available from this 10026 // block. 10027 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 10028 const BasicBlock *SuccBB = TI->getSuccessor(succ); 10029 if (!isa<PHINode>(SuccBB->begin())) continue; 10030 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 10031 10032 // If this terminator has multiple identical successors (common for 10033 // switches), only handle each succ once. 10034 if (!SuccsHandled.insert(SuccMBB).second) 10035 continue; 10036 10037 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 10038 10039 // At this point we know that there is a 1-1 correspondence between LLVM PHI 10040 // nodes and Machine PHI nodes, but the incoming operands have not been 10041 // emitted yet. 10042 for (const PHINode &PN : SuccBB->phis()) { 10043 // Ignore dead phi's. 10044 if (PN.use_empty()) 10045 continue; 10046 10047 // Skip empty types 10048 if (PN.getType()->isEmptyTy()) 10049 continue; 10050 10051 unsigned Reg; 10052 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 10053 10054 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 10055 unsigned &RegOut = ConstantsOut[C]; 10056 if (RegOut == 0) { 10057 RegOut = FuncInfo.CreateRegs(C); 10058 CopyValueToVirtualRegister(C, RegOut); 10059 } 10060 Reg = RegOut; 10061 } else { 10062 DenseMap<const Value *, Register>::iterator I = 10063 FuncInfo.ValueMap.find(PHIOp); 10064 if (I != FuncInfo.ValueMap.end()) 10065 Reg = I->second; 10066 else { 10067 assert(isa<AllocaInst>(PHIOp) && 10068 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 10069 "Didn't codegen value into a register!??"); 10070 Reg = FuncInfo.CreateRegs(PHIOp); 10071 CopyValueToVirtualRegister(PHIOp, Reg); 10072 } 10073 } 10074 10075 // Remember that this register needs to added to the machine PHI node as 10076 // the input for this MBB. 10077 SmallVector<EVT, 4> ValueVTs; 10078 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10079 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 10080 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 10081 EVT VT = ValueVTs[vti]; 10082 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 10083 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 10084 FuncInfo.PHINodesToUpdate.push_back( 10085 std::make_pair(&*MBBI++, Reg + i)); 10086 Reg += NumRegisters; 10087 } 10088 } 10089 } 10090 10091 ConstantsOut.clear(); 10092 } 10093 10094 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 10095 /// is 0. 10096 MachineBasicBlock * 10097 SelectionDAGBuilder::StackProtectorDescriptor:: 10098 AddSuccessorMBB(const BasicBlock *BB, 10099 MachineBasicBlock *ParentMBB, 10100 bool IsLikely, 10101 MachineBasicBlock *SuccMBB) { 10102 // If SuccBB has not been created yet, create it. 10103 if (!SuccMBB) { 10104 MachineFunction *MF = ParentMBB->getParent(); 10105 MachineFunction::iterator BBI(ParentMBB); 10106 SuccMBB = MF->CreateMachineBasicBlock(BB); 10107 MF->insert(++BBI, SuccMBB); 10108 } 10109 // Add it as a successor of ParentMBB. 10110 ParentMBB->addSuccessor( 10111 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 10112 return SuccMBB; 10113 } 10114 10115 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 10116 MachineFunction::iterator I(MBB); 10117 if (++I == FuncInfo.MF->end()) 10118 return nullptr; 10119 return &*I; 10120 } 10121 10122 /// During lowering new call nodes can be created (such as memset, etc.). 10123 /// Those will become new roots of the current DAG, but complications arise 10124 /// when they are tail calls. In such cases, the call lowering will update 10125 /// the root, but the builder still needs to know that a tail call has been 10126 /// lowered in order to avoid generating an additional return. 10127 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 10128 // If the node is null, we do have a tail call. 10129 if (MaybeTC.getNode() != nullptr) 10130 DAG.setRoot(MaybeTC); 10131 else 10132 HasTailCall = true; 10133 } 10134 10135 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10136 MachineBasicBlock *SwitchMBB, 10137 MachineBasicBlock *DefaultMBB) { 10138 MachineFunction *CurMF = FuncInfo.MF; 10139 MachineBasicBlock *NextMBB = nullptr; 10140 MachineFunction::iterator BBI(W.MBB); 10141 if (++BBI != FuncInfo.MF->end()) 10142 NextMBB = &*BBI; 10143 10144 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10145 10146 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10147 10148 if (Size == 2 && W.MBB == SwitchMBB) { 10149 // If any two of the cases has the same destination, and if one value 10150 // is the same as the other, but has one bit unset that the other has set, 10151 // use bit manipulation to do two compares at once. For example: 10152 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10153 // TODO: This could be extended to merge any 2 cases in switches with 3 10154 // cases. 10155 // TODO: Handle cases where W.CaseBB != SwitchBB. 10156 CaseCluster &Small = *W.FirstCluster; 10157 CaseCluster &Big = *W.LastCluster; 10158 10159 if (Small.Low == Small.High && Big.Low == Big.High && 10160 Small.MBB == Big.MBB) { 10161 const APInt &SmallValue = Small.Low->getValue(); 10162 const APInt &BigValue = Big.Low->getValue(); 10163 10164 // Check that there is only one bit different. 10165 APInt CommonBit = BigValue ^ SmallValue; 10166 if (CommonBit.isPowerOf2()) { 10167 SDValue CondLHS = getValue(Cond); 10168 EVT VT = CondLHS.getValueType(); 10169 SDLoc DL = getCurSDLoc(); 10170 10171 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10172 DAG.getConstant(CommonBit, DL, VT)); 10173 SDValue Cond = DAG.getSetCC( 10174 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10175 ISD::SETEQ); 10176 10177 // Update successor info. 10178 // Both Small and Big will jump to Small.BB, so we sum up the 10179 // probabilities. 10180 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10181 if (BPI) 10182 addSuccessorWithProb( 10183 SwitchMBB, DefaultMBB, 10184 // The default destination is the first successor in IR. 10185 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10186 else 10187 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10188 10189 // Insert the true branch. 10190 SDValue BrCond = 10191 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10192 DAG.getBasicBlock(Small.MBB)); 10193 // Insert the false branch. 10194 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10195 DAG.getBasicBlock(DefaultMBB)); 10196 10197 DAG.setRoot(BrCond); 10198 return; 10199 } 10200 } 10201 } 10202 10203 if (TM.getOptLevel() != CodeGenOpt::None) { 10204 // Here, we order cases by probability so the most likely case will be 10205 // checked first. However, two clusters can have the same probability in 10206 // which case their relative ordering is non-deterministic. So we use Low 10207 // as a tie-breaker as clusters are guaranteed to never overlap. 10208 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10209 [](const CaseCluster &a, const CaseCluster &b) { 10210 return a.Prob != b.Prob ? 10211 a.Prob > b.Prob : 10212 a.Low->getValue().slt(b.Low->getValue()); 10213 }); 10214 10215 // Rearrange the case blocks so that the last one falls through if possible 10216 // without changing the order of probabilities. 10217 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10218 --I; 10219 if (I->Prob > W.LastCluster->Prob) 10220 break; 10221 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10222 std::swap(*I, *W.LastCluster); 10223 break; 10224 } 10225 } 10226 } 10227 10228 // Compute total probability. 10229 BranchProbability DefaultProb = W.DefaultProb; 10230 BranchProbability UnhandledProbs = DefaultProb; 10231 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10232 UnhandledProbs += I->Prob; 10233 10234 MachineBasicBlock *CurMBB = W.MBB; 10235 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10236 bool FallthroughUnreachable = false; 10237 MachineBasicBlock *Fallthrough; 10238 if (I == W.LastCluster) { 10239 // For the last cluster, fall through to the default destination. 10240 Fallthrough = DefaultMBB; 10241 FallthroughUnreachable = isa<UnreachableInst>( 10242 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10243 } else { 10244 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10245 CurMF->insert(BBI, Fallthrough); 10246 // Put Cond in a virtual register to make it available from the new blocks. 10247 ExportFromCurrentBlock(Cond); 10248 } 10249 UnhandledProbs -= I->Prob; 10250 10251 switch (I->Kind) { 10252 case CC_JumpTable: { 10253 // FIXME: Optimize away range check based on pivot comparisons. 10254 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 10255 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 10256 10257 // The jump block hasn't been inserted yet; insert it here. 10258 MachineBasicBlock *JumpMBB = JT->MBB; 10259 CurMF->insert(BBI, JumpMBB); 10260 10261 auto JumpProb = I->Prob; 10262 auto FallthroughProb = UnhandledProbs; 10263 10264 // If the default statement is a target of the jump table, we evenly 10265 // distribute the default probability to successors of CurMBB. Also 10266 // update the probability on the edge from JumpMBB to Fallthrough. 10267 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10268 SE = JumpMBB->succ_end(); 10269 SI != SE; ++SI) { 10270 if (*SI == DefaultMBB) { 10271 JumpProb += DefaultProb / 2; 10272 FallthroughProb -= DefaultProb / 2; 10273 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10274 JumpMBB->normalizeSuccProbs(); 10275 break; 10276 } 10277 } 10278 10279 if (FallthroughUnreachable) { 10280 // Skip the range check if the fallthrough block is unreachable. 10281 JTH->OmitRangeCheck = true; 10282 } 10283 10284 if (!JTH->OmitRangeCheck) 10285 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10286 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10287 CurMBB->normalizeSuccProbs(); 10288 10289 // The jump table header will be inserted in our current block, do the 10290 // range check, and fall through to our fallthrough block. 10291 JTH->HeaderBB = CurMBB; 10292 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10293 10294 // If we're in the right place, emit the jump table header right now. 10295 if (CurMBB == SwitchMBB) { 10296 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10297 JTH->Emitted = true; 10298 } 10299 break; 10300 } 10301 case CC_BitTests: { 10302 // FIXME: Optimize away range check based on pivot comparisons. 10303 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 10304 10305 // The bit test blocks haven't been inserted yet; insert them here. 10306 for (BitTestCase &BTC : BTB->Cases) 10307 CurMF->insert(BBI, BTC.ThisBB); 10308 10309 // Fill in fields of the BitTestBlock. 10310 BTB->Parent = CurMBB; 10311 BTB->Default = Fallthrough; 10312 10313 BTB->DefaultProb = UnhandledProbs; 10314 // If the cases in bit test don't form a contiguous range, we evenly 10315 // distribute the probability on the edge to Fallthrough to two 10316 // successors of CurMBB. 10317 if (!BTB->ContiguousRange) { 10318 BTB->Prob += DefaultProb / 2; 10319 BTB->DefaultProb -= DefaultProb / 2; 10320 } 10321 10322 if (FallthroughUnreachable) { 10323 // Skip the range check if the fallthrough block is unreachable. 10324 BTB->OmitRangeCheck = true; 10325 } 10326 10327 // If we're in the right place, emit the bit test header right now. 10328 if (CurMBB == SwitchMBB) { 10329 visitBitTestHeader(*BTB, SwitchMBB); 10330 BTB->Emitted = true; 10331 } 10332 break; 10333 } 10334 case CC_Range: { 10335 const Value *RHS, *LHS, *MHS; 10336 ISD::CondCode CC; 10337 if (I->Low == I->High) { 10338 // Check Cond == I->Low. 10339 CC = ISD::SETEQ; 10340 LHS = Cond; 10341 RHS=I->Low; 10342 MHS = nullptr; 10343 } else { 10344 // Check I->Low <= Cond <= I->High. 10345 CC = ISD::SETLE; 10346 LHS = I->Low; 10347 MHS = Cond; 10348 RHS = I->High; 10349 } 10350 10351 // If Fallthrough is unreachable, fold away the comparison. 10352 if (FallthroughUnreachable) 10353 CC = ISD::SETTRUE; 10354 10355 // The false probability is the sum of all unhandled cases. 10356 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10357 getCurSDLoc(), I->Prob, UnhandledProbs); 10358 10359 if (CurMBB == SwitchMBB) 10360 visitSwitchCase(CB, SwitchMBB); 10361 else 10362 SL->SwitchCases.push_back(CB); 10363 10364 break; 10365 } 10366 } 10367 CurMBB = Fallthrough; 10368 } 10369 } 10370 10371 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10372 CaseClusterIt First, 10373 CaseClusterIt Last) { 10374 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10375 if (X.Prob != CC.Prob) 10376 return X.Prob > CC.Prob; 10377 10378 // Ties are broken by comparing the case value. 10379 return X.Low->getValue().slt(CC.Low->getValue()); 10380 }); 10381 } 10382 10383 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10384 const SwitchWorkListItem &W, 10385 Value *Cond, 10386 MachineBasicBlock *SwitchMBB) { 10387 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10388 "Clusters not sorted?"); 10389 10390 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10391 10392 // Balance the tree based on branch probabilities to create a near-optimal (in 10393 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10394 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10395 CaseClusterIt LastLeft = W.FirstCluster; 10396 CaseClusterIt FirstRight = W.LastCluster; 10397 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10398 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10399 10400 // Move LastLeft and FirstRight towards each other from opposite directions to 10401 // find a partitioning of the clusters which balances the probability on both 10402 // sides. If LeftProb and RightProb are equal, alternate which side is 10403 // taken to ensure 0-probability nodes are distributed evenly. 10404 unsigned I = 0; 10405 while (LastLeft + 1 < FirstRight) { 10406 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10407 LeftProb += (++LastLeft)->Prob; 10408 else 10409 RightProb += (--FirstRight)->Prob; 10410 I++; 10411 } 10412 10413 while (true) { 10414 // Our binary search tree differs from a typical BST in that ours can have up 10415 // to three values in each leaf. The pivot selection above doesn't take that 10416 // into account, which means the tree might require more nodes and be less 10417 // efficient. We compensate for this here. 10418 10419 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10420 unsigned NumRight = W.LastCluster - FirstRight + 1; 10421 10422 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10423 // If one side has less than 3 clusters, and the other has more than 3, 10424 // consider taking a cluster from the other side. 10425 10426 if (NumLeft < NumRight) { 10427 // Consider moving the first cluster on the right to the left side. 10428 CaseCluster &CC = *FirstRight; 10429 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10430 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10431 if (LeftSideRank <= RightSideRank) { 10432 // Moving the cluster to the left does not demote it. 10433 ++LastLeft; 10434 ++FirstRight; 10435 continue; 10436 } 10437 } else { 10438 assert(NumRight < NumLeft); 10439 // Consider moving the last element on the left to the right side. 10440 CaseCluster &CC = *LastLeft; 10441 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10442 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10443 if (RightSideRank <= LeftSideRank) { 10444 // Moving the cluster to the right does not demot it. 10445 --LastLeft; 10446 --FirstRight; 10447 continue; 10448 } 10449 } 10450 } 10451 break; 10452 } 10453 10454 assert(LastLeft + 1 == FirstRight); 10455 assert(LastLeft >= W.FirstCluster); 10456 assert(FirstRight <= W.LastCluster); 10457 10458 // Use the first element on the right as pivot since we will make less-than 10459 // comparisons against it. 10460 CaseClusterIt PivotCluster = FirstRight; 10461 assert(PivotCluster > W.FirstCluster); 10462 assert(PivotCluster <= W.LastCluster); 10463 10464 CaseClusterIt FirstLeft = W.FirstCluster; 10465 CaseClusterIt LastRight = W.LastCluster; 10466 10467 const ConstantInt *Pivot = PivotCluster->Low; 10468 10469 // New blocks will be inserted immediately after the current one. 10470 MachineFunction::iterator BBI(W.MBB); 10471 ++BBI; 10472 10473 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10474 // we can branch to its destination directly if it's squeezed exactly in 10475 // between the known lower bound and Pivot - 1. 10476 MachineBasicBlock *LeftMBB; 10477 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10478 FirstLeft->Low == W.GE && 10479 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10480 LeftMBB = FirstLeft->MBB; 10481 } else { 10482 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10483 FuncInfo.MF->insert(BBI, LeftMBB); 10484 WorkList.push_back( 10485 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10486 // Put Cond in a virtual register to make it available from the new blocks. 10487 ExportFromCurrentBlock(Cond); 10488 } 10489 10490 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10491 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10492 // directly if RHS.High equals the current upper bound. 10493 MachineBasicBlock *RightMBB; 10494 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10495 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10496 RightMBB = FirstRight->MBB; 10497 } else { 10498 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10499 FuncInfo.MF->insert(BBI, RightMBB); 10500 WorkList.push_back( 10501 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10502 // Put Cond in a virtual register to make it available from the new blocks. 10503 ExportFromCurrentBlock(Cond); 10504 } 10505 10506 // Create the CaseBlock record that will be used to lower the branch. 10507 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10508 getCurSDLoc(), LeftProb, RightProb); 10509 10510 if (W.MBB == SwitchMBB) 10511 visitSwitchCase(CB, SwitchMBB); 10512 else 10513 SL->SwitchCases.push_back(CB); 10514 } 10515 10516 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10517 // from the swith statement. 10518 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10519 BranchProbability PeeledCaseProb) { 10520 if (PeeledCaseProb == BranchProbability::getOne()) 10521 return BranchProbability::getZero(); 10522 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10523 10524 uint32_t Numerator = CaseProb.getNumerator(); 10525 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10526 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10527 } 10528 10529 // Try to peel the top probability case if it exceeds the threshold. 10530 // Return current MachineBasicBlock for the switch statement if the peeling 10531 // does not occur. 10532 // If the peeling is performed, return the newly created MachineBasicBlock 10533 // for the peeled switch statement. Also update Clusters to remove the peeled 10534 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10535 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10536 const SwitchInst &SI, CaseClusterVector &Clusters, 10537 BranchProbability &PeeledCaseProb) { 10538 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10539 // Don't perform if there is only one cluster or optimizing for size. 10540 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10541 TM.getOptLevel() == CodeGenOpt::None || 10542 SwitchMBB->getParent()->getFunction().hasMinSize()) 10543 return SwitchMBB; 10544 10545 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10546 unsigned PeeledCaseIndex = 0; 10547 bool SwitchPeeled = false; 10548 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10549 CaseCluster &CC = Clusters[Index]; 10550 if (CC.Prob < TopCaseProb) 10551 continue; 10552 TopCaseProb = CC.Prob; 10553 PeeledCaseIndex = Index; 10554 SwitchPeeled = true; 10555 } 10556 if (!SwitchPeeled) 10557 return SwitchMBB; 10558 10559 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10560 << TopCaseProb << "\n"); 10561 10562 // Record the MBB for the peeled switch statement. 10563 MachineFunction::iterator BBI(SwitchMBB); 10564 ++BBI; 10565 MachineBasicBlock *PeeledSwitchMBB = 10566 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10567 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10568 10569 ExportFromCurrentBlock(SI.getCondition()); 10570 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10571 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10572 nullptr, nullptr, TopCaseProb.getCompl()}; 10573 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10574 10575 Clusters.erase(PeeledCaseIt); 10576 for (CaseCluster &CC : Clusters) { 10577 LLVM_DEBUG( 10578 dbgs() << "Scale the probablity for one cluster, before scaling: " 10579 << CC.Prob << "\n"); 10580 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10581 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10582 } 10583 PeeledCaseProb = TopCaseProb; 10584 return PeeledSwitchMBB; 10585 } 10586 10587 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10588 // Extract cases from the switch. 10589 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10590 CaseClusterVector Clusters; 10591 Clusters.reserve(SI.getNumCases()); 10592 for (auto I : SI.cases()) { 10593 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10594 const ConstantInt *CaseVal = I.getCaseValue(); 10595 BranchProbability Prob = 10596 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10597 : BranchProbability(1, SI.getNumCases() + 1); 10598 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10599 } 10600 10601 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10602 10603 // Cluster adjacent cases with the same destination. We do this at all 10604 // optimization levels because it's cheap to do and will make codegen faster 10605 // if there are many clusters. 10606 sortAndRangeify(Clusters); 10607 10608 // The branch probablity of the peeled case. 10609 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10610 MachineBasicBlock *PeeledSwitchMBB = 10611 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10612 10613 // If there is only the default destination, jump there directly. 10614 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10615 if (Clusters.empty()) { 10616 assert(PeeledSwitchMBB == SwitchMBB); 10617 SwitchMBB->addSuccessor(DefaultMBB); 10618 if (DefaultMBB != NextBlock(SwitchMBB)) { 10619 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10620 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10621 } 10622 return; 10623 } 10624 10625 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 10626 SL->findBitTestClusters(Clusters, &SI); 10627 10628 LLVM_DEBUG({ 10629 dbgs() << "Case clusters: "; 10630 for (const CaseCluster &C : Clusters) { 10631 if (C.Kind == CC_JumpTable) 10632 dbgs() << "JT:"; 10633 if (C.Kind == CC_BitTests) 10634 dbgs() << "BT:"; 10635 10636 C.Low->getValue().print(dbgs(), true); 10637 if (C.Low != C.High) { 10638 dbgs() << '-'; 10639 C.High->getValue().print(dbgs(), true); 10640 } 10641 dbgs() << ' '; 10642 } 10643 dbgs() << '\n'; 10644 }); 10645 10646 assert(!Clusters.empty()); 10647 SwitchWorkList WorkList; 10648 CaseClusterIt First = Clusters.begin(); 10649 CaseClusterIt Last = Clusters.end() - 1; 10650 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10651 // Scale the branchprobability for DefaultMBB if the peel occurs and 10652 // DefaultMBB is not replaced. 10653 if (PeeledCaseProb != BranchProbability::getZero() && 10654 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10655 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10656 WorkList.push_back( 10657 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10658 10659 while (!WorkList.empty()) { 10660 SwitchWorkListItem W = WorkList.back(); 10661 WorkList.pop_back(); 10662 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10663 10664 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10665 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 10666 // For optimized builds, lower large range as a balanced binary tree. 10667 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10668 continue; 10669 } 10670 10671 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10672 } 10673 } 10674 10675 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 10676 SmallVector<EVT, 4> ValueVTs; 10677 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 10678 ValueVTs); 10679 unsigned NumValues = ValueVTs.size(); 10680 if (NumValues == 0) return; 10681 10682 SmallVector<SDValue, 4> Values(NumValues); 10683 SDValue Op = getValue(I.getOperand(0)); 10684 10685 for (unsigned i = 0; i != NumValues; ++i) 10686 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 10687 SDValue(Op.getNode(), Op.getResNo() + i)); 10688 10689 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 10690 DAG.getVTList(ValueVTs), Values)); 10691 } 10692