1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This implements routines for translating from LLVM IR into SelectionDAG IR. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "SelectionDAGBuilder.h" 14 #include "SDNodeDbgValue.h" 15 #include "llvm/ADT/APFloat.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/ArrayRef.h" 18 #include "llvm/ADT/BitVector.h" 19 #include "llvm/ADT/DenseMap.h" 20 #include "llvm/ADT/None.h" 21 #include "llvm/ADT/Optional.h" 22 #include "llvm/ADT/STLExtras.h" 23 #include "llvm/ADT/SmallPtrSet.h" 24 #include "llvm/ADT/SmallSet.h" 25 #include "llvm/ADT/SmallVector.h" 26 #include "llvm/ADT/StringRef.h" 27 #include "llvm/ADT/Triple.h" 28 #include "llvm/ADT/Twine.h" 29 #include "llvm/Analysis/AliasAnalysis.h" 30 #include "llvm/Analysis/BlockFrequencyInfo.h" 31 #include "llvm/Analysis/BranchProbabilityInfo.h" 32 #include "llvm/Analysis/ConstantFolding.h" 33 #include "llvm/Analysis/EHPersonalities.h" 34 #include "llvm/Analysis/Loads.h" 35 #include "llvm/Analysis/MemoryLocation.h" 36 #include "llvm/Analysis/ProfileSummaryInfo.h" 37 #include "llvm/Analysis/TargetLibraryInfo.h" 38 #include "llvm/Analysis/ValueTracking.h" 39 #include "llvm/Analysis/VectorUtils.h" 40 #include "llvm/CodeGen/Analysis.h" 41 #include "llvm/CodeGen/FunctionLoweringInfo.h" 42 #include "llvm/CodeGen/GCMetadata.h" 43 #include "llvm/CodeGen/ISDOpcodes.h" 44 #include "llvm/CodeGen/MachineBasicBlock.h" 45 #include "llvm/CodeGen/MachineFrameInfo.h" 46 #include "llvm/CodeGen/MachineFunction.h" 47 #include "llvm/CodeGen/MachineInstr.h" 48 #include "llvm/CodeGen/MachineInstrBuilder.h" 49 #include "llvm/CodeGen/MachineJumpTableInfo.h" 50 #include "llvm/CodeGen/MachineMemOperand.h" 51 #include "llvm/CodeGen/MachineModuleInfo.h" 52 #include "llvm/CodeGen/MachineOperand.h" 53 #include "llvm/CodeGen/MachineRegisterInfo.h" 54 #include "llvm/CodeGen/RuntimeLibcalls.h" 55 #include "llvm/CodeGen/SelectionDAG.h" 56 #include "llvm/CodeGen/SelectionDAGNodes.h" 57 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 58 #include "llvm/CodeGen/StackMaps.h" 59 #include "llvm/CodeGen/SwiftErrorValueTracking.h" 60 #include "llvm/CodeGen/TargetFrameLowering.h" 61 #include "llvm/CodeGen/TargetInstrInfo.h" 62 #include "llvm/CodeGen/TargetLowering.h" 63 #include "llvm/CodeGen/TargetOpcodes.h" 64 #include "llvm/CodeGen/TargetRegisterInfo.h" 65 #include "llvm/CodeGen/TargetSubtargetInfo.h" 66 #include "llvm/CodeGen/ValueTypes.h" 67 #include "llvm/CodeGen/WinEHFuncInfo.h" 68 #include "llvm/IR/Argument.h" 69 #include "llvm/IR/Attributes.h" 70 #include "llvm/IR/BasicBlock.h" 71 #include "llvm/IR/CFG.h" 72 #include "llvm/IR/CallSite.h" 73 #include "llvm/IR/CallingConv.h" 74 #include "llvm/IR/Constant.h" 75 #include "llvm/IR/ConstantRange.h" 76 #include "llvm/IR/Constants.h" 77 #include "llvm/IR/DataLayout.h" 78 #include "llvm/IR/DebugInfoMetadata.h" 79 #include "llvm/IR/DebugLoc.h" 80 #include "llvm/IR/DerivedTypes.h" 81 #include "llvm/IR/Function.h" 82 #include "llvm/IR/GetElementPtrTypeIterator.h" 83 #include "llvm/IR/InlineAsm.h" 84 #include "llvm/IR/InstrTypes.h" 85 #include "llvm/IR/Instruction.h" 86 #include "llvm/IR/Instructions.h" 87 #include "llvm/IR/IntrinsicInst.h" 88 #include "llvm/IR/Intrinsics.h" 89 #include "llvm/IR/IntrinsicsAArch64.h" 90 #include "llvm/IR/IntrinsicsWebAssembly.h" 91 #include "llvm/IR/LLVMContext.h" 92 #include "llvm/IR/Metadata.h" 93 #include "llvm/IR/Module.h" 94 #include "llvm/IR/Operator.h" 95 #include "llvm/IR/PatternMatch.h" 96 #include "llvm/IR/Statepoint.h" 97 #include "llvm/IR/Type.h" 98 #include "llvm/IR/User.h" 99 #include "llvm/IR/Value.h" 100 #include "llvm/MC/MCContext.h" 101 #include "llvm/MC/MCSymbol.h" 102 #include "llvm/Support/AtomicOrdering.h" 103 #include "llvm/Support/BranchProbability.h" 104 #include "llvm/Support/Casting.h" 105 #include "llvm/Support/CodeGen.h" 106 #include "llvm/Support/CommandLine.h" 107 #include "llvm/Support/Compiler.h" 108 #include "llvm/Support/Debug.h" 109 #include "llvm/Support/ErrorHandling.h" 110 #include "llvm/Support/MachineValueType.h" 111 #include "llvm/Support/MathExtras.h" 112 #include "llvm/Support/raw_ostream.h" 113 #include "llvm/Target/TargetIntrinsicInfo.h" 114 #include "llvm/Target/TargetMachine.h" 115 #include "llvm/Target/TargetOptions.h" 116 #include "llvm/Transforms/Utils/Local.h" 117 #include <algorithm> 118 #include <cassert> 119 #include <cstddef> 120 #include <cstdint> 121 #include <cstring> 122 #include <iterator> 123 #include <limits> 124 #include <numeric> 125 #include <tuple> 126 #include <utility> 127 #include <vector> 128 129 using namespace llvm; 130 using namespace PatternMatch; 131 using namespace SwitchCG; 132 133 #define DEBUG_TYPE "isel" 134 135 /// LimitFloatPrecision - Generate low-precision inline sequences for 136 /// some float libcalls (6, 8 or 12 bits). 137 static unsigned LimitFloatPrecision; 138 139 static cl::opt<unsigned, true> 140 LimitFPPrecision("limit-float-precision", 141 cl::desc("Generate low-precision inline sequences " 142 "for some float libcalls"), 143 cl::location(LimitFloatPrecision), cl::Hidden, 144 cl::init(0)); 145 146 static cl::opt<unsigned> SwitchPeelThreshold( 147 "switch-peel-threshold", cl::Hidden, cl::init(66), 148 cl::desc("Set the case probability threshold for peeling the case from a " 149 "switch statement. A value greater than 100 will void this " 150 "optimization")); 151 152 // Limit the width of DAG chains. This is important in general to prevent 153 // DAG-based analysis from blowing up. For example, alias analysis and 154 // load clustering may not complete in reasonable time. It is difficult to 155 // recognize and avoid this situation within each individual analysis, and 156 // future analyses are likely to have the same behavior. Limiting DAG width is 157 // the safe approach and will be especially important with global DAGs. 158 // 159 // MaxParallelChains default is arbitrarily high to avoid affecting 160 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 161 // sequence over this should have been converted to llvm.memcpy by the 162 // frontend. It is easy to induce this behavior with .ll code such as: 163 // %buffer = alloca [4096 x i8] 164 // %data = load [4096 x i8]* %argPtr 165 // store [4096 x i8] %data, [4096 x i8]* %buffer 166 static const unsigned MaxParallelChains = 64; 167 168 // Return the calling convention if the Value passed requires ABI mangling as it 169 // is a parameter to a function or a return value from a function which is not 170 // an intrinsic. 171 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) { 172 if (auto *R = dyn_cast<ReturnInst>(V)) 173 return R->getParent()->getParent()->getCallingConv(); 174 175 if (auto *CI = dyn_cast<CallInst>(V)) { 176 const bool IsInlineAsm = CI->isInlineAsm(); 177 const bool IsIndirectFunctionCall = 178 !IsInlineAsm && !CI->getCalledFunction(); 179 180 // It is possible that the call instruction is an inline asm statement or an 181 // indirect function call in which case the return value of 182 // getCalledFunction() would be nullptr. 183 const bool IsInstrinsicCall = 184 !IsInlineAsm && !IsIndirectFunctionCall && 185 CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic; 186 187 if (!IsInlineAsm && !IsInstrinsicCall) 188 return CI->getCallingConv(); 189 } 190 191 return None; 192 } 193 194 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 195 const SDValue *Parts, unsigned NumParts, 196 MVT PartVT, EVT ValueVT, const Value *V, 197 Optional<CallingConv::ID> CC); 198 199 /// getCopyFromParts - Create a value that contains the specified legal parts 200 /// combined into the value they represent. If the parts combine to a type 201 /// larger than ValueVT then AssertOp can be used to specify whether the extra 202 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 203 /// (ISD::AssertSext). 204 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 205 const SDValue *Parts, unsigned NumParts, 206 MVT PartVT, EVT ValueVT, const Value *V, 207 Optional<CallingConv::ID> CC = None, 208 Optional<ISD::NodeType> AssertOp = None) { 209 if (ValueVT.isVector()) 210 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 211 CC); 212 213 assert(NumParts > 0 && "No parts to assemble!"); 214 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 215 SDValue Val = Parts[0]; 216 217 if (NumParts > 1) { 218 // Assemble the value from multiple parts. 219 if (ValueVT.isInteger()) { 220 unsigned PartBits = PartVT.getSizeInBits(); 221 unsigned ValueBits = ValueVT.getSizeInBits(); 222 223 // Assemble the power of 2 part. 224 unsigned RoundParts = 225 (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts; 226 unsigned RoundBits = PartBits * RoundParts; 227 EVT RoundVT = RoundBits == ValueBits ? 228 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 229 SDValue Lo, Hi; 230 231 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 232 233 if (RoundParts > 2) { 234 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 235 PartVT, HalfVT, V); 236 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 237 RoundParts / 2, PartVT, HalfVT, V); 238 } else { 239 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 240 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 241 } 242 243 if (DAG.getDataLayout().isBigEndian()) 244 std::swap(Lo, Hi); 245 246 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 247 248 if (RoundParts < NumParts) { 249 // Assemble the trailing non-power-of-2 part. 250 unsigned OddParts = NumParts - RoundParts; 251 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 252 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 253 OddVT, V, CC); 254 255 // Combine the round and odd parts. 256 Lo = Val; 257 if (DAG.getDataLayout().isBigEndian()) 258 std::swap(Lo, Hi); 259 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 260 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 261 Hi = 262 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 263 DAG.getConstant(Lo.getValueSizeInBits(), DL, 264 TLI.getPointerTy(DAG.getDataLayout()))); 265 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 266 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 267 } 268 } else if (PartVT.isFloatingPoint()) { 269 // FP split into multiple FP parts (for ppcf128) 270 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 271 "Unexpected split"); 272 SDValue Lo, Hi; 273 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 274 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 275 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 276 std::swap(Lo, Hi); 277 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 278 } else { 279 // FP split into integer parts (soft fp) 280 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 281 !PartVT.isVector() && "Unexpected split"); 282 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 283 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 284 } 285 } 286 287 // There is now one part, held in Val. Correct it to match ValueVT. 288 // PartEVT is the type of the register class that holds the value. 289 // ValueVT is the type of the inline asm operation. 290 EVT PartEVT = Val.getValueType(); 291 292 if (PartEVT == ValueVT) 293 return Val; 294 295 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 296 ValueVT.bitsLT(PartEVT)) { 297 // For an FP value in an integer part, we need to truncate to the right 298 // width first. 299 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 300 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 301 } 302 303 // Handle types that have the same size. 304 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 305 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 306 307 // Handle types with different sizes. 308 if (PartEVT.isInteger() && ValueVT.isInteger()) { 309 if (ValueVT.bitsLT(PartEVT)) { 310 // For a truncate, see if we have any information to 311 // indicate whether the truncated bits will always be 312 // zero or sign-extension. 313 if (AssertOp.hasValue()) 314 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 315 DAG.getValueType(ValueVT)); 316 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 317 } 318 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 319 } 320 321 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 322 // FP_ROUND's are always exact here. 323 if (ValueVT.bitsLT(Val.getValueType())) 324 return DAG.getNode( 325 ISD::FP_ROUND, DL, ValueVT, Val, 326 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 327 328 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 329 } 330 331 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 332 // then truncating. 333 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 334 ValueVT.bitsLT(PartEVT)) { 335 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 336 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 337 } 338 339 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 340 } 341 342 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 343 const Twine &ErrMsg) { 344 const Instruction *I = dyn_cast_or_null<Instruction>(V); 345 if (!V) 346 return Ctx.emitError(ErrMsg); 347 348 const char *AsmError = ", possible invalid constraint for vector type"; 349 if (const CallInst *CI = dyn_cast<CallInst>(I)) 350 if (isa<InlineAsm>(CI->getCalledValue())) 351 return Ctx.emitError(I, ErrMsg + AsmError); 352 353 return Ctx.emitError(I, ErrMsg); 354 } 355 356 /// getCopyFromPartsVector - Create a value that contains the specified legal 357 /// parts combined into the value they represent. If the parts combine to a 358 /// type larger than ValueVT then AssertOp can be used to specify whether the 359 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 360 /// ValueVT (ISD::AssertSext). 361 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 362 const SDValue *Parts, unsigned NumParts, 363 MVT PartVT, EVT ValueVT, const Value *V, 364 Optional<CallingConv::ID> CallConv) { 365 assert(ValueVT.isVector() && "Not a vector value"); 366 assert(NumParts > 0 && "No parts to assemble!"); 367 const bool IsABIRegCopy = CallConv.hasValue(); 368 369 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 370 SDValue Val = Parts[0]; 371 372 // Handle a multi-element vector. 373 if (NumParts > 1) { 374 EVT IntermediateVT; 375 MVT RegisterVT; 376 unsigned NumIntermediates; 377 unsigned NumRegs; 378 379 if (IsABIRegCopy) { 380 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 381 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 382 NumIntermediates, RegisterVT); 383 } else { 384 NumRegs = 385 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 386 NumIntermediates, RegisterVT); 387 } 388 389 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 390 NumParts = NumRegs; // Silence a compiler warning. 391 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 392 assert(RegisterVT.getSizeInBits() == 393 Parts[0].getSimpleValueType().getSizeInBits() && 394 "Part type sizes don't match!"); 395 396 // Assemble the parts into intermediate operands. 397 SmallVector<SDValue, 8> Ops(NumIntermediates); 398 if (NumIntermediates == NumParts) { 399 // If the register was not expanded, truncate or copy the value, 400 // as appropriate. 401 for (unsigned i = 0; i != NumParts; ++i) 402 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 403 PartVT, IntermediateVT, V); 404 } else if (NumParts > 0) { 405 // If the intermediate type was expanded, build the intermediate 406 // operands from the parts. 407 assert(NumParts % NumIntermediates == 0 && 408 "Must expand into a divisible number of parts!"); 409 unsigned Factor = NumParts / NumIntermediates; 410 for (unsigned i = 0; i != NumIntermediates; ++i) 411 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 412 PartVT, IntermediateVT, V); 413 } 414 415 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 416 // intermediate operands. 417 EVT BuiltVectorTy = 418 EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(), 419 (IntermediateVT.isVector() 420 ? IntermediateVT.getVectorNumElements() * NumParts 421 : NumIntermediates)); 422 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 423 : ISD::BUILD_VECTOR, 424 DL, BuiltVectorTy, Ops); 425 } 426 427 // There is now one part, held in Val. Correct it to match ValueVT. 428 EVT PartEVT = Val.getValueType(); 429 430 if (PartEVT == ValueVT) 431 return Val; 432 433 if (PartEVT.isVector()) { 434 // If the element type of the source/dest vectors are the same, but the 435 // parts vector has more elements than the value vector, then we have a 436 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 437 // elements we want. 438 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { 439 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() && 440 "Cannot narrow, it would be a lossy transformation"); 441 return DAG.getNode( 442 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 443 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 444 } 445 446 // Vector/Vector bitcast. 447 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 448 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 449 450 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() && 451 "Cannot handle this kind of promotion"); 452 // Promoted vector extract 453 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 454 455 } 456 457 // Trivial bitcast if the types are the same size and the destination 458 // vector type is legal. 459 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 460 TLI.isTypeLegal(ValueVT)) 461 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 462 463 if (ValueVT.getVectorNumElements() != 1) { 464 // Certain ABIs require that vectors are passed as integers. For vectors 465 // are the same size, this is an obvious bitcast. 466 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 467 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 468 } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) { 469 // Bitcast Val back the original type and extract the corresponding 470 // vector we want. 471 unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits(); 472 EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(), 473 ValueVT.getVectorElementType(), Elts); 474 Val = DAG.getBitcast(WiderVecType, Val); 475 return DAG.getNode( 476 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 477 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 478 } 479 480 diagnosePossiblyInvalidConstraint( 481 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 482 return DAG.getUNDEF(ValueVT); 483 } 484 485 // Handle cases such as i8 -> <1 x i1> 486 EVT ValueSVT = ValueVT.getVectorElementType(); 487 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) 488 Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 489 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 490 491 return DAG.getBuildVector(ValueVT, DL, Val); 492 } 493 494 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 495 SDValue Val, SDValue *Parts, unsigned NumParts, 496 MVT PartVT, const Value *V, 497 Optional<CallingConv::ID> CallConv); 498 499 /// getCopyToParts - Create a series of nodes that contain the specified value 500 /// split into legal parts. If the parts contain more bits than Val, then, for 501 /// integers, ExtendKind can be used to specify how to generate the extra bits. 502 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 503 SDValue *Parts, unsigned NumParts, MVT PartVT, 504 const Value *V, 505 Optional<CallingConv::ID> CallConv = None, 506 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 507 EVT ValueVT = Val.getValueType(); 508 509 // Handle the vector case separately. 510 if (ValueVT.isVector()) 511 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 512 CallConv); 513 514 unsigned PartBits = PartVT.getSizeInBits(); 515 unsigned OrigNumParts = NumParts; 516 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 517 "Copying to an illegal type!"); 518 519 if (NumParts == 0) 520 return; 521 522 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 523 EVT PartEVT = PartVT; 524 if (PartEVT == ValueVT) { 525 assert(NumParts == 1 && "No-op copy with multiple parts!"); 526 Parts[0] = Val; 527 return; 528 } 529 530 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 531 // If the parts cover more bits than the value has, promote the value. 532 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 533 assert(NumParts == 1 && "Do not know what to promote to!"); 534 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 535 } else { 536 if (ValueVT.isFloatingPoint()) { 537 // FP values need to be bitcast, then extended if they are being put 538 // into a larger container. 539 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 540 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 541 } 542 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 543 ValueVT.isInteger() && 544 "Unknown mismatch!"); 545 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 546 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 547 if (PartVT == MVT::x86mmx) 548 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 549 } 550 } else if (PartBits == ValueVT.getSizeInBits()) { 551 // Different types of the same size. 552 assert(NumParts == 1 && PartEVT != ValueVT); 553 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 554 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 555 // If the parts cover less bits than value has, truncate the value. 556 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 557 ValueVT.isInteger() && 558 "Unknown mismatch!"); 559 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 560 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 561 if (PartVT == MVT::x86mmx) 562 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 563 } 564 565 // The value may have changed - recompute ValueVT. 566 ValueVT = Val.getValueType(); 567 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 568 "Failed to tile the value with PartVT!"); 569 570 if (NumParts == 1) { 571 if (PartEVT != ValueVT) { 572 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 573 "scalar-to-vector conversion failed"); 574 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 575 } 576 577 Parts[0] = Val; 578 return; 579 } 580 581 // Expand the value into multiple parts. 582 if (NumParts & (NumParts - 1)) { 583 // The number of parts is not a power of 2. Split off and copy the tail. 584 assert(PartVT.isInteger() && ValueVT.isInteger() && 585 "Do not know what to expand to!"); 586 unsigned RoundParts = 1 << Log2_32(NumParts); 587 unsigned RoundBits = RoundParts * PartBits; 588 unsigned OddParts = NumParts - RoundParts; 589 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 590 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false)); 591 592 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 593 CallConv); 594 595 if (DAG.getDataLayout().isBigEndian()) 596 // The odd parts were reversed by getCopyToParts - unreverse them. 597 std::reverse(Parts + RoundParts, Parts + NumParts); 598 599 NumParts = RoundParts; 600 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 601 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 602 } 603 604 // The number of parts is a power of 2. Repeatedly bisect the value using 605 // EXTRACT_ELEMENT. 606 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 607 EVT::getIntegerVT(*DAG.getContext(), 608 ValueVT.getSizeInBits()), 609 Val); 610 611 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 612 for (unsigned i = 0; i < NumParts; i += StepSize) { 613 unsigned ThisBits = StepSize * PartBits / 2; 614 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 615 SDValue &Part0 = Parts[i]; 616 SDValue &Part1 = Parts[i+StepSize/2]; 617 618 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 619 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 620 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 621 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 622 623 if (ThisBits == PartBits && ThisVT != PartVT) { 624 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 625 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 626 } 627 } 628 } 629 630 if (DAG.getDataLayout().isBigEndian()) 631 std::reverse(Parts, Parts + OrigNumParts); 632 } 633 634 static SDValue widenVectorToPartType(SelectionDAG &DAG, 635 SDValue Val, const SDLoc &DL, EVT PartVT) { 636 if (!PartVT.isVector()) 637 return SDValue(); 638 639 EVT ValueVT = Val.getValueType(); 640 unsigned PartNumElts = PartVT.getVectorNumElements(); 641 unsigned ValueNumElts = ValueVT.getVectorNumElements(); 642 if (PartNumElts > ValueNumElts && 643 PartVT.getVectorElementType() == ValueVT.getVectorElementType()) { 644 EVT ElementVT = PartVT.getVectorElementType(); 645 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 646 // undef elements. 647 SmallVector<SDValue, 16> Ops; 648 DAG.ExtractVectorElements(Val, Ops); 649 SDValue EltUndef = DAG.getUNDEF(ElementVT); 650 for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i) 651 Ops.push_back(EltUndef); 652 653 // FIXME: Use CONCAT for 2x -> 4x. 654 return DAG.getBuildVector(PartVT, DL, Ops); 655 } 656 657 return SDValue(); 658 } 659 660 /// getCopyToPartsVector - Create a series of nodes that contain the specified 661 /// value split into legal parts. 662 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 663 SDValue Val, SDValue *Parts, unsigned NumParts, 664 MVT PartVT, const Value *V, 665 Optional<CallingConv::ID> CallConv) { 666 EVT ValueVT = Val.getValueType(); 667 assert(ValueVT.isVector() && "Not a vector"); 668 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 669 const bool IsABIRegCopy = CallConv.hasValue(); 670 671 if (NumParts == 1) { 672 EVT PartEVT = PartVT; 673 if (PartEVT == ValueVT) { 674 // Nothing to do. 675 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 676 // Bitconvert vector->vector case. 677 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 678 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 679 Val = Widened; 680 } else if (PartVT.isVector() && 681 PartEVT.getVectorElementType().bitsGE( 682 ValueVT.getVectorElementType()) && 683 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) { 684 685 // Promoted vector extract 686 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 687 } else { 688 if (ValueVT.getVectorNumElements() == 1) { 689 Val = DAG.getNode( 690 ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 691 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 692 } else { 693 assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() && 694 "lossy conversion of vector to scalar type"); 695 EVT IntermediateType = 696 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 697 Val = DAG.getBitcast(IntermediateType, Val); 698 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 699 } 700 } 701 702 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 703 Parts[0] = Val; 704 return; 705 } 706 707 // Handle a multi-element vector. 708 EVT IntermediateVT; 709 MVT RegisterVT; 710 unsigned NumIntermediates; 711 unsigned NumRegs; 712 if (IsABIRegCopy) { 713 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 714 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 715 NumIntermediates, RegisterVT); 716 } else { 717 NumRegs = 718 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 719 NumIntermediates, RegisterVT); 720 } 721 722 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 723 NumParts = NumRegs; // Silence a compiler warning. 724 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 725 726 unsigned IntermediateNumElts = IntermediateVT.isVector() ? 727 IntermediateVT.getVectorNumElements() : 1; 728 729 // Convert the vector to the appropriate type if necessary. 730 unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts; 731 732 EVT BuiltVectorTy = EVT::getVectorVT( 733 *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts); 734 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 735 if (ValueVT != BuiltVectorTy) { 736 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) 737 Val = Widened; 738 739 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 740 } 741 742 // Split the vector into intermediate operands. 743 SmallVector<SDValue, 8> Ops(NumIntermediates); 744 for (unsigned i = 0; i != NumIntermediates; ++i) { 745 if (IntermediateVT.isVector()) { 746 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 747 DAG.getConstant(i * IntermediateNumElts, DL, IdxVT)); 748 } else { 749 Ops[i] = DAG.getNode( 750 ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 751 DAG.getConstant(i, DL, IdxVT)); 752 } 753 } 754 755 // Split the intermediate operands into legal parts. 756 if (NumParts == NumIntermediates) { 757 // If the register was not expanded, promote or copy the value, 758 // as appropriate. 759 for (unsigned i = 0; i != NumParts; ++i) 760 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 761 } else if (NumParts > 0) { 762 // If the intermediate type was expanded, split each the value into 763 // legal parts. 764 assert(NumIntermediates != 0 && "division by zero"); 765 assert(NumParts % NumIntermediates == 0 && 766 "Must expand into a divisible number of parts!"); 767 unsigned Factor = NumParts / NumIntermediates; 768 for (unsigned i = 0; i != NumIntermediates; ++i) 769 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 770 CallConv); 771 } 772 } 773 774 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 775 EVT valuevt, Optional<CallingConv::ID> CC) 776 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 777 RegCount(1, regs.size()), CallConv(CC) {} 778 779 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 780 const DataLayout &DL, unsigned Reg, Type *Ty, 781 Optional<CallingConv::ID> CC) { 782 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 783 784 CallConv = CC; 785 786 for (EVT ValueVT : ValueVTs) { 787 unsigned NumRegs = 788 isABIMangled() 789 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) 790 : TLI.getNumRegisters(Context, ValueVT); 791 MVT RegisterVT = 792 isABIMangled() 793 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) 794 : TLI.getRegisterType(Context, ValueVT); 795 for (unsigned i = 0; i != NumRegs; ++i) 796 Regs.push_back(Reg + i); 797 RegVTs.push_back(RegisterVT); 798 RegCount.push_back(NumRegs); 799 Reg += NumRegs; 800 } 801 } 802 803 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 804 FunctionLoweringInfo &FuncInfo, 805 const SDLoc &dl, SDValue &Chain, 806 SDValue *Flag, const Value *V) const { 807 // A Value with type {} or [0 x %t] needs no registers. 808 if (ValueVTs.empty()) 809 return SDValue(); 810 811 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 812 813 // Assemble the legal parts into the final values. 814 SmallVector<SDValue, 4> Values(ValueVTs.size()); 815 SmallVector<SDValue, 8> Parts; 816 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 817 // Copy the legal parts from the registers. 818 EVT ValueVT = ValueVTs[Value]; 819 unsigned NumRegs = RegCount[Value]; 820 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 821 *DAG.getContext(), 822 CallConv.getValue(), RegVTs[Value]) 823 : RegVTs[Value]; 824 825 Parts.resize(NumRegs); 826 for (unsigned i = 0; i != NumRegs; ++i) { 827 SDValue P; 828 if (!Flag) { 829 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 830 } else { 831 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 832 *Flag = P.getValue(2); 833 } 834 835 Chain = P.getValue(1); 836 Parts[i] = P; 837 838 // If the source register was virtual and if we know something about it, 839 // add an assert node. 840 if (!Register::isVirtualRegister(Regs[Part + i]) || 841 !RegisterVT.isInteger()) 842 continue; 843 844 const FunctionLoweringInfo::LiveOutInfo *LOI = 845 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 846 if (!LOI) 847 continue; 848 849 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 850 unsigned NumSignBits = LOI->NumSignBits; 851 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 852 853 if (NumZeroBits == RegSize) { 854 // The current value is a zero. 855 // Explicitly express that as it would be easier for 856 // optimizations to kick in. 857 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 858 continue; 859 } 860 861 // FIXME: We capture more information than the dag can represent. For 862 // now, just use the tightest assertzext/assertsext possible. 863 bool isSExt; 864 EVT FromVT(MVT::Other); 865 if (NumZeroBits) { 866 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 867 isSExt = false; 868 } else if (NumSignBits > 1) { 869 FromVT = 870 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 871 isSExt = true; 872 } else { 873 continue; 874 } 875 // Add an assertion node. 876 assert(FromVT != MVT::Other); 877 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 878 RegisterVT, P, DAG.getValueType(FromVT)); 879 } 880 881 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 882 RegisterVT, ValueVT, V, CallConv); 883 Part += NumRegs; 884 Parts.clear(); 885 } 886 887 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 888 } 889 890 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 891 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 892 const Value *V, 893 ISD::NodeType PreferredExtendType) const { 894 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 895 ISD::NodeType ExtendKind = PreferredExtendType; 896 897 // Get the list of the values's legal parts. 898 unsigned NumRegs = Regs.size(); 899 SmallVector<SDValue, 8> Parts(NumRegs); 900 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 901 unsigned NumParts = RegCount[Value]; 902 903 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 904 *DAG.getContext(), 905 CallConv.getValue(), RegVTs[Value]) 906 : RegVTs[Value]; 907 908 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 909 ExtendKind = ISD::ZERO_EXTEND; 910 911 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 912 NumParts, RegisterVT, V, CallConv, ExtendKind); 913 Part += NumParts; 914 } 915 916 // Copy the parts into the registers. 917 SmallVector<SDValue, 8> Chains(NumRegs); 918 for (unsigned i = 0; i != NumRegs; ++i) { 919 SDValue Part; 920 if (!Flag) { 921 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 922 } else { 923 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 924 *Flag = Part.getValue(1); 925 } 926 927 Chains[i] = Part.getValue(0); 928 } 929 930 if (NumRegs == 1 || Flag) 931 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 932 // flagged to it. That is the CopyToReg nodes and the user are considered 933 // a single scheduling unit. If we create a TokenFactor and return it as 934 // chain, then the TokenFactor is both a predecessor (operand) of the 935 // user as well as a successor (the TF operands are flagged to the user). 936 // c1, f1 = CopyToReg 937 // c2, f2 = CopyToReg 938 // c3 = TokenFactor c1, c2 939 // ... 940 // = op c3, ..., f2 941 Chain = Chains[NumRegs-1]; 942 else 943 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 944 } 945 946 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 947 unsigned MatchingIdx, const SDLoc &dl, 948 SelectionDAG &DAG, 949 std::vector<SDValue> &Ops) const { 950 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 951 952 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 953 if (HasMatching) 954 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 955 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 956 // Put the register class of the virtual registers in the flag word. That 957 // way, later passes can recompute register class constraints for inline 958 // assembly as well as normal instructions. 959 // Don't do this for tied operands that can use the regclass information 960 // from the def. 961 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 962 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 963 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 964 } 965 966 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 967 Ops.push_back(Res); 968 969 if (Code == InlineAsm::Kind_Clobber) { 970 // Clobbers should always have a 1:1 mapping with registers, and may 971 // reference registers that have illegal (e.g. vector) types. Hence, we 972 // shouldn't try to apply any sort of splitting logic to them. 973 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 974 "No 1:1 mapping from clobbers to regs?"); 975 unsigned SP = TLI.getStackPointerRegisterToSaveRestore(); 976 (void)SP; 977 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 978 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 979 assert( 980 (Regs[I] != SP || 981 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 982 "If we clobbered the stack pointer, MFI should know about it."); 983 } 984 return; 985 } 986 987 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 988 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 989 MVT RegisterVT = RegVTs[Value]; 990 for (unsigned i = 0; i != NumRegs; ++i) { 991 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 992 unsigned TheReg = Regs[Reg++]; 993 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 994 } 995 } 996 } 997 998 SmallVector<std::pair<unsigned, unsigned>, 4> 999 RegsForValue::getRegsAndSizes() const { 1000 SmallVector<std::pair<unsigned, unsigned>, 4> OutVec; 1001 unsigned I = 0; 1002 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1003 unsigned RegCount = std::get<0>(CountAndVT); 1004 MVT RegisterVT = std::get<1>(CountAndVT); 1005 unsigned RegisterSize = RegisterVT.getSizeInBits(); 1006 for (unsigned E = I + RegCount; I != E; ++I) 1007 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1008 } 1009 return OutVec; 1010 } 1011 1012 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1013 const TargetLibraryInfo *li) { 1014 AA = aa; 1015 GFI = gfi; 1016 LibInfo = li; 1017 DL = &DAG.getDataLayout(); 1018 Context = DAG.getContext(); 1019 LPadToCallSiteMap.clear(); 1020 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1021 } 1022 1023 void SelectionDAGBuilder::clear() { 1024 NodeMap.clear(); 1025 UnusedArgNodeMap.clear(); 1026 PendingLoads.clear(); 1027 PendingExports.clear(); 1028 PendingConstrainedFP.clear(); 1029 PendingConstrainedFPStrict.clear(); 1030 CurInst = nullptr; 1031 HasTailCall = false; 1032 SDNodeOrder = LowestSDNodeOrder; 1033 StatepointLowering.clear(); 1034 } 1035 1036 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1037 DanglingDebugInfoMap.clear(); 1038 } 1039 1040 // Update DAG root to include dependencies on Pending chains. 1041 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1042 SDValue Root = DAG.getRoot(); 1043 1044 if (Pending.empty()) 1045 return Root; 1046 1047 // Add current root to PendingChains, unless we already indirectly 1048 // depend on it. 1049 if (Root.getOpcode() != ISD::EntryToken) { 1050 unsigned i = 0, e = Pending.size(); 1051 for (; i != e; ++i) { 1052 assert(Pending[i].getNode()->getNumOperands() > 1); 1053 if (Pending[i].getNode()->getOperand(0) == Root) 1054 break; // Don't add the root if we already indirectly depend on it. 1055 } 1056 1057 if (i == e) 1058 Pending.push_back(Root); 1059 } 1060 1061 if (Pending.size() == 1) 1062 Root = Pending[0]; 1063 else 1064 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1065 1066 DAG.setRoot(Root); 1067 Pending.clear(); 1068 return Root; 1069 } 1070 1071 SDValue SelectionDAGBuilder::getMemoryRoot() { 1072 return updateRoot(PendingLoads); 1073 } 1074 1075 SDValue SelectionDAGBuilder::getRoot() { 1076 // Chain up all pending constrained intrinsics together with all 1077 // pending loads, by simply appending them to PendingLoads and 1078 // then calling getMemoryRoot(). 1079 PendingLoads.reserve(PendingLoads.size() + 1080 PendingConstrainedFP.size() + 1081 PendingConstrainedFPStrict.size()); 1082 PendingLoads.append(PendingConstrainedFP.begin(), 1083 PendingConstrainedFP.end()); 1084 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1085 PendingConstrainedFPStrict.end()); 1086 PendingConstrainedFP.clear(); 1087 PendingConstrainedFPStrict.clear(); 1088 return getMemoryRoot(); 1089 } 1090 1091 SDValue SelectionDAGBuilder::getControlRoot() { 1092 // We need to emit pending fpexcept.strict constrained intrinsics, 1093 // so append them to the PendingExports list. 1094 PendingExports.append(PendingConstrainedFPStrict.begin(), 1095 PendingConstrainedFPStrict.end()); 1096 PendingConstrainedFPStrict.clear(); 1097 return updateRoot(PendingExports); 1098 } 1099 1100 void SelectionDAGBuilder::visit(const Instruction &I) { 1101 // Set up outgoing PHI node register values before emitting the terminator. 1102 if (I.isTerminator()) { 1103 HandlePHINodesInSuccessorBlocks(I.getParent()); 1104 } 1105 1106 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1107 if (!isa<DbgInfoIntrinsic>(I)) 1108 ++SDNodeOrder; 1109 1110 CurInst = &I; 1111 1112 visit(I.getOpcode(), I); 1113 1114 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) { 1115 // Propagate the fast-math-flags of this IR instruction to the DAG node that 1116 // maps to this instruction. 1117 // TODO: We could handle all flags (nsw, etc) here. 1118 // TODO: If an IR instruction maps to >1 node, only the final node will have 1119 // flags set. 1120 if (SDNode *Node = getNodeForIRValue(&I)) { 1121 SDNodeFlags IncomingFlags; 1122 IncomingFlags.copyFMF(*FPMO); 1123 if (!Node->getFlags().isDefined()) 1124 Node->setFlags(IncomingFlags); 1125 else 1126 Node->intersectFlagsWith(IncomingFlags); 1127 } 1128 } 1129 // Constrained FP intrinsics with fpexcept.ignore should also get 1130 // the NoFPExcept flag. 1131 if (auto *FPI = dyn_cast<ConstrainedFPIntrinsic>(&I)) 1132 if (FPI->getExceptionBehavior() == fp::ExceptionBehavior::ebIgnore) 1133 if (SDNode *Node = getNodeForIRValue(&I)) { 1134 SDNodeFlags Flags = Node->getFlags(); 1135 Flags.setNoFPExcept(true); 1136 Node->setFlags(Flags); 1137 } 1138 1139 if (!I.isTerminator() && !HasTailCall && 1140 !isStatepoint(&I)) // statepoints handle their exports internally 1141 CopyToExportRegsIfNeeded(&I); 1142 1143 CurInst = nullptr; 1144 } 1145 1146 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1147 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1148 } 1149 1150 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1151 // Note: this doesn't use InstVisitor, because it has to work with 1152 // ConstantExpr's in addition to instructions. 1153 switch (Opcode) { 1154 default: llvm_unreachable("Unknown instruction type encountered!"); 1155 // Build the switch statement using the Instruction.def file. 1156 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1157 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1158 #include "llvm/IR/Instruction.def" 1159 } 1160 } 1161 1162 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1163 const DIExpression *Expr) { 1164 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1165 const DbgValueInst *DI = DDI.getDI(); 1166 DIVariable *DanglingVariable = DI->getVariable(); 1167 DIExpression *DanglingExpr = DI->getExpression(); 1168 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1169 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1170 return true; 1171 } 1172 return false; 1173 }; 1174 1175 for (auto &DDIMI : DanglingDebugInfoMap) { 1176 DanglingDebugInfoVector &DDIV = DDIMI.second; 1177 1178 // If debug info is to be dropped, run it through final checks to see 1179 // whether it can be salvaged. 1180 for (auto &DDI : DDIV) 1181 if (isMatchingDbgValue(DDI)) 1182 salvageUnresolvedDbgValue(DDI); 1183 1184 DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end()); 1185 } 1186 } 1187 1188 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1189 // generate the debug data structures now that we've seen its definition. 1190 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1191 SDValue Val) { 1192 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1193 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1194 return; 1195 1196 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1197 for (auto &DDI : DDIV) { 1198 const DbgValueInst *DI = DDI.getDI(); 1199 assert(DI && "Ill-formed DanglingDebugInfo"); 1200 DebugLoc dl = DDI.getdl(); 1201 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1202 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1203 DILocalVariable *Variable = DI->getVariable(); 1204 DIExpression *Expr = DI->getExpression(); 1205 assert(Variable->isValidLocationForIntrinsic(dl) && 1206 "Expected inlined-at fields to agree"); 1207 SDDbgValue *SDV; 1208 if (Val.getNode()) { 1209 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1210 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1211 // we couldn't resolve it directly when examining the DbgValue intrinsic 1212 // in the first place we should not be more successful here). Unless we 1213 // have some test case that prove this to be correct we should avoid 1214 // calling EmitFuncArgumentDbgValue here. 1215 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1216 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1217 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1218 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1219 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1220 // inserted after the definition of Val when emitting the instructions 1221 // after ISel. An alternative could be to teach 1222 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1223 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1224 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1225 << ValSDNodeOrder << "\n"); 1226 SDV = getDbgValue(Val, Variable, Expr, dl, 1227 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1228 DAG.AddDbgValue(SDV, Val.getNode(), false); 1229 } else 1230 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1231 << "in EmitFuncArgumentDbgValue\n"); 1232 } else { 1233 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1234 auto Undef = 1235 UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1236 auto SDV = 1237 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); 1238 DAG.AddDbgValue(SDV, nullptr, false); 1239 } 1240 } 1241 DDIV.clear(); 1242 } 1243 1244 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1245 Value *V = DDI.getDI()->getValue(); 1246 DILocalVariable *Var = DDI.getDI()->getVariable(); 1247 DIExpression *Expr = DDI.getDI()->getExpression(); 1248 DebugLoc DL = DDI.getdl(); 1249 DebugLoc InstDL = DDI.getDI()->getDebugLoc(); 1250 unsigned SDOrder = DDI.getSDNodeOrder(); 1251 1252 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1253 // that DW_OP_stack_value is desired. 1254 assert(isa<DbgValueInst>(DDI.getDI())); 1255 bool StackValue = true; 1256 1257 // Can this Value can be encoded without any further work? 1258 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) 1259 return; 1260 1261 // Attempt to salvage back through as many instructions as possible. Bail if 1262 // a non-instruction is seen, such as a constant expression or global 1263 // variable. FIXME: Further work could recover those too. 1264 while (isa<Instruction>(V)) { 1265 Instruction &VAsInst = *cast<Instruction>(V); 1266 DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue); 1267 1268 // If we cannot salvage any further, and haven't yet found a suitable debug 1269 // expression, bail out. 1270 if (!NewExpr) 1271 break; 1272 1273 // New value and expr now represent this debuginfo. 1274 V = VAsInst.getOperand(0); 1275 Expr = NewExpr; 1276 1277 // Some kind of simplification occurred: check whether the operand of the 1278 // salvaged debug expression can be encoded in this DAG. 1279 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) { 1280 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n " 1281 << DDI.getDI() << "\nBy stripping back to:\n " << V); 1282 return; 1283 } 1284 } 1285 1286 // This was the final opportunity to salvage this debug information, and it 1287 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1288 // any earlier variable location. 1289 auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1290 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1291 DAG.AddDbgValue(SDV, nullptr, false); 1292 1293 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI() 1294 << "\n"); 1295 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0) 1296 << "\n"); 1297 } 1298 1299 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var, 1300 DIExpression *Expr, DebugLoc dl, 1301 DebugLoc InstDL, unsigned Order) { 1302 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1303 SDDbgValue *SDV; 1304 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1305 isa<ConstantPointerNull>(V)) { 1306 SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder); 1307 DAG.AddDbgValue(SDV, nullptr, false); 1308 return true; 1309 } 1310 1311 // If the Value is a frame index, we can create a FrameIndex debug value 1312 // without relying on the DAG at all. 1313 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1314 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1315 if (SI != FuncInfo.StaticAllocaMap.end()) { 1316 auto SDV = 1317 DAG.getFrameIndexDbgValue(Var, Expr, SI->second, 1318 /*IsIndirect*/ false, dl, SDNodeOrder); 1319 // Do not attach the SDNodeDbgValue to an SDNode: this variable location 1320 // is still available even if the SDNode gets optimized out. 1321 DAG.AddDbgValue(SDV, nullptr, false); 1322 return true; 1323 } 1324 } 1325 1326 // Do not use getValue() in here; we don't want to generate code at 1327 // this point if it hasn't been done yet. 1328 SDValue N = NodeMap[V]; 1329 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1330 N = UnusedArgNodeMap[V]; 1331 if (N.getNode()) { 1332 if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N)) 1333 return true; 1334 SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder); 1335 DAG.AddDbgValue(SDV, N.getNode(), false); 1336 return true; 1337 } 1338 1339 // Special rules apply for the first dbg.values of parameter variables in a 1340 // function. Identify them by the fact they reference Argument Values, that 1341 // they're parameters, and they are parameters of the current function. We 1342 // need to let them dangle until they get an SDNode. 1343 bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() && 1344 !InstDL.getInlinedAt(); 1345 if (!IsParamOfFunc) { 1346 // The value is not used in this block yet (or it would have an SDNode). 1347 // We still want the value to appear for the user if possible -- if it has 1348 // an associated VReg, we can refer to that instead. 1349 auto VMI = FuncInfo.ValueMap.find(V); 1350 if (VMI != FuncInfo.ValueMap.end()) { 1351 unsigned Reg = VMI->second; 1352 // If this is a PHI node, it may be split up into several MI PHI nodes 1353 // (in FunctionLoweringInfo::set). 1354 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1355 V->getType(), None); 1356 if (RFV.occupiesMultipleRegs()) { 1357 unsigned Offset = 0; 1358 unsigned BitsToDescribe = 0; 1359 if (auto VarSize = Var->getSizeInBits()) 1360 BitsToDescribe = *VarSize; 1361 if (auto Fragment = Expr->getFragmentInfo()) 1362 BitsToDescribe = Fragment->SizeInBits; 1363 for (auto RegAndSize : RFV.getRegsAndSizes()) { 1364 unsigned RegisterSize = RegAndSize.second; 1365 // Bail out if all bits are described already. 1366 if (Offset >= BitsToDescribe) 1367 break; 1368 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1369 ? BitsToDescribe - Offset 1370 : RegisterSize; 1371 auto FragmentExpr = DIExpression::createFragmentExpression( 1372 Expr, Offset, FragmentSize); 1373 if (!FragmentExpr) 1374 continue; 1375 SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first, 1376 false, dl, SDNodeOrder); 1377 DAG.AddDbgValue(SDV, nullptr, false); 1378 Offset += RegisterSize; 1379 } 1380 } else { 1381 SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder); 1382 DAG.AddDbgValue(SDV, nullptr, false); 1383 } 1384 return true; 1385 } 1386 } 1387 1388 return false; 1389 } 1390 1391 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1392 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1393 for (auto &Pair : DanglingDebugInfoMap) 1394 for (auto &DDI : Pair.second) 1395 salvageUnresolvedDbgValue(DDI); 1396 clearDanglingDebugInfo(); 1397 } 1398 1399 /// getCopyFromRegs - If there was virtual register allocated for the value V 1400 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1401 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1402 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V); 1403 SDValue Result; 1404 1405 if (It != FuncInfo.ValueMap.end()) { 1406 unsigned InReg = It->second; 1407 1408 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1409 DAG.getDataLayout(), InReg, Ty, 1410 None); // This is not an ABI copy. 1411 SDValue Chain = DAG.getEntryNode(); 1412 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1413 V); 1414 resolveDanglingDebugInfo(V, Result); 1415 } 1416 1417 return Result; 1418 } 1419 1420 /// getValue - Return an SDValue for the given Value. 1421 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1422 // If we already have an SDValue for this value, use it. It's important 1423 // to do this first, so that we don't create a CopyFromReg if we already 1424 // have a regular SDValue. 1425 SDValue &N = NodeMap[V]; 1426 if (N.getNode()) return N; 1427 1428 // If there's a virtual register allocated and initialized for this 1429 // value, use it. 1430 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1431 return copyFromReg; 1432 1433 // Otherwise create a new SDValue and remember it. 1434 SDValue Val = getValueImpl(V); 1435 NodeMap[V] = Val; 1436 resolveDanglingDebugInfo(V, Val); 1437 return Val; 1438 } 1439 1440 // Return true if SDValue exists for the given Value 1441 bool SelectionDAGBuilder::findValue(const Value *V) const { 1442 return (NodeMap.find(V) != NodeMap.end()) || 1443 (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end()); 1444 } 1445 1446 /// getNonRegisterValue - Return an SDValue for the given Value, but 1447 /// don't look in FuncInfo.ValueMap for a virtual register. 1448 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1449 // If we already have an SDValue for this value, use it. 1450 SDValue &N = NodeMap[V]; 1451 if (N.getNode()) { 1452 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1453 // Remove the debug location from the node as the node is about to be used 1454 // in a location which may differ from the original debug location. This 1455 // is relevant to Constant and ConstantFP nodes because they can appear 1456 // as constant expressions inside PHI nodes. 1457 N->setDebugLoc(DebugLoc()); 1458 } 1459 return N; 1460 } 1461 1462 // Otherwise create a new SDValue and remember it. 1463 SDValue Val = getValueImpl(V); 1464 NodeMap[V] = Val; 1465 resolveDanglingDebugInfo(V, Val); 1466 return Val; 1467 } 1468 1469 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1470 /// Create an SDValue for the given value. 1471 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1472 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1473 1474 if (const Constant *C = dyn_cast<Constant>(V)) { 1475 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1476 1477 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1478 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1479 1480 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1481 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1482 1483 if (isa<ConstantPointerNull>(C)) { 1484 unsigned AS = V->getType()->getPointerAddressSpace(); 1485 return DAG.getConstant(0, getCurSDLoc(), 1486 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1487 } 1488 1489 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1490 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1491 1492 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1493 return DAG.getUNDEF(VT); 1494 1495 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1496 visit(CE->getOpcode(), *CE); 1497 SDValue N1 = NodeMap[V]; 1498 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1499 return N1; 1500 } 1501 1502 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1503 SmallVector<SDValue, 4> Constants; 1504 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 1505 OI != OE; ++OI) { 1506 SDNode *Val = getValue(*OI).getNode(); 1507 // If the operand is an empty aggregate, there are no values. 1508 if (!Val) continue; 1509 // Add each leaf value from the operand to the Constants list 1510 // to form a flattened list of all the values. 1511 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1512 Constants.push_back(SDValue(Val, i)); 1513 } 1514 1515 return DAG.getMergeValues(Constants, getCurSDLoc()); 1516 } 1517 1518 if (const ConstantDataSequential *CDS = 1519 dyn_cast<ConstantDataSequential>(C)) { 1520 SmallVector<SDValue, 4> Ops; 1521 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1522 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1523 // Add each leaf value from the operand to the Constants list 1524 // to form a flattened list of all the values. 1525 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1526 Ops.push_back(SDValue(Val, i)); 1527 } 1528 1529 if (isa<ArrayType>(CDS->getType())) 1530 return DAG.getMergeValues(Ops, getCurSDLoc()); 1531 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1532 } 1533 1534 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1535 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1536 "Unknown struct or array constant!"); 1537 1538 SmallVector<EVT, 4> ValueVTs; 1539 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1540 unsigned NumElts = ValueVTs.size(); 1541 if (NumElts == 0) 1542 return SDValue(); // empty struct 1543 SmallVector<SDValue, 4> Constants(NumElts); 1544 for (unsigned i = 0; i != NumElts; ++i) { 1545 EVT EltVT = ValueVTs[i]; 1546 if (isa<UndefValue>(C)) 1547 Constants[i] = DAG.getUNDEF(EltVT); 1548 else if (EltVT.isFloatingPoint()) 1549 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1550 else 1551 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1552 } 1553 1554 return DAG.getMergeValues(Constants, getCurSDLoc()); 1555 } 1556 1557 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1558 return DAG.getBlockAddress(BA, VT); 1559 1560 VectorType *VecTy = cast<VectorType>(V->getType()); 1561 unsigned NumElements = VecTy->getNumElements(); 1562 1563 // Now that we know the number and type of the elements, get that number of 1564 // elements into the Ops array based on what kind of constant it is. 1565 SmallVector<SDValue, 16> Ops; 1566 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1567 for (unsigned i = 0; i != NumElements; ++i) 1568 Ops.push_back(getValue(CV->getOperand(i))); 1569 } else { 1570 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!"); 1571 EVT EltVT = 1572 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1573 1574 SDValue Op; 1575 if (EltVT.isFloatingPoint()) 1576 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1577 else 1578 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1579 Ops.assign(NumElements, Op); 1580 } 1581 1582 // Create a BUILD_VECTOR node. 1583 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1584 } 1585 1586 // If this is a static alloca, generate it as the frameindex instead of 1587 // computation. 1588 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1589 DenseMap<const AllocaInst*, int>::iterator SI = 1590 FuncInfo.StaticAllocaMap.find(AI); 1591 if (SI != FuncInfo.StaticAllocaMap.end()) 1592 return DAG.getFrameIndex(SI->second, 1593 TLI.getFrameIndexTy(DAG.getDataLayout())); 1594 } 1595 1596 // If this is an instruction which fast-isel has deferred, select it now. 1597 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1598 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1599 1600 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1601 Inst->getType(), getABIRegCopyCC(V)); 1602 SDValue Chain = DAG.getEntryNode(); 1603 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1604 } 1605 1606 llvm_unreachable("Can't get register for value!"); 1607 } 1608 1609 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1610 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1611 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1612 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1613 bool IsSEH = isAsynchronousEHPersonality(Pers); 1614 bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX; 1615 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1616 if (!IsSEH) 1617 CatchPadMBB->setIsEHScopeEntry(); 1618 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1619 if (IsMSVCCXX || IsCoreCLR) 1620 CatchPadMBB->setIsEHFuncletEntry(); 1621 // Wasm does not need catchpads anymore 1622 if (!IsWasmCXX) 1623 DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other, 1624 getControlRoot())); 1625 } 1626 1627 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1628 // Update machine-CFG edge. 1629 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1630 FuncInfo.MBB->addSuccessor(TargetMBB); 1631 1632 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1633 bool IsSEH = isAsynchronousEHPersonality(Pers); 1634 if (IsSEH) { 1635 // If this is not a fall-through branch or optimizations are switched off, 1636 // emit the branch. 1637 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1638 TM.getOptLevel() == CodeGenOpt::None) 1639 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1640 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1641 return; 1642 } 1643 1644 // Figure out the funclet membership for the catchret's successor. 1645 // This will be used by the FuncletLayout pass to determine how to order the 1646 // BB's. 1647 // A 'catchret' returns to the outer scope's color. 1648 Value *ParentPad = I.getCatchSwitchParentPad(); 1649 const BasicBlock *SuccessorColor; 1650 if (isa<ConstantTokenNone>(ParentPad)) 1651 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1652 else 1653 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1654 assert(SuccessorColor && "No parent funclet for catchret!"); 1655 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1656 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1657 1658 // Create the terminator node. 1659 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1660 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1661 DAG.getBasicBlock(SuccessorColorMBB)); 1662 DAG.setRoot(Ret); 1663 } 1664 1665 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1666 // Don't emit any special code for the cleanuppad instruction. It just marks 1667 // the start of an EH scope/funclet. 1668 FuncInfo.MBB->setIsEHScopeEntry(); 1669 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1670 if (Pers != EHPersonality::Wasm_CXX) { 1671 FuncInfo.MBB->setIsEHFuncletEntry(); 1672 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1673 } 1674 } 1675 1676 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and 1677 // the control flow always stops at the single catch pad, as it does for a 1678 // cleanup pad. In case the exception caught is not of the types the catch pad 1679 // catches, it will be rethrown by a rethrow. 1680 static void findWasmUnwindDestinations( 1681 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1682 BranchProbability Prob, 1683 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1684 &UnwindDests) { 1685 while (EHPadBB) { 1686 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1687 if (isa<CleanupPadInst>(Pad)) { 1688 // Stop on cleanup pads. 1689 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1690 UnwindDests.back().first->setIsEHScopeEntry(); 1691 break; 1692 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1693 // Add the catchpad handlers to the possible destinations. We don't 1694 // continue to the unwind destination of the catchswitch for wasm. 1695 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1696 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1697 UnwindDests.back().first->setIsEHScopeEntry(); 1698 } 1699 break; 1700 } else { 1701 continue; 1702 } 1703 } 1704 } 1705 1706 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1707 /// many places it could ultimately go. In the IR, we have a single unwind 1708 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1709 /// This function skips over imaginary basic blocks that hold catchswitch 1710 /// instructions, and finds all the "real" machine 1711 /// basic block destinations. As those destinations may not be successors of 1712 /// EHPadBB, here we also calculate the edge probability to those destinations. 1713 /// The passed-in Prob is the edge probability to EHPadBB. 1714 static void findUnwindDestinations( 1715 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1716 BranchProbability Prob, 1717 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1718 &UnwindDests) { 1719 EHPersonality Personality = 1720 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1721 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1722 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1723 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1724 bool IsSEH = isAsynchronousEHPersonality(Personality); 1725 1726 if (IsWasmCXX) { 1727 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1728 assert(UnwindDests.size() <= 1 && 1729 "There should be at most one unwind destination for wasm"); 1730 return; 1731 } 1732 1733 while (EHPadBB) { 1734 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1735 BasicBlock *NewEHPadBB = nullptr; 1736 if (isa<LandingPadInst>(Pad)) { 1737 // Stop on landingpads. They are not funclets. 1738 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1739 break; 1740 } else if (isa<CleanupPadInst>(Pad)) { 1741 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1742 // personalities. 1743 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1744 UnwindDests.back().first->setIsEHScopeEntry(); 1745 UnwindDests.back().first->setIsEHFuncletEntry(); 1746 break; 1747 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1748 // Add the catchpad handlers to the possible destinations. 1749 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1750 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1751 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1752 if (IsMSVCCXX || IsCoreCLR) 1753 UnwindDests.back().first->setIsEHFuncletEntry(); 1754 if (!IsSEH) 1755 UnwindDests.back().first->setIsEHScopeEntry(); 1756 } 1757 NewEHPadBB = CatchSwitch->getUnwindDest(); 1758 } else { 1759 continue; 1760 } 1761 1762 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1763 if (BPI && NewEHPadBB) 1764 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1765 EHPadBB = NewEHPadBB; 1766 } 1767 } 1768 1769 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1770 // Update successor info. 1771 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1772 auto UnwindDest = I.getUnwindDest(); 1773 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1774 BranchProbability UnwindDestProb = 1775 (BPI && UnwindDest) 1776 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1777 : BranchProbability::getZero(); 1778 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1779 for (auto &UnwindDest : UnwindDests) { 1780 UnwindDest.first->setIsEHPad(); 1781 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1782 } 1783 FuncInfo.MBB->normalizeSuccProbs(); 1784 1785 // Create the terminator node. 1786 SDValue Ret = 1787 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1788 DAG.setRoot(Ret); 1789 } 1790 1791 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1792 report_fatal_error("visitCatchSwitch not yet implemented!"); 1793 } 1794 1795 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1796 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1797 auto &DL = DAG.getDataLayout(); 1798 SDValue Chain = getControlRoot(); 1799 SmallVector<ISD::OutputArg, 8> Outs; 1800 SmallVector<SDValue, 8> OutVals; 1801 1802 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1803 // lower 1804 // 1805 // %val = call <ty> @llvm.experimental.deoptimize() 1806 // ret <ty> %val 1807 // 1808 // differently. 1809 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1810 LowerDeoptimizingReturn(); 1811 return; 1812 } 1813 1814 if (!FuncInfo.CanLowerReturn) { 1815 unsigned DemoteReg = FuncInfo.DemoteRegister; 1816 const Function *F = I.getParent()->getParent(); 1817 1818 // Emit a store of the return value through the virtual register. 1819 // Leave Outs empty so that LowerReturn won't try to load return 1820 // registers the usual way. 1821 SmallVector<EVT, 1> PtrValueVTs; 1822 ComputeValueVTs(TLI, DL, 1823 F->getReturnType()->getPointerTo( 1824 DAG.getDataLayout().getAllocaAddrSpace()), 1825 PtrValueVTs); 1826 1827 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1828 DemoteReg, PtrValueVTs[0]); 1829 SDValue RetOp = getValue(I.getOperand(0)); 1830 1831 SmallVector<EVT, 4> ValueVTs, MemVTs; 1832 SmallVector<uint64_t, 4> Offsets; 1833 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1834 &Offsets); 1835 unsigned NumValues = ValueVTs.size(); 1836 1837 SmallVector<SDValue, 4> Chains(NumValues); 1838 for (unsigned i = 0; i != NumValues; ++i) { 1839 // An aggregate return value cannot wrap around the address space, so 1840 // offsets to its parts don't wrap either. 1841 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]); 1842 1843 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 1844 if (MemVTs[i] != ValueVTs[i]) 1845 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 1846 Chains[i] = DAG.getStore(Chain, getCurSDLoc(), Val, 1847 // FIXME: better loc info would be nice. 1848 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction())); 1849 } 1850 1851 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1852 MVT::Other, Chains); 1853 } else if (I.getNumOperands() != 0) { 1854 SmallVector<EVT, 4> ValueVTs; 1855 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1856 unsigned NumValues = ValueVTs.size(); 1857 if (NumValues) { 1858 SDValue RetOp = getValue(I.getOperand(0)); 1859 1860 const Function *F = I.getParent()->getParent(); 1861 1862 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 1863 I.getOperand(0)->getType(), F->getCallingConv(), 1864 /*IsVarArg*/ false); 1865 1866 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1867 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1868 Attribute::SExt)) 1869 ExtendKind = ISD::SIGN_EXTEND; 1870 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1871 Attribute::ZExt)) 1872 ExtendKind = ISD::ZERO_EXTEND; 1873 1874 LLVMContext &Context = F->getContext(); 1875 bool RetInReg = F->getAttributes().hasAttribute( 1876 AttributeList::ReturnIndex, Attribute::InReg); 1877 1878 for (unsigned j = 0; j != NumValues; ++j) { 1879 EVT VT = ValueVTs[j]; 1880 1881 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1882 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1883 1884 CallingConv::ID CC = F->getCallingConv(); 1885 1886 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1887 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1888 SmallVector<SDValue, 4> Parts(NumParts); 1889 getCopyToParts(DAG, getCurSDLoc(), 1890 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1891 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1892 1893 // 'inreg' on function refers to return value 1894 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1895 if (RetInReg) 1896 Flags.setInReg(); 1897 1898 if (I.getOperand(0)->getType()->isPointerTy()) { 1899 Flags.setPointer(); 1900 Flags.setPointerAddrSpace( 1901 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 1902 } 1903 1904 if (NeedsRegBlock) { 1905 Flags.setInConsecutiveRegs(); 1906 if (j == NumValues - 1) 1907 Flags.setInConsecutiveRegsLast(); 1908 } 1909 1910 // Propagate extension type if any 1911 if (ExtendKind == ISD::SIGN_EXTEND) 1912 Flags.setSExt(); 1913 else if (ExtendKind == ISD::ZERO_EXTEND) 1914 Flags.setZExt(); 1915 1916 for (unsigned i = 0; i < NumParts; ++i) { 1917 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1918 VT, /*isfixed=*/true, 0, 0)); 1919 OutVals.push_back(Parts[i]); 1920 } 1921 } 1922 } 1923 } 1924 1925 // Push in swifterror virtual register as the last element of Outs. This makes 1926 // sure swifterror virtual register will be returned in the swifterror 1927 // physical register. 1928 const Function *F = I.getParent()->getParent(); 1929 if (TLI.supportSwiftError() && 1930 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 1931 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 1932 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1933 Flags.setSwiftError(); 1934 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 1935 EVT(TLI.getPointerTy(DL)) /*argvt*/, 1936 true /*isfixed*/, 1 /*origidx*/, 1937 0 /*partOffs*/)); 1938 // Create SDNode for the swifterror virtual register. 1939 OutVals.push_back( 1940 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 1941 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 1942 EVT(TLI.getPointerTy(DL)))); 1943 } 1944 1945 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 1946 CallingConv::ID CallConv = 1947 DAG.getMachineFunction().getFunction().getCallingConv(); 1948 Chain = DAG.getTargetLoweringInfo().LowerReturn( 1949 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 1950 1951 // Verify that the target's LowerReturn behaved as expected. 1952 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 1953 "LowerReturn didn't return a valid chain!"); 1954 1955 // Update the DAG with the new chain value resulting from return lowering. 1956 DAG.setRoot(Chain); 1957 } 1958 1959 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 1960 /// created for it, emit nodes to copy the value into the virtual 1961 /// registers. 1962 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 1963 // Skip empty types 1964 if (V->getType()->isEmptyTy()) 1965 return; 1966 1967 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 1968 if (VMI != FuncInfo.ValueMap.end()) { 1969 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 1970 CopyValueToVirtualRegister(V, VMI->second); 1971 } 1972 } 1973 1974 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 1975 /// the current basic block, add it to ValueMap now so that we'll get a 1976 /// CopyTo/FromReg. 1977 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 1978 // No need to export constants. 1979 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 1980 1981 // Already exported? 1982 if (FuncInfo.isExportedInst(V)) return; 1983 1984 unsigned Reg = FuncInfo.InitializeRegForValue(V); 1985 CopyValueToVirtualRegister(V, Reg); 1986 } 1987 1988 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 1989 const BasicBlock *FromBB) { 1990 // The operands of the setcc have to be in this block. We don't know 1991 // how to export them from some other block. 1992 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 1993 // Can export from current BB. 1994 if (VI->getParent() == FromBB) 1995 return true; 1996 1997 // Is already exported, noop. 1998 return FuncInfo.isExportedInst(V); 1999 } 2000 2001 // If this is an argument, we can export it if the BB is the entry block or 2002 // if it is already exported. 2003 if (isa<Argument>(V)) { 2004 if (FromBB == &FromBB->getParent()->getEntryBlock()) 2005 return true; 2006 2007 // Otherwise, can only export this if it is already exported. 2008 return FuncInfo.isExportedInst(V); 2009 } 2010 2011 // Otherwise, constants can always be exported. 2012 return true; 2013 } 2014 2015 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2016 BranchProbability 2017 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2018 const MachineBasicBlock *Dst) const { 2019 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2020 const BasicBlock *SrcBB = Src->getBasicBlock(); 2021 const BasicBlock *DstBB = Dst->getBasicBlock(); 2022 if (!BPI) { 2023 // If BPI is not available, set the default probability as 1 / N, where N is 2024 // the number of successors. 2025 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2026 return BranchProbability(1, SuccSize); 2027 } 2028 return BPI->getEdgeProbability(SrcBB, DstBB); 2029 } 2030 2031 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2032 MachineBasicBlock *Dst, 2033 BranchProbability Prob) { 2034 if (!FuncInfo.BPI) 2035 Src->addSuccessorWithoutProb(Dst); 2036 else { 2037 if (Prob.isUnknown()) 2038 Prob = getEdgeProbability(Src, Dst); 2039 Src->addSuccessor(Dst, Prob); 2040 } 2041 } 2042 2043 static bool InBlock(const Value *V, const BasicBlock *BB) { 2044 if (const Instruction *I = dyn_cast<Instruction>(V)) 2045 return I->getParent() == BB; 2046 return true; 2047 } 2048 2049 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2050 /// This function emits a branch and is used at the leaves of an OR or an 2051 /// AND operator tree. 2052 void 2053 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2054 MachineBasicBlock *TBB, 2055 MachineBasicBlock *FBB, 2056 MachineBasicBlock *CurBB, 2057 MachineBasicBlock *SwitchBB, 2058 BranchProbability TProb, 2059 BranchProbability FProb, 2060 bool InvertCond) { 2061 const BasicBlock *BB = CurBB->getBasicBlock(); 2062 2063 // If the leaf of the tree is a comparison, merge the condition into 2064 // the caseblock. 2065 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2066 // The operands of the cmp have to be in this block. We don't know 2067 // how to export them from some other block. If this is the first block 2068 // of the sequence, no exporting is needed. 2069 if (CurBB == SwitchBB || 2070 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2071 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2072 ISD::CondCode Condition; 2073 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2074 ICmpInst::Predicate Pred = 2075 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2076 Condition = getICmpCondCode(Pred); 2077 } else { 2078 const FCmpInst *FC = cast<FCmpInst>(Cond); 2079 FCmpInst::Predicate Pred = 2080 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2081 Condition = getFCmpCondCode(Pred); 2082 if (TM.Options.NoNaNsFPMath) 2083 Condition = getFCmpCodeWithoutNaN(Condition); 2084 } 2085 2086 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2087 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2088 SL->SwitchCases.push_back(CB); 2089 return; 2090 } 2091 } 2092 2093 // Create a CaseBlock record representing this branch. 2094 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2095 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2096 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2097 SL->SwitchCases.push_back(CB); 2098 } 2099 2100 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2101 MachineBasicBlock *TBB, 2102 MachineBasicBlock *FBB, 2103 MachineBasicBlock *CurBB, 2104 MachineBasicBlock *SwitchBB, 2105 Instruction::BinaryOps Opc, 2106 BranchProbability TProb, 2107 BranchProbability FProb, 2108 bool InvertCond) { 2109 // Skip over not part of the tree and remember to invert op and operands at 2110 // next level. 2111 Value *NotCond; 2112 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2113 InBlock(NotCond, CurBB->getBasicBlock())) { 2114 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2115 !InvertCond); 2116 return; 2117 } 2118 2119 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2120 // Compute the effective opcode for Cond, taking into account whether it needs 2121 // to be inverted, e.g. 2122 // and (not (or A, B)), C 2123 // gets lowered as 2124 // and (and (not A, not B), C) 2125 unsigned BOpc = 0; 2126 if (BOp) { 2127 BOpc = BOp->getOpcode(); 2128 if (InvertCond) { 2129 if (BOpc == Instruction::And) 2130 BOpc = Instruction::Or; 2131 else if (BOpc == Instruction::Or) 2132 BOpc = Instruction::And; 2133 } 2134 } 2135 2136 // If this node is not part of the or/and tree, emit it as a branch. 2137 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 2138 BOpc != unsigned(Opc) || !BOp->hasOneUse() || 2139 BOp->getParent() != CurBB->getBasicBlock() || 2140 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 2141 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 2142 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2143 TProb, FProb, InvertCond); 2144 return; 2145 } 2146 2147 // Create TmpBB after CurBB. 2148 MachineFunction::iterator BBI(CurBB); 2149 MachineFunction &MF = DAG.getMachineFunction(); 2150 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2151 CurBB->getParent()->insert(++BBI, TmpBB); 2152 2153 if (Opc == Instruction::Or) { 2154 // Codegen X | Y as: 2155 // BB1: 2156 // jmp_if_X TBB 2157 // jmp TmpBB 2158 // TmpBB: 2159 // jmp_if_Y TBB 2160 // jmp FBB 2161 // 2162 2163 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2164 // The requirement is that 2165 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2166 // = TrueProb for original BB. 2167 // Assuming the original probabilities are A and B, one choice is to set 2168 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2169 // A/(1+B) and 2B/(1+B). This choice assumes that 2170 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2171 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2172 // TmpBB, but the math is more complicated. 2173 2174 auto NewTrueProb = TProb / 2; 2175 auto NewFalseProb = TProb / 2 + FProb; 2176 // Emit the LHS condition. 2177 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc, 2178 NewTrueProb, NewFalseProb, InvertCond); 2179 2180 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2181 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2182 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2183 // Emit the RHS condition into TmpBB. 2184 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2185 Probs[0], Probs[1], InvertCond); 2186 } else { 2187 assert(Opc == Instruction::And && "Unknown merge op!"); 2188 // Codegen X & Y as: 2189 // BB1: 2190 // jmp_if_X TmpBB 2191 // jmp FBB 2192 // TmpBB: 2193 // jmp_if_Y TBB 2194 // jmp FBB 2195 // 2196 // This requires creation of TmpBB after CurBB. 2197 2198 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2199 // The requirement is that 2200 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2201 // = FalseProb for original BB. 2202 // Assuming the original probabilities are A and B, one choice is to set 2203 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2204 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2205 // TrueProb for BB1 * FalseProb for TmpBB. 2206 2207 auto NewTrueProb = TProb + FProb / 2; 2208 auto NewFalseProb = FProb / 2; 2209 // Emit the LHS condition. 2210 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc, 2211 NewTrueProb, NewFalseProb, InvertCond); 2212 2213 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2214 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2215 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2216 // Emit the RHS condition into TmpBB. 2217 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2218 Probs[0], Probs[1], InvertCond); 2219 } 2220 } 2221 2222 /// If the set of cases should be emitted as a series of branches, return true. 2223 /// If we should emit this as a bunch of and/or'd together conditions, return 2224 /// false. 2225 bool 2226 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2227 if (Cases.size() != 2) return true; 2228 2229 // If this is two comparisons of the same values or'd or and'd together, they 2230 // will get folded into a single comparison, so don't emit two blocks. 2231 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2232 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2233 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2234 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2235 return false; 2236 } 2237 2238 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2239 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2240 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2241 Cases[0].CC == Cases[1].CC && 2242 isa<Constant>(Cases[0].CmpRHS) && 2243 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2244 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2245 return false; 2246 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2247 return false; 2248 } 2249 2250 return true; 2251 } 2252 2253 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2254 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2255 2256 // Update machine-CFG edges. 2257 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2258 2259 if (I.isUnconditional()) { 2260 // Update machine-CFG edges. 2261 BrMBB->addSuccessor(Succ0MBB); 2262 2263 // If this is not a fall-through branch or optimizations are switched off, 2264 // emit the branch. 2265 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2266 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2267 MVT::Other, getControlRoot(), 2268 DAG.getBasicBlock(Succ0MBB))); 2269 2270 return; 2271 } 2272 2273 // If this condition is one of the special cases we handle, do special stuff 2274 // now. 2275 const Value *CondVal = I.getCondition(); 2276 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2277 2278 // If this is a series of conditions that are or'd or and'd together, emit 2279 // this as a sequence of branches instead of setcc's with and/or operations. 2280 // As long as jumps are not expensive, this should improve performance. 2281 // For example, instead of something like: 2282 // cmp A, B 2283 // C = seteq 2284 // cmp D, E 2285 // F = setle 2286 // or C, F 2287 // jnz foo 2288 // Emit: 2289 // cmp A, B 2290 // je foo 2291 // cmp D, E 2292 // jle foo 2293 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 2294 Instruction::BinaryOps Opcode = BOp->getOpcode(); 2295 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() && 2296 !I.hasMetadata(LLVMContext::MD_unpredictable) && 2297 (Opcode == Instruction::And || Opcode == Instruction::Or)) { 2298 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, 2299 Opcode, 2300 getEdgeProbability(BrMBB, Succ0MBB), 2301 getEdgeProbability(BrMBB, Succ1MBB), 2302 /*InvertCond=*/false); 2303 // If the compares in later blocks need to use values not currently 2304 // exported from this block, export them now. This block should always 2305 // be the first entry. 2306 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2307 2308 // Allow some cases to be rejected. 2309 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2310 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2311 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2312 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2313 } 2314 2315 // Emit the branch for this block. 2316 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2317 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2318 return; 2319 } 2320 2321 // Okay, we decided not to do this, remove any inserted MBB's and clear 2322 // SwitchCases. 2323 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2324 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2325 2326 SL->SwitchCases.clear(); 2327 } 2328 } 2329 2330 // Create a CaseBlock record representing this branch. 2331 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2332 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2333 2334 // Use visitSwitchCase to actually insert the fast branch sequence for this 2335 // cond branch. 2336 visitSwitchCase(CB, BrMBB); 2337 } 2338 2339 /// visitSwitchCase - Emits the necessary code to represent a single node in 2340 /// the binary search tree resulting from lowering a switch instruction. 2341 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2342 MachineBasicBlock *SwitchBB) { 2343 SDValue Cond; 2344 SDValue CondLHS = getValue(CB.CmpLHS); 2345 SDLoc dl = CB.DL; 2346 2347 if (CB.CC == ISD::SETTRUE) { 2348 // Branch or fall through to TrueBB. 2349 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2350 SwitchBB->normalizeSuccProbs(); 2351 if (CB.TrueBB != NextBlock(SwitchBB)) { 2352 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2353 DAG.getBasicBlock(CB.TrueBB))); 2354 } 2355 return; 2356 } 2357 2358 auto &TLI = DAG.getTargetLoweringInfo(); 2359 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2360 2361 // Build the setcc now. 2362 if (!CB.CmpMHS) { 2363 // Fold "(X == true)" to X and "(X == false)" to !X to 2364 // handle common cases produced by branch lowering. 2365 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2366 CB.CC == ISD::SETEQ) 2367 Cond = CondLHS; 2368 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2369 CB.CC == ISD::SETEQ) { 2370 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2371 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2372 } else { 2373 SDValue CondRHS = getValue(CB.CmpRHS); 2374 2375 // If a pointer's DAG type is larger than its memory type then the DAG 2376 // values are zero-extended. This breaks signed comparisons so truncate 2377 // back to the underlying type before doing the compare. 2378 if (CondLHS.getValueType() != MemVT) { 2379 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2380 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2381 } 2382 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2383 } 2384 } else { 2385 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2386 2387 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2388 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2389 2390 SDValue CmpOp = getValue(CB.CmpMHS); 2391 EVT VT = CmpOp.getValueType(); 2392 2393 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2394 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2395 ISD::SETLE); 2396 } else { 2397 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2398 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2399 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2400 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2401 } 2402 } 2403 2404 // Update successor info 2405 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2406 // TrueBB and FalseBB are always different unless the incoming IR is 2407 // degenerate. This only happens when running llc on weird IR. 2408 if (CB.TrueBB != CB.FalseBB) 2409 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2410 SwitchBB->normalizeSuccProbs(); 2411 2412 // If the lhs block is the next block, invert the condition so that we can 2413 // fall through to the lhs instead of the rhs block. 2414 if (CB.TrueBB == NextBlock(SwitchBB)) { 2415 std::swap(CB.TrueBB, CB.FalseBB); 2416 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2417 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2418 } 2419 2420 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2421 MVT::Other, getControlRoot(), Cond, 2422 DAG.getBasicBlock(CB.TrueBB)); 2423 2424 // Insert the false branch. Do this even if it's a fall through branch, 2425 // this makes it easier to do DAG optimizations which require inverting 2426 // the branch condition. 2427 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2428 DAG.getBasicBlock(CB.FalseBB)); 2429 2430 DAG.setRoot(BrCond); 2431 } 2432 2433 /// visitJumpTable - Emit JumpTable node in the current MBB 2434 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2435 // Emit the code for the jump table 2436 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2437 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2438 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2439 JT.Reg, PTy); 2440 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2441 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2442 MVT::Other, Index.getValue(1), 2443 Table, Index); 2444 DAG.setRoot(BrJumpTable); 2445 } 2446 2447 /// visitJumpTableHeader - This function emits necessary code to produce index 2448 /// in the JumpTable from switch case. 2449 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2450 JumpTableHeader &JTH, 2451 MachineBasicBlock *SwitchBB) { 2452 SDLoc dl = getCurSDLoc(); 2453 2454 // Subtract the lowest switch case value from the value being switched on. 2455 SDValue SwitchOp = getValue(JTH.SValue); 2456 EVT VT = SwitchOp.getValueType(); 2457 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2458 DAG.getConstant(JTH.First, dl, VT)); 2459 2460 // The SDNode we just created, which holds the value being switched on minus 2461 // the smallest case value, needs to be copied to a virtual register so it 2462 // can be used as an index into the jump table in a subsequent basic block. 2463 // This value may be smaller or larger than the target's pointer type, and 2464 // therefore require extension or truncating. 2465 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2466 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2467 2468 unsigned JumpTableReg = 2469 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2470 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2471 JumpTableReg, SwitchOp); 2472 JT.Reg = JumpTableReg; 2473 2474 if (!JTH.OmitRangeCheck) { 2475 // Emit the range check for the jump table, and branch to the default block 2476 // for the switch statement if the value being switched on exceeds the 2477 // largest case in the switch. 2478 SDValue CMP = DAG.getSetCC( 2479 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2480 Sub.getValueType()), 2481 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2482 2483 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2484 MVT::Other, CopyTo, CMP, 2485 DAG.getBasicBlock(JT.Default)); 2486 2487 // Avoid emitting unnecessary branches to the next block. 2488 if (JT.MBB != NextBlock(SwitchBB)) 2489 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2490 DAG.getBasicBlock(JT.MBB)); 2491 2492 DAG.setRoot(BrCond); 2493 } else { 2494 // Avoid emitting unnecessary branches to the next block. 2495 if (JT.MBB != NextBlock(SwitchBB)) 2496 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2497 DAG.getBasicBlock(JT.MBB))); 2498 else 2499 DAG.setRoot(CopyTo); 2500 } 2501 } 2502 2503 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2504 /// variable if there exists one. 2505 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2506 SDValue &Chain) { 2507 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2508 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2509 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2510 MachineFunction &MF = DAG.getMachineFunction(); 2511 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2512 MachineSDNode *Node = 2513 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2514 if (Global) { 2515 MachinePointerInfo MPInfo(Global); 2516 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2517 MachineMemOperand::MODereferenceable; 2518 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2519 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy)); 2520 DAG.setNodeMemRefs(Node, {MemRef}); 2521 } 2522 if (PtrTy != PtrMemTy) 2523 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2524 return SDValue(Node, 0); 2525 } 2526 2527 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2528 /// tail spliced into a stack protector check success bb. 2529 /// 2530 /// For a high level explanation of how this fits into the stack protector 2531 /// generation see the comment on the declaration of class 2532 /// StackProtectorDescriptor. 2533 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2534 MachineBasicBlock *ParentBB) { 2535 2536 // First create the loads to the guard/stack slot for the comparison. 2537 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2538 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2539 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2540 2541 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2542 int FI = MFI.getStackProtectorIndex(); 2543 2544 SDValue Guard; 2545 SDLoc dl = getCurSDLoc(); 2546 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2547 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2548 unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext())); 2549 2550 // Generate code to load the content of the guard slot. 2551 SDValue GuardVal = DAG.getLoad( 2552 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2553 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2554 MachineMemOperand::MOVolatile); 2555 2556 if (TLI.useStackGuardXorFP()) 2557 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2558 2559 // Retrieve guard check function, nullptr if instrumentation is inlined. 2560 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2561 // The target provides a guard check function to validate the guard value. 2562 // Generate a call to that function with the content of the guard slot as 2563 // argument. 2564 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2565 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2566 2567 TargetLowering::ArgListTy Args; 2568 TargetLowering::ArgListEntry Entry; 2569 Entry.Node = GuardVal; 2570 Entry.Ty = FnTy->getParamType(0); 2571 if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg)) 2572 Entry.IsInReg = true; 2573 Args.push_back(Entry); 2574 2575 TargetLowering::CallLoweringInfo CLI(DAG); 2576 CLI.setDebugLoc(getCurSDLoc()) 2577 .setChain(DAG.getEntryNode()) 2578 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2579 getValue(GuardCheckFn), std::move(Args)); 2580 2581 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2582 DAG.setRoot(Result.second); 2583 return; 2584 } 2585 2586 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2587 // Otherwise, emit a volatile load to retrieve the stack guard value. 2588 SDValue Chain = DAG.getEntryNode(); 2589 if (TLI.useLoadStackGuardNode()) { 2590 Guard = getLoadStackGuard(DAG, dl, Chain); 2591 } else { 2592 const Value *IRGuard = TLI.getSDagStackGuard(M); 2593 SDValue GuardPtr = getValue(IRGuard); 2594 2595 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2596 MachinePointerInfo(IRGuard, 0), Align, 2597 MachineMemOperand::MOVolatile); 2598 } 2599 2600 // Perform the comparison via a subtract/getsetcc. 2601 EVT VT = Guard.getValueType(); 2602 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal); 2603 2604 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2605 *DAG.getContext(), 2606 Sub.getValueType()), 2607 Sub, DAG.getConstant(0, dl, VT), ISD::SETNE); 2608 2609 // If the sub is not 0, then we know the guard/stackslot do not equal, so 2610 // branch to failure MBB. 2611 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2612 MVT::Other, GuardVal.getOperand(0), 2613 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2614 // Otherwise branch to success MBB. 2615 SDValue Br = DAG.getNode(ISD::BR, dl, 2616 MVT::Other, BrCond, 2617 DAG.getBasicBlock(SPD.getSuccessMBB())); 2618 2619 DAG.setRoot(Br); 2620 } 2621 2622 /// Codegen the failure basic block for a stack protector check. 2623 /// 2624 /// A failure stack protector machine basic block consists simply of a call to 2625 /// __stack_chk_fail(). 2626 /// 2627 /// For a high level explanation of how this fits into the stack protector 2628 /// generation see the comment on the declaration of class 2629 /// StackProtectorDescriptor. 2630 void 2631 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2632 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2633 TargetLowering::MakeLibCallOptions CallOptions; 2634 CallOptions.setDiscardResult(true); 2635 SDValue Chain = 2636 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2637 None, CallOptions, getCurSDLoc()).second; 2638 // On PS4, the "return address" must still be within the calling function, 2639 // even if it's at the very end, so emit an explicit TRAP here. 2640 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2641 if (TM.getTargetTriple().isPS4CPU()) 2642 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2643 2644 DAG.setRoot(Chain); 2645 } 2646 2647 /// visitBitTestHeader - This function emits necessary code to produce value 2648 /// suitable for "bit tests" 2649 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2650 MachineBasicBlock *SwitchBB) { 2651 SDLoc dl = getCurSDLoc(); 2652 2653 // Subtract the minimum value. 2654 SDValue SwitchOp = getValue(B.SValue); 2655 EVT VT = SwitchOp.getValueType(); 2656 SDValue RangeSub = 2657 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2658 2659 // Determine the type of the test operands. 2660 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2661 bool UsePtrType = false; 2662 if (!TLI.isTypeLegal(VT)) { 2663 UsePtrType = true; 2664 } else { 2665 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2666 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2667 // Switch table case range are encoded into series of masks. 2668 // Just use pointer type, it's guaranteed to fit. 2669 UsePtrType = true; 2670 break; 2671 } 2672 } 2673 SDValue Sub = RangeSub; 2674 if (UsePtrType) { 2675 VT = TLI.getPointerTy(DAG.getDataLayout()); 2676 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2677 } 2678 2679 B.RegVT = VT.getSimpleVT(); 2680 B.Reg = FuncInfo.CreateReg(B.RegVT); 2681 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2682 2683 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2684 2685 if (!B.OmitRangeCheck) 2686 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2687 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2688 SwitchBB->normalizeSuccProbs(); 2689 2690 SDValue Root = CopyTo; 2691 if (!B.OmitRangeCheck) { 2692 // Conditional branch to the default block. 2693 SDValue RangeCmp = DAG.getSetCC(dl, 2694 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2695 RangeSub.getValueType()), 2696 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2697 ISD::SETUGT); 2698 2699 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2700 DAG.getBasicBlock(B.Default)); 2701 } 2702 2703 // Avoid emitting unnecessary branches to the next block. 2704 if (MBB != NextBlock(SwitchBB)) 2705 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2706 2707 DAG.setRoot(Root); 2708 } 2709 2710 /// visitBitTestCase - this function produces one "bit test" 2711 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2712 MachineBasicBlock* NextMBB, 2713 BranchProbability BranchProbToNext, 2714 unsigned Reg, 2715 BitTestCase &B, 2716 MachineBasicBlock *SwitchBB) { 2717 SDLoc dl = getCurSDLoc(); 2718 MVT VT = BB.RegVT; 2719 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2720 SDValue Cmp; 2721 unsigned PopCount = countPopulation(B.Mask); 2722 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2723 if (PopCount == 1) { 2724 // Testing for a single bit; just compare the shift count with what it 2725 // would need to be to shift a 1 bit in that position. 2726 Cmp = DAG.getSetCC( 2727 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2728 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2729 ISD::SETEQ); 2730 } else if (PopCount == BB.Range) { 2731 // There is only one zero bit in the range, test for it directly. 2732 Cmp = DAG.getSetCC( 2733 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2734 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2735 ISD::SETNE); 2736 } else { 2737 // Make desired shift 2738 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2739 DAG.getConstant(1, dl, VT), ShiftOp); 2740 2741 // Emit bit tests and jumps 2742 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2743 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2744 Cmp = DAG.getSetCC( 2745 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2746 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2747 } 2748 2749 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2750 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2751 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2752 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2753 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2754 // one as they are relative probabilities (and thus work more like weights), 2755 // and hence we need to normalize them to let the sum of them become one. 2756 SwitchBB->normalizeSuccProbs(); 2757 2758 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2759 MVT::Other, getControlRoot(), 2760 Cmp, DAG.getBasicBlock(B.TargetBB)); 2761 2762 // Avoid emitting unnecessary branches to the next block. 2763 if (NextMBB != NextBlock(SwitchBB)) 2764 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2765 DAG.getBasicBlock(NextMBB)); 2766 2767 DAG.setRoot(BrAnd); 2768 } 2769 2770 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2771 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2772 2773 // Retrieve successors. Look through artificial IR level blocks like 2774 // catchswitch for successors. 2775 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2776 const BasicBlock *EHPadBB = I.getSuccessor(1); 2777 2778 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2779 // have to do anything here to lower funclet bundles. 2780 assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt, 2781 LLVMContext::OB_funclet, 2782 LLVMContext::OB_cfguardtarget}) && 2783 "Cannot lower invokes with arbitrary operand bundles yet!"); 2784 2785 const Value *Callee(I.getCalledValue()); 2786 const Function *Fn = dyn_cast<Function>(Callee); 2787 if (isa<InlineAsm>(Callee)) 2788 visitInlineAsm(&I); 2789 else if (Fn && Fn->isIntrinsic()) { 2790 switch (Fn->getIntrinsicID()) { 2791 default: 2792 llvm_unreachable("Cannot invoke this intrinsic"); 2793 case Intrinsic::donothing: 2794 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2795 break; 2796 case Intrinsic::experimental_patchpoint_void: 2797 case Intrinsic::experimental_patchpoint_i64: 2798 visitPatchpoint(&I, EHPadBB); 2799 break; 2800 case Intrinsic::experimental_gc_statepoint: 2801 LowerStatepoint(ImmutableStatepoint(&I), EHPadBB); 2802 break; 2803 case Intrinsic::wasm_rethrow_in_catch: { 2804 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2805 // special because it can be invoked, so we manually lower it to a DAG 2806 // node here. 2807 SmallVector<SDValue, 8> Ops; 2808 Ops.push_back(getRoot()); // inchain 2809 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2810 Ops.push_back( 2811 DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(), 2812 TLI.getPointerTy(DAG.getDataLayout()))); 2813 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2814 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2815 break; 2816 } 2817 } 2818 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2819 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2820 // Eventually we will support lowering the @llvm.experimental.deoptimize 2821 // intrinsic, and right now there are no plans to support other intrinsics 2822 // with deopt state. 2823 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2824 } else { 2825 LowerCallTo(&I, getValue(Callee), false, EHPadBB); 2826 } 2827 2828 // If the value of the invoke is used outside of its defining block, make it 2829 // available as a virtual register. 2830 // We already took care of the exported value for the statepoint instruction 2831 // during call to the LowerStatepoint. 2832 if (!isStatepoint(I)) { 2833 CopyToExportRegsIfNeeded(&I); 2834 } 2835 2836 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2837 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2838 BranchProbability EHPadBBProb = 2839 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2840 : BranchProbability::getZero(); 2841 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2842 2843 // Update successor info. 2844 addSuccessorWithProb(InvokeMBB, Return); 2845 for (auto &UnwindDest : UnwindDests) { 2846 UnwindDest.first->setIsEHPad(); 2847 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2848 } 2849 InvokeMBB->normalizeSuccProbs(); 2850 2851 // Drop into normal successor. 2852 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 2853 DAG.getBasicBlock(Return))); 2854 } 2855 2856 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 2857 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 2858 2859 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2860 // have to do anything here to lower funclet bundles. 2861 assert(!I.hasOperandBundlesOtherThan( 2862 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2863 "Cannot lower callbrs with arbitrary operand bundles yet!"); 2864 2865 assert(isa<InlineAsm>(I.getCalledValue()) && 2866 "Only know how to handle inlineasm callbr"); 2867 visitInlineAsm(&I); 2868 2869 // Retrieve successors. 2870 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 2871 2872 // Update successor info. 2873 addSuccessorWithProb(CallBrMBB, Return); 2874 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 2875 MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)]; 2876 addSuccessorWithProb(CallBrMBB, Target); 2877 } 2878 CallBrMBB->normalizeSuccProbs(); 2879 2880 // Drop into default successor. 2881 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2882 MVT::Other, getControlRoot(), 2883 DAG.getBasicBlock(Return))); 2884 } 2885 2886 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2887 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2888 } 2889 2890 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2891 assert(FuncInfo.MBB->isEHPad() && 2892 "Call to landingpad not in landing pad!"); 2893 2894 // If there aren't registers to copy the values into (e.g., during SjLj 2895 // exceptions), then don't bother to create these DAG nodes. 2896 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2897 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2898 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2899 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2900 return; 2901 2902 // If landingpad's return type is token type, we don't create DAG nodes 2903 // for its exception pointer and selector value. The extraction of exception 2904 // pointer or selector value from token type landingpads is not currently 2905 // supported. 2906 if (LP.getType()->isTokenTy()) 2907 return; 2908 2909 SmallVector<EVT, 2> ValueVTs; 2910 SDLoc dl = getCurSDLoc(); 2911 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2912 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2913 2914 // Get the two live-in registers as SDValues. The physregs have already been 2915 // copied into virtual registers. 2916 SDValue Ops[2]; 2917 if (FuncInfo.ExceptionPointerVirtReg) { 2918 Ops[0] = DAG.getZExtOrTrunc( 2919 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2920 FuncInfo.ExceptionPointerVirtReg, 2921 TLI.getPointerTy(DAG.getDataLayout())), 2922 dl, ValueVTs[0]); 2923 } else { 2924 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2925 } 2926 Ops[1] = DAG.getZExtOrTrunc( 2927 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2928 FuncInfo.ExceptionSelectorVirtReg, 2929 TLI.getPointerTy(DAG.getDataLayout())), 2930 dl, ValueVTs[1]); 2931 2932 // Merge into one. 2933 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 2934 DAG.getVTList(ValueVTs), Ops); 2935 setValue(&LP, Res); 2936 } 2937 2938 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2939 MachineBasicBlock *Last) { 2940 // Update JTCases. 2941 for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i) 2942 if (SL->JTCases[i].first.HeaderBB == First) 2943 SL->JTCases[i].first.HeaderBB = Last; 2944 2945 // Update BitTestCases. 2946 for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i) 2947 if (SL->BitTestCases[i].Parent == First) 2948 SL->BitTestCases[i].Parent = Last; 2949 } 2950 2951 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2952 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2953 2954 // Update machine-CFG edges with unique successors. 2955 SmallSet<BasicBlock*, 32> Done; 2956 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 2957 BasicBlock *BB = I.getSuccessor(i); 2958 bool Inserted = Done.insert(BB).second; 2959 if (!Inserted) 2960 continue; 2961 2962 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 2963 addSuccessorWithProb(IndirectBrMBB, Succ); 2964 } 2965 IndirectBrMBB->normalizeSuccProbs(); 2966 2967 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 2968 MVT::Other, getControlRoot(), 2969 getValue(I.getAddress()))); 2970 } 2971 2972 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 2973 if (!DAG.getTarget().Options.TrapUnreachable) 2974 return; 2975 2976 // We may be able to ignore unreachable behind a noreturn call. 2977 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 2978 const BasicBlock &BB = *I.getParent(); 2979 if (&I != &BB.front()) { 2980 BasicBlock::const_iterator PredI = 2981 std::prev(BasicBlock::const_iterator(&I)); 2982 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 2983 if (Call->doesNotReturn()) 2984 return; 2985 } 2986 } 2987 } 2988 2989 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 2990 } 2991 2992 void SelectionDAGBuilder::visitFSub(const User &I) { 2993 // -0.0 - X --> fneg 2994 Type *Ty = I.getType(); 2995 if (isa<Constant>(I.getOperand(0)) && 2996 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) { 2997 SDValue Op2 = getValue(I.getOperand(1)); 2998 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(), 2999 Op2.getValueType(), Op2)); 3000 return; 3001 } 3002 3003 visitBinary(I, ISD::FSUB); 3004 } 3005 3006 /// Checks if the given instruction performs a vector reduction, in which case 3007 /// we have the freedom to alter the elements in the result as long as the 3008 /// reduction of them stays unchanged. 3009 static bool isVectorReductionOp(const User *I) { 3010 const Instruction *Inst = dyn_cast<Instruction>(I); 3011 if (!Inst || !Inst->getType()->isVectorTy()) 3012 return false; 3013 3014 auto OpCode = Inst->getOpcode(); 3015 switch (OpCode) { 3016 case Instruction::Add: 3017 case Instruction::Mul: 3018 case Instruction::And: 3019 case Instruction::Or: 3020 case Instruction::Xor: 3021 break; 3022 case Instruction::FAdd: 3023 case Instruction::FMul: 3024 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 3025 if (FPOp->getFastMathFlags().isFast()) 3026 break; 3027 LLVM_FALLTHROUGH; 3028 default: 3029 return false; 3030 } 3031 3032 unsigned ElemNum = Inst->getType()->getVectorNumElements(); 3033 // Ensure the reduction size is a power of 2. 3034 if (!isPowerOf2_32(ElemNum)) 3035 return false; 3036 3037 unsigned ElemNumToReduce = ElemNum; 3038 3039 // Do DFS search on the def-use chain from the given instruction. We only 3040 // allow four kinds of operations during the search until we reach the 3041 // instruction that extracts the first element from the vector: 3042 // 3043 // 1. The reduction operation of the same opcode as the given instruction. 3044 // 3045 // 2. PHI node. 3046 // 3047 // 3. ShuffleVector instruction together with a reduction operation that 3048 // does a partial reduction. 3049 // 3050 // 4. ExtractElement that extracts the first element from the vector, and we 3051 // stop searching the def-use chain here. 3052 // 3053 // 3 & 4 above perform a reduction on all elements of the vector. We push defs 3054 // from 1-3 to the stack to continue the DFS. The given instruction is not 3055 // a reduction operation if we meet any other instructions other than those 3056 // listed above. 3057 3058 SmallVector<const User *, 16> UsersToVisit{Inst}; 3059 SmallPtrSet<const User *, 16> Visited; 3060 bool ReduxExtracted = false; 3061 3062 while (!UsersToVisit.empty()) { 3063 auto User = UsersToVisit.back(); 3064 UsersToVisit.pop_back(); 3065 if (!Visited.insert(User).second) 3066 continue; 3067 3068 for (const auto *U : User->users()) { 3069 auto Inst = dyn_cast<Instruction>(U); 3070 if (!Inst) 3071 return false; 3072 3073 if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) { 3074 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 3075 if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast()) 3076 return false; 3077 UsersToVisit.push_back(U); 3078 } else if (const ShuffleVectorInst *ShufInst = 3079 dyn_cast<ShuffleVectorInst>(U)) { 3080 // Detect the following pattern: A ShuffleVector instruction together 3081 // with a reduction that do partial reduction on the first and second 3082 // ElemNumToReduce / 2 elements, and store the result in 3083 // ElemNumToReduce / 2 elements in another vector. 3084 3085 unsigned ResultElements = ShufInst->getType()->getVectorNumElements(); 3086 if (ResultElements < ElemNum) 3087 return false; 3088 3089 if (ElemNumToReduce == 1) 3090 return false; 3091 if (!isa<UndefValue>(U->getOperand(1))) 3092 return false; 3093 for (unsigned i = 0; i < ElemNumToReduce / 2; ++i) 3094 if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2)) 3095 return false; 3096 for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i) 3097 if (ShufInst->getMaskValue(i) != -1) 3098 return false; 3099 3100 // There is only one user of this ShuffleVector instruction, which 3101 // must be a reduction operation. 3102 if (!U->hasOneUse()) 3103 return false; 3104 3105 auto U2 = dyn_cast<Instruction>(*U->user_begin()); 3106 if (!U2 || U2->getOpcode() != OpCode) 3107 return false; 3108 3109 // Check operands of the reduction operation. 3110 if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) || 3111 (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) { 3112 UsersToVisit.push_back(U2); 3113 ElemNumToReduce /= 2; 3114 } else 3115 return false; 3116 } else if (isa<ExtractElementInst>(U)) { 3117 // At this moment we should have reduced all elements in the vector. 3118 if (ElemNumToReduce != 1) 3119 return false; 3120 3121 const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1)); 3122 if (!Val || !Val->isZero()) 3123 return false; 3124 3125 ReduxExtracted = true; 3126 } else 3127 return false; 3128 } 3129 } 3130 return ReduxExtracted; 3131 } 3132 3133 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3134 SDNodeFlags Flags; 3135 3136 SDValue Op = getValue(I.getOperand(0)); 3137 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3138 Op, Flags); 3139 setValue(&I, UnNodeValue); 3140 } 3141 3142 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3143 SDNodeFlags Flags; 3144 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3145 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3146 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3147 } 3148 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) { 3149 Flags.setExact(ExactOp->isExact()); 3150 } 3151 if (isVectorReductionOp(&I)) { 3152 Flags.setVectorReduction(true); 3153 LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n"); 3154 3155 // If no flags are set we will propagate the incoming flags, if any flags 3156 // are set, we will intersect them with the incoming flag and so we need to 3157 // copy the FMF flags here. 3158 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) { 3159 Flags.copyFMF(*FPOp); 3160 } 3161 } 3162 3163 SDValue Op1 = getValue(I.getOperand(0)); 3164 SDValue Op2 = getValue(I.getOperand(1)); 3165 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3166 Op1, Op2, Flags); 3167 setValue(&I, BinNodeValue); 3168 } 3169 3170 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3171 SDValue Op1 = getValue(I.getOperand(0)); 3172 SDValue Op2 = getValue(I.getOperand(1)); 3173 3174 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3175 Op1.getValueType(), DAG.getDataLayout()); 3176 3177 // Coerce the shift amount to the right type if we can. 3178 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3179 unsigned ShiftSize = ShiftTy.getSizeInBits(); 3180 unsigned Op2Size = Op2.getValueSizeInBits(); 3181 SDLoc DL = getCurSDLoc(); 3182 3183 // If the operand is smaller than the shift count type, promote it. 3184 if (ShiftSize > Op2Size) 3185 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 3186 3187 // If the operand is larger than the shift count type but the shift 3188 // count type has enough bits to represent any shift value, truncate 3189 // it now. This is a common case and it exposes the truncate to 3190 // optimization early. 3191 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 3192 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 3193 // Otherwise we'll need to temporarily settle for some other convenient 3194 // type. Type legalization will make adjustments once the shiftee is split. 3195 else 3196 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 3197 } 3198 3199 bool nuw = false; 3200 bool nsw = false; 3201 bool exact = false; 3202 3203 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3204 3205 if (const OverflowingBinaryOperator *OFBinOp = 3206 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3207 nuw = OFBinOp->hasNoUnsignedWrap(); 3208 nsw = OFBinOp->hasNoSignedWrap(); 3209 } 3210 if (const PossiblyExactOperator *ExactOp = 3211 dyn_cast<const PossiblyExactOperator>(&I)) 3212 exact = ExactOp->isExact(); 3213 } 3214 SDNodeFlags Flags; 3215 Flags.setExact(exact); 3216 Flags.setNoSignedWrap(nsw); 3217 Flags.setNoUnsignedWrap(nuw); 3218 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3219 Flags); 3220 setValue(&I, Res); 3221 } 3222 3223 void SelectionDAGBuilder::visitSDiv(const User &I) { 3224 SDValue Op1 = getValue(I.getOperand(0)); 3225 SDValue Op2 = getValue(I.getOperand(1)); 3226 3227 SDNodeFlags Flags; 3228 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3229 cast<PossiblyExactOperator>(&I)->isExact()); 3230 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3231 Op2, Flags)); 3232 } 3233 3234 void SelectionDAGBuilder::visitICmp(const User &I) { 3235 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3236 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3237 predicate = IC->getPredicate(); 3238 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3239 predicate = ICmpInst::Predicate(IC->getPredicate()); 3240 SDValue Op1 = getValue(I.getOperand(0)); 3241 SDValue Op2 = getValue(I.getOperand(1)); 3242 ISD::CondCode Opcode = getICmpCondCode(predicate); 3243 3244 auto &TLI = DAG.getTargetLoweringInfo(); 3245 EVT MemVT = 3246 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3247 3248 // If a pointer's DAG type is larger than its memory type then the DAG values 3249 // are zero-extended. This breaks signed comparisons so truncate back to the 3250 // underlying type before doing the compare. 3251 if (Op1.getValueType() != MemVT) { 3252 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3253 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3254 } 3255 3256 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3257 I.getType()); 3258 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3259 } 3260 3261 void SelectionDAGBuilder::visitFCmp(const User &I) { 3262 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3263 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3264 predicate = FC->getPredicate(); 3265 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3266 predicate = FCmpInst::Predicate(FC->getPredicate()); 3267 SDValue Op1 = getValue(I.getOperand(0)); 3268 SDValue Op2 = getValue(I.getOperand(1)); 3269 3270 ISD::CondCode Condition = getFCmpCondCode(predicate); 3271 auto *FPMO = dyn_cast<FPMathOperator>(&I); 3272 if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath) 3273 Condition = getFCmpCodeWithoutNaN(Condition); 3274 3275 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3276 I.getType()); 3277 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3278 } 3279 3280 // Check if the condition of the select has one use or two users that are both 3281 // selects with the same condition. 3282 static bool hasOnlySelectUsers(const Value *Cond) { 3283 return llvm::all_of(Cond->users(), [](const Value *V) { 3284 return isa<SelectInst>(V); 3285 }); 3286 } 3287 3288 void SelectionDAGBuilder::visitSelect(const User &I) { 3289 SmallVector<EVT, 4> ValueVTs; 3290 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3291 ValueVTs); 3292 unsigned NumValues = ValueVTs.size(); 3293 if (NumValues == 0) return; 3294 3295 SmallVector<SDValue, 4> Values(NumValues); 3296 SDValue Cond = getValue(I.getOperand(0)); 3297 SDValue LHSVal = getValue(I.getOperand(1)); 3298 SDValue RHSVal = getValue(I.getOperand(2)); 3299 auto BaseOps = {Cond}; 3300 ISD::NodeType OpCode = Cond.getValueType().isVector() ? 3301 ISD::VSELECT : ISD::SELECT; 3302 3303 bool IsUnaryAbs = false; 3304 3305 // Min/max matching is only viable if all output VTs are the same. 3306 if (is_splat(ValueVTs)) { 3307 EVT VT = ValueVTs[0]; 3308 LLVMContext &Ctx = *DAG.getContext(); 3309 auto &TLI = DAG.getTargetLoweringInfo(); 3310 3311 // We care about the legality of the operation after it has been type 3312 // legalized. 3313 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3314 VT = TLI.getTypeToTransformTo(Ctx, VT); 3315 3316 // If the vselect is legal, assume we want to leave this as a vector setcc + 3317 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3318 // min/max is legal on the scalar type. 3319 bool UseScalarMinMax = VT.isVector() && 3320 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3321 3322 Value *LHS, *RHS; 3323 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3324 ISD::NodeType Opc = ISD::DELETED_NODE; 3325 switch (SPR.Flavor) { 3326 case SPF_UMAX: Opc = ISD::UMAX; break; 3327 case SPF_UMIN: Opc = ISD::UMIN; break; 3328 case SPF_SMAX: Opc = ISD::SMAX; break; 3329 case SPF_SMIN: Opc = ISD::SMIN; break; 3330 case SPF_FMINNUM: 3331 switch (SPR.NaNBehavior) { 3332 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3333 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3334 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3335 case SPNB_RETURNS_ANY: { 3336 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3337 Opc = ISD::FMINNUM; 3338 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3339 Opc = ISD::FMINIMUM; 3340 else if (UseScalarMinMax) 3341 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3342 ISD::FMINNUM : ISD::FMINIMUM; 3343 break; 3344 } 3345 } 3346 break; 3347 case SPF_FMAXNUM: 3348 switch (SPR.NaNBehavior) { 3349 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3350 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3351 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3352 case SPNB_RETURNS_ANY: 3353 3354 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3355 Opc = ISD::FMAXNUM; 3356 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3357 Opc = ISD::FMAXIMUM; 3358 else if (UseScalarMinMax) 3359 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3360 ISD::FMAXNUM : ISD::FMAXIMUM; 3361 break; 3362 } 3363 break; 3364 case SPF_ABS: 3365 IsUnaryAbs = true; 3366 Opc = ISD::ABS; 3367 break; 3368 case SPF_NABS: 3369 // TODO: we need to produce sub(0, abs(X)). 3370 default: break; 3371 } 3372 3373 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3374 (TLI.isOperationLegalOrCustom(Opc, VT) || 3375 (UseScalarMinMax && 3376 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3377 // If the underlying comparison instruction is used by any other 3378 // instruction, the consumed instructions won't be destroyed, so it is 3379 // not profitable to convert to a min/max. 3380 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3381 OpCode = Opc; 3382 LHSVal = getValue(LHS); 3383 RHSVal = getValue(RHS); 3384 BaseOps = {}; 3385 } 3386 3387 if (IsUnaryAbs) { 3388 OpCode = Opc; 3389 LHSVal = getValue(LHS); 3390 BaseOps = {}; 3391 } 3392 } 3393 3394 if (IsUnaryAbs) { 3395 for (unsigned i = 0; i != NumValues; ++i) { 3396 Values[i] = 3397 DAG.getNode(OpCode, getCurSDLoc(), 3398 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), 3399 SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3400 } 3401 } else { 3402 for (unsigned i = 0; i != NumValues; ++i) { 3403 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3404 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3405 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3406 Values[i] = DAG.getNode( 3407 OpCode, getCurSDLoc(), 3408 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops); 3409 } 3410 } 3411 3412 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3413 DAG.getVTList(ValueVTs), Values)); 3414 } 3415 3416 void SelectionDAGBuilder::visitTrunc(const User &I) { 3417 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3418 SDValue N = getValue(I.getOperand(0)); 3419 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3420 I.getType()); 3421 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3422 } 3423 3424 void SelectionDAGBuilder::visitZExt(const User &I) { 3425 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3426 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3427 SDValue N = getValue(I.getOperand(0)); 3428 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3429 I.getType()); 3430 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3431 } 3432 3433 void SelectionDAGBuilder::visitSExt(const User &I) { 3434 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3435 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3436 SDValue N = getValue(I.getOperand(0)); 3437 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3438 I.getType()); 3439 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3440 } 3441 3442 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3443 // FPTrunc is never a no-op cast, no need to check 3444 SDValue N = getValue(I.getOperand(0)); 3445 SDLoc dl = getCurSDLoc(); 3446 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3447 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3448 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3449 DAG.getTargetConstant( 3450 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3451 } 3452 3453 void SelectionDAGBuilder::visitFPExt(const User &I) { 3454 // FPExt is never a no-op cast, no need to check 3455 SDValue N = getValue(I.getOperand(0)); 3456 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3457 I.getType()); 3458 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3459 } 3460 3461 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3462 // FPToUI is never a no-op cast, no need to check 3463 SDValue N = getValue(I.getOperand(0)); 3464 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3465 I.getType()); 3466 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3467 } 3468 3469 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3470 // FPToSI is never a no-op cast, no need to check 3471 SDValue N = getValue(I.getOperand(0)); 3472 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3473 I.getType()); 3474 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3475 } 3476 3477 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3478 // UIToFP is never a no-op cast, no need to check 3479 SDValue N = getValue(I.getOperand(0)); 3480 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3481 I.getType()); 3482 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3483 } 3484 3485 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3486 // SIToFP is never a no-op cast, no need to check 3487 SDValue N = getValue(I.getOperand(0)); 3488 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3489 I.getType()); 3490 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3491 } 3492 3493 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3494 // What to do depends on the size of the integer and the size of the pointer. 3495 // We can either truncate, zero extend, or no-op, accordingly. 3496 SDValue N = getValue(I.getOperand(0)); 3497 auto &TLI = DAG.getTargetLoweringInfo(); 3498 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3499 I.getType()); 3500 EVT PtrMemVT = 3501 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3502 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3503 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3504 setValue(&I, N); 3505 } 3506 3507 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3508 // What to do depends on the size of the integer and the size of the pointer. 3509 // We can either truncate, zero extend, or no-op, accordingly. 3510 SDValue N = getValue(I.getOperand(0)); 3511 auto &TLI = DAG.getTargetLoweringInfo(); 3512 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3513 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3514 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3515 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3516 setValue(&I, N); 3517 } 3518 3519 void SelectionDAGBuilder::visitBitCast(const User &I) { 3520 SDValue N = getValue(I.getOperand(0)); 3521 SDLoc dl = getCurSDLoc(); 3522 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3523 I.getType()); 3524 3525 // BitCast assures us that source and destination are the same size so this is 3526 // either a BITCAST or a no-op. 3527 if (DestVT != N.getValueType()) 3528 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3529 DestVT, N)); // convert types. 3530 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3531 // might fold any kind of constant expression to an integer constant and that 3532 // is not what we are looking for. Only recognize a bitcast of a genuine 3533 // constant integer as an opaque constant. 3534 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3535 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3536 /*isOpaque*/true)); 3537 else 3538 setValue(&I, N); // noop cast. 3539 } 3540 3541 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3542 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3543 const Value *SV = I.getOperand(0); 3544 SDValue N = getValue(SV); 3545 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3546 3547 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3548 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3549 3550 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) 3551 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3552 3553 setValue(&I, N); 3554 } 3555 3556 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3557 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3558 SDValue InVec = getValue(I.getOperand(0)); 3559 SDValue InVal = getValue(I.getOperand(1)); 3560 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3561 TLI.getVectorIdxTy(DAG.getDataLayout())); 3562 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3563 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3564 InVec, InVal, InIdx)); 3565 } 3566 3567 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3568 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3569 SDValue InVec = getValue(I.getOperand(0)); 3570 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3571 TLI.getVectorIdxTy(DAG.getDataLayout())); 3572 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3573 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3574 InVec, InIdx)); 3575 } 3576 3577 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3578 SDValue Src1 = getValue(I.getOperand(0)); 3579 SDValue Src2 = getValue(I.getOperand(1)); 3580 Constant *MaskV = cast<Constant>(I.getOperand(2)); 3581 SDLoc DL = getCurSDLoc(); 3582 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3583 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3584 EVT SrcVT = Src1.getValueType(); 3585 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3586 3587 if (MaskV->isNullValue() && VT.isScalableVector()) { 3588 // Canonical splat form of first element of first input vector. 3589 SDValue FirstElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 3590 SrcVT.getScalarType(), Src1, 3591 DAG.getConstant(0, DL, 3592 TLI.getVectorIdxTy(DAG.getDataLayout()))); 3593 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3594 return; 3595 } 3596 3597 // For now, we only handle splats for scalable vectors. 3598 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3599 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3600 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3601 3602 SmallVector<int, 8> Mask; 3603 ShuffleVectorInst::getShuffleMask(MaskV, Mask); 3604 unsigned MaskNumElts = Mask.size(); 3605 3606 if (SrcNumElts == MaskNumElts) { 3607 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3608 return; 3609 } 3610 3611 // Normalize the shuffle vector since mask and vector length don't match. 3612 if (SrcNumElts < MaskNumElts) { 3613 // Mask is longer than the source vectors. We can use concatenate vector to 3614 // make the mask and vectors lengths match. 3615 3616 if (MaskNumElts % SrcNumElts == 0) { 3617 // Mask length is a multiple of the source vector length. 3618 // Check if the shuffle is some kind of concatenation of the input 3619 // vectors. 3620 unsigned NumConcat = MaskNumElts / SrcNumElts; 3621 bool IsConcat = true; 3622 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3623 for (unsigned i = 0; i != MaskNumElts; ++i) { 3624 int Idx = Mask[i]; 3625 if (Idx < 0) 3626 continue; 3627 // Ensure the indices in each SrcVT sized piece are sequential and that 3628 // the same source is used for the whole piece. 3629 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3630 (ConcatSrcs[i / SrcNumElts] >= 0 && 3631 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3632 IsConcat = false; 3633 break; 3634 } 3635 // Remember which source this index came from. 3636 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3637 } 3638 3639 // The shuffle is concatenating multiple vectors together. Just emit 3640 // a CONCAT_VECTORS operation. 3641 if (IsConcat) { 3642 SmallVector<SDValue, 8> ConcatOps; 3643 for (auto Src : ConcatSrcs) { 3644 if (Src < 0) 3645 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3646 else if (Src == 0) 3647 ConcatOps.push_back(Src1); 3648 else 3649 ConcatOps.push_back(Src2); 3650 } 3651 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3652 return; 3653 } 3654 } 3655 3656 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3657 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3658 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3659 PaddedMaskNumElts); 3660 3661 // Pad both vectors with undefs to make them the same length as the mask. 3662 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3663 3664 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3665 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3666 MOps1[0] = Src1; 3667 MOps2[0] = Src2; 3668 3669 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3670 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3671 3672 // Readjust mask for new input vector length. 3673 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3674 for (unsigned i = 0; i != MaskNumElts; ++i) { 3675 int Idx = Mask[i]; 3676 if (Idx >= (int)SrcNumElts) 3677 Idx -= SrcNumElts - PaddedMaskNumElts; 3678 MappedOps[i] = Idx; 3679 } 3680 3681 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3682 3683 // If the concatenated vector was padded, extract a subvector with the 3684 // correct number of elements. 3685 if (MaskNumElts != PaddedMaskNumElts) 3686 Result = DAG.getNode( 3687 ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3688 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 3689 3690 setValue(&I, Result); 3691 return; 3692 } 3693 3694 if (SrcNumElts > MaskNumElts) { 3695 // Analyze the access pattern of the vector to see if we can extract 3696 // two subvectors and do the shuffle. 3697 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3698 bool CanExtract = true; 3699 for (int Idx : Mask) { 3700 unsigned Input = 0; 3701 if (Idx < 0) 3702 continue; 3703 3704 if (Idx >= (int)SrcNumElts) { 3705 Input = 1; 3706 Idx -= SrcNumElts; 3707 } 3708 3709 // If all the indices come from the same MaskNumElts sized portion of 3710 // the sources we can use extract. Also make sure the extract wouldn't 3711 // extract past the end of the source. 3712 int NewStartIdx = alignDown(Idx, MaskNumElts); 3713 if (NewStartIdx + MaskNumElts > SrcNumElts || 3714 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3715 CanExtract = false; 3716 // Make sure we always update StartIdx as we use it to track if all 3717 // elements are undef. 3718 StartIdx[Input] = NewStartIdx; 3719 } 3720 3721 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3722 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3723 return; 3724 } 3725 if (CanExtract) { 3726 // Extract appropriate subvector and generate a vector shuffle 3727 for (unsigned Input = 0; Input < 2; ++Input) { 3728 SDValue &Src = Input == 0 ? Src1 : Src2; 3729 if (StartIdx[Input] < 0) 3730 Src = DAG.getUNDEF(VT); 3731 else { 3732 Src = DAG.getNode( 3733 ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3734 DAG.getConstant(StartIdx[Input], DL, 3735 TLI.getVectorIdxTy(DAG.getDataLayout()))); 3736 } 3737 } 3738 3739 // Calculate new mask. 3740 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3741 for (int &Idx : MappedOps) { 3742 if (Idx >= (int)SrcNumElts) 3743 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3744 else if (Idx >= 0) 3745 Idx -= StartIdx[0]; 3746 } 3747 3748 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3749 return; 3750 } 3751 } 3752 3753 // We can't use either concat vectors or extract subvectors so fall back to 3754 // replacing the shuffle with extract and build vector. 3755 // to insert and build vector. 3756 EVT EltVT = VT.getVectorElementType(); 3757 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 3758 SmallVector<SDValue,8> Ops; 3759 for (int Idx : Mask) { 3760 SDValue Res; 3761 3762 if (Idx < 0) { 3763 Res = DAG.getUNDEF(EltVT); 3764 } else { 3765 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3766 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3767 3768 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 3769 EltVT, Src, DAG.getConstant(Idx, DL, IdxVT)); 3770 } 3771 3772 Ops.push_back(Res); 3773 } 3774 3775 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3776 } 3777 3778 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3779 ArrayRef<unsigned> Indices; 3780 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3781 Indices = IV->getIndices(); 3782 else 3783 Indices = cast<ConstantExpr>(&I)->getIndices(); 3784 3785 const Value *Op0 = I.getOperand(0); 3786 const Value *Op1 = I.getOperand(1); 3787 Type *AggTy = I.getType(); 3788 Type *ValTy = Op1->getType(); 3789 bool IntoUndef = isa<UndefValue>(Op0); 3790 bool FromUndef = isa<UndefValue>(Op1); 3791 3792 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3793 3794 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3795 SmallVector<EVT, 4> AggValueVTs; 3796 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3797 SmallVector<EVT, 4> ValValueVTs; 3798 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3799 3800 unsigned NumAggValues = AggValueVTs.size(); 3801 unsigned NumValValues = ValValueVTs.size(); 3802 SmallVector<SDValue, 4> Values(NumAggValues); 3803 3804 // Ignore an insertvalue that produces an empty object 3805 if (!NumAggValues) { 3806 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3807 return; 3808 } 3809 3810 SDValue Agg = getValue(Op0); 3811 unsigned i = 0; 3812 // Copy the beginning value(s) from the original aggregate. 3813 for (; i != LinearIndex; ++i) 3814 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3815 SDValue(Agg.getNode(), Agg.getResNo() + i); 3816 // Copy values from the inserted value(s). 3817 if (NumValValues) { 3818 SDValue Val = getValue(Op1); 3819 for (; i != LinearIndex + NumValValues; ++i) 3820 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3821 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3822 } 3823 // Copy remaining value(s) from the original aggregate. 3824 for (; i != NumAggValues; ++i) 3825 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3826 SDValue(Agg.getNode(), Agg.getResNo() + i); 3827 3828 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3829 DAG.getVTList(AggValueVTs), Values)); 3830 } 3831 3832 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3833 ArrayRef<unsigned> Indices; 3834 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3835 Indices = EV->getIndices(); 3836 else 3837 Indices = cast<ConstantExpr>(&I)->getIndices(); 3838 3839 const Value *Op0 = I.getOperand(0); 3840 Type *AggTy = Op0->getType(); 3841 Type *ValTy = I.getType(); 3842 bool OutOfUndef = isa<UndefValue>(Op0); 3843 3844 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3845 3846 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3847 SmallVector<EVT, 4> ValValueVTs; 3848 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3849 3850 unsigned NumValValues = ValValueVTs.size(); 3851 3852 // Ignore a extractvalue that produces an empty object 3853 if (!NumValValues) { 3854 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3855 return; 3856 } 3857 3858 SmallVector<SDValue, 4> Values(NumValValues); 3859 3860 SDValue Agg = getValue(Op0); 3861 // Copy out the selected value(s). 3862 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3863 Values[i - LinearIndex] = 3864 OutOfUndef ? 3865 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3866 SDValue(Agg.getNode(), Agg.getResNo() + i); 3867 3868 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3869 DAG.getVTList(ValValueVTs), Values)); 3870 } 3871 3872 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3873 Value *Op0 = I.getOperand(0); 3874 // Note that the pointer operand may be a vector of pointers. Take the scalar 3875 // element which holds a pointer. 3876 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3877 SDValue N = getValue(Op0); 3878 SDLoc dl = getCurSDLoc(); 3879 auto &TLI = DAG.getTargetLoweringInfo(); 3880 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 3881 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 3882 3883 // Normalize Vector GEP - all scalar operands should be converted to the 3884 // splat vector. 3885 unsigned VectorWidth = I.getType()->isVectorTy() ? 3886 I.getType()->getVectorNumElements() : 0; 3887 3888 if (VectorWidth && !N.getValueType().isVector()) { 3889 LLVMContext &Context = *DAG.getContext(); 3890 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth); 3891 N = DAG.getSplatBuildVector(VT, dl, N); 3892 } 3893 3894 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3895 GTI != E; ++GTI) { 3896 const Value *Idx = GTI.getOperand(); 3897 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3898 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3899 if (Field) { 3900 // N = N + Offset 3901 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3902 3903 // In an inbounds GEP with an offset that is nonnegative even when 3904 // interpreted as signed, assume there is no unsigned overflow. 3905 SDNodeFlags Flags; 3906 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3907 Flags.setNoUnsignedWrap(true); 3908 3909 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3910 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3911 } 3912 } else { 3913 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3914 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3915 APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType())); 3916 3917 // If this is a scalar constant or a splat vector of constants, 3918 // handle it quickly. 3919 const auto *C = dyn_cast<Constant>(Idx); 3920 if (C && isa<VectorType>(C->getType())) 3921 C = C->getSplatValue(); 3922 3923 if (const auto *CI = dyn_cast_or_null<ConstantInt>(C)) { 3924 if (CI->isZero()) 3925 continue; 3926 APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize); 3927 LLVMContext &Context = *DAG.getContext(); 3928 SDValue OffsVal = VectorWidth ? 3929 DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) : 3930 DAG.getConstant(Offs, dl, IdxTy); 3931 3932 // In an inbounds GEP with an offset that is nonnegative even when 3933 // interpreted as signed, assume there is no unsigned overflow. 3934 SDNodeFlags Flags; 3935 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3936 Flags.setNoUnsignedWrap(true); 3937 3938 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3939 3940 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3941 continue; 3942 } 3943 3944 // N = N + Idx * ElementSize; 3945 SDValue IdxN = getValue(Idx); 3946 3947 if (!IdxN.getValueType().isVector() && VectorWidth) { 3948 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth); 3949 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3950 } 3951 3952 // If the index is smaller or larger than intptr_t, truncate or extend 3953 // it. 3954 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3955 3956 // If this is a multiply by a power of two, turn it into a shl 3957 // immediately. This is a very common case. 3958 if (ElementSize != 1) { 3959 if (ElementSize.isPowerOf2()) { 3960 unsigned Amt = ElementSize.logBase2(); 3961 IdxN = DAG.getNode(ISD::SHL, dl, 3962 N.getValueType(), IdxN, 3963 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3964 } else { 3965 SDValue Scale = DAG.getConstant(ElementSize.getZExtValue(), dl, 3966 IdxN.getValueType()); 3967 IdxN = DAG.getNode(ISD::MUL, dl, 3968 N.getValueType(), IdxN, Scale); 3969 } 3970 } 3971 3972 N = DAG.getNode(ISD::ADD, dl, 3973 N.getValueType(), N, IdxN); 3974 } 3975 } 3976 3977 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 3978 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 3979 3980 setValue(&I, N); 3981 } 3982 3983 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3984 // If this is a fixed sized alloca in the entry block of the function, 3985 // allocate it statically on the stack. 3986 if (FuncInfo.StaticAllocaMap.count(&I)) 3987 return; // getValue will auto-populate this. 3988 3989 SDLoc dl = getCurSDLoc(); 3990 Type *Ty = I.getAllocatedType(); 3991 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3992 auto &DL = DAG.getDataLayout(); 3993 uint64_t TySize = DL.getTypeAllocSize(Ty); 3994 unsigned Align = 3995 std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment()); 3996 3997 SDValue AllocSize = getValue(I.getArraySize()); 3998 3999 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 4000 if (AllocSize.getValueType() != IntPtr) 4001 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 4002 4003 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 4004 AllocSize, 4005 DAG.getConstant(TySize, dl, IntPtr)); 4006 4007 // Handle alignment. If the requested alignment is less than or equal to 4008 // the stack alignment, ignore it. If the size is greater than or equal to 4009 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4010 unsigned StackAlign = 4011 DAG.getSubtarget().getFrameLowering()->getStackAlignment(); 4012 if (Align <= StackAlign) 4013 Align = 0; 4014 4015 // Round the size of the allocation up to the stack alignment size 4016 // by add SA-1 to the size. This doesn't overflow because we're computing 4017 // an address inside an alloca. 4018 SDNodeFlags Flags; 4019 Flags.setNoUnsignedWrap(true); 4020 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4021 DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags); 4022 4023 // Mask out the low bits for alignment purposes. 4024 AllocSize = 4025 DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4026 DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr)); 4027 4028 SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)}; 4029 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4030 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4031 setValue(&I, DSA); 4032 DAG.setRoot(DSA.getValue(1)); 4033 4034 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4035 } 4036 4037 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4038 if (I.isAtomic()) 4039 return visitAtomicLoad(I); 4040 4041 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4042 const Value *SV = I.getOperand(0); 4043 if (TLI.supportSwiftError()) { 4044 // Swifterror values can come from either a function parameter with 4045 // swifterror attribute or an alloca with swifterror attribute. 4046 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4047 if (Arg->hasSwiftErrorAttr()) 4048 return visitLoadFromSwiftError(I); 4049 } 4050 4051 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4052 if (Alloca->isSwiftError()) 4053 return visitLoadFromSwiftError(I); 4054 } 4055 } 4056 4057 SDValue Ptr = getValue(SV); 4058 4059 Type *Ty = I.getType(); 4060 unsigned Alignment = I.getAlignment(); 4061 4062 AAMDNodes AAInfo; 4063 I.getAAMetadata(AAInfo); 4064 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4065 4066 SmallVector<EVT, 4> ValueVTs, MemVTs; 4067 SmallVector<uint64_t, 4> Offsets; 4068 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4069 unsigned NumValues = ValueVTs.size(); 4070 if (NumValues == 0) 4071 return; 4072 4073 bool isVolatile = I.isVolatile(); 4074 4075 SDValue Root; 4076 bool ConstantMemory = false; 4077 if (isVolatile) 4078 // Serialize volatile loads with other side effects. 4079 Root = getRoot(); 4080 else if (NumValues > MaxParallelChains) 4081 Root = getMemoryRoot(); 4082 else if (AA && 4083 AA->pointsToConstantMemory(MemoryLocation( 4084 SV, 4085 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4086 AAInfo))) { 4087 // Do not serialize (non-volatile) loads of constant memory with anything. 4088 Root = DAG.getEntryNode(); 4089 ConstantMemory = true; 4090 } else { 4091 // Do not serialize non-volatile loads against each other. 4092 Root = DAG.getRoot(); 4093 } 4094 4095 SDLoc dl = getCurSDLoc(); 4096 4097 if (isVolatile) 4098 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4099 4100 // An aggregate load cannot wrap around the address space, so offsets to its 4101 // parts don't wrap either. 4102 SDNodeFlags Flags; 4103 Flags.setNoUnsignedWrap(true); 4104 4105 SmallVector<SDValue, 4> Values(NumValues); 4106 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4107 EVT PtrVT = Ptr.getValueType(); 4108 4109 MachineMemOperand::Flags MMOFlags 4110 = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4111 4112 unsigned ChainI = 0; 4113 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4114 // Serializing loads here may result in excessive register pressure, and 4115 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4116 // could recover a bit by hoisting nodes upward in the chain by recognizing 4117 // they are side-effect free or do not alias. The optimizer should really 4118 // avoid this case by converting large object/array copies to llvm.memcpy 4119 // (MaxParallelChains should always remain as failsafe). 4120 if (ChainI == MaxParallelChains) { 4121 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4122 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4123 makeArrayRef(Chains.data(), ChainI)); 4124 Root = Chain; 4125 ChainI = 0; 4126 } 4127 SDValue A = DAG.getNode(ISD::ADD, dl, 4128 PtrVT, Ptr, 4129 DAG.getConstant(Offsets[i], dl, PtrVT), 4130 Flags); 4131 4132 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4133 MachinePointerInfo(SV, Offsets[i]), Alignment, 4134 MMOFlags, AAInfo, Ranges); 4135 Chains[ChainI] = L.getValue(1); 4136 4137 if (MemVTs[i] != ValueVTs[i]) 4138 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4139 4140 Values[i] = L; 4141 } 4142 4143 if (!ConstantMemory) { 4144 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4145 makeArrayRef(Chains.data(), ChainI)); 4146 if (isVolatile) 4147 DAG.setRoot(Chain); 4148 else 4149 PendingLoads.push_back(Chain); 4150 } 4151 4152 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4153 DAG.getVTList(ValueVTs), Values)); 4154 } 4155 4156 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4157 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4158 "call visitStoreToSwiftError when backend supports swifterror"); 4159 4160 SmallVector<EVT, 4> ValueVTs; 4161 SmallVector<uint64_t, 4> Offsets; 4162 const Value *SrcV = I.getOperand(0); 4163 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4164 SrcV->getType(), ValueVTs, &Offsets); 4165 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4166 "expect a single EVT for swifterror"); 4167 4168 SDValue Src = getValue(SrcV); 4169 // Create a virtual register, then update the virtual register. 4170 Register VReg = 4171 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4172 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4173 // Chain can be getRoot or getControlRoot. 4174 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4175 SDValue(Src.getNode(), Src.getResNo())); 4176 DAG.setRoot(CopyNode); 4177 } 4178 4179 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4180 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4181 "call visitLoadFromSwiftError when backend supports swifterror"); 4182 4183 assert(!I.isVolatile() && 4184 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4185 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4186 "Support volatile, non temporal, invariant for load_from_swift_error"); 4187 4188 const Value *SV = I.getOperand(0); 4189 Type *Ty = I.getType(); 4190 AAMDNodes AAInfo; 4191 I.getAAMetadata(AAInfo); 4192 assert( 4193 (!AA || 4194 !AA->pointsToConstantMemory(MemoryLocation( 4195 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4196 AAInfo))) && 4197 "load_from_swift_error should not be constant memory"); 4198 4199 SmallVector<EVT, 4> ValueVTs; 4200 SmallVector<uint64_t, 4> Offsets; 4201 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4202 ValueVTs, &Offsets); 4203 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4204 "expect a single EVT for swifterror"); 4205 4206 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4207 SDValue L = DAG.getCopyFromReg( 4208 getRoot(), getCurSDLoc(), 4209 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4210 4211 setValue(&I, L); 4212 } 4213 4214 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4215 if (I.isAtomic()) 4216 return visitAtomicStore(I); 4217 4218 const Value *SrcV = I.getOperand(0); 4219 const Value *PtrV = I.getOperand(1); 4220 4221 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4222 if (TLI.supportSwiftError()) { 4223 // Swifterror values can come from either a function parameter with 4224 // swifterror attribute or an alloca with swifterror attribute. 4225 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4226 if (Arg->hasSwiftErrorAttr()) 4227 return visitStoreToSwiftError(I); 4228 } 4229 4230 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4231 if (Alloca->isSwiftError()) 4232 return visitStoreToSwiftError(I); 4233 } 4234 } 4235 4236 SmallVector<EVT, 4> ValueVTs, MemVTs; 4237 SmallVector<uint64_t, 4> Offsets; 4238 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4239 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4240 unsigned NumValues = ValueVTs.size(); 4241 if (NumValues == 0) 4242 return; 4243 4244 // Get the lowered operands. Note that we do this after 4245 // checking if NumResults is zero, because with zero results 4246 // the operands won't have values in the map. 4247 SDValue Src = getValue(SrcV); 4248 SDValue Ptr = getValue(PtrV); 4249 4250 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4251 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4252 SDLoc dl = getCurSDLoc(); 4253 unsigned Alignment = I.getAlignment(); 4254 AAMDNodes AAInfo; 4255 I.getAAMetadata(AAInfo); 4256 4257 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4258 4259 // An aggregate load cannot wrap around the address space, so offsets to its 4260 // parts don't wrap either. 4261 SDNodeFlags Flags; 4262 Flags.setNoUnsignedWrap(true); 4263 4264 unsigned ChainI = 0; 4265 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4266 // See visitLoad comments. 4267 if (ChainI == MaxParallelChains) { 4268 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4269 makeArrayRef(Chains.data(), ChainI)); 4270 Root = Chain; 4271 ChainI = 0; 4272 } 4273 SDValue Add = DAG.getMemBasePlusOffset(Ptr, Offsets[i], dl, Flags); 4274 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4275 if (MemVTs[i] != ValueVTs[i]) 4276 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4277 SDValue St = 4278 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4279 Alignment, MMOFlags, AAInfo); 4280 Chains[ChainI] = St; 4281 } 4282 4283 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4284 makeArrayRef(Chains.data(), ChainI)); 4285 DAG.setRoot(StoreNode); 4286 } 4287 4288 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4289 bool IsCompressing) { 4290 SDLoc sdl = getCurSDLoc(); 4291 4292 auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4293 unsigned& Alignment) { 4294 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4295 Src0 = I.getArgOperand(0); 4296 Ptr = I.getArgOperand(1); 4297 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 4298 Mask = I.getArgOperand(3); 4299 }; 4300 auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4301 unsigned& Alignment) { 4302 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4303 Src0 = I.getArgOperand(0); 4304 Ptr = I.getArgOperand(1); 4305 Mask = I.getArgOperand(2); 4306 Alignment = 0; 4307 }; 4308 4309 Value *PtrOperand, *MaskOperand, *Src0Operand; 4310 unsigned Alignment; 4311 if (IsCompressing) 4312 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4313 else 4314 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4315 4316 SDValue Ptr = getValue(PtrOperand); 4317 SDValue Src0 = getValue(Src0Operand); 4318 SDValue Mask = getValue(MaskOperand); 4319 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4320 4321 EVT VT = Src0.getValueType(); 4322 if (!Alignment) 4323 Alignment = DAG.getEVTAlignment(VT); 4324 4325 AAMDNodes AAInfo; 4326 I.getAAMetadata(AAInfo); 4327 4328 MachineMemOperand *MMO = 4329 DAG.getMachineFunction(). 4330 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4331 MachineMemOperand::MOStore, 4332 // TODO: Make MachineMemOperands aware of scalable 4333 // vectors. 4334 VT.getStoreSize().getKnownMinSize(), 4335 Alignment, AAInfo); 4336 SDValue StoreNode = 4337 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4338 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4339 DAG.setRoot(StoreNode); 4340 setValue(&I, StoreNode); 4341 } 4342 4343 // Get a uniform base for the Gather/Scatter intrinsic. 4344 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4345 // We try to represent it as a base pointer + vector of indices. 4346 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4347 // The first operand of the GEP may be a single pointer or a vector of pointers 4348 // Example: 4349 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4350 // or 4351 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4352 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4353 // 4354 // When the first GEP operand is a single pointer - it is the uniform base we 4355 // are looking for. If first operand of the GEP is a splat vector - we 4356 // extract the splat value and use it as a uniform base. 4357 // In all other cases the function returns 'false'. 4358 static bool getUniformBase(const Value *&Ptr, SDValue &Base, SDValue &Index, 4359 ISD::MemIndexType &IndexType, SDValue &Scale, 4360 SelectionDAGBuilder *SDB) { 4361 SelectionDAG& DAG = SDB->DAG; 4362 LLVMContext &Context = *DAG.getContext(); 4363 4364 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 4365 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4366 if (!GEP) 4367 return false; 4368 4369 const Value *GEPPtr = GEP->getPointerOperand(); 4370 if (!GEPPtr->getType()->isVectorTy()) 4371 Ptr = GEPPtr; 4372 else if (!(Ptr = getSplatValue(GEPPtr))) 4373 return false; 4374 4375 unsigned FinalIndex = GEP->getNumOperands() - 1; 4376 Value *IndexVal = GEP->getOperand(FinalIndex); 4377 gep_type_iterator GTI = gep_type_begin(*GEP); 4378 4379 // Ensure all the other indices are 0. 4380 for (unsigned i = 1; i < FinalIndex; ++i, ++GTI) { 4381 auto *C = dyn_cast<Constant>(GEP->getOperand(i)); 4382 if (!C) 4383 return false; 4384 if (isa<VectorType>(C->getType())) 4385 C = C->getSplatValue(); 4386 auto *CI = dyn_cast_or_null<ConstantInt>(C); 4387 if (!CI || !CI->isZero()) 4388 return false; 4389 } 4390 4391 // The operands of the GEP may be defined in another basic block. 4392 // In this case we'll not find nodes for the operands. 4393 if (!SDB->findValue(Ptr)) 4394 return false; 4395 Constant *C = dyn_cast<Constant>(IndexVal); 4396 if (!C && !SDB->findValue(IndexVal)) 4397 return false; 4398 4399 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4400 const DataLayout &DL = DAG.getDataLayout(); 4401 StructType *STy = GTI.getStructTypeOrNull(); 4402 4403 if (STy) { 4404 const StructLayout *SL = DL.getStructLayout(STy); 4405 if (isa<VectorType>(C->getType())) { 4406 C = C->getSplatValue(); 4407 // FIXME: If getSplatValue may return nullptr for a structure? 4408 // If not, the following check can be removed. 4409 if (!C) 4410 return false; 4411 } 4412 auto *CI = cast<ConstantInt>(C); 4413 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4414 Index = DAG.getConstant(SL->getElementOffset(CI->getZExtValue()), 4415 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4416 } else { 4417 Scale = DAG.getTargetConstant( 4418 DL.getTypeAllocSize(GEP->getResultElementType()), 4419 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4420 Index = SDB->getValue(IndexVal); 4421 } 4422 Base = SDB->getValue(Ptr); 4423 IndexType = ISD::SIGNED_SCALED; 4424 4425 if (STy || !Index.getValueType().isVector()) { 4426 unsigned GEPWidth = GEP->getType()->getVectorNumElements(); 4427 EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth); 4428 Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index); 4429 } 4430 return true; 4431 } 4432 4433 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4434 SDLoc sdl = getCurSDLoc(); 4435 4436 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4437 const Value *Ptr = I.getArgOperand(1); 4438 SDValue Src0 = getValue(I.getArgOperand(0)); 4439 SDValue Mask = getValue(I.getArgOperand(3)); 4440 EVT VT = Src0.getValueType(); 4441 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue(); 4442 if (!Alignment) 4443 Alignment = DAG.getEVTAlignment(VT); 4444 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4445 4446 AAMDNodes AAInfo; 4447 I.getAAMetadata(AAInfo); 4448 4449 SDValue Base; 4450 SDValue Index; 4451 ISD::MemIndexType IndexType; 4452 SDValue Scale; 4453 const Value *BasePtr = Ptr; 4454 bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale, 4455 this); 4456 4457 const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr; 4458 MachineMemOperand *MMO = DAG.getMachineFunction(). 4459 getMachineMemOperand(MachinePointerInfo(MemOpBasePtr), 4460 MachineMemOperand::MOStore, 4461 // TODO: Make MachineMemOperands aware of scalable 4462 // vectors. 4463 VT.getStoreSize().getKnownMinSize(), 4464 Alignment, AAInfo); 4465 if (!UniformBase) { 4466 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4467 Index = getValue(Ptr); 4468 IndexType = ISD::SIGNED_SCALED; 4469 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4470 } 4471 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4472 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4473 Ops, MMO, IndexType); 4474 DAG.setRoot(Scatter); 4475 setValue(&I, Scatter); 4476 } 4477 4478 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4479 SDLoc sdl = getCurSDLoc(); 4480 4481 auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4482 unsigned& Alignment) { 4483 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4484 Ptr = I.getArgOperand(0); 4485 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 4486 Mask = I.getArgOperand(2); 4487 Src0 = I.getArgOperand(3); 4488 }; 4489 auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4490 unsigned& Alignment) { 4491 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4492 Ptr = I.getArgOperand(0); 4493 Alignment = 0; 4494 Mask = I.getArgOperand(1); 4495 Src0 = I.getArgOperand(2); 4496 }; 4497 4498 Value *PtrOperand, *MaskOperand, *Src0Operand; 4499 unsigned Alignment; 4500 if (IsExpanding) 4501 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4502 else 4503 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4504 4505 SDValue Ptr = getValue(PtrOperand); 4506 SDValue Src0 = getValue(Src0Operand); 4507 SDValue Mask = getValue(MaskOperand); 4508 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4509 4510 EVT VT = Src0.getValueType(); 4511 if (!Alignment) 4512 Alignment = DAG.getEVTAlignment(VT); 4513 4514 AAMDNodes AAInfo; 4515 I.getAAMetadata(AAInfo); 4516 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4517 4518 // Do not serialize masked loads of constant memory with anything. 4519 MemoryLocation ML; 4520 if (VT.isScalableVector()) 4521 ML = MemoryLocation(PtrOperand); 4522 else 4523 ML = MemoryLocation(PtrOperand, LocationSize::precise( 4524 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4525 AAInfo); 4526 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4527 4528 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4529 4530 MachineMemOperand *MMO = 4531 DAG.getMachineFunction(). 4532 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4533 MachineMemOperand::MOLoad, 4534 // TODO: Make MachineMemOperands aware of scalable 4535 // vectors. 4536 VT.getStoreSize().getKnownMinSize(), 4537 Alignment, AAInfo, Ranges); 4538 4539 SDValue Load = 4540 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4541 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4542 if (AddToChain) 4543 PendingLoads.push_back(Load.getValue(1)); 4544 setValue(&I, Load); 4545 } 4546 4547 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4548 SDLoc sdl = getCurSDLoc(); 4549 4550 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4551 const Value *Ptr = I.getArgOperand(0); 4552 SDValue Src0 = getValue(I.getArgOperand(3)); 4553 SDValue Mask = getValue(I.getArgOperand(2)); 4554 4555 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4556 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4557 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue(); 4558 if (!Alignment) 4559 Alignment = DAG.getEVTAlignment(VT); 4560 4561 AAMDNodes AAInfo; 4562 I.getAAMetadata(AAInfo); 4563 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4564 4565 SDValue Root = DAG.getRoot(); 4566 SDValue Base; 4567 SDValue Index; 4568 ISD::MemIndexType IndexType; 4569 SDValue Scale; 4570 const Value *BasePtr = Ptr; 4571 bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale, 4572 this); 4573 bool ConstantMemory = false; 4574 if (UniformBase && AA && 4575 AA->pointsToConstantMemory( 4576 MemoryLocation(BasePtr, 4577 LocationSize::precise( 4578 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4579 AAInfo))) { 4580 // Do not serialize (non-volatile) loads of constant memory with anything. 4581 Root = DAG.getEntryNode(); 4582 ConstantMemory = true; 4583 } 4584 4585 MachineMemOperand *MMO = 4586 DAG.getMachineFunction(). 4587 getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr), 4588 MachineMemOperand::MOLoad, 4589 // TODO: Make MachineMemOperands aware of scalable 4590 // vectors. 4591 VT.getStoreSize().getKnownMinSize(), 4592 Alignment, AAInfo, Ranges); 4593 4594 if (!UniformBase) { 4595 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4596 Index = getValue(Ptr); 4597 IndexType = ISD::SIGNED_SCALED; 4598 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4599 } 4600 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4601 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4602 Ops, MMO, IndexType); 4603 4604 SDValue OutChain = Gather.getValue(1); 4605 if (!ConstantMemory) 4606 PendingLoads.push_back(OutChain); 4607 setValue(&I, Gather); 4608 } 4609 4610 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4611 SDLoc dl = getCurSDLoc(); 4612 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4613 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4614 SyncScope::ID SSID = I.getSyncScopeID(); 4615 4616 SDValue InChain = getRoot(); 4617 4618 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4619 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4620 4621 auto Alignment = DAG.getEVTAlignment(MemVT); 4622 4623 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 4624 if (I.isVolatile()) 4625 Flags |= MachineMemOperand::MOVolatile; 4626 Flags |= DAG.getTargetLoweringInfo().getTargetMMOFlags(I); 4627 4628 MachineFunction &MF = DAG.getMachineFunction(); 4629 MachineMemOperand *MMO = 4630 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4631 Flags, MemVT.getStoreSize(), Alignment, 4632 AAMDNodes(), nullptr, SSID, SuccessOrdering, 4633 FailureOrdering); 4634 4635 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4636 dl, MemVT, VTs, InChain, 4637 getValue(I.getPointerOperand()), 4638 getValue(I.getCompareOperand()), 4639 getValue(I.getNewValOperand()), MMO); 4640 4641 SDValue OutChain = L.getValue(2); 4642 4643 setValue(&I, L); 4644 DAG.setRoot(OutChain); 4645 } 4646 4647 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4648 SDLoc dl = getCurSDLoc(); 4649 ISD::NodeType NT; 4650 switch (I.getOperation()) { 4651 default: llvm_unreachable("Unknown atomicrmw operation"); 4652 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4653 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4654 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4655 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4656 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4657 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4658 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4659 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4660 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4661 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4662 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4663 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4664 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4665 } 4666 AtomicOrdering Ordering = I.getOrdering(); 4667 SyncScope::ID SSID = I.getSyncScopeID(); 4668 4669 SDValue InChain = getRoot(); 4670 4671 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4672 auto Alignment = DAG.getEVTAlignment(MemVT); 4673 4674 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 4675 if (I.isVolatile()) 4676 Flags |= MachineMemOperand::MOVolatile; 4677 Flags |= DAG.getTargetLoweringInfo().getTargetMMOFlags(I); 4678 4679 MachineFunction &MF = DAG.getMachineFunction(); 4680 MachineMemOperand *MMO = 4681 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags, 4682 MemVT.getStoreSize(), Alignment, AAMDNodes(), 4683 nullptr, SSID, Ordering); 4684 4685 SDValue L = 4686 DAG.getAtomic(NT, dl, MemVT, InChain, 4687 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4688 MMO); 4689 4690 SDValue OutChain = L.getValue(1); 4691 4692 setValue(&I, L); 4693 DAG.setRoot(OutChain); 4694 } 4695 4696 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4697 SDLoc dl = getCurSDLoc(); 4698 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4699 SDValue Ops[3]; 4700 Ops[0] = getRoot(); 4701 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4702 TLI.getFenceOperandTy(DAG.getDataLayout())); 4703 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4704 TLI.getFenceOperandTy(DAG.getDataLayout())); 4705 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4706 } 4707 4708 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4709 SDLoc dl = getCurSDLoc(); 4710 AtomicOrdering Order = I.getOrdering(); 4711 SyncScope::ID SSID = I.getSyncScopeID(); 4712 4713 SDValue InChain = getRoot(); 4714 4715 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4716 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4717 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4718 4719 if (!TLI.supportsUnalignedAtomics() && 4720 I.getAlignment() < MemVT.getSizeInBits() / 8) 4721 report_fatal_error("Cannot generate unaligned atomic load"); 4722 4723 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4724 4725 MachineMemOperand *MMO = 4726 DAG.getMachineFunction(). 4727 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4728 Flags, MemVT.getStoreSize(), 4729 I.getAlignment() ? I.getAlignment() : 4730 DAG.getEVTAlignment(MemVT), 4731 AAMDNodes(), nullptr, SSID, Order); 4732 4733 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4734 4735 SDValue Ptr = getValue(I.getPointerOperand()); 4736 4737 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4738 // TODO: Once this is better exercised by tests, it should be merged with 4739 // the normal path for loads to prevent future divergence. 4740 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4741 if (MemVT != VT) 4742 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4743 4744 setValue(&I, L); 4745 SDValue OutChain = L.getValue(1); 4746 if (!I.isUnordered()) 4747 DAG.setRoot(OutChain); 4748 else 4749 PendingLoads.push_back(OutChain); 4750 return; 4751 } 4752 4753 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4754 Ptr, MMO); 4755 4756 SDValue OutChain = L.getValue(1); 4757 if (MemVT != VT) 4758 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4759 4760 setValue(&I, L); 4761 DAG.setRoot(OutChain); 4762 } 4763 4764 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4765 SDLoc dl = getCurSDLoc(); 4766 4767 AtomicOrdering Ordering = I.getOrdering(); 4768 SyncScope::ID SSID = I.getSyncScopeID(); 4769 4770 SDValue InChain = getRoot(); 4771 4772 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4773 EVT MemVT = 4774 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4775 4776 if (I.getAlignment() < MemVT.getSizeInBits() / 8) 4777 report_fatal_error("Cannot generate unaligned atomic store"); 4778 4779 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4780 4781 MachineFunction &MF = DAG.getMachineFunction(); 4782 MachineMemOperand *MMO = 4783 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags, 4784 MemVT.getStoreSize(), I.getAlignment(), AAMDNodes(), 4785 nullptr, SSID, Ordering); 4786 4787 SDValue Val = getValue(I.getValueOperand()); 4788 if (Val.getValueType() != MemVT) 4789 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4790 SDValue Ptr = getValue(I.getPointerOperand()); 4791 4792 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4793 // TODO: Once this is better exercised by tests, it should be merged with 4794 // the normal path for stores to prevent future divergence. 4795 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4796 DAG.setRoot(S); 4797 return; 4798 } 4799 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4800 Ptr, Val, MMO); 4801 4802 4803 DAG.setRoot(OutChain); 4804 } 4805 4806 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4807 /// node. 4808 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4809 unsigned Intrinsic) { 4810 // Ignore the callsite's attributes. A specific call site may be marked with 4811 // readnone, but the lowering code will expect the chain based on the 4812 // definition. 4813 const Function *F = I.getCalledFunction(); 4814 bool HasChain = !F->doesNotAccessMemory(); 4815 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4816 4817 // Build the operand list. 4818 SmallVector<SDValue, 8> Ops; 4819 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4820 if (OnlyLoad) { 4821 // We don't need to serialize loads against other loads. 4822 Ops.push_back(DAG.getRoot()); 4823 } else { 4824 Ops.push_back(getRoot()); 4825 } 4826 } 4827 4828 // Info is set by getTgtMemInstrinsic 4829 TargetLowering::IntrinsicInfo Info; 4830 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4831 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4832 DAG.getMachineFunction(), 4833 Intrinsic); 4834 4835 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4836 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4837 Info.opc == ISD::INTRINSIC_W_CHAIN) 4838 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4839 TLI.getPointerTy(DAG.getDataLayout()))); 4840 4841 // Add all operands of the call to the operand list. 4842 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4843 const Value *Arg = I.getArgOperand(i); 4844 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4845 Ops.push_back(getValue(Arg)); 4846 continue; 4847 } 4848 4849 // Use TargetConstant instead of a regular constant for immarg. 4850 EVT VT = TLI.getValueType(*DL, Arg->getType(), true); 4851 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4852 assert(CI->getBitWidth() <= 64 && 4853 "large intrinsic immediates not handled"); 4854 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4855 } else { 4856 Ops.push_back( 4857 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4858 } 4859 } 4860 4861 SmallVector<EVT, 4> ValueVTs; 4862 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4863 4864 if (HasChain) 4865 ValueVTs.push_back(MVT::Other); 4866 4867 SDVTList VTs = DAG.getVTList(ValueVTs); 4868 4869 // Create the node. 4870 SDValue Result; 4871 if (IsTgtIntrinsic) { 4872 // This is target intrinsic that touches memory 4873 AAMDNodes AAInfo; 4874 I.getAAMetadata(AAInfo); 4875 Result = DAG.getMemIntrinsicNode( 4876 Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT, 4877 MachinePointerInfo(Info.ptrVal, Info.offset), 4878 Info.align ? Info.align->value() : 0, Info.flags, Info.size, AAInfo); 4879 } else if (!HasChain) { 4880 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4881 } else if (!I.getType()->isVoidTy()) { 4882 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4883 } else { 4884 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4885 } 4886 4887 if (HasChain) { 4888 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4889 if (OnlyLoad) 4890 PendingLoads.push_back(Chain); 4891 else 4892 DAG.setRoot(Chain); 4893 } 4894 4895 if (!I.getType()->isVoidTy()) { 4896 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4897 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4898 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4899 } else 4900 Result = lowerRangeToAssertZExt(DAG, I, Result); 4901 4902 setValue(&I, Result); 4903 } 4904 } 4905 4906 /// GetSignificand - Get the significand and build it into a floating-point 4907 /// number with exponent of 1: 4908 /// 4909 /// Op = (Op & 0x007fffff) | 0x3f800000; 4910 /// 4911 /// where Op is the hexadecimal representation of floating point value. 4912 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4913 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4914 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4915 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4916 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4917 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4918 } 4919 4920 /// GetExponent - Get the exponent: 4921 /// 4922 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4923 /// 4924 /// where Op is the hexadecimal representation of floating point value. 4925 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4926 const TargetLowering &TLI, const SDLoc &dl) { 4927 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4928 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4929 SDValue t1 = DAG.getNode( 4930 ISD::SRL, dl, MVT::i32, t0, 4931 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4932 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4933 DAG.getConstant(127, dl, MVT::i32)); 4934 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4935 } 4936 4937 /// getF32Constant - Get 32-bit floating point constant. 4938 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4939 const SDLoc &dl) { 4940 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4941 MVT::f32); 4942 } 4943 4944 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4945 SelectionDAG &DAG) { 4946 // TODO: What fast-math-flags should be set on the floating-point nodes? 4947 4948 // IntegerPartOfX = ((int32_t)(t0); 4949 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4950 4951 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4952 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4953 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4954 4955 // IntegerPartOfX <<= 23; 4956 IntegerPartOfX = DAG.getNode( 4957 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4958 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4959 DAG.getDataLayout()))); 4960 4961 SDValue TwoToFractionalPartOfX; 4962 if (LimitFloatPrecision <= 6) { 4963 // For floating-point precision of 6: 4964 // 4965 // TwoToFractionalPartOfX = 4966 // 0.997535578f + 4967 // (0.735607626f + 0.252464424f * x) * x; 4968 // 4969 // error 0.0144103317, which is 6 bits 4970 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4971 getF32Constant(DAG, 0x3e814304, dl)); 4972 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4973 getF32Constant(DAG, 0x3f3c50c8, dl)); 4974 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4975 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4976 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4977 } else if (LimitFloatPrecision <= 12) { 4978 // For floating-point precision of 12: 4979 // 4980 // TwoToFractionalPartOfX = 4981 // 0.999892986f + 4982 // (0.696457318f + 4983 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4984 // 4985 // error 0.000107046256, which is 13 to 14 bits 4986 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4987 getF32Constant(DAG, 0x3da235e3, dl)); 4988 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4989 getF32Constant(DAG, 0x3e65b8f3, dl)); 4990 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4991 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4992 getF32Constant(DAG, 0x3f324b07, dl)); 4993 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4994 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4995 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4996 } else { // LimitFloatPrecision <= 18 4997 // For floating-point precision of 18: 4998 // 4999 // TwoToFractionalPartOfX = 5000 // 0.999999982f + 5001 // (0.693148872f + 5002 // (0.240227044f + 5003 // (0.554906021e-1f + 5004 // (0.961591928e-2f + 5005 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 5006 // error 2.47208000*10^(-7), which is better than 18 bits 5007 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5008 getF32Constant(DAG, 0x3924b03e, dl)); 5009 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5010 getF32Constant(DAG, 0x3ab24b87, dl)); 5011 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5012 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5013 getF32Constant(DAG, 0x3c1d8c17, dl)); 5014 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5015 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5016 getF32Constant(DAG, 0x3d634a1d, dl)); 5017 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5018 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5019 getF32Constant(DAG, 0x3e75fe14, dl)); 5020 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5021 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 5022 getF32Constant(DAG, 0x3f317234, dl)); 5023 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 5024 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 5025 getF32Constant(DAG, 0x3f800000, dl)); 5026 } 5027 5028 // Add the exponent into the result in integer domain. 5029 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 5030 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5031 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 5032 } 5033 5034 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5035 /// limited-precision mode. 5036 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5037 const TargetLowering &TLI) { 5038 if (Op.getValueType() == MVT::f32 && 5039 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5040 5041 // Put the exponent in the right bit position for later addition to the 5042 // final result: 5043 // 5044 // t0 = Op * log2(e) 5045 5046 // TODO: What fast-math-flags should be set here? 5047 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5048 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5049 return getLimitedPrecisionExp2(t0, dl, DAG); 5050 } 5051 5052 // No special expansion. 5053 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op); 5054 } 5055 5056 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5057 /// limited-precision mode. 5058 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5059 const TargetLowering &TLI) { 5060 // TODO: What fast-math-flags should be set on the floating-point nodes? 5061 5062 if (Op.getValueType() == MVT::f32 && 5063 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5064 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5065 5066 // Scale the exponent by log(2). 5067 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5068 SDValue LogOfExponent = 5069 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5070 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5071 5072 // Get the significand and build it into a floating-point number with 5073 // exponent of 1. 5074 SDValue X = GetSignificand(DAG, Op1, dl); 5075 5076 SDValue LogOfMantissa; 5077 if (LimitFloatPrecision <= 6) { 5078 // For floating-point precision of 6: 5079 // 5080 // LogofMantissa = 5081 // -1.1609546f + 5082 // (1.4034025f - 0.23903021f * x) * x; 5083 // 5084 // error 0.0034276066, which is better than 8 bits 5085 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5086 getF32Constant(DAG, 0xbe74c456, dl)); 5087 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5088 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5089 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5090 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5091 getF32Constant(DAG, 0x3f949a29, dl)); 5092 } else if (LimitFloatPrecision <= 12) { 5093 // For floating-point precision of 12: 5094 // 5095 // LogOfMantissa = 5096 // -1.7417939f + 5097 // (2.8212026f + 5098 // (-1.4699568f + 5099 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5100 // 5101 // error 0.000061011436, which is 14 bits 5102 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5103 getF32Constant(DAG, 0xbd67b6d6, dl)); 5104 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5105 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5106 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5107 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5108 getF32Constant(DAG, 0x3fbc278b, dl)); 5109 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5110 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5111 getF32Constant(DAG, 0x40348e95, dl)); 5112 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5113 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5114 getF32Constant(DAG, 0x3fdef31a, dl)); 5115 } else { // LimitFloatPrecision <= 18 5116 // For floating-point precision of 18: 5117 // 5118 // LogOfMantissa = 5119 // -2.1072184f + 5120 // (4.2372794f + 5121 // (-3.7029485f + 5122 // (2.2781945f + 5123 // (-0.87823314f + 5124 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5125 // 5126 // error 0.0000023660568, which is better than 18 bits 5127 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5128 getF32Constant(DAG, 0xbc91e5ac, dl)); 5129 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5130 getF32Constant(DAG, 0x3e4350aa, dl)); 5131 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5132 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5133 getF32Constant(DAG, 0x3f60d3e3, dl)); 5134 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5135 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5136 getF32Constant(DAG, 0x4011cdf0, dl)); 5137 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5138 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5139 getF32Constant(DAG, 0x406cfd1c, dl)); 5140 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5141 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5142 getF32Constant(DAG, 0x408797cb, dl)); 5143 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5144 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5145 getF32Constant(DAG, 0x4006dcab, dl)); 5146 } 5147 5148 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5149 } 5150 5151 // No special expansion. 5152 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op); 5153 } 5154 5155 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5156 /// limited-precision mode. 5157 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5158 const TargetLowering &TLI) { 5159 // TODO: What fast-math-flags should be set on the floating-point nodes? 5160 5161 if (Op.getValueType() == MVT::f32 && 5162 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5163 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5164 5165 // Get the exponent. 5166 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5167 5168 // Get the significand and build it into a floating-point number with 5169 // exponent of 1. 5170 SDValue X = GetSignificand(DAG, Op1, dl); 5171 5172 // Different possible minimax approximations of significand in 5173 // floating-point for various degrees of accuracy over [1,2]. 5174 SDValue Log2ofMantissa; 5175 if (LimitFloatPrecision <= 6) { 5176 // For floating-point precision of 6: 5177 // 5178 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5179 // 5180 // error 0.0049451742, which is more than 7 bits 5181 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5182 getF32Constant(DAG, 0xbeb08fe0, dl)); 5183 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5184 getF32Constant(DAG, 0x40019463, dl)); 5185 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5186 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5187 getF32Constant(DAG, 0x3fd6633d, dl)); 5188 } else if (LimitFloatPrecision <= 12) { 5189 // For floating-point precision of 12: 5190 // 5191 // Log2ofMantissa = 5192 // -2.51285454f + 5193 // (4.07009056f + 5194 // (-2.12067489f + 5195 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5196 // 5197 // error 0.0000876136000, which is better than 13 bits 5198 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5199 getF32Constant(DAG, 0xbda7262e, dl)); 5200 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5201 getF32Constant(DAG, 0x3f25280b, dl)); 5202 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5203 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5204 getF32Constant(DAG, 0x4007b923, dl)); 5205 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5206 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5207 getF32Constant(DAG, 0x40823e2f, dl)); 5208 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5209 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5210 getF32Constant(DAG, 0x4020d29c, dl)); 5211 } else { // LimitFloatPrecision <= 18 5212 // For floating-point precision of 18: 5213 // 5214 // Log2ofMantissa = 5215 // -3.0400495f + 5216 // (6.1129976f + 5217 // (-5.3420409f + 5218 // (3.2865683f + 5219 // (-1.2669343f + 5220 // (0.27515199f - 5221 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5222 // 5223 // error 0.0000018516, which is better than 18 bits 5224 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5225 getF32Constant(DAG, 0xbcd2769e, dl)); 5226 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5227 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5228 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5229 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5230 getF32Constant(DAG, 0x3fa22ae7, dl)); 5231 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5232 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5233 getF32Constant(DAG, 0x40525723, dl)); 5234 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5235 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5236 getF32Constant(DAG, 0x40aaf200, dl)); 5237 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5238 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5239 getF32Constant(DAG, 0x40c39dad, dl)); 5240 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5241 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5242 getF32Constant(DAG, 0x4042902c, dl)); 5243 } 5244 5245 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5246 } 5247 5248 // No special expansion. 5249 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op); 5250 } 5251 5252 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5253 /// limited-precision mode. 5254 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5255 const TargetLowering &TLI) { 5256 // TODO: What fast-math-flags should be set on the floating-point nodes? 5257 5258 if (Op.getValueType() == MVT::f32 && 5259 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5260 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5261 5262 // Scale the exponent by log10(2) [0.30102999f]. 5263 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5264 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5265 getF32Constant(DAG, 0x3e9a209a, dl)); 5266 5267 // Get the significand and build it into a floating-point number with 5268 // exponent of 1. 5269 SDValue X = GetSignificand(DAG, Op1, dl); 5270 5271 SDValue Log10ofMantissa; 5272 if (LimitFloatPrecision <= 6) { 5273 // For floating-point precision of 6: 5274 // 5275 // Log10ofMantissa = 5276 // -0.50419619f + 5277 // (0.60948995f - 0.10380950f * x) * x; 5278 // 5279 // error 0.0014886165, which is 6 bits 5280 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5281 getF32Constant(DAG, 0xbdd49a13, dl)); 5282 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5283 getF32Constant(DAG, 0x3f1c0789, dl)); 5284 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5285 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5286 getF32Constant(DAG, 0x3f011300, dl)); 5287 } else if (LimitFloatPrecision <= 12) { 5288 // For floating-point precision of 12: 5289 // 5290 // Log10ofMantissa = 5291 // -0.64831180f + 5292 // (0.91751397f + 5293 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5294 // 5295 // error 0.00019228036, which is better than 12 bits 5296 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5297 getF32Constant(DAG, 0x3d431f31, dl)); 5298 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5299 getF32Constant(DAG, 0x3ea21fb2, dl)); 5300 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5301 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5302 getF32Constant(DAG, 0x3f6ae232, dl)); 5303 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5304 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5305 getF32Constant(DAG, 0x3f25f7c3, dl)); 5306 } else { // LimitFloatPrecision <= 18 5307 // For floating-point precision of 18: 5308 // 5309 // Log10ofMantissa = 5310 // -0.84299375f + 5311 // (1.5327582f + 5312 // (-1.0688956f + 5313 // (0.49102474f + 5314 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5315 // 5316 // error 0.0000037995730, which is better than 18 bits 5317 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5318 getF32Constant(DAG, 0x3c5d51ce, dl)); 5319 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5320 getF32Constant(DAG, 0x3e00685a, dl)); 5321 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5322 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5323 getF32Constant(DAG, 0x3efb6798, dl)); 5324 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5325 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5326 getF32Constant(DAG, 0x3f88d192, dl)); 5327 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5328 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5329 getF32Constant(DAG, 0x3fc4316c, dl)); 5330 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5331 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5332 getF32Constant(DAG, 0x3f57ce70, dl)); 5333 } 5334 5335 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5336 } 5337 5338 // No special expansion. 5339 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op); 5340 } 5341 5342 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5343 /// limited-precision mode. 5344 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5345 const TargetLowering &TLI) { 5346 if (Op.getValueType() == MVT::f32 && 5347 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5348 return getLimitedPrecisionExp2(Op, dl, DAG); 5349 5350 // No special expansion. 5351 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op); 5352 } 5353 5354 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5355 /// limited-precision mode with x == 10.0f. 5356 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5357 SelectionDAG &DAG, const TargetLowering &TLI) { 5358 bool IsExp10 = false; 5359 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5360 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5361 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5362 APFloat Ten(10.0f); 5363 IsExp10 = LHSC->isExactlyValue(Ten); 5364 } 5365 } 5366 5367 // TODO: What fast-math-flags should be set on the FMUL node? 5368 if (IsExp10) { 5369 // Put the exponent in the right bit position for later addition to the 5370 // final result: 5371 // 5372 // #define LOG2OF10 3.3219281f 5373 // t0 = Op * LOG2OF10; 5374 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5375 getF32Constant(DAG, 0x40549a78, dl)); 5376 return getLimitedPrecisionExp2(t0, dl, DAG); 5377 } 5378 5379 // No special expansion. 5380 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS); 5381 } 5382 5383 /// ExpandPowI - Expand a llvm.powi intrinsic. 5384 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5385 SelectionDAG &DAG) { 5386 // If RHS is a constant, we can expand this out to a multiplication tree, 5387 // otherwise we end up lowering to a call to __powidf2 (for example). When 5388 // optimizing for size, we only want to do this if the expansion would produce 5389 // a small number of multiplies, otherwise we do the full expansion. 5390 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5391 // Get the exponent as a positive value. 5392 unsigned Val = RHSC->getSExtValue(); 5393 if ((int)Val < 0) Val = -Val; 5394 5395 // powi(x, 0) -> 1.0 5396 if (Val == 0) 5397 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5398 5399 bool OptForSize = DAG.shouldOptForSize(); 5400 if (!OptForSize || 5401 // If optimizing for size, don't insert too many multiplies. 5402 // This inserts up to 5 multiplies. 5403 countPopulation(Val) + Log2_32(Val) < 7) { 5404 // We use the simple binary decomposition method to generate the multiply 5405 // sequence. There are more optimal ways to do this (for example, 5406 // powi(x,15) generates one more multiply than it should), but this has 5407 // the benefit of being both really simple and much better than a libcall. 5408 SDValue Res; // Logically starts equal to 1.0 5409 SDValue CurSquare = LHS; 5410 // TODO: Intrinsics should have fast-math-flags that propagate to these 5411 // nodes. 5412 while (Val) { 5413 if (Val & 1) { 5414 if (Res.getNode()) 5415 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 5416 else 5417 Res = CurSquare; // 1.0*CurSquare. 5418 } 5419 5420 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5421 CurSquare, CurSquare); 5422 Val >>= 1; 5423 } 5424 5425 // If the original was negative, invert the result, producing 1/(x*x*x). 5426 if (RHSC->getSExtValue() < 0) 5427 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5428 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5429 return Res; 5430 } 5431 } 5432 5433 // Otherwise, expand to a libcall. 5434 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5435 } 5436 5437 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5438 SDValue LHS, SDValue RHS, SDValue Scale, 5439 SelectionDAG &DAG, const TargetLowering &TLI) { 5440 EVT VT = LHS.getValueType(); 5441 bool Signed = Opcode == ISD::SDIVFIX; 5442 LLVMContext &Ctx = *DAG.getContext(); 5443 5444 // If the type is legal but the operation isn't, this node might survive all 5445 // the way to operation legalization. If we end up there and we do not have 5446 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5447 // node. 5448 5449 // Coax the legalizer into expanding the node during type legalization instead 5450 // by bumping the size by one bit. This will force it to Promote, enabling the 5451 // early expansion and avoiding the need to expand later. 5452 5453 // We don't have to do this if Scale is 0; that can always be expanded. 5454 5455 // FIXME: We wouldn't have to do this (or any of the early 5456 // expansion/promotion) if it was possible to expand a libcall of an 5457 // illegal type during operation legalization. But it's not, so things 5458 // get a bit hacky. 5459 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5460 if (ScaleInt > 0 && 5461 (TLI.isTypeLegal(VT) || 5462 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5463 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5464 Opcode, VT, ScaleInt); 5465 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5466 EVT PromVT; 5467 if (VT.isScalarInteger()) 5468 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5469 else if (VT.isVector()) { 5470 PromVT = VT.getVectorElementType(); 5471 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5472 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5473 } else 5474 llvm_unreachable("Wrong VT for DIVFIX?"); 5475 if (Signed) { 5476 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5477 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5478 } else { 5479 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5480 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5481 } 5482 // TODO: Saturation. 5483 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5484 return DAG.getZExtOrTrunc(Res, DL, VT); 5485 } 5486 } 5487 5488 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5489 } 5490 5491 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5492 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5493 static void 5494 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs, 5495 const SDValue &N) { 5496 switch (N.getOpcode()) { 5497 case ISD::CopyFromReg: { 5498 SDValue Op = N.getOperand(1); 5499 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5500 Op.getValueType().getSizeInBits()); 5501 return; 5502 } 5503 case ISD::BITCAST: 5504 case ISD::AssertZext: 5505 case ISD::AssertSext: 5506 case ISD::TRUNCATE: 5507 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5508 return; 5509 case ISD::BUILD_PAIR: 5510 case ISD::BUILD_VECTOR: 5511 case ISD::CONCAT_VECTORS: 5512 for (SDValue Op : N->op_values()) 5513 getUnderlyingArgRegs(Regs, Op); 5514 return; 5515 default: 5516 return; 5517 } 5518 } 5519 5520 /// If the DbgValueInst is a dbg_value of a function argument, create the 5521 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5522 /// instruction selection, they will be inserted to the entry BB. 5523 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5524 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5525 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 5526 const Argument *Arg = dyn_cast<Argument>(V); 5527 if (!Arg) 5528 return false; 5529 5530 if (!IsDbgDeclare) { 5531 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5532 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5533 // the entry block. 5534 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5535 if (!IsInEntryBlock) 5536 return false; 5537 5538 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5539 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5540 // variable that also is a param. 5541 // 5542 // Although, if we are at the top of the entry block already, we can still 5543 // emit using ArgDbgValue. This might catch some situations when the 5544 // dbg.value refers to an argument that isn't used in the entry block, so 5545 // any CopyToReg node would be optimized out and the only way to express 5546 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5547 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5548 // we should only emit as ArgDbgValue if the Variable is an argument to the 5549 // current function, and the dbg.value intrinsic is found in the entry 5550 // block. 5551 bool VariableIsFunctionInputArg = Variable->isParameter() && 5552 !DL->getInlinedAt(); 5553 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5554 if (!IsInPrologue && !VariableIsFunctionInputArg) 5555 return false; 5556 5557 // Here we assume that a function argument on IR level only can be used to 5558 // describe one input parameter on source level. If we for example have 5559 // source code like this 5560 // 5561 // struct A { long x, y; }; 5562 // void foo(struct A a, long b) { 5563 // ... 5564 // b = a.x; 5565 // ... 5566 // } 5567 // 5568 // and IR like this 5569 // 5570 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5571 // entry: 5572 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5573 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5574 // call void @llvm.dbg.value(metadata i32 %b, "b", 5575 // ... 5576 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5577 // ... 5578 // 5579 // then the last dbg.value is describing a parameter "b" using a value that 5580 // is an argument. But since we already has used %a1 to describe a parameter 5581 // we should not handle that last dbg.value here (that would result in an 5582 // incorrect hoisting of the DBG_VALUE to the function entry). 5583 // Notice that we allow one dbg.value per IR level argument, to accommodate 5584 // for the situation with fragments above. 5585 if (VariableIsFunctionInputArg) { 5586 unsigned ArgNo = Arg->getArgNo(); 5587 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5588 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5589 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5590 return false; 5591 FuncInfo.DescribedArgs.set(ArgNo); 5592 } 5593 } 5594 5595 MachineFunction &MF = DAG.getMachineFunction(); 5596 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5597 5598 Optional<MachineOperand> Op; 5599 // Some arguments' frame index is recorded during argument lowering. 5600 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5601 if (FI != std::numeric_limits<int>::max()) 5602 Op = MachineOperand::CreateFI(FI); 5603 5604 SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes; 5605 if (!Op && N.getNode()) { 5606 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5607 Register Reg; 5608 if (ArgRegsAndSizes.size() == 1) 5609 Reg = ArgRegsAndSizes.front().first; 5610 5611 if (Reg && Reg.isVirtual()) { 5612 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5613 Register PR = RegInfo.getLiveInPhysReg(Reg); 5614 if (PR) 5615 Reg = PR; 5616 } 5617 if (Reg) { 5618 Op = MachineOperand::CreateReg(Reg, false); 5619 } 5620 } 5621 5622 if (!Op && N.getNode()) { 5623 // Check if frame index is available. 5624 SDValue LCandidate = peekThroughBitcasts(N); 5625 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5626 if (FrameIndexSDNode *FINode = 5627 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5628 Op = MachineOperand::CreateFI(FINode->getIndex()); 5629 } 5630 5631 if (!Op) { 5632 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5633 auto splitMultiRegDbgValue 5634 = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) { 5635 unsigned Offset = 0; 5636 for (auto RegAndSize : SplitRegs) { 5637 // If the expression is already a fragment, the current register 5638 // offset+size might extend beyond the fragment. In this case, only 5639 // the register bits that are inside the fragment are relevant. 5640 int RegFragmentSizeInBits = RegAndSize.second; 5641 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5642 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5643 // The register is entirely outside the expression fragment, 5644 // so is irrelevant for debug info. 5645 if (Offset >= ExprFragmentSizeInBits) 5646 break; 5647 // The register is partially outside the expression fragment, only 5648 // the low bits within the fragment are relevant for debug info. 5649 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5650 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5651 } 5652 } 5653 5654 auto FragmentExpr = DIExpression::createFragmentExpression( 5655 Expr, Offset, RegFragmentSizeInBits); 5656 Offset += RegAndSize.second; 5657 // If a valid fragment expression cannot be created, the variable's 5658 // correct value cannot be determined and so it is set as Undef. 5659 if (!FragmentExpr) { 5660 SDDbgValue *SDV = DAG.getConstantDbgValue( 5661 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5662 DAG.AddDbgValue(SDV, nullptr, false); 5663 continue; 5664 } 5665 assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?"); 5666 FuncInfo.ArgDbgValues.push_back( 5667 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), false, 5668 RegAndSize.first, Variable, *FragmentExpr)); 5669 } 5670 }; 5671 5672 // Check if ValueMap has reg number. 5673 DenseMap<const Value *, unsigned>::const_iterator 5674 VMI = FuncInfo.ValueMap.find(V); 5675 if (VMI != FuncInfo.ValueMap.end()) { 5676 const auto &TLI = DAG.getTargetLoweringInfo(); 5677 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5678 V->getType(), getABIRegCopyCC(V)); 5679 if (RFV.occupiesMultipleRegs()) { 5680 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5681 return true; 5682 } 5683 5684 Op = MachineOperand::CreateReg(VMI->second, false); 5685 } else if (ArgRegsAndSizes.size() > 1) { 5686 // This was split due to the calling convention, and no virtual register 5687 // mapping exists for the value. 5688 splitMultiRegDbgValue(ArgRegsAndSizes); 5689 return true; 5690 } 5691 } 5692 5693 if (!Op) 5694 return false; 5695 5696 assert(Variable->isValidLocationForIntrinsic(DL) && 5697 "Expected inlined-at fields to agree"); 5698 5699 // If the argument arrives in a stack slot, then what the IR thought was a 5700 // normal Value is actually in memory, and we must add a deref to load it. 5701 if (Op->isFI()) { 5702 int FI = Op->getIndex(); 5703 unsigned Size = DAG.getMachineFunction().getFrameInfo().getObjectSize(FI); 5704 if (Expr->isImplicit()) { 5705 SmallVector<uint64_t, 2> Ops = {dwarf::DW_OP_deref_size, Size}; 5706 Expr = DIExpression::prependOpcodes(Expr, Ops); 5707 } else { 5708 Expr = DIExpression::prepend(Expr, DIExpression::DerefBefore); 5709 } 5710 } 5711 5712 // If this location was specified with a dbg.declare, then it and its 5713 // expression calculate the address of the variable. Append a deref to 5714 // force it to be a memory location. 5715 if (IsDbgDeclare) 5716 Expr = DIExpression::append(Expr, {dwarf::DW_OP_deref}); 5717 5718 FuncInfo.ArgDbgValues.push_back( 5719 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), false, 5720 *Op, Variable, Expr)); 5721 5722 return true; 5723 } 5724 5725 /// Return the appropriate SDDbgValue based on N. 5726 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5727 DILocalVariable *Variable, 5728 DIExpression *Expr, 5729 const DebugLoc &dl, 5730 unsigned DbgSDNodeOrder) { 5731 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5732 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5733 // stack slot locations. 5734 // 5735 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5736 // debug values here after optimization: 5737 // 5738 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5739 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5740 // 5741 // Both describe the direct values of their associated variables. 5742 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5743 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5744 } 5745 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5746 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5747 } 5748 5749 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5750 switch (Intrinsic) { 5751 case Intrinsic::smul_fix: 5752 return ISD::SMULFIX; 5753 case Intrinsic::umul_fix: 5754 return ISD::UMULFIX; 5755 case Intrinsic::smul_fix_sat: 5756 return ISD::SMULFIXSAT; 5757 case Intrinsic::umul_fix_sat: 5758 return ISD::UMULFIXSAT; 5759 case Intrinsic::sdiv_fix: 5760 return ISD::SDIVFIX; 5761 case Intrinsic::udiv_fix: 5762 return ISD::UDIVFIX; 5763 default: 5764 llvm_unreachable("Unhandled fixed point intrinsic"); 5765 } 5766 } 5767 5768 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5769 const char *FunctionName) { 5770 assert(FunctionName && "FunctionName must not be nullptr"); 5771 SDValue Callee = DAG.getExternalSymbol( 5772 FunctionName, 5773 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5774 LowerCallTo(&I, Callee, I.isTailCall()); 5775 } 5776 5777 /// Lower the call to the specified intrinsic function. 5778 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5779 unsigned Intrinsic) { 5780 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5781 SDLoc sdl = getCurSDLoc(); 5782 DebugLoc dl = getCurDebugLoc(); 5783 SDValue Res; 5784 5785 switch (Intrinsic) { 5786 default: 5787 // By default, turn this into a target intrinsic node. 5788 visitTargetIntrinsic(I, Intrinsic); 5789 return; 5790 case Intrinsic::vastart: visitVAStart(I); return; 5791 case Intrinsic::vaend: visitVAEnd(I); return; 5792 case Intrinsic::vacopy: visitVACopy(I); return; 5793 case Intrinsic::returnaddress: 5794 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5795 TLI.getPointerTy(DAG.getDataLayout()), 5796 getValue(I.getArgOperand(0)))); 5797 return; 5798 case Intrinsic::addressofreturnaddress: 5799 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5800 TLI.getPointerTy(DAG.getDataLayout()))); 5801 return; 5802 case Intrinsic::sponentry: 5803 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5804 TLI.getFrameIndexTy(DAG.getDataLayout()))); 5805 return; 5806 case Intrinsic::frameaddress: 5807 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5808 TLI.getFrameIndexTy(DAG.getDataLayout()), 5809 getValue(I.getArgOperand(0)))); 5810 return; 5811 case Intrinsic::read_register: { 5812 Value *Reg = I.getArgOperand(0); 5813 SDValue Chain = getRoot(); 5814 SDValue RegName = 5815 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5816 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5817 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5818 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5819 setValue(&I, Res); 5820 DAG.setRoot(Res.getValue(1)); 5821 return; 5822 } 5823 case Intrinsic::write_register: { 5824 Value *Reg = I.getArgOperand(0); 5825 Value *RegValue = I.getArgOperand(1); 5826 SDValue Chain = getRoot(); 5827 SDValue RegName = 5828 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5829 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5830 RegName, getValue(RegValue))); 5831 return; 5832 } 5833 case Intrinsic::memcpy: { 5834 const auto &MCI = cast<MemCpyInst>(I); 5835 SDValue Op1 = getValue(I.getArgOperand(0)); 5836 SDValue Op2 = getValue(I.getArgOperand(1)); 5837 SDValue Op3 = getValue(I.getArgOperand(2)); 5838 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5839 unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1); 5840 unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1); 5841 unsigned Align = MinAlign(DstAlign, SrcAlign); 5842 bool isVol = MCI.isVolatile(); 5843 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5844 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5845 // node. 5846 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5847 SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Align, isVol, 5848 false, isTC, 5849 MachinePointerInfo(I.getArgOperand(0)), 5850 MachinePointerInfo(I.getArgOperand(1))); 5851 updateDAGForMaybeTailCall(MC); 5852 return; 5853 } 5854 case Intrinsic::memset: { 5855 const auto &MSI = cast<MemSetInst>(I); 5856 SDValue Op1 = getValue(I.getArgOperand(0)); 5857 SDValue Op2 = getValue(I.getArgOperand(1)); 5858 SDValue Op3 = getValue(I.getArgOperand(2)); 5859 // @llvm.memset defines 0 and 1 to both mean no alignment. 5860 unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1); 5861 bool isVol = MSI.isVolatile(); 5862 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5863 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5864 SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Align, isVol, 5865 isTC, MachinePointerInfo(I.getArgOperand(0))); 5866 updateDAGForMaybeTailCall(MS); 5867 return; 5868 } 5869 case Intrinsic::memmove: { 5870 const auto &MMI = cast<MemMoveInst>(I); 5871 SDValue Op1 = getValue(I.getArgOperand(0)); 5872 SDValue Op2 = getValue(I.getArgOperand(1)); 5873 SDValue Op3 = getValue(I.getArgOperand(2)); 5874 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5875 unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1); 5876 unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1); 5877 unsigned Align = MinAlign(DstAlign, SrcAlign); 5878 bool isVol = MMI.isVolatile(); 5879 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5880 // FIXME: Support passing different dest/src alignments to the memmove DAG 5881 // node. 5882 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5883 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Align, isVol, 5884 isTC, MachinePointerInfo(I.getArgOperand(0)), 5885 MachinePointerInfo(I.getArgOperand(1))); 5886 updateDAGForMaybeTailCall(MM); 5887 return; 5888 } 5889 case Intrinsic::memcpy_element_unordered_atomic: { 5890 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5891 SDValue Dst = getValue(MI.getRawDest()); 5892 SDValue Src = getValue(MI.getRawSource()); 5893 SDValue Length = getValue(MI.getLength()); 5894 5895 unsigned DstAlign = MI.getDestAlignment(); 5896 unsigned SrcAlign = MI.getSourceAlignment(); 5897 Type *LengthTy = MI.getLength()->getType(); 5898 unsigned ElemSz = MI.getElementSizeInBytes(); 5899 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5900 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5901 SrcAlign, Length, LengthTy, ElemSz, isTC, 5902 MachinePointerInfo(MI.getRawDest()), 5903 MachinePointerInfo(MI.getRawSource())); 5904 updateDAGForMaybeTailCall(MC); 5905 return; 5906 } 5907 case Intrinsic::memmove_element_unordered_atomic: { 5908 auto &MI = cast<AtomicMemMoveInst>(I); 5909 SDValue Dst = getValue(MI.getRawDest()); 5910 SDValue Src = getValue(MI.getRawSource()); 5911 SDValue Length = getValue(MI.getLength()); 5912 5913 unsigned DstAlign = MI.getDestAlignment(); 5914 unsigned SrcAlign = MI.getSourceAlignment(); 5915 Type *LengthTy = MI.getLength()->getType(); 5916 unsigned ElemSz = MI.getElementSizeInBytes(); 5917 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5918 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5919 SrcAlign, Length, LengthTy, ElemSz, isTC, 5920 MachinePointerInfo(MI.getRawDest()), 5921 MachinePointerInfo(MI.getRawSource())); 5922 updateDAGForMaybeTailCall(MC); 5923 return; 5924 } 5925 case Intrinsic::memset_element_unordered_atomic: { 5926 auto &MI = cast<AtomicMemSetInst>(I); 5927 SDValue Dst = getValue(MI.getRawDest()); 5928 SDValue Val = getValue(MI.getValue()); 5929 SDValue Length = getValue(MI.getLength()); 5930 5931 unsigned DstAlign = MI.getDestAlignment(); 5932 Type *LengthTy = MI.getLength()->getType(); 5933 unsigned ElemSz = MI.getElementSizeInBytes(); 5934 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5935 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5936 LengthTy, ElemSz, isTC, 5937 MachinePointerInfo(MI.getRawDest())); 5938 updateDAGForMaybeTailCall(MC); 5939 return; 5940 } 5941 case Intrinsic::dbg_addr: 5942 case Intrinsic::dbg_declare: { 5943 const auto &DI = cast<DbgVariableIntrinsic>(I); 5944 DILocalVariable *Variable = DI.getVariable(); 5945 DIExpression *Expression = DI.getExpression(); 5946 dropDanglingDebugInfo(Variable, Expression); 5947 assert(Variable && "Missing variable"); 5948 5949 // Check if address has undef value. 5950 const Value *Address = DI.getVariableLocation(); 5951 if (!Address || isa<UndefValue>(Address) || 5952 (Address->use_empty() && !isa<Argument>(Address))) { 5953 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5954 return; 5955 } 5956 5957 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5958 5959 // Check if this variable can be described by a frame index, typically 5960 // either as a static alloca or a byval parameter. 5961 int FI = std::numeric_limits<int>::max(); 5962 if (const auto *AI = 5963 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5964 if (AI->isStaticAlloca()) { 5965 auto I = FuncInfo.StaticAllocaMap.find(AI); 5966 if (I != FuncInfo.StaticAllocaMap.end()) 5967 FI = I->second; 5968 } 5969 } else if (const auto *Arg = dyn_cast<Argument>( 5970 Address->stripInBoundsConstantOffsets())) { 5971 FI = FuncInfo.getArgumentFrameIndex(Arg); 5972 } 5973 5974 // llvm.dbg.addr is control dependent and always generates indirect 5975 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5976 // the MachineFunction variable table. 5977 if (FI != std::numeric_limits<int>::max()) { 5978 if (Intrinsic == Intrinsic::dbg_addr) { 5979 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 5980 Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder); 5981 DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter); 5982 } 5983 return; 5984 } 5985 5986 SDValue &N = NodeMap[Address]; 5987 if (!N.getNode() && isa<Argument>(Address)) 5988 // Check unused arguments map. 5989 N = UnusedArgNodeMap[Address]; 5990 SDDbgValue *SDV; 5991 if (N.getNode()) { 5992 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 5993 Address = BCI->getOperand(0); 5994 // Parameters are handled specially. 5995 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 5996 if (isParameter && FINode) { 5997 // Byval parameter. We have a frame index at this point. 5998 SDV = 5999 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 6000 /*IsIndirect*/ true, dl, SDNodeOrder); 6001 } else if (isa<Argument>(Address)) { 6002 // Address is an argument, so try to emit its dbg value using 6003 // virtual register info from the FuncInfo.ValueMap. 6004 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 6005 return; 6006 } else { 6007 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 6008 true, dl, SDNodeOrder); 6009 } 6010 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 6011 } else { 6012 // If Address is an argument then try to emit its dbg value using 6013 // virtual register info from the FuncInfo.ValueMap. 6014 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 6015 N)) { 6016 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 6017 } 6018 } 6019 return; 6020 } 6021 case Intrinsic::dbg_label: { 6022 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6023 DILabel *Label = DI.getLabel(); 6024 assert(Label && "Missing label"); 6025 6026 SDDbgLabel *SDV; 6027 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6028 DAG.AddDbgLabel(SDV); 6029 return; 6030 } 6031 case Intrinsic::dbg_value: { 6032 const DbgValueInst &DI = cast<DbgValueInst>(I); 6033 assert(DI.getVariable() && "Missing variable"); 6034 6035 DILocalVariable *Variable = DI.getVariable(); 6036 DIExpression *Expression = DI.getExpression(); 6037 dropDanglingDebugInfo(Variable, Expression); 6038 const Value *V = DI.getValue(); 6039 if (!V) 6040 return; 6041 6042 if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(), 6043 SDNodeOrder)) 6044 return; 6045 6046 // TODO: Dangling debug info will eventually either be resolved or produce 6047 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 6048 // between the original dbg.value location and its resolved DBG_VALUE, which 6049 // we should ideally fill with an extra Undef DBG_VALUE. 6050 6051 DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder); 6052 return; 6053 } 6054 6055 case Intrinsic::eh_typeid_for: { 6056 // Find the type id for the given typeinfo. 6057 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6058 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6059 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6060 setValue(&I, Res); 6061 return; 6062 } 6063 6064 case Intrinsic::eh_return_i32: 6065 case Intrinsic::eh_return_i64: 6066 DAG.getMachineFunction().setCallsEHReturn(true); 6067 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6068 MVT::Other, 6069 getControlRoot(), 6070 getValue(I.getArgOperand(0)), 6071 getValue(I.getArgOperand(1)))); 6072 return; 6073 case Intrinsic::eh_unwind_init: 6074 DAG.getMachineFunction().setCallsUnwindInit(true); 6075 return; 6076 case Intrinsic::eh_dwarf_cfa: 6077 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6078 TLI.getPointerTy(DAG.getDataLayout()), 6079 getValue(I.getArgOperand(0)))); 6080 return; 6081 case Intrinsic::eh_sjlj_callsite: { 6082 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6083 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 6084 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 6085 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6086 6087 MMI.setCurrentCallSite(CI->getZExtValue()); 6088 return; 6089 } 6090 case Intrinsic::eh_sjlj_functioncontext: { 6091 // Get and store the index of the function context. 6092 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6093 AllocaInst *FnCtx = 6094 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6095 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6096 MFI.setFunctionContextIndex(FI); 6097 return; 6098 } 6099 case Intrinsic::eh_sjlj_setjmp: { 6100 SDValue Ops[2]; 6101 Ops[0] = getRoot(); 6102 Ops[1] = getValue(I.getArgOperand(0)); 6103 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6104 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6105 setValue(&I, Op.getValue(0)); 6106 DAG.setRoot(Op.getValue(1)); 6107 return; 6108 } 6109 case Intrinsic::eh_sjlj_longjmp: 6110 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6111 getRoot(), getValue(I.getArgOperand(0)))); 6112 return; 6113 case Intrinsic::eh_sjlj_setup_dispatch: 6114 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6115 getRoot())); 6116 return; 6117 case Intrinsic::masked_gather: 6118 visitMaskedGather(I); 6119 return; 6120 case Intrinsic::masked_load: 6121 visitMaskedLoad(I); 6122 return; 6123 case Intrinsic::masked_scatter: 6124 visitMaskedScatter(I); 6125 return; 6126 case Intrinsic::masked_store: 6127 visitMaskedStore(I); 6128 return; 6129 case Intrinsic::masked_expandload: 6130 visitMaskedLoad(I, true /* IsExpanding */); 6131 return; 6132 case Intrinsic::masked_compressstore: 6133 visitMaskedStore(I, true /* IsCompressing */); 6134 return; 6135 case Intrinsic::powi: 6136 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6137 getValue(I.getArgOperand(1)), DAG)); 6138 return; 6139 case Intrinsic::log: 6140 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6141 return; 6142 case Intrinsic::log2: 6143 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6144 return; 6145 case Intrinsic::log10: 6146 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6147 return; 6148 case Intrinsic::exp: 6149 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6150 return; 6151 case Intrinsic::exp2: 6152 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6153 return; 6154 case Intrinsic::pow: 6155 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6156 getValue(I.getArgOperand(1)), DAG, TLI)); 6157 return; 6158 case Intrinsic::sqrt: 6159 case Intrinsic::fabs: 6160 case Intrinsic::sin: 6161 case Intrinsic::cos: 6162 case Intrinsic::floor: 6163 case Intrinsic::ceil: 6164 case Intrinsic::trunc: 6165 case Intrinsic::rint: 6166 case Intrinsic::nearbyint: 6167 case Intrinsic::round: 6168 case Intrinsic::canonicalize: { 6169 unsigned Opcode; 6170 switch (Intrinsic) { 6171 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6172 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6173 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6174 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6175 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6176 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6177 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6178 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6179 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6180 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6181 case Intrinsic::round: Opcode = ISD::FROUND; break; 6182 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6183 } 6184 6185 setValue(&I, DAG.getNode(Opcode, sdl, 6186 getValue(I.getArgOperand(0)).getValueType(), 6187 getValue(I.getArgOperand(0)))); 6188 return; 6189 } 6190 case Intrinsic::lround: 6191 case Intrinsic::llround: 6192 case Intrinsic::lrint: 6193 case Intrinsic::llrint: { 6194 unsigned Opcode; 6195 switch (Intrinsic) { 6196 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6197 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6198 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6199 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6200 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6201 } 6202 6203 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6204 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6205 getValue(I.getArgOperand(0)))); 6206 return; 6207 } 6208 case Intrinsic::minnum: 6209 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6210 getValue(I.getArgOperand(0)).getValueType(), 6211 getValue(I.getArgOperand(0)), 6212 getValue(I.getArgOperand(1)))); 6213 return; 6214 case Intrinsic::maxnum: 6215 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6216 getValue(I.getArgOperand(0)).getValueType(), 6217 getValue(I.getArgOperand(0)), 6218 getValue(I.getArgOperand(1)))); 6219 return; 6220 case Intrinsic::minimum: 6221 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6222 getValue(I.getArgOperand(0)).getValueType(), 6223 getValue(I.getArgOperand(0)), 6224 getValue(I.getArgOperand(1)))); 6225 return; 6226 case Intrinsic::maximum: 6227 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6228 getValue(I.getArgOperand(0)).getValueType(), 6229 getValue(I.getArgOperand(0)), 6230 getValue(I.getArgOperand(1)))); 6231 return; 6232 case Intrinsic::copysign: 6233 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6234 getValue(I.getArgOperand(0)).getValueType(), 6235 getValue(I.getArgOperand(0)), 6236 getValue(I.getArgOperand(1)))); 6237 return; 6238 case Intrinsic::fma: 6239 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6240 getValue(I.getArgOperand(0)).getValueType(), 6241 getValue(I.getArgOperand(0)), 6242 getValue(I.getArgOperand(1)), 6243 getValue(I.getArgOperand(2)))); 6244 return; 6245 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 6246 case Intrinsic::INTRINSIC: 6247 #include "llvm/IR/ConstrainedOps.def" 6248 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6249 return; 6250 case Intrinsic::fmuladd: { 6251 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6252 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6253 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6254 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6255 getValue(I.getArgOperand(0)).getValueType(), 6256 getValue(I.getArgOperand(0)), 6257 getValue(I.getArgOperand(1)), 6258 getValue(I.getArgOperand(2)))); 6259 } else { 6260 // TODO: Intrinsic calls should have fast-math-flags. 6261 SDValue Mul = DAG.getNode(ISD::FMUL, sdl, 6262 getValue(I.getArgOperand(0)).getValueType(), 6263 getValue(I.getArgOperand(0)), 6264 getValue(I.getArgOperand(1))); 6265 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6266 getValue(I.getArgOperand(0)).getValueType(), 6267 Mul, 6268 getValue(I.getArgOperand(2))); 6269 setValue(&I, Add); 6270 } 6271 return; 6272 } 6273 case Intrinsic::convert_to_fp16: 6274 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6275 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6276 getValue(I.getArgOperand(0)), 6277 DAG.getTargetConstant(0, sdl, 6278 MVT::i32)))); 6279 return; 6280 case Intrinsic::convert_from_fp16: 6281 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6282 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6283 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6284 getValue(I.getArgOperand(0))))); 6285 return; 6286 case Intrinsic::pcmarker: { 6287 SDValue Tmp = getValue(I.getArgOperand(0)); 6288 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6289 return; 6290 } 6291 case Intrinsic::readcyclecounter: { 6292 SDValue Op = getRoot(); 6293 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6294 DAG.getVTList(MVT::i64, MVT::Other), Op); 6295 setValue(&I, Res); 6296 DAG.setRoot(Res.getValue(1)); 6297 return; 6298 } 6299 case Intrinsic::bitreverse: 6300 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6301 getValue(I.getArgOperand(0)).getValueType(), 6302 getValue(I.getArgOperand(0)))); 6303 return; 6304 case Intrinsic::bswap: 6305 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6306 getValue(I.getArgOperand(0)).getValueType(), 6307 getValue(I.getArgOperand(0)))); 6308 return; 6309 case Intrinsic::cttz: { 6310 SDValue Arg = getValue(I.getArgOperand(0)); 6311 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6312 EVT Ty = Arg.getValueType(); 6313 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6314 sdl, Ty, Arg)); 6315 return; 6316 } 6317 case Intrinsic::ctlz: { 6318 SDValue Arg = getValue(I.getArgOperand(0)); 6319 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6320 EVT Ty = Arg.getValueType(); 6321 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6322 sdl, Ty, Arg)); 6323 return; 6324 } 6325 case Intrinsic::ctpop: { 6326 SDValue Arg = getValue(I.getArgOperand(0)); 6327 EVT Ty = Arg.getValueType(); 6328 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6329 return; 6330 } 6331 case Intrinsic::fshl: 6332 case Intrinsic::fshr: { 6333 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6334 SDValue X = getValue(I.getArgOperand(0)); 6335 SDValue Y = getValue(I.getArgOperand(1)); 6336 SDValue Z = getValue(I.getArgOperand(2)); 6337 EVT VT = X.getValueType(); 6338 SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT); 6339 SDValue Zero = DAG.getConstant(0, sdl, VT); 6340 SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC); 6341 6342 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6343 if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) { 6344 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6345 return; 6346 } 6347 6348 // When X == Y, this is rotate. If the data type has a power-of-2 size, we 6349 // avoid the select that is necessary in the general case to filter out 6350 // the 0-shift possibility that leads to UB. 6351 if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) { 6352 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6353 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 6354 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6355 return; 6356 } 6357 6358 // Some targets only rotate one way. Try the opposite direction. 6359 RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL; 6360 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 6361 // Negate the shift amount because it is safe to ignore the high bits. 6362 SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 6363 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt)); 6364 return; 6365 } 6366 6367 // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW)) 6368 // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW)) 6369 SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 6370 SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC); 6371 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt); 6372 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt); 6373 setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY)); 6374 return; 6375 } 6376 6377 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 6378 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 6379 SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt); 6380 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt); 6381 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt); 6382 SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY); 6383 6384 // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth, 6385 // and that is undefined. We must compare and select to avoid UB. 6386 EVT CCVT = MVT::i1; 6387 if (VT.isVector()) 6388 CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements()); 6389 6390 // For fshl, 0-shift returns the 1st arg (X). 6391 // For fshr, 0-shift returns the 2nd arg (Y). 6392 SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ); 6393 setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or)); 6394 return; 6395 } 6396 case Intrinsic::sadd_sat: { 6397 SDValue Op1 = getValue(I.getArgOperand(0)); 6398 SDValue Op2 = getValue(I.getArgOperand(1)); 6399 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6400 return; 6401 } 6402 case Intrinsic::uadd_sat: { 6403 SDValue Op1 = getValue(I.getArgOperand(0)); 6404 SDValue Op2 = getValue(I.getArgOperand(1)); 6405 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6406 return; 6407 } 6408 case Intrinsic::ssub_sat: { 6409 SDValue Op1 = getValue(I.getArgOperand(0)); 6410 SDValue Op2 = getValue(I.getArgOperand(1)); 6411 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6412 return; 6413 } 6414 case Intrinsic::usub_sat: { 6415 SDValue Op1 = getValue(I.getArgOperand(0)); 6416 SDValue Op2 = getValue(I.getArgOperand(1)); 6417 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6418 return; 6419 } 6420 case Intrinsic::smul_fix: 6421 case Intrinsic::umul_fix: 6422 case Intrinsic::smul_fix_sat: 6423 case Intrinsic::umul_fix_sat: { 6424 SDValue Op1 = getValue(I.getArgOperand(0)); 6425 SDValue Op2 = getValue(I.getArgOperand(1)); 6426 SDValue Op3 = getValue(I.getArgOperand(2)); 6427 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6428 Op1.getValueType(), Op1, Op2, Op3)); 6429 return; 6430 } 6431 case Intrinsic::sdiv_fix: 6432 case Intrinsic::udiv_fix: { 6433 SDValue Op1 = getValue(I.getArgOperand(0)); 6434 SDValue Op2 = getValue(I.getArgOperand(1)); 6435 SDValue Op3 = getValue(I.getArgOperand(2)); 6436 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6437 Op1, Op2, Op3, DAG, TLI)); 6438 return; 6439 } 6440 case Intrinsic::stacksave: { 6441 SDValue Op = getRoot(); 6442 Res = DAG.getNode( 6443 ISD::STACKSAVE, sdl, 6444 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op); 6445 setValue(&I, Res); 6446 DAG.setRoot(Res.getValue(1)); 6447 return; 6448 } 6449 case Intrinsic::stackrestore: 6450 Res = getValue(I.getArgOperand(0)); 6451 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6452 return; 6453 case Intrinsic::get_dynamic_area_offset: { 6454 SDValue Op = getRoot(); 6455 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6456 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6457 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6458 // target. 6459 if (PtrTy.getSizeInBits() < ResTy.getSizeInBits()) 6460 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6461 " intrinsic!"); 6462 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6463 Op); 6464 DAG.setRoot(Op); 6465 setValue(&I, Res); 6466 return; 6467 } 6468 case Intrinsic::stackguard: { 6469 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6470 MachineFunction &MF = DAG.getMachineFunction(); 6471 const Module &M = *MF.getFunction().getParent(); 6472 SDValue Chain = getRoot(); 6473 if (TLI.useLoadStackGuardNode()) { 6474 Res = getLoadStackGuard(DAG, sdl, Chain); 6475 } else { 6476 const Value *Global = TLI.getSDagStackGuard(M); 6477 unsigned Align = DL->getPrefTypeAlignment(Global->getType()); 6478 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6479 MachinePointerInfo(Global, 0), Align, 6480 MachineMemOperand::MOVolatile); 6481 } 6482 if (TLI.useStackGuardXorFP()) 6483 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6484 DAG.setRoot(Chain); 6485 setValue(&I, Res); 6486 return; 6487 } 6488 case Intrinsic::stackprotector: { 6489 // Emit code into the DAG to store the stack guard onto the stack. 6490 MachineFunction &MF = DAG.getMachineFunction(); 6491 MachineFrameInfo &MFI = MF.getFrameInfo(); 6492 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6493 SDValue Src, Chain = getRoot(); 6494 6495 if (TLI.useLoadStackGuardNode()) 6496 Src = getLoadStackGuard(DAG, sdl, Chain); 6497 else 6498 Src = getValue(I.getArgOperand(0)); // The guard's value. 6499 6500 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6501 6502 int FI = FuncInfo.StaticAllocaMap[Slot]; 6503 MFI.setStackProtectorIndex(FI); 6504 6505 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6506 6507 // Store the stack protector onto the stack. 6508 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack( 6509 DAG.getMachineFunction(), FI), 6510 /* Alignment = */ 0, MachineMemOperand::MOVolatile); 6511 setValue(&I, Res); 6512 DAG.setRoot(Res); 6513 return; 6514 } 6515 case Intrinsic::objectsize: 6516 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6517 6518 case Intrinsic::is_constant: 6519 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6520 6521 case Intrinsic::annotation: 6522 case Intrinsic::ptr_annotation: 6523 case Intrinsic::launder_invariant_group: 6524 case Intrinsic::strip_invariant_group: 6525 // Drop the intrinsic, but forward the value 6526 setValue(&I, getValue(I.getOperand(0))); 6527 return; 6528 case Intrinsic::assume: 6529 case Intrinsic::var_annotation: 6530 case Intrinsic::sideeffect: 6531 // Discard annotate attributes, assumptions, and artificial side-effects. 6532 return; 6533 6534 case Intrinsic::codeview_annotation: { 6535 // Emit a label associated with this metadata. 6536 MachineFunction &MF = DAG.getMachineFunction(); 6537 MCSymbol *Label = 6538 MF.getMMI().getContext().createTempSymbol("annotation", true); 6539 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6540 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6541 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6542 DAG.setRoot(Res); 6543 return; 6544 } 6545 6546 case Intrinsic::init_trampoline: { 6547 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6548 6549 SDValue Ops[6]; 6550 Ops[0] = getRoot(); 6551 Ops[1] = getValue(I.getArgOperand(0)); 6552 Ops[2] = getValue(I.getArgOperand(1)); 6553 Ops[3] = getValue(I.getArgOperand(2)); 6554 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6555 Ops[5] = DAG.getSrcValue(F); 6556 6557 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6558 6559 DAG.setRoot(Res); 6560 return; 6561 } 6562 case Intrinsic::adjust_trampoline: 6563 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6564 TLI.getPointerTy(DAG.getDataLayout()), 6565 getValue(I.getArgOperand(0)))); 6566 return; 6567 case Intrinsic::gcroot: { 6568 assert(DAG.getMachineFunction().getFunction().hasGC() && 6569 "only valid in functions with gc specified, enforced by Verifier"); 6570 assert(GFI && "implied by previous"); 6571 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6572 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6573 6574 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6575 GFI->addStackRoot(FI->getIndex(), TypeMap); 6576 return; 6577 } 6578 case Intrinsic::gcread: 6579 case Intrinsic::gcwrite: 6580 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6581 case Intrinsic::flt_rounds: 6582 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32)); 6583 return; 6584 6585 case Intrinsic::expect: 6586 // Just replace __builtin_expect(exp, c) with EXP. 6587 setValue(&I, getValue(I.getArgOperand(0))); 6588 return; 6589 6590 case Intrinsic::debugtrap: 6591 case Intrinsic::trap: { 6592 StringRef TrapFuncName = 6593 I.getAttributes() 6594 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6595 .getValueAsString(); 6596 if (TrapFuncName.empty()) { 6597 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 6598 ISD::TRAP : ISD::DEBUGTRAP; 6599 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 6600 return; 6601 } 6602 TargetLowering::ArgListTy Args; 6603 6604 TargetLowering::CallLoweringInfo CLI(DAG); 6605 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6606 CallingConv::C, I.getType(), 6607 DAG.getExternalSymbol(TrapFuncName.data(), 6608 TLI.getPointerTy(DAG.getDataLayout())), 6609 std::move(Args)); 6610 6611 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6612 DAG.setRoot(Result.second); 6613 return; 6614 } 6615 6616 case Intrinsic::uadd_with_overflow: 6617 case Intrinsic::sadd_with_overflow: 6618 case Intrinsic::usub_with_overflow: 6619 case Intrinsic::ssub_with_overflow: 6620 case Intrinsic::umul_with_overflow: 6621 case Intrinsic::smul_with_overflow: { 6622 ISD::NodeType Op; 6623 switch (Intrinsic) { 6624 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6625 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6626 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6627 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6628 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6629 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6630 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6631 } 6632 SDValue Op1 = getValue(I.getArgOperand(0)); 6633 SDValue Op2 = getValue(I.getArgOperand(1)); 6634 6635 EVT ResultVT = Op1.getValueType(); 6636 EVT OverflowVT = MVT::i1; 6637 if (ResultVT.isVector()) 6638 OverflowVT = EVT::getVectorVT( 6639 *Context, OverflowVT, ResultVT.getVectorNumElements()); 6640 6641 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6642 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6643 return; 6644 } 6645 case Intrinsic::prefetch: { 6646 SDValue Ops[5]; 6647 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6648 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6649 Ops[0] = DAG.getRoot(); 6650 Ops[1] = getValue(I.getArgOperand(0)); 6651 Ops[2] = getValue(I.getArgOperand(1)); 6652 Ops[3] = getValue(I.getArgOperand(2)); 6653 Ops[4] = getValue(I.getArgOperand(3)); 6654 SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl, 6655 DAG.getVTList(MVT::Other), Ops, 6656 EVT::getIntegerVT(*Context, 8), 6657 MachinePointerInfo(I.getArgOperand(0)), 6658 0, /* align */ 6659 Flags); 6660 6661 // Chain the prefetch in parallell with any pending loads, to stay out of 6662 // the way of later optimizations. 6663 PendingLoads.push_back(Result); 6664 Result = getRoot(); 6665 DAG.setRoot(Result); 6666 return; 6667 } 6668 case Intrinsic::lifetime_start: 6669 case Intrinsic::lifetime_end: { 6670 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6671 // Stack coloring is not enabled in O0, discard region information. 6672 if (TM.getOptLevel() == CodeGenOpt::None) 6673 return; 6674 6675 const int64_t ObjectSize = 6676 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6677 Value *const ObjectPtr = I.getArgOperand(1); 6678 SmallVector<const Value *, 4> Allocas; 6679 GetUnderlyingObjects(ObjectPtr, Allocas, *DL); 6680 6681 for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(), 6682 E = Allocas.end(); Object != E; ++Object) { 6683 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 6684 6685 // Could not find an Alloca. 6686 if (!LifetimeObject) 6687 continue; 6688 6689 // First check that the Alloca is static, otherwise it won't have a 6690 // valid frame index. 6691 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6692 if (SI == FuncInfo.StaticAllocaMap.end()) 6693 return; 6694 6695 const int FrameIndex = SI->second; 6696 int64_t Offset; 6697 if (GetPointerBaseWithConstantOffset( 6698 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6699 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6700 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6701 Offset); 6702 DAG.setRoot(Res); 6703 } 6704 return; 6705 } 6706 case Intrinsic::invariant_start: 6707 // Discard region information. 6708 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6709 return; 6710 case Intrinsic::invariant_end: 6711 // Discard region information. 6712 return; 6713 case Intrinsic::clear_cache: 6714 /// FunctionName may be null. 6715 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6716 lowerCallToExternalSymbol(I, FunctionName); 6717 return; 6718 case Intrinsic::donothing: 6719 // ignore 6720 return; 6721 case Intrinsic::experimental_stackmap: 6722 visitStackmap(I); 6723 return; 6724 case Intrinsic::experimental_patchpoint_void: 6725 case Intrinsic::experimental_patchpoint_i64: 6726 visitPatchpoint(&I); 6727 return; 6728 case Intrinsic::experimental_gc_statepoint: 6729 LowerStatepoint(ImmutableStatepoint(&I)); 6730 return; 6731 case Intrinsic::experimental_gc_result: 6732 visitGCResult(cast<GCResultInst>(I)); 6733 return; 6734 case Intrinsic::experimental_gc_relocate: 6735 visitGCRelocate(cast<GCRelocateInst>(I)); 6736 return; 6737 case Intrinsic::instrprof_increment: 6738 llvm_unreachable("instrprof failed to lower an increment"); 6739 case Intrinsic::instrprof_value_profile: 6740 llvm_unreachable("instrprof failed to lower a value profiling call"); 6741 case Intrinsic::localescape: { 6742 MachineFunction &MF = DAG.getMachineFunction(); 6743 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6744 6745 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6746 // is the same on all targets. 6747 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6748 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6749 if (isa<ConstantPointerNull>(Arg)) 6750 continue; // Skip null pointers. They represent a hole in index space. 6751 AllocaInst *Slot = cast<AllocaInst>(Arg); 6752 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6753 "can only escape static allocas"); 6754 int FI = FuncInfo.StaticAllocaMap[Slot]; 6755 MCSymbol *FrameAllocSym = 6756 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6757 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6758 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6759 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6760 .addSym(FrameAllocSym) 6761 .addFrameIndex(FI); 6762 } 6763 6764 return; 6765 } 6766 6767 case Intrinsic::localrecover: { 6768 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6769 MachineFunction &MF = DAG.getMachineFunction(); 6770 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0); 6771 6772 // Get the symbol that defines the frame offset. 6773 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6774 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6775 unsigned IdxVal = 6776 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6777 MCSymbol *FrameAllocSym = 6778 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6779 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6780 6781 // Create a MCSymbol for the label to avoid any target lowering 6782 // that would make this PC relative. 6783 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6784 SDValue OffsetVal = 6785 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6786 6787 // Add the offset to the FP. 6788 Value *FP = I.getArgOperand(1); 6789 SDValue FPVal = getValue(FP); 6790 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 6791 setValue(&I, Add); 6792 6793 return; 6794 } 6795 6796 case Intrinsic::eh_exceptionpointer: 6797 case Intrinsic::eh_exceptioncode: { 6798 // Get the exception pointer vreg, copy from it, and resize it to fit. 6799 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6800 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6801 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6802 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6803 SDValue N = 6804 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6805 if (Intrinsic == Intrinsic::eh_exceptioncode) 6806 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6807 setValue(&I, N); 6808 return; 6809 } 6810 case Intrinsic::xray_customevent: { 6811 // Here we want to make sure that the intrinsic behaves as if it has a 6812 // specific calling convention, and only for x86_64. 6813 // FIXME: Support other platforms later. 6814 const auto &Triple = DAG.getTarget().getTargetTriple(); 6815 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6816 return; 6817 6818 SDLoc DL = getCurSDLoc(); 6819 SmallVector<SDValue, 8> Ops; 6820 6821 // We want to say that we always want the arguments in registers. 6822 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6823 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6824 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6825 SDValue Chain = getRoot(); 6826 Ops.push_back(LogEntryVal); 6827 Ops.push_back(StrSizeVal); 6828 Ops.push_back(Chain); 6829 6830 // We need to enforce the calling convention for the callsite, so that 6831 // argument ordering is enforced correctly, and that register allocation can 6832 // see that some registers may be assumed clobbered and have to preserve 6833 // them across calls to the intrinsic. 6834 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6835 DL, NodeTys, Ops); 6836 SDValue patchableNode = SDValue(MN, 0); 6837 DAG.setRoot(patchableNode); 6838 setValue(&I, patchableNode); 6839 return; 6840 } 6841 case Intrinsic::xray_typedevent: { 6842 // Here we want to make sure that the intrinsic behaves as if it has a 6843 // specific calling convention, and only for x86_64. 6844 // FIXME: Support other platforms later. 6845 const auto &Triple = DAG.getTarget().getTargetTriple(); 6846 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6847 return; 6848 6849 SDLoc DL = getCurSDLoc(); 6850 SmallVector<SDValue, 8> Ops; 6851 6852 // We want to say that we always want the arguments in registers. 6853 // It's unclear to me how manipulating the selection DAG here forces callers 6854 // to provide arguments in registers instead of on the stack. 6855 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6856 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6857 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6858 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6859 SDValue Chain = getRoot(); 6860 Ops.push_back(LogTypeId); 6861 Ops.push_back(LogEntryVal); 6862 Ops.push_back(StrSizeVal); 6863 Ops.push_back(Chain); 6864 6865 // We need to enforce the calling convention for the callsite, so that 6866 // argument ordering is enforced correctly, and that register allocation can 6867 // see that some registers may be assumed clobbered and have to preserve 6868 // them across calls to the intrinsic. 6869 MachineSDNode *MN = DAG.getMachineNode( 6870 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6871 SDValue patchableNode = SDValue(MN, 0); 6872 DAG.setRoot(patchableNode); 6873 setValue(&I, patchableNode); 6874 return; 6875 } 6876 case Intrinsic::experimental_deoptimize: 6877 LowerDeoptimizeCall(&I); 6878 return; 6879 6880 case Intrinsic::experimental_vector_reduce_v2_fadd: 6881 case Intrinsic::experimental_vector_reduce_v2_fmul: 6882 case Intrinsic::experimental_vector_reduce_add: 6883 case Intrinsic::experimental_vector_reduce_mul: 6884 case Intrinsic::experimental_vector_reduce_and: 6885 case Intrinsic::experimental_vector_reduce_or: 6886 case Intrinsic::experimental_vector_reduce_xor: 6887 case Intrinsic::experimental_vector_reduce_smax: 6888 case Intrinsic::experimental_vector_reduce_smin: 6889 case Intrinsic::experimental_vector_reduce_umax: 6890 case Intrinsic::experimental_vector_reduce_umin: 6891 case Intrinsic::experimental_vector_reduce_fmax: 6892 case Intrinsic::experimental_vector_reduce_fmin: 6893 visitVectorReduce(I, Intrinsic); 6894 return; 6895 6896 case Intrinsic::icall_branch_funnel: { 6897 SmallVector<SDValue, 16> Ops; 6898 Ops.push_back(getValue(I.getArgOperand(0))); 6899 6900 int64_t Offset; 6901 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6902 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6903 if (!Base) 6904 report_fatal_error( 6905 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6906 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6907 6908 struct BranchFunnelTarget { 6909 int64_t Offset; 6910 SDValue Target; 6911 }; 6912 SmallVector<BranchFunnelTarget, 8> Targets; 6913 6914 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6915 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6916 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6917 if (ElemBase != Base) 6918 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6919 "to the same GlobalValue"); 6920 6921 SDValue Val = getValue(I.getArgOperand(Op + 1)); 6922 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 6923 if (!GA) 6924 report_fatal_error( 6925 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6926 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 6927 GA->getGlobal(), getCurSDLoc(), 6928 Val.getValueType(), GA->getOffset())}); 6929 } 6930 llvm::sort(Targets, 6931 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 6932 return T1.Offset < T2.Offset; 6933 }); 6934 6935 for (auto &T : Targets) { 6936 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 6937 Ops.push_back(T.Target); 6938 } 6939 6940 Ops.push_back(DAG.getRoot()); // Chain 6941 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 6942 getCurSDLoc(), MVT::Other, Ops), 6943 0); 6944 DAG.setRoot(N); 6945 setValue(&I, N); 6946 HasTailCall = true; 6947 return; 6948 } 6949 6950 case Intrinsic::wasm_landingpad_index: 6951 // Information this intrinsic contained has been transferred to 6952 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 6953 // delete it now. 6954 return; 6955 6956 case Intrinsic::aarch64_settag: 6957 case Intrinsic::aarch64_settag_zero: { 6958 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6959 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 6960 SDValue Val = TSI.EmitTargetCodeForSetTag( 6961 DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)), 6962 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 6963 ZeroMemory); 6964 DAG.setRoot(Val); 6965 setValue(&I, Val); 6966 return; 6967 } 6968 case Intrinsic::ptrmask: { 6969 SDValue Ptr = getValue(I.getOperand(0)); 6970 SDValue Const = getValue(I.getOperand(1)); 6971 6972 EVT DestVT = 6973 EVT(DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 6974 6975 setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), DestVT, Ptr, 6976 DAG.getZExtOrTrunc(Const, getCurSDLoc(), DestVT))); 6977 return; 6978 } 6979 } 6980 } 6981 6982 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 6983 const ConstrainedFPIntrinsic &FPI) { 6984 SDLoc sdl = getCurSDLoc(); 6985 6986 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6987 SmallVector<EVT, 4> ValueVTs; 6988 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 6989 ValueVTs.push_back(MVT::Other); // Out chain 6990 6991 // We do not need to serialize constrained FP intrinsics against 6992 // each other or against (nonvolatile) loads, so they can be 6993 // chained like loads. 6994 SDValue Chain = DAG.getRoot(); 6995 SmallVector<SDValue, 4> Opers; 6996 Opers.push_back(Chain); 6997 if (FPI.isUnaryOp()) { 6998 Opers.push_back(getValue(FPI.getArgOperand(0))); 6999 } else if (FPI.isTernaryOp()) { 7000 Opers.push_back(getValue(FPI.getArgOperand(0))); 7001 Opers.push_back(getValue(FPI.getArgOperand(1))); 7002 Opers.push_back(getValue(FPI.getArgOperand(2))); 7003 } else { 7004 Opers.push_back(getValue(FPI.getArgOperand(0))); 7005 Opers.push_back(getValue(FPI.getArgOperand(1))); 7006 } 7007 7008 unsigned Opcode; 7009 switch (FPI.getIntrinsicID()) { 7010 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7011 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7012 case Intrinsic::INTRINSIC: \ 7013 Opcode = ISD::STRICT_##DAGN; \ 7014 break; 7015 #include "llvm/IR/ConstrainedOps.def" 7016 } 7017 7018 // A few strict DAG nodes carry additional operands that are not 7019 // set up by the default code above. 7020 switch (Opcode) { 7021 default: break; 7022 case ISD::STRICT_FP_ROUND: 7023 Opers.push_back( 7024 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7025 break; 7026 case ISD::STRICT_FSETCC: 7027 case ISD::STRICT_FSETCCS: { 7028 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7029 Opers.push_back(DAG.getCondCode(getFCmpCondCode(FPCmp->getPredicate()))); 7030 break; 7031 } 7032 } 7033 7034 SDVTList VTs = DAG.getVTList(ValueVTs); 7035 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers); 7036 7037 assert(Result.getNode()->getNumValues() == 2); 7038 7039 // Push node to the appropriate list so that future instructions can be 7040 // chained up correctly. 7041 SDValue OutChain = Result.getValue(1); 7042 switch (FPI.getExceptionBehavior().getValue()) { 7043 case fp::ExceptionBehavior::ebIgnore: 7044 // The only reason why ebIgnore nodes still need to be chained is that 7045 // they might depend on the current rounding mode, and therefore must 7046 // not be moved across instruction that may change that mode. 7047 LLVM_FALLTHROUGH; 7048 case fp::ExceptionBehavior::ebMayTrap: 7049 // These must not be moved across calls or instructions that may change 7050 // floating-point exception masks. 7051 PendingConstrainedFP.push_back(OutChain); 7052 break; 7053 case fp::ExceptionBehavior::ebStrict: 7054 // These must not be moved across calls or instructions that may change 7055 // floating-point exception masks or read floating-point exception flags. 7056 // In addition, they cannot be optimized out even if unused. 7057 PendingConstrainedFPStrict.push_back(OutChain); 7058 break; 7059 } 7060 7061 SDValue FPResult = Result.getValue(0); 7062 setValue(&FPI, FPResult); 7063 } 7064 7065 std::pair<SDValue, SDValue> 7066 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7067 const BasicBlock *EHPadBB) { 7068 MachineFunction &MF = DAG.getMachineFunction(); 7069 MachineModuleInfo &MMI = MF.getMMI(); 7070 MCSymbol *BeginLabel = nullptr; 7071 7072 if (EHPadBB) { 7073 // Insert a label before the invoke call to mark the try range. This can be 7074 // used to detect deletion of the invoke via the MachineModuleInfo. 7075 BeginLabel = MMI.getContext().createTempSymbol(); 7076 7077 // For SjLj, keep track of which landing pads go with which invokes 7078 // so as to maintain the ordering of pads in the LSDA. 7079 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7080 if (CallSiteIndex) { 7081 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7082 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7083 7084 // Now that the call site is handled, stop tracking it. 7085 MMI.setCurrentCallSite(0); 7086 } 7087 7088 // Both PendingLoads and PendingExports must be flushed here; 7089 // this call might not return. 7090 (void)getRoot(); 7091 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 7092 7093 CLI.setChain(getRoot()); 7094 } 7095 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7096 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7097 7098 assert((CLI.IsTailCall || Result.second.getNode()) && 7099 "Non-null chain expected with non-tail call!"); 7100 assert((Result.second.getNode() || !Result.first.getNode()) && 7101 "Null value expected with tail call!"); 7102 7103 if (!Result.second.getNode()) { 7104 // As a special case, a null chain means that a tail call has been emitted 7105 // and the DAG root is already updated. 7106 HasTailCall = true; 7107 7108 // Since there's no actual continuation from this block, nothing can be 7109 // relying on us setting vregs for them. 7110 PendingExports.clear(); 7111 } else { 7112 DAG.setRoot(Result.second); 7113 } 7114 7115 if (EHPadBB) { 7116 // Insert a label at the end of the invoke call to mark the try range. This 7117 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7118 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7119 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 7120 7121 // Inform MachineModuleInfo of range. 7122 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7123 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7124 // actually use outlined funclets and their LSDA info style. 7125 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7126 assert(CLI.CS); 7127 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 7128 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()), 7129 BeginLabel, EndLabel); 7130 } else if (!isScopedEHPersonality(Pers)) { 7131 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7132 } 7133 } 7134 7135 return Result; 7136 } 7137 7138 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee, 7139 bool isTailCall, 7140 const BasicBlock *EHPadBB) { 7141 auto &DL = DAG.getDataLayout(); 7142 FunctionType *FTy = CS.getFunctionType(); 7143 Type *RetTy = CS.getType(); 7144 7145 TargetLowering::ArgListTy Args; 7146 Args.reserve(CS.arg_size()); 7147 7148 const Value *SwiftErrorVal = nullptr; 7149 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7150 7151 if (isTailCall) { 7152 // Avoid emitting tail calls in functions with the disable-tail-calls 7153 // attribute. 7154 auto *Caller = CS.getInstruction()->getParent()->getParent(); 7155 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7156 "true") 7157 isTailCall = false; 7158 7159 // We can't tail call inside a function with a swifterror argument. Lowering 7160 // does not support this yet. It would have to move into the swifterror 7161 // register before the call. 7162 if (TLI.supportSwiftError() && 7163 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7164 isTailCall = false; 7165 } 7166 7167 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 7168 i != e; ++i) { 7169 TargetLowering::ArgListEntry Entry; 7170 const Value *V = *i; 7171 7172 // Skip empty types 7173 if (V->getType()->isEmptyTy()) 7174 continue; 7175 7176 SDValue ArgNode = getValue(V); 7177 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7178 7179 Entry.setAttributes(&CS, i - CS.arg_begin()); 7180 7181 // Use swifterror virtual register as input to the call. 7182 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7183 SwiftErrorVal = V; 7184 // We find the virtual register for the actual swifterror argument. 7185 // Instead of using the Value, we use the virtual register instead. 7186 Entry.Node = DAG.getRegister( 7187 SwiftError.getOrCreateVRegUseAt(CS.getInstruction(), FuncInfo.MBB, V), 7188 EVT(TLI.getPointerTy(DL))); 7189 } 7190 7191 Args.push_back(Entry); 7192 7193 // If we have an explicit sret argument that is an Instruction, (i.e., it 7194 // might point to function-local memory), we can't meaningfully tail-call. 7195 if (Entry.IsSRet && isa<Instruction>(V)) 7196 isTailCall = false; 7197 } 7198 7199 // If call site has a cfguardtarget operand bundle, create and add an 7200 // additional ArgListEntry. 7201 if (auto Bundle = CS.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7202 TargetLowering::ArgListEntry Entry; 7203 Value *V = Bundle->Inputs[0]; 7204 SDValue ArgNode = getValue(V); 7205 Entry.Node = ArgNode; 7206 Entry.Ty = V->getType(); 7207 Entry.IsCFGuardTarget = true; 7208 Args.push_back(Entry); 7209 } 7210 7211 // Check if target-independent constraints permit a tail call here. 7212 // Target-dependent constraints are checked within TLI->LowerCallTo. 7213 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget())) 7214 isTailCall = false; 7215 7216 // Disable tail calls if there is an swifterror argument. Targets have not 7217 // been updated to support tail calls. 7218 if (TLI.supportSwiftError() && SwiftErrorVal) 7219 isTailCall = false; 7220 7221 TargetLowering::CallLoweringInfo CLI(DAG); 7222 CLI.setDebugLoc(getCurSDLoc()) 7223 .setChain(getRoot()) 7224 .setCallee(RetTy, FTy, Callee, std::move(Args), CS) 7225 .setTailCall(isTailCall) 7226 .setConvergent(CS.isConvergent()); 7227 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7228 7229 if (Result.first.getNode()) { 7230 const Instruction *Inst = CS.getInstruction(); 7231 Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first); 7232 setValue(Inst, Result.first); 7233 } 7234 7235 // The last element of CLI.InVals has the SDValue for swifterror return. 7236 // Here we copy it to a virtual register and update SwiftErrorMap for 7237 // book-keeping. 7238 if (SwiftErrorVal && TLI.supportSwiftError()) { 7239 // Get the last element of InVals. 7240 SDValue Src = CLI.InVals.back(); 7241 Register VReg = SwiftError.getOrCreateVRegDefAt( 7242 CS.getInstruction(), FuncInfo.MBB, SwiftErrorVal); 7243 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7244 DAG.setRoot(CopyNode); 7245 } 7246 } 7247 7248 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7249 SelectionDAGBuilder &Builder) { 7250 // Check to see if this load can be trivially constant folded, e.g. if the 7251 // input is from a string literal. 7252 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7253 // Cast pointer to the type we really want to load. 7254 Type *LoadTy = 7255 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7256 if (LoadVT.isVector()) 7257 LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7258 7259 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7260 PointerType::getUnqual(LoadTy)); 7261 7262 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 7263 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 7264 return Builder.getValue(LoadCst); 7265 } 7266 7267 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7268 // still constant memory, the input chain can be the entry node. 7269 SDValue Root; 7270 bool ConstantMemory = false; 7271 7272 // Do not serialize (non-volatile) loads of constant memory with anything. 7273 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7274 Root = Builder.DAG.getEntryNode(); 7275 ConstantMemory = true; 7276 } else { 7277 // Do not serialize non-volatile loads against each other. 7278 Root = Builder.DAG.getRoot(); 7279 } 7280 7281 SDValue Ptr = Builder.getValue(PtrVal); 7282 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, 7283 Ptr, MachinePointerInfo(PtrVal), 7284 /* Alignment = */ 1); 7285 7286 if (!ConstantMemory) 7287 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7288 return LoadVal; 7289 } 7290 7291 /// Record the value for an instruction that produces an integer result, 7292 /// converting the type where necessary. 7293 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7294 SDValue Value, 7295 bool IsSigned) { 7296 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7297 I.getType(), true); 7298 if (IsSigned) 7299 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7300 else 7301 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7302 setValue(&I, Value); 7303 } 7304 7305 /// See if we can lower a memcmp call into an optimized form. If so, return 7306 /// true and lower it. Otherwise return false, and it will be lowered like a 7307 /// normal call. 7308 /// The caller already checked that \p I calls the appropriate LibFunc with a 7309 /// correct prototype. 7310 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 7311 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 7312 const Value *Size = I.getArgOperand(2); 7313 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 7314 if (CSize && CSize->getZExtValue() == 0) { 7315 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7316 I.getType(), true); 7317 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 7318 return true; 7319 } 7320 7321 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7322 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 7323 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 7324 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 7325 if (Res.first.getNode()) { 7326 processIntegerCallValue(I, Res.first, true); 7327 PendingLoads.push_back(Res.second); 7328 return true; 7329 } 7330 7331 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 7332 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 7333 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 7334 return false; 7335 7336 // If the target has a fast compare for the given size, it will return a 7337 // preferred load type for that size. Require that the load VT is legal and 7338 // that the target supports unaligned loads of that type. Otherwise, return 7339 // INVALID. 7340 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 7341 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7342 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 7343 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 7344 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 7345 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 7346 // TODO: Check alignment of src and dest ptrs. 7347 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 7348 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 7349 if (!TLI.isTypeLegal(LVT) || 7350 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 7351 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 7352 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 7353 } 7354 7355 return LVT; 7356 }; 7357 7358 // This turns into unaligned loads. We only do this if the target natively 7359 // supports the MVT we'll be loading or if it is small enough (<= 4) that 7360 // we'll only produce a small number of byte loads. 7361 MVT LoadVT; 7362 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 7363 switch (NumBitsToCompare) { 7364 default: 7365 return false; 7366 case 16: 7367 LoadVT = MVT::i16; 7368 break; 7369 case 32: 7370 LoadVT = MVT::i32; 7371 break; 7372 case 64: 7373 case 128: 7374 case 256: 7375 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 7376 break; 7377 } 7378 7379 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 7380 return false; 7381 7382 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 7383 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 7384 7385 // Bitcast to a wide integer type if the loads are vectors. 7386 if (LoadVT.isVector()) { 7387 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 7388 LoadL = DAG.getBitcast(CmpVT, LoadL); 7389 LoadR = DAG.getBitcast(CmpVT, LoadR); 7390 } 7391 7392 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 7393 processIntegerCallValue(I, Cmp, false); 7394 return true; 7395 } 7396 7397 /// See if we can lower a memchr call into an optimized form. If so, return 7398 /// true and lower it. Otherwise return false, and it will be lowered like a 7399 /// normal call. 7400 /// The caller already checked that \p I calls the appropriate LibFunc with a 7401 /// correct prototype. 7402 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 7403 const Value *Src = I.getArgOperand(0); 7404 const Value *Char = I.getArgOperand(1); 7405 const Value *Length = I.getArgOperand(2); 7406 7407 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7408 std::pair<SDValue, SDValue> Res = 7409 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 7410 getValue(Src), getValue(Char), getValue(Length), 7411 MachinePointerInfo(Src)); 7412 if (Res.first.getNode()) { 7413 setValue(&I, Res.first); 7414 PendingLoads.push_back(Res.second); 7415 return true; 7416 } 7417 7418 return false; 7419 } 7420 7421 /// See if we can lower a mempcpy call into an optimized form. If so, return 7422 /// true and lower it. Otherwise return false, and it will be lowered like a 7423 /// normal call. 7424 /// The caller already checked that \p I calls the appropriate LibFunc with a 7425 /// correct prototype. 7426 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 7427 SDValue Dst = getValue(I.getArgOperand(0)); 7428 SDValue Src = getValue(I.getArgOperand(1)); 7429 SDValue Size = getValue(I.getArgOperand(2)); 7430 7431 unsigned DstAlign = DAG.InferPtrAlignment(Dst); 7432 unsigned SrcAlign = DAG.InferPtrAlignment(Src); 7433 unsigned Align = std::min(DstAlign, SrcAlign); 7434 if (Align == 0) // Alignment of one or both could not be inferred. 7435 Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved. 7436 7437 bool isVol = false; 7438 SDLoc sdl = getCurSDLoc(); 7439 7440 // In the mempcpy context we need to pass in a false value for isTailCall 7441 // because the return pointer needs to be adjusted by the size of 7442 // the copied memory. 7443 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 7444 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Align, isVol, 7445 false, /*isTailCall=*/false, 7446 MachinePointerInfo(I.getArgOperand(0)), 7447 MachinePointerInfo(I.getArgOperand(1))); 7448 assert(MC.getNode() != nullptr && 7449 "** memcpy should not be lowered as TailCall in mempcpy context **"); 7450 DAG.setRoot(MC); 7451 7452 // Check if Size needs to be truncated or extended. 7453 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 7454 7455 // Adjust return pointer to point just past the last dst byte. 7456 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 7457 Dst, Size); 7458 setValue(&I, DstPlusSize); 7459 return true; 7460 } 7461 7462 /// See if we can lower a strcpy call into an optimized form. If so, return 7463 /// true and lower it, otherwise return false and it will be lowered like a 7464 /// normal call. 7465 /// The caller already checked that \p I calls the appropriate LibFunc with a 7466 /// correct prototype. 7467 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 7468 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7469 7470 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7471 std::pair<SDValue, SDValue> Res = 7472 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 7473 getValue(Arg0), getValue(Arg1), 7474 MachinePointerInfo(Arg0), 7475 MachinePointerInfo(Arg1), isStpcpy); 7476 if (Res.first.getNode()) { 7477 setValue(&I, Res.first); 7478 DAG.setRoot(Res.second); 7479 return true; 7480 } 7481 7482 return false; 7483 } 7484 7485 /// See if we can lower a strcmp call into an optimized form. If so, return 7486 /// true and lower it, otherwise return false and it will be lowered like a 7487 /// normal call. 7488 /// The caller already checked that \p I calls the appropriate LibFunc with a 7489 /// correct prototype. 7490 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 7491 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7492 7493 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7494 std::pair<SDValue, SDValue> Res = 7495 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 7496 getValue(Arg0), getValue(Arg1), 7497 MachinePointerInfo(Arg0), 7498 MachinePointerInfo(Arg1)); 7499 if (Res.first.getNode()) { 7500 processIntegerCallValue(I, Res.first, true); 7501 PendingLoads.push_back(Res.second); 7502 return true; 7503 } 7504 7505 return false; 7506 } 7507 7508 /// See if we can lower a strlen call into an optimized form. If so, return 7509 /// true and lower it, otherwise return false and it will be lowered like a 7510 /// normal call. 7511 /// The caller already checked that \p I calls the appropriate LibFunc with a 7512 /// correct prototype. 7513 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 7514 const Value *Arg0 = I.getArgOperand(0); 7515 7516 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7517 std::pair<SDValue, SDValue> Res = 7518 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 7519 getValue(Arg0), MachinePointerInfo(Arg0)); 7520 if (Res.first.getNode()) { 7521 processIntegerCallValue(I, Res.first, false); 7522 PendingLoads.push_back(Res.second); 7523 return true; 7524 } 7525 7526 return false; 7527 } 7528 7529 /// See if we can lower a strnlen call into an optimized form. If so, return 7530 /// true and lower it, otherwise return false and it will be lowered like a 7531 /// normal call. 7532 /// The caller already checked that \p I calls the appropriate LibFunc with a 7533 /// correct prototype. 7534 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 7535 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7536 7537 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7538 std::pair<SDValue, SDValue> Res = 7539 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 7540 getValue(Arg0), getValue(Arg1), 7541 MachinePointerInfo(Arg0)); 7542 if (Res.first.getNode()) { 7543 processIntegerCallValue(I, Res.first, false); 7544 PendingLoads.push_back(Res.second); 7545 return true; 7546 } 7547 7548 return false; 7549 } 7550 7551 /// See if we can lower a unary floating-point operation into an SDNode with 7552 /// the specified Opcode. If so, return true and lower it, otherwise return 7553 /// false and it will be lowered like a normal call. 7554 /// The caller already checked that \p I calls the appropriate LibFunc with a 7555 /// correct prototype. 7556 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 7557 unsigned Opcode) { 7558 // We already checked this call's prototype; verify it doesn't modify errno. 7559 if (!I.onlyReadsMemory()) 7560 return false; 7561 7562 SDValue Tmp = getValue(I.getArgOperand(0)); 7563 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); 7564 return true; 7565 } 7566 7567 /// See if we can lower a binary floating-point operation into an SDNode with 7568 /// the specified Opcode. If so, return true and lower it. Otherwise return 7569 /// false, and it will be lowered like a normal call. 7570 /// The caller already checked that \p I calls the appropriate LibFunc with a 7571 /// correct prototype. 7572 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 7573 unsigned Opcode) { 7574 // We already checked this call's prototype; verify it doesn't modify errno. 7575 if (!I.onlyReadsMemory()) 7576 return false; 7577 7578 SDValue Tmp0 = getValue(I.getArgOperand(0)); 7579 SDValue Tmp1 = getValue(I.getArgOperand(1)); 7580 EVT VT = Tmp0.getValueType(); 7581 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1)); 7582 return true; 7583 } 7584 7585 void SelectionDAGBuilder::visitCall(const CallInst &I) { 7586 // Handle inline assembly differently. 7587 if (isa<InlineAsm>(I.getCalledValue())) { 7588 visitInlineAsm(&I); 7589 return; 7590 } 7591 7592 if (Function *F = I.getCalledFunction()) { 7593 if (F->isDeclaration()) { 7594 // Is this an LLVM intrinsic or a target-specific intrinsic? 7595 unsigned IID = F->getIntrinsicID(); 7596 if (!IID) 7597 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7598 IID = II->getIntrinsicID(F); 7599 7600 if (IID) { 7601 visitIntrinsicCall(I, IID); 7602 return; 7603 } 7604 } 7605 7606 // Check for well-known libc/libm calls. If the function is internal, it 7607 // can't be a library call. Don't do the check if marked as nobuiltin for 7608 // some reason or the call site requires strict floating point semantics. 7609 LibFunc Func; 7610 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7611 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7612 LibInfo->hasOptimizedCodeGen(Func)) { 7613 switch (Func) { 7614 default: break; 7615 case LibFunc_copysign: 7616 case LibFunc_copysignf: 7617 case LibFunc_copysignl: 7618 // We already checked this call's prototype; verify it doesn't modify 7619 // errno. 7620 if (I.onlyReadsMemory()) { 7621 SDValue LHS = getValue(I.getArgOperand(0)); 7622 SDValue RHS = getValue(I.getArgOperand(1)); 7623 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7624 LHS.getValueType(), LHS, RHS)); 7625 return; 7626 } 7627 break; 7628 case LibFunc_fabs: 7629 case LibFunc_fabsf: 7630 case LibFunc_fabsl: 7631 if (visitUnaryFloatCall(I, ISD::FABS)) 7632 return; 7633 break; 7634 case LibFunc_fmin: 7635 case LibFunc_fminf: 7636 case LibFunc_fminl: 7637 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7638 return; 7639 break; 7640 case LibFunc_fmax: 7641 case LibFunc_fmaxf: 7642 case LibFunc_fmaxl: 7643 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7644 return; 7645 break; 7646 case LibFunc_sin: 7647 case LibFunc_sinf: 7648 case LibFunc_sinl: 7649 if (visitUnaryFloatCall(I, ISD::FSIN)) 7650 return; 7651 break; 7652 case LibFunc_cos: 7653 case LibFunc_cosf: 7654 case LibFunc_cosl: 7655 if (visitUnaryFloatCall(I, ISD::FCOS)) 7656 return; 7657 break; 7658 case LibFunc_sqrt: 7659 case LibFunc_sqrtf: 7660 case LibFunc_sqrtl: 7661 case LibFunc_sqrt_finite: 7662 case LibFunc_sqrtf_finite: 7663 case LibFunc_sqrtl_finite: 7664 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7665 return; 7666 break; 7667 case LibFunc_floor: 7668 case LibFunc_floorf: 7669 case LibFunc_floorl: 7670 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7671 return; 7672 break; 7673 case LibFunc_nearbyint: 7674 case LibFunc_nearbyintf: 7675 case LibFunc_nearbyintl: 7676 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7677 return; 7678 break; 7679 case LibFunc_ceil: 7680 case LibFunc_ceilf: 7681 case LibFunc_ceill: 7682 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7683 return; 7684 break; 7685 case LibFunc_rint: 7686 case LibFunc_rintf: 7687 case LibFunc_rintl: 7688 if (visitUnaryFloatCall(I, ISD::FRINT)) 7689 return; 7690 break; 7691 case LibFunc_round: 7692 case LibFunc_roundf: 7693 case LibFunc_roundl: 7694 if (visitUnaryFloatCall(I, ISD::FROUND)) 7695 return; 7696 break; 7697 case LibFunc_trunc: 7698 case LibFunc_truncf: 7699 case LibFunc_truncl: 7700 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7701 return; 7702 break; 7703 case LibFunc_log2: 7704 case LibFunc_log2f: 7705 case LibFunc_log2l: 7706 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7707 return; 7708 break; 7709 case LibFunc_exp2: 7710 case LibFunc_exp2f: 7711 case LibFunc_exp2l: 7712 if (visitUnaryFloatCall(I, ISD::FEXP2)) 7713 return; 7714 break; 7715 case LibFunc_memcmp: 7716 if (visitMemCmpCall(I)) 7717 return; 7718 break; 7719 case LibFunc_mempcpy: 7720 if (visitMemPCpyCall(I)) 7721 return; 7722 break; 7723 case LibFunc_memchr: 7724 if (visitMemChrCall(I)) 7725 return; 7726 break; 7727 case LibFunc_strcpy: 7728 if (visitStrCpyCall(I, false)) 7729 return; 7730 break; 7731 case LibFunc_stpcpy: 7732 if (visitStrCpyCall(I, true)) 7733 return; 7734 break; 7735 case LibFunc_strcmp: 7736 if (visitStrCmpCall(I)) 7737 return; 7738 break; 7739 case LibFunc_strlen: 7740 if (visitStrLenCall(I)) 7741 return; 7742 break; 7743 case LibFunc_strnlen: 7744 if (visitStrNLenCall(I)) 7745 return; 7746 break; 7747 } 7748 } 7749 } 7750 7751 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 7752 // have to do anything here to lower funclet bundles. 7753 // CFGuardTarget bundles are lowered in LowerCallTo. 7754 assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt, 7755 LLVMContext::OB_funclet, 7756 LLVMContext::OB_cfguardtarget}) && 7757 "Cannot lower calls with arbitrary operand bundles!"); 7758 7759 SDValue Callee = getValue(I.getCalledValue()); 7760 7761 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 7762 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 7763 else 7764 // Check if we can potentially perform a tail call. More detailed checking 7765 // is be done within LowerCallTo, after more information about the call is 7766 // known. 7767 LowerCallTo(&I, Callee, I.isTailCall()); 7768 } 7769 7770 namespace { 7771 7772 /// AsmOperandInfo - This contains information for each constraint that we are 7773 /// lowering. 7774 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 7775 public: 7776 /// CallOperand - If this is the result output operand or a clobber 7777 /// this is null, otherwise it is the incoming operand to the CallInst. 7778 /// This gets modified as the asm is processed. 7779 SDValue CallOperand; 7780 7781 /// AssignedRegs - If this is a register or register class operand, this 7782 /// contains the set of register corresponding to the operand. 7783 RegsForValue AssignedRegs; 7784 7785 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 7786 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 7787 } 7788 7789 /// Whether or not this operand accesses memory 7790 bool hasMemory(const TargetLowering &TLI) const { 7791 // Indirect operand accesses access memory. 7792 if (isIndirect) 7793 return true; 7794 7795 for (const auto &Code : Codes) 7796 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 7797 return true; 7798 7799 return false; 7800 } 7801 7802 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 7803 /// corresponds to. If there is no Value* for this operand, it returns 7804 /// MVT::Other. 7805 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 7806 const DataLayout &DL) const { 7807 if (!CallOperandVal) return MVT::Other; 7808 7809 if (isa<BasicBlock>(CallOperandVal)) 7810 return TLI.getPointerTy(DL); 7811 7812 llvm::Type *OpTy = CallOperandVal->getType(); 7813 7814 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 7815 // If this is an indirect operand, the operand is a pointer to the 7816 // accessed type. 7817 if (isIndirect) { 7818 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 7819 if (!PtrTy) 7820 report_fatal_error("Indirect operand for inline asm not a pointer!"); 7821 OpTy = PtrTy->getElementType(); 7822 } 7823 7824 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 7825 if (StructType *STy = dyn_cast<StructType>(OpTy)) 7826 if (STy->getNumElements() == 1) 7827 OpTy = STy->getElementType(0); 7828 7829 // If OpTy is not a single value, it may be a struct/union that we 7830 // can tile with integers. 7831 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 7832 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 7833 switch (BitSize) { 7834 default: break; 7835 case 1: 7836 case 8: 7837 case 16: 7838 case 32: 7839 case 64: 7840 case 128: 7841 OpTy = IntegerType::get(Context, BitSize); 7842 break; 7843 } 7844 } 7845 7846 return TLI.getValueType(DL, OpTy, true); 7847 } 7848 }; 7849 7850 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>; 7851 7852 } // end anonymous namespace 7853 7854 /// Make sure that the output operand \p OpInfo and its corresponding input 7855 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 7856 /// out). 7857 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 7858 SDISelAsmOperandInfo &MatchingOpInfo, 7859 SelectionDAG &DAG) { 7860 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 7861 return; 7862 7863 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 7864 const auto &TLI = DAG.getTargetLoweringInfo(); 7865 7866 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 7867 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 7868 OpInfo.ConstraintVT); 7869 std::pair<unsigned, const TargetRegisterClass *> InputRC = 7870 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 7871 MatchingOpInfo.ConstraintVT); 7872 if ((OpInfo.ConstraintVT.isInteger() != 7873 MatchingOpInfo.ConstraintVT.isInteger()) || 7874 (MatchRC.second != InputRC.second)) { 7875 // FIXME: error out in a more elegant fashion 7876 report_fatal_error("Unsupported asm: input constraint" 7877 " with a matching output constraint of" 7878 " incompatible type!"); 7879 } 7880 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 7881 } 7882 7883 /// Get a direct memory input to behave well as an indirect operand. 7884 /// This may introduce stores, hence the need for a \p Chain. 7885 /// \return The (possibly updated) chain. 7886 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 7887 SDISelAsmOperandInfo &OpInfo, 7888 SelectionDAG &DAG) { 7889 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7890 7891 // If we don't have an indirect input, put it in the constpool if we can, 7892 // otherwise spill it to a stack slot. 7893 // TODO: This isn't quite right. We need to handle these according to 7894 // the addressing mode that the constraint wants. Also, this may take 7895 // an additional register for the computation and we don't want that 7896 // either. 7897 7898 // If the operand is a float, integer, or vector constant, spill to a 7899 // constant pool entry to get its address. 7900 const Value *OpVal = OpInfo.CallOperandVal; 7901 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 7902 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 7903 OpInfo.CallOperand = DAG.getConstantPool( 7904 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 7905 return Chain; 7906 } 7907 7908 // Otherwise, create a stack slot and emit a store to it before the asm. 7909 Type *Ty = OpVal->getType(); 7910 auto &DL = DAG.getDataLayout(); 7911 uint64_t TySize = DL.getTypeAllocSize(Ty); 7912 unsigned Align = DL.getPrefTypeAlignment(Ty); 7913 MachineFunction &MF = DAG.getMachineFunction(); 7914 int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 7915 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 7916 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 7917 MachinePointerInfo::getFixedStack(MF, SSFI), 7918 TLI.getMemValueType(DL, Ty)); 7919 OpInfo.CallOperand = StackSlot; 7920 7921 return Chain; 7922 } 7923 7924 /// GetRegistersForValue - Assign registers (virtual or physical) for the 7925 /// specified operand. We prefer to assign virtual registers, to allow the 7926 /// register allocator to handle the assignment process. However, if the asm 7927 /// uses features that we can't model on machineinstrs, we have SDISel do the 7928 /// allocation. This produces generally horrible, but correct, code. 7929 /// 7930 /// OpInfo describes the operand 7931 /// RefOpInfo describes the matching operand if any, the operand otherwise 7932 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 7933 SDISelAsmOperandInfo &OpInfo, 7934 SDISelAsmOperandInfo &RefOpInfo) { 7935 LLVMContext &Context = *DAG.getContext(); 7936 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7937 7938 MachineFunction &MF = DAG.getMachineFunction(); 7939 SmallVector<unsigned, 4> Regs; 7940 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 7941 7942 // No work to do for memory operations. 7943 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 7944 return; 7945 7946 // If this is a constraint for a single physreg, or a constraint for a 7947 // register class, find it. 7948 unsigned AssignedReg; 7949 const TargetRegisterClass *RC; 7950 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 7951 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 7952 // RC is unset only on failure. Return immediately. 7953 if (!RC) 7954 return; 7955 7956 // Get the actual register value type. This is important, because the user 7957 // may have asked for (e.g.) the AX register in i32 type. We need to 7958 // remember that AX is actually i16 to get the right extension. 7959 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 7960 7961 if (OpInfo.ConstraintVT != MVT::Other) { 7962 // If this is an FP operand in an integer register (or visa versa), or more 7963 // generally if the operand value disagrees with the register class we plan 7964 // to stick it in, fix the operand type. 7965 // 7966 // If this is an input value, the bitcast to the new type is done now. 7967 // Bitcast for output value is done at the end of visitInlineAsm(). 7968 if ((OpInfo.Type == InlineAsm::isOutput || 7969 OpInfo.Type == InlineAsm::isInput) && 7970 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 7971 // Try to convert to the first EVT that the reg class contains. If the 7972 // types are identical size, use a bitcast to convert (e.g. two differing 7973 // vector types). Note: output bitcast is done at the end of 7974 // visitInlineAsm(). 7975 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 7976 // Exclude indirect inputs while they are unsupported because the code 7977 // to perform the load is missing and thus OpInfo.CallOperand still 7978 // refers to the input address rather than the pointed-to value. 7979 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 7980 OpInfo.CallOperand = 7981 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 7982 OpInfo.ConstraintVT = RegVT; 7983 // If the operand is an FP value and we want it in integer registers, 7984 // use the corresponding integer type. This turns an f64 value into 7985 // i64, which can be passed with two i32 values on a 32-bit machine. 7986 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 7987 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 7988 if (OpInfo.Type == InlineAsm::isInput) 7989 OpInfo.CallOperand = 7990 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 7991 OpInfo.ConstraintVT = VT; 7992 } 7993 } 7994 } 7995 7996 // No need to allocate a matching input constraint since the constraint it's 7997 // matching to has already been allocated. 7998 if (OpInfo.isMatchingInputConstraint()) 7999 return; 8000 8001 EVT ValueVT = OpInfo.ConstraintVT; 8002 if (OpInfo.ConstraintVT == MVT::Other) 8003 ValueVT = RegVT; 8004 8005 // Initialize NumRegs. 8006 unsigned NumRegs = 1; 8007 if (OpInfo.ConstraintVT != MVT::Other) 8008 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 8009 8010 // If this is a constraint for a specific physical register, like {r17}, 8011 // assign it now. 8012 8013 // If this associated to a specific register, initialize iterator to correct 8014 // place. If virtual, make sure we have enough registers 8015 8016 // Initialize iterator if necessary 8017 TargetRegisterClass::iterator I = RC->begin(); 8018 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8019 8020 // Do not check for single registers. 8021 if (AssignedReg) { 8022 for (; *I != AssignedReg; ++I) 8023 assert(I != RC->end() && "AssignedReg should be member of RC"); 8024 } 8025 8026 for (; NumRegs; --NumRegs, ++I) { 8027 assert(I != RC->end() && "Ran out of registers to allocate!"); 8028 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8029 Regs.push_back(R); 8030 } 8031 8032 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8033 } 8034 8035 static unsigned 8036 findMatchingInlineAsmOperand(unsigned OperandNo, 8037 const std::vector<SDValue> &AsmNodeOperands) { 8038 // Scan until we find the definition we already emitted of this operand. 8039 unsigned CurOp = InlineAsm::Op_FirstOperand; 8040 for (; OperandNo; --OperandNo) { 8041 // Advance to the next operand. 8042 unsigned OpFlag = 8043 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8044 assert((InlineAsm::isRegDefKind(OpFlag) || 8045 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8046 InlineAsm::isMemKind(OpFlag)) && 8047 "Skipped past definitions?"); 8048 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8049 } 8050 return CurOp; 8051 } 8052 8053 namespace { 8054 8055 class ExtraFlags { 8056 unsigned Flags = 0; 8057 8058 public: 8059 explicit ExtraFlags(ImmutableCallSite CS) { 8060 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 8061 if (IA->hasSideEffects()) 8062 Flags |= InlineAsm::Extra_HasSideEffects; 8063 if (IA->isAlignStack()) 8064 Flags |= InlineAsm::Extra_IsAlignStack; 8065 if (CS.isConvergent()) 8066 Flags |= InlineAsm::Extra_IsConvergent; 8067 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8068 } 8069 8070 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8071 // Ideally, we would only check against memory constraints. However, the 8072 // meaning of an Other constraint can be target-specific and we can't easily 8073 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8074 // for Other constraints as well. 8075 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8076 OpInfo.ConstraintType == TargetLowering::C_Other) { 8077 if (OpInfo.Type == InlineAsm::isInput) 8078 Flags |= InlineAsm::Extra_MayLoad; 8079 else if (OpInfo.Type == InlineAsm::isOutput) 8080 Flags |= InlineAsm::Extra_MayStore; 8081 else if (OpInfo.Type == InlineAsm::isClobber) 8082 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8083 } 8084 } 8085 8086 unsigned get() const { return Flags; } 8087 }; 8088 8089 } // end anonymous namespace 8090 8091 /// visitInlineAsm - Handle a call to an InlineAsm object. 8092 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) { 8093 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 8094 8095 /// ConstraintOperands - Information about all of the constraints. 8096 SDISelAsmOperandInfoVector ConstraintOperands; 8097 8098 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8099 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8100 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS); 8101 8102 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8103 // AsmDialect, MayLoad, MayStore). 8104 bool HasSideEffect = IA->hasSideEffects(); 8105 ExtraFlags ExtraInfo(CS); 8106 8107 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 8108 unsigned ResNo = 0; // ResNo - The result number of the next output. 8109 for (auto &T : TargetConstraints) { 8110 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8111 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8112 8113 // Compute the value type for each operand. 8114 if (OpInfo.Type == InlineAsm::isInput || 8115 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 8116 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 8117 8118 // Process the call argument. BasicBlocks are labels, currently appearing 8119 // only in asm's. 8120 const Instruction *I = CS.getInstruction(); 8121 if (isa<CallBrInst>(I) && 8122 (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() - 8123 cast<CallBrInst>(I)->getNumIndirectDests())) { 8124 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal); 8125 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true); 8126 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT); 8127 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 8128 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 8129 } else { 8130 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8131 } 8132 8133 OpInfo.ConstraintVT = 8134 OpInfo 8135 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout()) 8136 .getSimpleVT(); 8137 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 8138 // The return value of the call is this value. As such, there is no 8139 // corresponding argument. 8140 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 8141 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 8142 OpInfo.ConstraintVT = TLI.getSimpleValueType( 8143 DAG.getDataLayout(), STy->getElementType(ResNo)); 8144 } else { 8145 assert(ResNo == 0 && "Asm only has one result!"); 8146 OpInfo.ConstraintVT = 8147 TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType()); 8148 } 8149 ++ResNo; 8150 } else { 8151 OpInfo.ConstraintVT = MVT::Other; 8152 } 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( 8168 CS, "constraint '" + Twine(T.ConstraintCode) + "' expects an " 8169 "integer constant 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>(CS.getInstruction()); 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.getPointerTy(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 = CS.getInstruction()->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 switch (OpInfo.Type) { 8253 case InlineAsm::isOutput: 8254 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8255 unsigned ConstraintID = 8256 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8257 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8258 "Failed to convert memory constraint code to constraint id."); 8259 8260 // Add information to the INLINEASM node to know about this output. 8261 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8262 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8263 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8264 MVT::i32)); 8265 AsmNodeOperands.push_back(OpInfo.CallOperand); 8266 } else { 8267 // Otherwise, this outputs to a register (directly for C_Register / 8268 // C_RegisterClass, and a target-defined fashion for 8269 // C_Immediate/C_Other). Find a register that we can use. 8270 if (OpInfo.AssignedRegs.Regs.empty()) { 8271 emitInlineAsmError( 8272 CS, "couldn't allocate output register for constraint '" + 8273 Twine(OpInfo.ConstraintCode) + "'"); 8274 return; 8275 } 8276 8277 // Add information to the INLINEASM node to know that this register is 8278 // set. 8279 OpInfo.AssignedRegs.AddInlineAsmOperands( 8280 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8281 : InlineAsm::Kind_RegDef, 8282 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8283 } 8284 break; 8285 8286 case InlineAsm::isInput: { 8287 SDValue InOperandVal = OpInfo.CallOperand; 8288 8289 if (OpInfo.isMatchingInputConstraint()) { 8290 // If this is required to match an output register we have already set, 8291 // just use its register. 8292 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8293 AsmNodeOperands); 8294 unsigned OpFlag = 8295 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8296 if (InlineAsm::isRegDefKind(OpFlag) || 8297 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8298 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8299 if (OpInfo.isIndirect) { 8300 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8301 emitInlineAsmError(CS, "inline asm not supported yet:" 8302 " don't know how to handle tied " 8303 "indirect register inputs"); 8304 return; 8305 } 8306 8307 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 8308 SmallVector<unsigned, 4> Regs; 8309 8310 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { 8311 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8312 MachineRegisterInfo &RegInfo = 8313 DAG.getMachineFunction().getRegInfo(); 8314 for (unsigned i = 0; i != NumRegs; ++i) 8315 Regs.push_back(RegInfo.createVirtualRegister(RC)); 8316 } else { 8317 emitInlineAsmError(CS, "inline asm error: This value type register " 8318 "class is not natively supported!"); 8319 return; 8320 } 8321 8322 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8323 8324 SDLoc dl = getCurSDLoc(); 8325 // Use the produced MatchedRegs object to 8326 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 8327 CS.getInstruction()); 8328 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8329 true, OpInfo.getMatchedOperand(), dl, 8330 DAG, AsmNodeOperands); 8331 break; 8332 } 8333 8334 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8335 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8336 "Unexpected number of operands"); 8337 // Add information to the INLINEASM node to know about this input. 8338 // See InlineAsm.h isUseOperandTiedToDef. 8339 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8340 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8341 OpInfo.getMatchedOperand()); 8342 AsmNodeOperands.push_back(DAG.getTargetConstant( 8343 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8344 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8345 break; 8346 } 8347 8348 // Treat indirect 'X' constraint as memory. 8349 if (OpInfo.ConstraintType == TargetLowering::C_Other && 8350 OpInfo.isIndirect) 8351 OpInfo.ConstraintType = TargetLowering::C_Memory; 8352 8353 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 8354 OpInfo.ConstraintType == TargetLowering::C_Other) { 8355 std::vector<SDValue> Ops; 8356 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 8357 Ops, DAG); 8358 if (Ops.empty()) { 8359 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 8360 if (isa<ConstantSDNode>(InOperandVal)) { 8361 emitInlineAsmError(CS, "value out of range for constraint '" + 8362 Twine(OpInfo.ConstraintCode) + "'"); 8363 return; 8364 } 8365 8366 emitInlineAsmError(CS, "invalid operand for inline asm constraint '" + 8367 Twine(OpInfo.ConstraintCode) + "'"); 8368 return; 8369 } 8370 8371 // Add information to the INLINEASM node to know about this input. 8372 unsigned ResOpType = 8373 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 8374 AsmNodeOperands.push_back(DAG.getTargetConstant( 8375 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8376 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 8377 break; 8378 } 8379 8380 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8381 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 8382 assert(InOperandVal.getValueType() == 8383 TLI.getPointerTy(DAG.getDataLayout()) && 8384 "Memory operands expect pointer values"); 8385 8386 unsigned ConstraintID = 8387 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8388 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8389 "Failed to convert memory constraint code to constraint id."); 8390 8391 // Add information to the INLINEASM node to know about this input. 8392 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8393 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 8394 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 8395 getCurSDLoc(), 8396 MVT::i32)); 8397 AsmNodeOperands.push_back(InOperandVal); 8398 break; 8399 } 8400 8401 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 8402 OpInfo.ConstraintType == TargetLowering::C_Register) && 8403 "Unknown constraint type!"); 8404 8405 // TODO: Support this. 8406 if (OpInfo.isIndirect) { 8407 emitInlineAsmError( 8408 CS, "Don't know how to handle indirect register inputs yet " 8409 "for constraint '" + 8410 Twine(OpInfo.ConstraintCode) + "'"); 8411 return; 8412 } 8413 8414 // Copy the input into the appropriate registers. 8415 if (OpInfo.AssignedRegs.Regs.empty()) { 8416 emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" + 8417 Twine(OpInfo.ConstraintCode) + "'"); 8418 return; 8419 } 8420 8421 SDLoc dl = getCurSDLoc(); 8422 8423 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, 8424 Chain, &Flag, CS.getInstruction()); 8425 8426 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 8427 dl, DAG, AsmNodeOperands); 8428 break; 8429 } 8430 case InlineAsm::isClobber: 8431 // Add the clobbered value to the operand list, so that the register 8432 // allocator is aware that the physreg got clobbered. 8433 if (!OpInfo.AssignedRegs.Regs.empty()) 8434 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 8435 false, 0, getCurSDLoc(), DAG, 8436 AsmNodeOperands); 8437 break; 8438 } 8439 } 8440 8441 // Finish up input operands. Set the input chain and add the flag last. 8442 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 8443 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 8444 8445 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 8446 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 8447 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 8448 Flag = Chain.getValue(1); 8449 8450 // Do additional work to generate outputs. 8451 8452 SmallVector<EVT, 1> ResultVTs; 8453 SmallVector<SDValue, 1> ResultValues; 8454 SmallVector<SDValue, 8> OutChains; 8455 8456 llvm::Type *CSResultType = CS.getType(); 8457 ArrayRef<Type *> ResultTypes; 8458 if (StructType *StructResult = dyn_cast<StructType>(CSResultType)) 8459 ResultTypes = StructResult->elements(); 8460 else if (!CSResultType->isVoidTy()) 8461 ResultTypes = makeArrayRef(CSResultType); 8462 8463 auto CurResultType = ResultTypes.begin(); 8464 auto handleRegAssign = [&](SDValue V) { 8465 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 8466 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 8467 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 8468 ++CurResultType; 8469 // If the type of the inline asm call site return value is different but has 8470 // same size as the type of the asm output bitcast it. One example of this 8471 // is for vectors with different width / number of elements. This can 8472 // happen for register classes that can contain multiple different value 8473 // types. The preg or vreg allocated may not have the same VT as was 8474 // expected. 8475 // 8476 // This can also happen for a return value that disagrees with the register 8477 // class it is put in, eg. a double in a general-purpose register on a 8478 // 32-bit machine. 8479 if (ResultVT != V.getValueType() && 8480 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 8481 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 8482 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 8483 V.getValueType().isInteger()) { 8484 // If a result value was tied to an input value, the computed result 8485 // may have a wider width than the expected result. Extract the 8486 // relevant portion. 8487 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 8488 } 8489 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 8490 ResultVTs.push_back(ResultVT); 8491 ResultValues.push_back(V); 8492 }; 8493 8494 // Deal with output operands. 8495 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8496 if (OpInfo.Type == InlineAsm::isOutput) { 8497 SDValue Val; 8498 // Skip trivial output operands. 8499 if (OpInfo.AssignedRegs.Regs.empty()) 8500 continue; 8501 8502 switch (OpInfo.ConstraintType) { 8503 case TargetLowering::C_Register: 8504 case TargetLowering::C_RegisterClass: 8505 Val = OpInfo.AssignedRegs.getCopyFromRegs( 8506 DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction()); 8507 break; 8508 case TargetLowering::C_Immediate: 8509 case TargetLowering::C_Other: 8510 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 8511 OpInfo, DAG); 8512 break; 8513 case TargetLowering::C_Memory: 8514 break; // Already handled. 8515 case TargetLowering::C_Unknown: 8516 assert(false && "Unexpected unknown constraint"); 8517 } 8518 8519 // Indirect output manifest as stores. Record output chains. 8520 if (OpInfo.isIndirect) { 8521 const Value *Ptr = OpInfo.CallOperandVal; 8522 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 8523 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 8524 MachinePointerInfo(Ptr)); 8525 OutChains.push_back(Store); 8526 } else { 8527 // generate CopyFromRegs to associated registers. 8528 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 8529 if (Val.getOpcode() == ISD::MERGE_VALUES) { 8530 for (const SDValue &V : Val->op_values()) 8531 handleRegAssign(V); 8532 } else 8533 handleRegAssign(Val); 8534 } 8535 } 8536 } 8537 8538 // Set results. 8539 if (!ResultValues.empty()) { 8540 assert(CurResultType == ResultTypes.end() && 8541 "Mismatch in number of ResultTypes"); 8542 assert(ResultValues.size() == ResultTypes.size() && 8543 "Mismatch in number of output operands in asm result"); 8544 8545 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 8546 DAG.getVTList(ResultVTs), ResultValues); 8547 setValue(CS.getInstruction(), V); 8548 } 8549 8550 // Collect store chains. 8551 if (!OutChains.empty()) 8552 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 8553 8554 // Only Update Root if inline assembly has a memory effect. 8555 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr) 8556 DAG.setRoot(Chain); 8557 } 8558 8559 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS, 8560 const Twine &Message) { 8561 LLVMContext &Ctx = *DAG.getContext(); 8562 Ctx.emitError(CS.getInstruction(), Message); 8563 8564 // Make sure we leave the DAG in a valid state 8565 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8566 SmallVector<EVT, 1> ValueVTs; 8567 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8568 8569 if (ValueVTs.empty()) 8570 return; 8571 8572 SmallVector<SDValue, 1> Ops; 8573 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 8574 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 8575 8576 setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc())); 8577 } 8578 8579 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 8580 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 8581 MVT::Other, getRoot(), 8582 getValue(I.getArgOperand(0)), 8583 DAG.getSrcValue(I.getArgOperand(0)))); 8584 } 8585 8586 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 8587 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8588 const DataLayout &DL = DAG.getDataLayout(); 8589 SDValue V = DAG.getVAArg( 8590 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 8591 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 8592 DL.getABITypeAlignment(I.getType())); 8593 DAG.setRoot(V.getValue(1)); 8594 8595 if (I.getType()->isPointerTy()) 8596 V = DAG.getPtrExtOrTrunc( 8597 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 8598 setValue(&I, V); 8599 } 8600 8601 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 8602 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 8603 MVT::Other, getRoot(), 8604 getValue(I.getArgOperand(0)), 8605 DAG.getSrcValue(I.getArgOperand(0)))); 8606 } 8607 8608 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 8609 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 8610 MVT::Other, getRoot(), 8611 getValue(I.getArgOperand(0)), 8612 getValue(I.getArgOperand(1)), 8613 DAG.getSrcValue(I.getArgOperand(0)), 8614 DAG.getSrcValue(I.getArgOperand(1)))); 8615 } 8616 8617 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 8618 const Instruction &I, 8619 SDValue Op) { 8620 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 8621 if (!Range) 8622 return Op; 8623 8624 ConstantRange CR = getConstantRangeFromMetadata(*Range); 8625 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 8626 return Op; 8627 8628 APInt Lo = CR.getUnsignedMin(); 8629 if (!Lo.isMinValue()) 8630 return Op; 8631 8632 APInt Hi = CR.getUnsignedMax(); 8633 unsigned Bits = std::max(Hi.getActiveBits(), 8634 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 8635 8636 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8637 8638 SDLoc SL = getCurSDLoc(); 8639 8640 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8641 DAG.getValueType(SmallVT)); 8642 unsigned NumVals = Op.getNode()->getNumValues(); 8643 if (NumVals == 1) 8644 return ZExt; 8645 8646 SmallVector<SDValue, 4> Ops; 8647 8648 Ops.push_back(ZExt); 8649 for (unsigned I = 1; I != NumVals; ++I) 8650 Ops.push_back(Op.getValue(I)); 8651 8652 return DAG.getMergeValues(Ops, SL); 8653 } 8654 8655 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8656 /// the call being lowered. 8657 /// 8658 /// This is a helper for lowering intrinsics that follow a target calling 8659 /// convention or require stack pointer adjustment. Only a subset of the 8660 /// intrinsic's operands need to participate in the calling convention. 8661 void SelectionDAGBuilder::populateCallLoweringInfo( 8662 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 8663 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8664 bool IsPatchPoint) { 8665 TargetLowering::ArgListTy Args; 8666 Args.reserve(NumArgs); 8667 8668 // Populate the argument list. 8669 // Attributes for args start at offset 1, after the return attribute. 8670 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8671 ArgI != ArgE; ++ArgI) { 8672 const Value *V = Call->getOperand(ArgI); 8673 8674 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 8675 8676 TargetLowering::ArgListEntry Entry; 8677 Entry.Node = getValue(V); 8678 Entry.Ty = V->getType(); 8679 Entry.setAttributes(Call, ArgI); 8680 Args.push_back(Entry); 8681 } 8682 8683 CLI.setDebugLoc(getCurSDLoc()) 8684 .setChain(getRoot()) 8685 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 8686 .setDiscardResult(Call->use_empty()) 8687 .setIsPatchPoint(IsPatchPoint); 8688 } 8689 8690 /// Add a stack map intrinsic call's live variable operands to a stackmap 8691 /// or patchpoint target node's operand list. 8692 /// 8693 /// Constants are converted to TargetConstants purely as an optimization to 8694 /// avoid constant materialization and register allocation. 8695 /// 8696 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 8697 /// generate addess computation nodes, and so FinalizeISel can convert the 8698 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 8699 /// address materialization and register allocation, but may also be required 8700 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 8701 /// alloca in the entry block, then the runtime may assume that the alloca's 8702 /// StackMap location can be read immediately after compilation and that the 8703 /// location is valid at any point during execution (this is similar to the 8704 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 8705 /// only available in a register, then the runtime would need to trap when 8706 /// execution reaches the StackMap in order to read the alloca's location. 8707 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx, 8708 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 8709 SelectionDAGBuilder &Builder) { 8710 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) { 8711 SDValue OpVal = Builder.getValue(CS.getArgument(i)); 8712 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 8713 Ops.push_back( 8714 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 8715 Ops.push_back( 8716 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 8717 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 8718 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 8719 Ops.push_back(Builder.DAG.getTargetFrameIndex( 8720 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 8721 } else 8722 Ops.push_back(OpVal); 8723 } 8724 } 8725 8726 /// Lower llvm.experimental.stackmap directly to its target opcode. 8727 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 8728 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 8729 // [live variables...]) 8730 8731 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 8732 8733 SDValue Chain, InFlag, Callee, NullPtr; 8734 SmallVector<SDValue, 32> Ops; 8735 8736 SDLoc DL = getCurSDLoc(); 8737 Callee = getValue(CI.getCalledValue()); 8738 NullPtr = DAG.getIntPtrConstant(0, DL, true); 8739 8740 // The stackmap intrinsic only records the live variables (the arguments 8741 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 8742 // intrinsic, this won't be lowered to a function call. This means we don't 8743 // have to worry about calling conventions and target specific lowering code. 8744 // Instead we perform the call lowering right here. 8745 // 8746 // chain, flag = CALLSEQ_START(chain, 0, 0) 8747 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 8748 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 8749 // 8750 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 8751 InFlag = Chain.getValue(1); 8752 8753 // Add the <id> and <numBytes> constants. 8754 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 8755 Ops.push_back(DAG.getTargetConstant( 8756 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 8757 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 8758 Ops.push_back(DAG.getTargetConstant( 8759 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 8760 MVT::i32)); 8761 8762 // Push live variables for the stack map. 8763 addStackMapLiveVars(&CI, 2, DL, Ops, *this); 8764 8765 // We are not pushing any register mask info here on the operands list, 8766 // because the stackmap doesn't clobber anything. 8767 8768 // Push the chain and the glue flag. 8769 Ops.push_back(Chain); 8770 Ops.push_back(InFlag); 8771 8772 // Create the STACKMAP node. 8773 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8774 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 8775 Chain = SDValue(SM, 0); 8776 InFlag = Chain.getValue(1); 8777 8778 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 8779 8780 // Stackmaps don't generate values, so nothing goes into the NodeMap. 8781 8782 // Set the root to the target-lowered call chain. 8783 DAG.setRoot(Chain); 8784 8785 // Inform the Frame Information that we have a stackmap in this function. 8786 FuncInfo.MF->getFrameInfo().setHasStackMap(); 8787 } 8788 8789 /// Lower llvm.experimental.patchpoint directly to its target opcode. 8790 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS, 8791 const BasicBlock *EHPadBB) { 8792 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 8793 // i32 <numBytes>, 8794 // i8* <target>, 8795 // i32 <numArgs>, 8796 // [Args...], 8797 // [live variables...]) 8798 8799 CallingConv::ID CC = CS.getCallingConv(); 8800 bool IsAnyRegCC = CC == CallingConv::AnyReg; 8801 bool HasDef = !CS->getType()->isVoidTy(); 8802 SDLoc dl = getCurSDLoc(); 8803 SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos)); 8804 8805 // Handle immediate and symbolic callees. 8806 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 8807 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 8808 /*isTarget=*/true); 8809 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 8810 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 8811 SDLoc(SymbolicCallee), 8812 SymbolicCallee->getValueType(0)); 8813 8814 // Get the real number of arguments participating in the call <numArgs> 8815 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos)); 8816 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 8817 8818 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 8819 // Intrinsics include all meta-operands up to but not including CC. 8820 unsigned NumMetaOpers = PatchPointOpers::CCPos; 8821 assert(CS.arg_size() >= NumMetaOpers + NumArgs && 8822 "Not enough arguments provided to the patchpoint intrinsic"); 8823 8824 // For AnyRegCC the arguments are lowered later on manually. 8825 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 8826 Type *ReturnTy = 8827 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType(); 8828 8829 TargetLowering::CallLoweringInfo CLI(DAG); 8830 populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()), 8831 NumMetaOpers, NumCallArgs, Callee, ReturnTy, true); 8832 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8833 8834 SDNode *CallEnd = Result.second.getNode(); 8835 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 8836 CallEnd = CallEnd->getOperand(0).getNode(); 8837 8838 /// Get a call instruction from the call sequence chain. 8839 /// Tail calls are not allowed. 8840 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 8841 "Expected a callseq node."); 8842 SDNode *Call = CallEnd->getOperand(0).getNode(); 8843 bool HasGlue = Call->getGluedNode(); 8844 8845 // Replace the target specific call node with the patchable intrinsic. 8846 SmallVector<SDValue, 8> Ops; 8847 8848 // Add the <id> and <numBytes> constants. 8849 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos)); 8850 Ops.push_back(DAG.getTargetConstant( 8851 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 8852 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos)); 8853 Ops.push_back(DAG.getTargetConstant( 8854 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 8855 MVT::i32)); 8856 8857 // Add the callee. 8858 Ops.push_back(Callee); 8859 8860 // Adjust <numArgs> to account for any arguments that have been passed on the 8861 // stack instead. 8862 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 8863 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 8864 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 8865 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 8866 8867 // Add the calling convention 8868 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 8869 8870 // Add the arguments we omitted previously. The register allocator should 8871 // place these in any free register. 8872 if (IsAnyRegCC) 8873 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 8874 Ops.push_back(getValue(CS.getArgument(i))); 8875 8876 // Push the arguments from the call instruction up to the register mask. 8877 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 8878 Ops.append(Call->op_begin() + 2, e); 8879 8880 // Push live variables for the stack map. 8881 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this); 8882 8883 // Push the register mask info. 8884 if (HasGlue) 8885 Ops.push_back(*(Call->op_end()-2)); 8886 else 8887 Ops.push_back(*(Call->op_end()-1)); 8888 8889 // Push the chain (this is originally the first operand of the call, but 8890 // becomes now the last or second to last operand). 8891 Ops.push_back(*(Call->op_begin())); 8892 8893 // Push the glue flag (last operand). 8894 if (HasGlue) 8895 Ops.push_back(*(Call->op_end()-1)); 8896 8897 SDVTList NodeTys; 8898 if (IsAnyRegCC && HasDef) { 8899 // Create the return types based on the intrinsic definition 8900 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8901 SmallVector<EVT, 3> ValueVTs; 8902 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8903 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 8904 8905 // There is always a chain and a glue type at the end 8906 ValueVTs.push_back(MVT::Other); 8907 ValueVTs.push_back(MVT::Glue); 8908 NodeTys = DAG.getVTList(ValueVTs); 8909 } else 8910 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8911 8912 // Replace the target specific call node with a PATCHPOINT node. 8913 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 8914 dl, NodeTys, Ops); 8915 8916 // Update the NodeMap. 8917 if (HasDef) { 8918 if (IsAnyRegCC) 8919 setValue(CS.getInstruction(), SDValue(MN, 0)); 8920 else 8921 setValue(CS.getInstruction(), Result.first); 8922 } 8923 8924 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 8925 // call sequence. Furthermore the location of the chain and glue can change 8926 // when the AnyReg calling convention is used and the intrinsic returns a 8927 // value. 8928 if (IsAnyRegCC && HasDef) { 8929 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 8930 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 8931 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 8932 } else 8933 DAG.ReplaceAllUsesWith(Call, MN); 8934 DAG.DeleteNode(Call); 8935 8936 // Inform the Frame Information that we have a patchpoint in this function. 8937 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 8938 } 8939 8940 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 8941 unsigned Intrinsic) { 8942 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8943 SDValue Op1 = getValue(I.getArgOperand(0)); 8944 SDValue Op2; 8945 if (I.getNumArgOperands() > 1) 8946 Op2 = getValue(I.getArgOperand(1)); 8947 SDLoc dl = getCurSDLoc(); 8948 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8949 SDValue Res; 8950 FastMathFlags FMF; 8951 if (isa<FPMathOperator>(I)) 8952 FMF = I.getFastMathFlags(); 8953 8954 switch (Intrinsic) { 8955 case Intrinsic::experimental_vector_reduce_v2_fadd: 8956 if (FMF.allowReassoc()) 8957 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 8958 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2)); 8959 else 8960 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2); 8961 break; 8962 case Intrinsic::experimental_vector_reduce_v2_fmul: 8963 if (FMF.allowReassoc()) 8964 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 8965 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2)); 8966 else 8967 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2); 8968 break; 8969 case Intrinsic::experimental_vector_reduce_add: 8970 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 8971 break; 8972 case Intrinsic::experimental_vector_reduce_mul: 8973 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 8974 break; 8975 case Intrinsic::experimental_vector_reduce_and: 8976 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 8977 break; 8978 case Intrinsic::experimental_vector_reduce_or: 8979 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 8980 break; 8981 case Intrinsic::experimental_vector_reduce_xor: 8982 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 8983 break; 8984 case Intrinsic::experimental_vector_reduce_smax: 8985 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 8986 break; 8987 case Intrinsic::experimental_vector_reduce_smin: 8988 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 8989 break; 8990 case Intrinsic::experimental_vector_reduce_umax: 8991 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 8992 break; 8993 case Intrinsic::experimental_vector_reduce_umin: 8994 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 8995 break; 8996 case Intrinsic::experimental_vector_reduce_fmax: 8997 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1); 8998 break; 8999 case Intrinsic::experimental_vector_reduce_fmin: 9000 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1); 9001 break; 9002 default: 9003 llvm_unreachable("Unhandled vector reduce intrinsic"); 9004 } 9005 setValue(&I, Res); 9006 } 9007 9008 /// Returns an AttributeList representing the attributes applied to the return 9009 /// value of the given call. 9010 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9011 SmallVector<Attribute::AttrKind, 2> Attrs; 9012 if (CLI.RetSExt) 9013 Attrs.push_back(Attribute::SExt); 9014 if (CLI.RetZExt) 9015 Attrs.push_back(Attribute::ZExt); 9016 if (CLI.IsInReg) 9017 Attrs.push_back(Attribute::InReg); 9018 9019 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9020 Attrs); 9021 } 9022 9023 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9024 /// implementation, which just calls LowerCall. 9025 /// FIXME: When all targets are 9026 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9027 std::pair<SDValue, SDValue> 9028 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9029 // Handle the incoming return values from the call. 9030 CLI.Ins.clear(); 9031 Type *OrigRetTy = CLI.RetTy; 9032 SmallVector<EVT, 4> RetTys; 9033 SmallVector<uint64_t, 4> Offsets; 9034 auto &DL = CLI.DAG.getDataLayout(); 9035 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 9036 9037 if (CLI.IsPostTypeLegalization) { 9038 // If we are lowering a libcall after legalization, split the return type. 9039 SmallVector<EVT, 4> OldRetTys; 9040 SmallVector<uint64_t, 4> OldOffsets; 9041 RetTys.swap(OldRetTys); 9042 Offsets.swap(OldOffsets); 9043 9044 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9045 EVT RetVT = OldRetTys[i]; 9046 uint64_t Offset = OldOffsets[i]; 9047 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9048 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9049 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9050 RetTys.append(NumRegs, RegisterVT); 9051 for (unsigned j = 0; j != NumRegs; ++j) 9052 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9053 } 9054 } 9055 9056 SmallVector<ISD::OutputArg, 4> Outs; 9057 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9058 9059 bool CanLowerReturn = 9060 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9061 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9062 9063 SDValue DemoteStackSlot; 9064 int DemoteStackIdx = -100; 9065 if (!CanLowerReturn) { 9066 // FIXME: equivalent assert? 9067 // assert(!CS.hasInAllocaArgument() && 9068 // "sret demotion is incompatible with inalloca"); 9069 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9070 unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy); 9071 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9072 DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 9073 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9074 DL.getAllocaAddrSpace()); 9075 9076 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9077 ArgListEntry Entry; 9078 Entry.Node = DemoteStackSlot; 9079 Entry.Ty = StackSlotPtrType; 9080 Entry.IsSExt = false; 9081 Entry.IsZExt = false; 9082 Entry.IsInReg = false; 9083 Entry.IsSRet = true; 9084 Entry.IsNest = false; 9085 Entry.IsByVal = false; 9086 Entry.IsReturned = false; 9087 Entry.IsSwiftSelf = false; 9088 Entry.IsSwiftError = false; 9089 Entry.IsCFGuardTarget = false; 9090 Entry.Alignment = Align; 9091 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9092 CLI.NumFixedArgs += 1; 9093 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9094 9095 // sret demotion isn't compatible with tail-calls, since the sret argument 9096 // points into the callers stack frame. 9097 CLI.IsTailCall = false; 9098 } else { 9099 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9100 CLI.RetTy, CLI.CallConv, CLI.IsVarArg); 9101 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9102 ISD::ArgFlagsTy Flags; 9103 if (NeedsRegBlock) { 9104 Flags.setInConsecutiveRegs(); 9105 if (I == RetTys.size() - 1) 9106 Flags.setInConsecutiveRegsLast(); 9107 } 9108 EVT VT = RetTys[I]; 9109 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9110 CLI.CallConv, VT); 9111 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9112 CLI.CallConv, VT); 9113 for (unsigned i = 0; i != NumRegs; ++i) { 9114 ISD::InputArg MyFlags; 9115 MyFlags.Flags = Flags; 9116 MyFlags.VT = RegisterVT; 9117 MyFlags.ArgVT = VT; 9118 MyFlags.Used = CLI.IsReturnValueUsed; 9119 if (CLI.RetTy->isPointerTy()) { 9120 MyFlags.Flags.setPointer(); 9121 MyFlags.Flags.setPointerAddrSpace( 9122 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9123 } 9124 if (CLI.RetSExt) 9125 MyFlags.Flags.setSExt(); 9126 if (CLI.RetZExt) 9127 MyFlags.Flags.setZExt(); 9128 if (CLI.IsInReg) 9129 MyFlags.Flags.setInReg(); 9130 CLI.Ins.push_back(MyFlags); 9131 } 9132 } 9133 } 9134 9135 // We push in swifterror return as the last element of CLI.Ins. 9136 ArgListTy &Args = CLI.getArgs(); 9137 if (supportSwiftError()) { 9138 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9139 if (Args[i].IsSwiftError) { 9140 ISD::InputArg MyFlags; 9141 MyFlags.VT = getPointerTy(DL); 9142 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9143 MyFlags.Flags.setSwiftError(); 9144 CLI.Ins.push_back(MyFlags); 9145 } 9146 } 9147 } 9148 9149 // Handle all of the outgoing arguments. 9150 CLI.Outs.clear(); 9151 CLI.OutVals.clear(); 9152 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9153 SmallVector<EVT, 4> ValueVTs; 9154 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9155 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9156 Type *FinalType = Args[i].Ty; 9157 if (Args[i].IsByVal) 9158 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 9159 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9160 FinalType, CLI.CallConv, CLI.IsVarArg); 9161 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9162 ++Value) { 9163 EVT VT = ValueVTs[Value]; 9164 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9165 SDValue Op = SDValue(Args[i].Node.getNode(), 9166 Args[i].Node.getResNo() + Value); 9167 ISD::ArgFlagsTy Flags; 9168 9169 // Certain targets (such as MIPS), may have a different ABI alignment 9170 // for a type depending on the context. Give the target a chance to 9171 // specify the alignment it wants. 9172 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 9173 9174 if (Args[i].Ty->isPointerTy()) { 9175 Flags.setPointer(); 9176 Flags.setPointerAddrSpace( 9177 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9178 } 9179 if (Args[i].IsZExt) 9180 Flags.setZExt(); 9181 if (Args[i].IsSExt) 9182 Flags.setSExt(); 9183 if (Args[i].IsInReg) { 9184 // If we are using vectorcall calling convention, a structure that is 9185 // passed InReg - is surely an HVA 9186 if (CLI.CallConv == CallingConv::X86_VectorCall && 9187 isa<StructType>(FinalType)) { 9188 // The first value of a structure is marked 9189 if (0 == Value) 9190 Flags.setHvaStart(); 9191 Flags.setHva(); 9192 } 9193 // Set InReg Flag 9194 Flags.setInReg(); 9195 } 9196 if (Args[i].IsSRet) 9197 Flags.setSRet(); 9198 if (Args[i].IsSwiftSelf) 9199 Flags.setSwiftSelf(); 9200 if (Args[i].IsSwiftError) 9201 Flags.setSwiftError(); 9202 if (Args[i].IsCFGuardTarget) 9203 Flags.setCFGuardTarget(); 9204 if (Args[i].IsByVal) 9205 Flags.setByVal(); 9206 if (Args[i].IsInAlloca) { 9207 Flags.setInAlloca(); 9208 // Set the byval flag for CCAssignFn callbacks that don't know about 9209 // inalloca. This way we can know how many bytes we should've allocated 9210 // and how many bytes a callee cleanup function will pop. If we port 9211 // inalloca to more targets, we'll have to add custom inalloca handling 9212 // in the various CC lowering callbacks. 9213 Flags.setByVal(); 9214 } 9215 if (Args[i].IsByVal || Args[i].IsInAlloca) { 9216 PointerType *Ty = cast<PointerType>(Args[i].Ty); 9217 Type *ElementTy = Ty->getElementType(); 9218 9219 unsigned FrameSize = DL.getTypeAllocSize( 9220 Args[i].ByValType ? Args[i].ByValType : ElementTy); 9221 Flags.setByValSize(FrameSize); 9222 9223 // info is not there but there are cases it cannot get right. 9224 unsigned FrameAlign; 9225 if (Args[i].Alignment) 9226 FrameAlign = Args[i].Alignment; 9227 else 9228 FrameAlign = getByValTypeAlignment(ElementTy, DL); 9229 Flags.setByValAlign(Align(FrameAlign)); 9230 } 9231 if (Args[i].IsNest) 9232 Flags.setNest(); 9233 if (NeedsRegBlock) 9234 Flags.setInConsecutiveRegs(); 9235 Flags.setOrigAlign(OriginalAlignment); 9236 9237 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9238 CLI.CallConv, VT); 9239 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9240 CLI.CallConv, VT); 9241 SmallVector<SDValue, 4> Parts(NumParts); 9242 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9243 9244 if (Args[i].IsSExt) 9245 ExtendKind = ISD::SIGN_EXTEND; 9246 else if (Args[i].IsZExt) 9247 ExtendKind = ISD::ZERO_EXTEND; 9248 9249 // Conservatively only handle 'returned' on non-vectors that can be lowered, 9250 // for now. 9251 if (Args[i].IsReturned && !Op.getValueType().isVector() && 9252 CanLowerReturn) { 9253 assert((CLI.RetTy == Args[i].Ty || 9254 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 9255 CLI.RetTy->getPointerAddressSpace() == 9256 Args[i].Ty->getPointerAddressSpace())) && 9257 RetTys.size() == NumValues && "unexpected use of 'returned'"); 9258 // Before passing 'returned' to the target lowering code, ensure that 9259 // either the register MVT and the actual EVT are the same size or that 9260 // the return value and argument are extended in the same way; in these 9261 // cases it's safe to pass the argument register value unchanged as the 9262 // return register value (although it's at the target's option whether 9263 // to do so) 9264 // TODO: allow code generation to take advantage of partially preserved 9265 // registers rather than clobbering the entire register when the 9266 // parameter extension method is not compatible with the return 9267 // extension method 9268 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9269 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9270 CLI.RetZExt == Args[i].IsZExt)) 9271 Flags.setReturned(); 9272 } 9273 9274 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, 9275 CLI.CS.getInstruction(), CLI.CallConv, ExtendKind); 9276 9277 for (unsigned j = 0; j != NumParts; ++j) { 9278 // if it isn't first piece, alignment must be 1 9279 // For scalable vectors the scalable part is currently handled 9280 // by individual targets, so we just use the known minimum size here. 9281 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 9282 i < CLI.NumFixedArgs, i, 9283 j*Parts[j].getValueType().getStoreSize().getKnownMinSize()); 9284 if (NumParts > 1 && j == 0) 9285 MyFlags.Flags.setSplit(); 9286 else if (j != 0) { 9287 MyFlags.Flags.setOrigAlign(Align::None()); 9288 if (j == NumParts - 1) 9289 MyFlags.Flags.setSplitEnd(); 9290 } 9291 9292 CLI.Outs.push_back(MyFlags); 9293 CLI.OutVals.push_back(Parts[j]); 9294 } 9295 9296 if (NeedsRegBlock && Value == NumValues - 1) 9297 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 9298 } 9299 } 9300 9301 SmallVector<SDValue, 4> InVals; 9302 CLI.Chain = LowerCall(CLI, InVals); 9303 9304 // Update CLI.InVals to use outside of this function. 9305 CLI.InVals = InVals; 9306 9307 // Verify that the target's LowerCall behaved as expected. 9308 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 9309 "LowerCall didn't return a valid chain!"); 9310 assert((!CLI.IsTailCall || InVals.empty()) && 9311 "LowerCall emitted a return value for a tail call!"); 9312 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9313 "LowerCall didn't emit the correct number of values!"); 9314 9315 // For a tail call, the return value is merely live-out and there aren't 9316 // any nodes in the DAG representing it. Return a special value to 9317 // indicate that a tail call has been emitted and no more Instructions 9318 // should be processed in the current block. 9319 if (CLI.IsTailCall) { 9320 CLI.DAG.setRoot(CLI.Chain); 9321 return std::make_pair(SDValue(), SDValue()); 9322 } 9323 9324 #ifndef NDEBUG 9325 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 9326 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 9327 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 9328 "LowerCall emitted a value with the wrong type!"); 9329 } 9330 #endif 9331 9332 SmallVector<SDValue, 4> ReturnValues; 9333 if (!CanLowerReturn) { 9334 // The instruction result is the result of loading from the 9335 // hidden sret parameter. 9336 SmallVector<EVT, 1> PVTs; 9337 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 9338 9339 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 9340 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 9341 EVT PtrVT = PVTs[0]; 9342 9343 unsigned NumValues = RetTys.size(); 9344 ReturnValues.resize(NumValues); 9345 SmallVector<SDValue, 4> Chains(NumValues); 9346 9347 // An aggregate return value cannot wrap around the address space, so 9348 // offsets to its parts don't wrap either. 9349 SDNodeFlags Flags; 9350 Flags.setNoUnsignedWrap(true); 9351 9352 for (unsigned i = 0; i < NumValues; ++i) { 9353 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 9354 CLI.DAG.getConstant(Offsets[i], CLI.DL, 9355 PtrVT), Flags); 9356 SDValue L = CLI.DAG.getLoad( 9357 RetTys[i], CLI.DL, CLI.Chain, Add, 9358 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 9359 DemoteStackIdx, Offsets[i]), 9360 /* Alignment = */ 1); 9361 ReturnValues[i] = L; 9362 Chains[i] = L.getValue(1); 9363 } 9364 9365 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 9366 } else { 9367 // Collect the legal value parts into potentially illegal values 9368 // that correspond to the original function's return values. 9369 Optional<ISD::NodeType> AssertOp; 9370 if (CLI.RetSExt) 9371 AssertOp = ISD::AssertSext; 9372 else if (CLI.RetZExt) 9373 AssertOp = ISD::AssertZext; 9374 unsigned CurReg = 0; 9375 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9376 EVT VT = RetTys[I]; 9377 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9378 CLI.CallConv, VT); 9379 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9380 CLI.CallConv, VT); 9381 9382 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 9383 NumRegs, RegisterVT, VT, nullptr, 9384 CLI.CallConv, AssertOp)); 9385 CurReg += NumRegs; 9386 } 9387 9388 // For a function returning void, there is no return value. We can't create 9389 // such a node, so we just return a null return value in that case. In 9390 // that case, nothing will actually look at the value. 9391 if (ReturnValues.empty()) 9392 return std::make_pair(SDValue(), CLI.Chain); 9393 } 9394 9395 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 9396 CLI.DAG.getVTList(RetTys), ReturnValues); 9397 return std::make_pair(Res, CLI.Chain); 9398 } 9399 9400 void TargetLowering::LowerOperationWrapper(SDNode *N, 9401 SmallVectorImpl<SDValue> &Results, 9402 SelectionDAG &DAG) const { 9403 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG)) 9404 Results.push_back(Res); 9405 } 9406 9407 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9408 llvm_unreachable("LowerOperation not implemented for this target!"); 9409 } 9410 9411 void 9412 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 9413 SDValue Op = getNonRegisterValue(V); 9414 assert((Op.getOpcode() != ISD::CopyFromReg || 9415 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 9416 "Copy from a reg to the same reg!"); 9417 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 9418 9419 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9420 // If this is an InlineAsm we have to match the registers required, not the 9421 // notional registers required by the type. 9422 9423 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 9424 None); // This is not an ABI copy. 9425 SDValue Chain = DAG.getEntryNode(); 9426 9427 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 9428 FuncInfo.PreferredExtendType.end()) 9429 ? ISD::ANY_EXTEND 9430 : FuncInfo.PreferredExtendType[V]; 9431 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 9432 PendingExports.push_back(Chain); 9433 } 9434 9435 #include "llvm/CodeGen/SelectionDAGISel.h" 9436 9437 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 9438 /// entry block, return true. This includes arguments used by switches, since 9439 /// the switch may expand into multiple basic blocks. 9440 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 9441 // With FastISel active, we may be splitting blocks, so force creation 9442 // of virtual registers for all non-dead arguments. 9443 if (FastISel) 9444 return A->use_empty(); 9445 9446 const BasicBlock &Entry = A->getParent()->front(); 9447 for (const User *U : A->users()) 9448 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 9449 return false; // Use not in entry block. 9450 9451 return true; 9452 } 9453 9454 using ArgCopyElisionMapTy = 9455 DenseMap<const Argument *, 9456 std::pair<const AllocaInst *, const StoreInst *>>; 9457 9458 /// Scan the entry block of the function in FuncInfo for arguments that look 9459 /// like copies into a local alloca. Record any copied arguments in 9460 /// ArgCopyElisionCandidates. 9461 static void 9462 findArgumentCopyElisionCandidates(const DataLayout &DL, 9463 FunctionLoweringInfo *FuncInfo, 9464 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 9465 // Record the state of every static alloca used in the entry block. Argument 9466 // allocas are all used in the entry block, so we need approximately as many 9467 // entries as we have arguments. 9468 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 9469 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 9470 unsigned NumArgs = FuncInfo->Fn->arg_size(); 9471 StaticAllocas.reserve(NumArgs * 2); 9472 9473 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 9474 if (!V) 9475 return nullptr; 9476 V = V->stripPointerCasts(); 9477 const auto *AI = dyn_cast<AllocaInst>(V); 9478 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 9479 return nullptr; 9480 auto Iter = StaticAllocas.insert({AI, Unknown}); 9481 return &Iter.first->second; 9482 }; 9483 9484 // Look for stores of arguments to static allocas. Look through bitcasts and 9485 // GEPs to handle type coercions, as long as the alloca is fully initialized 9486 // by the store. Any non-store use of an alloca escapes it and any subsequent 9487 // unanalyzed store might write it. 9488 // FIXME: Handle structs initialized with multiple stores. 9489 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 9490 // Look for stores, and handle non-store uses conservatively. 9491 const auto *SI = dyn_cast<StoreInst>(&I); 9492 if (!SI) { 9493 // We will look through cast uses, so ignore them completely. 9494 if (I.isCast()) 9495 continue; 9496 // Ignore debug info intrinsics, they don't escape or store to allocas. 9497 if (isa<DbgInfoIntrinsic>(I)) 9498 continue; 9499 // This is an unknown instruction. Assume it escapes or writes to all 9500 // static alloca operands. 9501 for (const Use &U : I.operands()) { 9502 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 9503 *Info = StaticAllocaInfo::Clobbered; 9504 } 9505 continue; 9506 } 9507 9508 // If the stored value is a static alloca, mark it as escaped. 9509 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 9510 *Info = StaticAllocaInfo::Clobbered; 9511 9512 // Check if the destination is a static alloca. 9513 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 9514 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 9515 if (!Info) 9516 continue; 9517 const AllocaInst *AI = cast<AllocaInst>(Dst); 9518 9519 // Skip allocas that have been initialized or clobbered. 9520 if (*Info != StaticAllocaInfo::Unknown) 9521 continue; 9522 9523 // Check if the stored value is an argument, and that this store fully 9524 // initializes the alloca. Don't elide copies from the same argument twice. 9525 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 9526 const auto *Arg = dyn_cast<Argument>(Val); 9527 if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() || 9528 Arg->getType()->isEmptyTy() || 9529 DL.getTypeStoreSize(Arg->getType()) != 9530 DL.getTypeAllocSize(AI->getAllocatedType()) || 9531 ArgCopyElisionCandidates.count(Arg)) { 9532 *Info = StaticAllocaInfo::Clobbered; 9533 continue; 9534 } 9535 9536 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 9537 << '\n'); 9538 9539 // Mark this alloca and store for argument copy elision. 9540 *Info = StaticAllocaInfo::Elidable; 9541 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 9542 9543 // Stop scanning if we've seen all arguments. This will happen early in -O0 9544 // builds, which is useful, because -O0 builds have large entry blocks and 9545 // many allocas. 9546 if (ArgCopyElisionCandidates.size() == NumArgs) 9547 break; 9548 } 9549 } 9550 9551 /// Try to elide argument copies from memory into a local alloca. Succeeds if 9552 /// ArgVal is a load from a suitable fixed stack object. 9553 static void tryToElideArgumentCopy( 9554 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 9555 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 9556 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 9557 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 9558 SDValue ArgVal, bool &ArgHasUses) { 9559 // Check if this is a load from a fixed stack object. 9560 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 9561 if (!LNode) 9562 return; 9563 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 9564 if (!FINode) 9565 return; 9566 9567 // Check that the fixed stack object is the right size and alignment. 9568 // Look at the alignment that the user wrote on the alloca instead of looking 9569 // at the stack object. 9570 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 9571 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 9572 const AllocaInst *AI = ArgCopyIter->second.first; 9573 int FixedIndex = FINode->getIndex(); 9574 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 9575 int OldIndex = AllocaIndex; 9576 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 9577 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 9578 LLVM_DEBUG( 9579 dbgs() << " argument copy elision failed due to bad fixed stack " 9580 "object size\n"); 9581 return; 9582 } 9583 unsigned RequiredAlignment = AI->getAlignment(); 9584 if (!RequiredAlignment) { 9585 RequiredAlignment = FuncInfo.MF->getDataLayout().getABITypeAlignment( 9586 AI->getAllocatedType()); 9587 } 9588 if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) { 9589 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 9590 "greater than stack argument alignment (" 9591 << RequiredAlignment << " vs " 9592 << MFI.getObjectAlignment(FixedIndex) << ")\n"); 9593 return; 9594 } 9595 9596 // Perform the elision. Delete the old stack object and replace its only use 9597 // in the variable info map. Mark the stack object as mutable. 9598 LLVM_DEBUG({ 9599 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 9600 << " Replacing frame index " << OldIndex << " with " << FixedIndex 9601 << '\n'; 9602 }); 9603 MFI.RemoveStackObject(OldIndex); 9604 MFI.setIsImmutableObjectIndex(FixedIndex, false); 9605 AllocaIndex = FixedIndex; 9606 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 9607 Chains.push_back(ArgVal.getValue(1)); 9608 9609 // Avoid emitting code for the store implementing the copy. 9610 const StoreInst *SI = ArgCopyIter->second.second; 9611 ElidedArgCopyInstrs.insert(SI); 9612 9613 // Check for uses of the argument again so that we can avoid exporting ArgVal 9614 // if it is't used by anything other than the store. 9615 for (const Value *U : Arg.users()) { 9616 if (U != SI) { 9617 ArgHasUses = true; 9618 break; 9619 } 9620 } 9621 } 9622 9623 void SelectionDAGISel::LowerArguments(const Function &F) { 9624 SelectionDAG &DAG = SDB->DAG; 9625 SDLoc dl = SDB->getCurSDLoc(); 9626 const DataLayout &DL = DAG.getDataLayout(); 9627 SmallVector<ISD::InputArg, 16> Ins; 9628 9629 if (!FuncInfo->CanLowerReturn) { 9630 // Put in an sret pointer parameter before all the other parameters. 9631 SmallVector<EVT, 1> ValueVTs; 9632 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9633 F.getReturnType()->getPointerTo( 9634 DAG.getDataLayout().getAllocaAddrSpace()), 9635 ValueVTs); 9636 9637 // NOTE: Assuming that a pointer will never break down to more than one VT 9638 // or one register. 9639 ISD::ArgFlagsTy Flags; 9640 Flags.setSRet(); 9641 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 9642 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 9643 ISD::InputArg::NoArgIndex, 0); 9644 Ins.push_back(RetArg); 9645 } 9646 9647 // Look for stores of arguments to static allocas. Mark such arguments with a 9648 // flag to ask the target to give us the memory location of that argument if 9649 // available. 9650 ArgCopyElisionMapTy ArgCopyElisionCandidates; 9651 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 9652 ArgCopyElisionCandidates); 9653 9654 // Set up the incoming argument description vector. 9655 for (const Argument &Arg : F.args()) { 9656 unsigned ArgNo = Arg.getArgNo(); 9657 SmallVector<EVT, 4> ValueVTs; 9658 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9659 bool isArgValueUsed = !Arg.use_empty(); 9660 unsigned PartBase = 0; 9661 Type *FinalType = Arg.getType(); 9662 if (Arg.hasAttribute(Attribute::ByVal)) 9663 FinalType = Arg.getParamByValType(); 9664 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 9665 FinalType, F.getCallingConv(), F.isVarArg()); 9666 for (unsigned Value = 0, NumValues = ValueVTs.size(); 9667 Value != NumValues; ++Value) { 9668 EVT VT = ValueVTs[Value]; 9669 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 9670 ISD::ArgFlagsTy Flags; 9671 9672 // Certain targets (such as MIPS), may have a different ABI alignment 9673 // for a type depending on the context. Give the target a chance to 9674 // specify the alignment it wants. 9675 const Align OriginalAlignment( 9676 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 9677 9678 if (Arg.getType()->isPointerTy()) { 9679 Flags.setPointer(); 9680 Flags.setPointerAddrSpace( 9681 cast<PointerType>(Arg.getType())->getAddressSpace()); 9682 } 9683 if (Arg.hasAttribute(Attribute::ZExt)) 9684 Flags.setZExt(); 9685 if (Arg.hasAttribute(Attribute::SExt)) 9686 Flags.setSExt(); 9687 if (Arg.hasAttribute(Attribute::InReg)) { 9688 // If we are using vectorcall calling convention, a structure that is 9689 // passed InReg - is surely an HVA 9690 if (F.getCallingConv() == CallingConv::X86_VectorCall && 9691 isa<StructType>(Arg.getType())) { 9692 // The first value of a structure is marked 9693 if (0 == Value) 9694 Flags.setHvaStart(); 9695 Flags.setHva(); 9696 } 9697 // Set InReg Flag 9698 Flags.setInReg(); 9699 } 9700 if (Arg.hasAttribute(Attribute::StructRet)) 9701 Flags.setSRet(); 9702 if (Arg.hasAttribute(Attribute::SwiftSelf)) 9703 Flags.setSwiftSelf(); 9704 if (Arg.hasAttribute(Attribute::SwiftError)) 9705 Flags.setSwiftError(); 9706 if (Arg.hasAttribute(Attribute::ByVal)) 9707 Flags.setByVal(); 9708 if (Arg.hasAttribute(Attribute::InAlloca)) { 9709 Flags.setInAlloca(); 9710 // Set the byval flag for CCAssignFn callbacks that don't know about 9711 // inalloca. This way we can know how many bytes we should've allocated 9712 // and how many bytes a callee cleanup function will pop. If we port 9713 // inalloca to more targets, we'll have to add custom inalloca handling 9714 // in the various CC lowering callbacks. 9715 Flags.setByVal(); 9716 } 9717 if (F.getCallingConv() == CallingConv::X86_INTR) { 9718 // IA Interrupt passes frame (1st parameter) by value in the stack. 9719 if (ArgNo == 0) 9720 Flags.setByVal(); 9721 } 9722 if (Flags.isByVal() || Flags.isInAlloca()) { 9723 Type *ElementTy = Arg.getParamByValType(); 9724 9725 // For ByVal, size and alignment should be passed from FE. BE will 9726 // guess if this info is not there but there are cases it cannot get 9727 // right. 9728 unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType()); 9729 Flags.setByValSize(FrameSize); 9730 9731 unsigned FrameAlign; 9732 if (Arg.getParamAlignment()) 9733 FrameAlign = Arg.getParamAlignment(); 9734 else 9735 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL); 9736 Flags.setByValAlign(Align(FrameAlign)); 9737 } 9738 if (Arg.hasAttribute(Attribute::Nest)) 9739 Flags.setNest(); 9740 if (NeedsRegBlock) 9741 Flags.setInConsecutiveRegs(); 9742 Flags.setOrigAlign(OriginalAlignment); 9743 if (ArgCopyElisionCandidates.count(&Arg)) 9744 Flags.setCopyElisionCandidate(); 9745 if (Arg.hasAttribute(Attribute::Returned)) 9746 Flags.setReturned(); 9747 9748 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 9749 *CurDAG->getContext(), F.getCallingConv(), VT); 9750 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 9751 *CurDAG->getContext(), F.getCallingConv(), VT); 9752 for (unsigned i = 0; i != NumRegs; ++i) { 9753 // For scalable vectors, use the minimum size; individual targets 9754 // are responsible for handling scalable vector arguments and 9755 // return values. 9756 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 9757 ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize()); 9758 if (NumRegs > 1 && i == 0) 9759 MyFlags.Flags.setSplit(); 9760 // if it isn't first piece, alignment must be 1 9761 else if (i > 0) { 9762 MyFlags.Flags.setOrigAlign(Align::None()); 9763 if (i == NumRegs - 1) 9764 MyFlags.Flags.setSplitEnd(); 9765 } 9766 Ins.push_back(MyFlags); 9767 } 9768 if (NeedsRegBlock && Value == NumValues - 1) 9769 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 9770 PartBase += VT.getStoreSize().getKnownMinSize(); 9771 } 9772 } 9773 9774 // Call the target to set up the argument values. 9775 SmallVector<SDValue, 8> InVals; 9776 SDValue NewRoot = TLI->LowerFormalArguments( 9777 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 9778 9779 // Verify that the target's LowerFormalArguments behaved as expected. 9780 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 9781 "LowerFormalArguments didn't return a valid chain!"); 9782 assert(InVals.size() == Ins.size() && 9783 "LowerFormalArguments didn't emit the correct number of values!"); 9784 LLVM_DEBUG({ 9785 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 9786 assert(InVals[i].getNode() && 9787 "LowerFormalArguments emitted a null value!"); 9788 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 9789 "LowerFormalArguments emitted a value with the wrong type!"); 9790 } 9791 }); 9792 9793 // Update the DAG with the new chain value resulting from argument lowering. 9794 DAG.setRoot(NewRoot); 9795 9796 // Set up the argument values. 9797 unsigned i = 0; 9798 if (!FuncInfo->CanLowerReturn) { 9799 // Create a virtual register for the sret pointer, and put in a copy 9800 // from the sret argument into it. 9801 SmallVector<EVT, 1> ValueVTs; 9802 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9803 F.getReturnType()->getPointerTo( 9804 DAG.getDataLayout().getAllocaAddrSpace()), 9805 ValueVTs); 9806 MVT VT = ValueVTs[0].getSimpleVT(); 9807 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 9808 Optional<ISD::NodeType> AssertOp = None; 9809 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 9810 nullptr, F.getCallingConv(), AssertOp); 9811 9812 MachineFunction& MF = SDB->DAG.getMachineFunction(); 9813 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 9814 Register SRetReg = 9815 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 9816 FuncInfo->DemoteRegister = SRetReg; 9817 NewRoot = 9818 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 9819 DAG.setRoot(NewRoot); 9820 9821 // i indexes lowered arguments. Bump it past the hidden sret argument. 9822 ++i; 9823 } 9824 9825 SmallVector<SDValue, 4> Chains; 9826 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 9827 for (const Argument &Arg : F.args()) { 9828 SmallVector<SDValue, 4> ArgValues; 9829 SmallVector<EVT, 4> ValueVTs; 9830 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9831 unsigned NumValues = ValueVTs.size(); 9832 if (NumValues == 0) 9833 continue; 9834 9835 bool ArgHasUses = !Arg.use_empty(); 9836 9837 // Elide the copying store if the target loaded this argument from a 9838 // suitable fixed stack object. 9839 if (Ins[i].Flags.isCopyElisionCandidate()) { 9840 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 9841 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 9842 InVals[i], ArgHasUses); 9843 } 9844 9845 // If this argument is unused then remember its value. It is used to generate 9846 // debugging information. 9847 bool isSwiftErrorArg = 9848 TLI->supportSwiftError() && 9849 Arg.hasAttribute(Attribute::SwiftError); 9850 if (!ArgHasUses && !isSwiftErrorArg) { 9851 SDB->setUnusedArgValue(&Arg, InVals[i]); 9852 9853 // Also remember any frame index for use in FastISel. 9854 if (FrameIndexSDNode *FI = 9855 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 9856 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9857 } 9858 9859 for (unsigned Val = 0; Val != NumValues; ++Val) { 9860 EVT VT = ValueVTs[Val]; 9861 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 9862 F.getCallingConv(), VT); 9863 unsigned NumParts = TLI->getNumRegistersForCallingConv( 9864 *CurDAG->getContext(), F.getCallingConv(), VT); 9865 9866 // Even an apparent 'unused' swifterror argument needs to be returned. So 9867 // we do generate a copy for it that can be used on return from the 9868 // function. 9869 if (ArgHasUses || isSwiftErrorArg) { 9870 Optional<ISD::NodeType> AssertOp; 9871 if (Arg.hasAttribute(Attribute::SExt)) 9872 AssertOp = ISD::AssertSext; 9873 else if (Arg.hasAttribute(Attribute::ZExt)) 9874 AssertOp = ISD::AssertZext; 9875 9876 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 9877 PartVT, VT, nullptr, 9878 F.getCallingConv(), AssertOp)); 9879 } 9880 9881 i += NumParts; 9882 } 9883 9884 // We don't need to do anything else for unused arguments. 9885 if (ArgValues.empty()) 9886 continue; 9887 9888 // Note down frame index. 9889 if (FrameIndexSDNode *FI = 9890 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 9891 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9892 9893 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 9894 SDB->getCurSDLoc()); 9895 9896 SDB->setValue(&Arg, Res); 9897 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 9898 // We want to associate the argument with the frame index, among 9899 // involved operands, that correspond to the lowest address. The 9900 // getCopyFromParts function, called earlier, is swapping the order of 9901 // the operands to BUILD_PAIR depending on endianness. The result of 9902 // that swapping is that the least significant bits of the argument will 9903 // be in the first operand of the BUILD_PAIR node, and the most 9904 // significant bits will be in the second operand. 9905 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 9906 if (LoadSDNode *LNode = 9907 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 9908 if (FrameIndexSDNode *FI = 9909 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 9910 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9911 } 9912 9913 // Analyses past this point are naive and don't expect an assertion. 9914 if (Res.getOpcode() == ISD::AssertZext) 9915 Res = Res.getOperand(0); 9916 9917 // Update the SwiftErrorVRegDefMap. 9918 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 9919 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9920 if (Register::isVirtualRegister(Reg)) 9921 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 9922 Reg); 9923 } 9924 9925 // If this argument is live outside of the entry block, insert a copy from 9926 // wherever we got it to the vreg that other BB's will reference it as. 9927 if (Res.getOpcode() == ISD::CopyFromReg) { 9928 // If we can, though, try to skip creating an unnecessary vreg. 9929 // FIXME: This isn't very clean... it would be nice to make this more 9930 // general. 9931 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9932 if (Register::isVirtualRegister(Reg)) { 9933 FuncInfo->ValueMap[&Arg] = Reg; 9934 continue; 9935 } 9936 } 9937 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 9938 FuncInfo->InitializeRegForValue(&Arg); 9939 SDB->CopyToExportRegsIfNeeded(&Arg); 9940 } 9941 } 9942 9943 if (!Chains.empty()) { 9944 Chains.push_back(NewRoot); 9945 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 9946 } 9947 9948 DAG.setRoot(NewRoot); 9949 9950 assert(i == InVals.size() && "Argument register count mismatch!"); 9951 9952 // If any argument copy elisions occurred and we have debug info, update the 9953 // stale frame indices used in the dbg.declare variable info table. 9954 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 9955 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 9956 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 9957 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 9958 if (I != ArgCopyElisionFrameIndexMap.end()) 9959 VI.Slot = I->second; 9960 } 9961 } 9962 9963 // Finally, if the target has anything special to do, allow it to do so. 9964 EmitFunctionEntryCode(); 9965 } 9966 9967 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 9968 /// ensure constants are generated when needed. Remember the virtual registers 9969 /// that need to be added to the Machine PHI nodes as input. We cannot just 9970 /// directly add them, because expansion might result in multiple MBB's for one 9971 /// BB. As such, the start of the BB might correspond to a different MBB than 9972 /// the end. 9973 void 9974 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 9975 const Instruction *TI = LLVMBB->getTerminator(); 9976 9977 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 9978 9979 // Check PHI nodes in successors that expect a value to be available from this 9980 // block. 9981 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 9982 const BasicBlock *SuccBB = TI->getSuccessor(succ); 9983 if (!isa<PHINode>(SuccBB->begin())) continue; 9984 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 9985 9986 // If this terminator has multiple identical successors (common for 9987 // switches), only handle each succ once. 9988 if (!SuccsHandled.insert(SuccMBB).second) 9989 continue; 9990 9991 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 9992 9993 // At this point we know that there is a 1-1 correspondence between LLVM PHI 9994 // nodes and Machine PHI nodes, but the incoming operands have not been 9995 // emitted yet. 9996 for (const PHINode &PN : SuccBB->phis()) { 9997 // Ignore dead phi's. 9998 if (PN.use_empty()) 9999 continue; 10000 10001 // Skip empty types 10002 if (PN.getType()->isEmptyTy()) 10003 continue; 10004 10005 unsigned Reg; 10006 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 10007 10008 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 10009 unsigned &RegOut = ConstantsOut[C]; 10010 if (RegOut == 0) { 10011 RegOut = FuncInfo.CreateRegs(C); 10012 CopyValueToVirtualRegister(C, RegOut); 10013 } 10014 Reg = RegOut; 10015 } else { 10016 DenseMap<const Value *, unsigned>::iterator I = 10017 FuncInfo.ValueMap.find(PHIOp); 10018 if (I != FuncInfo.ValueMap.end()) 10019 Reg = I->second; 10020 else { 10021 assert(isa<AllocaInst>(PHIOp) && 10022 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 10023 "Didn't codegen value into a register!??"); 10024 Reg = FuncInfo.CreateRegs(PHIOp); 10025 CopyValueToVirtualRegister(PHIOp, Reg); 10026 } 10027 } 10028 10029 // Remember that this register needs to added to the machine PHI node as 10030 // the input for this MBB. 10031 SmallVector<EVT, 4> ValueVTs; 10032 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10033 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 10034 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 10035 EVT VT = ValueVTs[vti]; 10036 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 10037 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 10038 FuncInfo.PHINodesToUpdate.push_back( 10039 std::make_pair(&*MBBI++, Reg + i)); 10040 Reg += NumRegisters; 10041 } 10042 } 10043 } 10044 10045 ConstantsOut.clear(); 10046 } 10047 10048 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 10049 /// is 0. 10050 MachineBasicBlock * 10051 SelectionDAGBuilder::StackProtectorDescriptor:: 10052 AddSuccessorMBB(const BasicBlock *BB, 10053 MachineBasicBlock *ParentMBB, 10054 bool IsLikely, 10055 MachineBasicBlock *SuccMBB) { 10056 // If SuccBB has not been created yet, create it. 10057 if (!SuccMBB) { 10058 MachineFunction *MF = ParentMBB->getParent(); 10059 MachineFunction::iterator BBI(ParentMBB); 10060 SuccMBB = MF->CreateMachineBasicBlock(BB); 10061 MF->insert(++BBI, SuccMBB); 10062 } 10063 // Add it as a successor of ParentMBB. 10064 ParentMBB->addSuccessor( 10065 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 10066 return SuccMBB; 10067 } 10068 10069 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 10070 MachineFunction::iterator I(MBB); 10071 if (++I == FuncInfo.MF->end()) 10072 return nullptr; 10073 return &*I; 10074 } 10075 10076 /// During lowering new call nodes can be created (such as memset, etc.). 10077 /// Those will become new roots of the current DAG, but complications arise 10078 /// when they are tail calls. In such cases, the call lowering will update 10079 /// the root, but the builder still needs to know that a tail call has been 10080 /// lowered in order to avoid generating an additional return. 10081 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 10082 // If the node is null, we do have a tail call. 10083 if (MaybeTC.getNode() != nullptr) 10084 DAG.setRoot(MaybeTC); 10085 else 10086 HasTailCall = true; 10087 } 10088 10089 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10090 MachineBasicBlock *SwitchMBB, 10091 MachineBasicBlock *DefaultMBB) { 10092 MachineFunction *CurMF = FuncInfo.MF; 10093 MachineBasicBlock *NextMBB = nullptr; 10094 MachineFunction::iterator BBI(W.MBB); 10095 if (++BBI != FuncInfo.MF->end()) 10096 NextMBB = &*BBI; 10097 10098 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10099 10100 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10101 10102 if (Size == 2 && W.MBB == SwitchMBB) { 10103 // If any two of the cases has the same destination, and if one value 10104 // is the same as the other, but has one bit unset that the other has set, 10105 // use bit manipulation to do two compares at once. For example: 10106 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10107 // TODO: This could be extended to merge any 2 cases in switches with 3 10108 // cases. 10109 // TODO: Handle cases where W.CaseBB != SwitchBB. 10110 CaseCluster &Small = *W.FirstCluster; 10111 CaseCluster &Big = *W.LastCluster; 10112 10113 if (Small.Low == Small.High && Big.Low == Big.High && 10114 Small.MBB == Big.MBB) { 10115 const APInt &SmallValue = Small.Low->getValue(); 10116 const APInt &BigValue = Big.Low->getValue(); 10117 10118 // Check that there is only one bit different. 10119 APInt CommonBit = BigValue ^ SmallValue; 10120 if (CommonBit.isPowerOf2()) { 10121 SDValue CondLHS = getValue(Cond); 10122 EVT VT = CondLHS.getValueType(); 10123 SDLoc DL = getCurSDLoc(); 10124 10125 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10126 DAG.getConstant(CommonBit, DL, VT)); 10127 SDValue Cond = DAG.getSetCC( 10128 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10129 ISD::SETEQ); 10130 10131 // Update successor info. 10132 // Both Small and Big will jump to Small.BB, so we sum up the 10133 // probabilities. 10134 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10135 if (BPI) 10136 addSuccessorWithProb( 10137 SwitchMBB, DefaultMBB, 10138 // The default destination is the first successor in IR. 10139 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10140 else 10141 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10142 10143 // Insert the true branch. 10144 SDValue BrCond = 10145 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10146 DAG.getBasicBlock(Small.MBB)); 10147 // Insert the false branch. 10148 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10149 DAG.getBasicBlock(DefaultMBB)); 10150 10151 DAG.setRoot(BrCond); 10152 return; 10153 } 10154 } 10155 } 10156 10157 if (TM.getOptLevel() != CodeGenOpt::None) { 10158 // Here, we order cases by probability so the most likely case will be 10159 // checked first. However, two clusters can have the same probability in 10160 // which case their relative ordering is non-deterministic. So we use Low 10161 // as a tie-breaker as clusters are guaranteed to never overlap. 10162 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10163 [](const CaseCluster &a, const CaseCluster &b) { 10164 return a.Prob != b.Prob ? 10165 a.Prob > b.Prob : 10166 a.Low->getValue().slt(b.Low->getValue()); 10167 }); 10168 10169 // Rearrange the case blocks so that the last one falls through if possible 10170 // without changing the order of probabilities. 10171 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10172 --I; 10173 if (I->Prob > W.LastCluster->Prob) 10174 break; 10175 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10176 std::swap(*I, *W.LastCluster); 10177 break; 10178 } 10179 } 10180 } 10181 10182 // Compute total probability. 10183 BranchProbability DefaultProb = W.DefaultProb; 10184 BranchProbability UnhandledProbs = DefaultProb; 10185 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10186 UnhandledProbs += I->Prob; 10187 10188 MachineBasicBlock *CurMBB = W.MBB; 10189 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10190 bool FallthroughUnreachable = false; 10191 MachineBasicBlock *Fallthrough; 10192 if (I == W.LastCluster) { 10193 // For the last cluster, fall through to the default destination. 10194 Fallthrough = DefaultMBB; 10195 FallthroughUnreachable = isa<UnreachableInst>( 10196 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10197 } else { 10198 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10199 CurMF->insert(BBI, Fallthrough); 10200 // Put Cond in a virtual register to make it available from the new blocks. 10201 ExportFromCurrentBlock(Cond); 10202 } 10203 UnhandledProbs -= I->Prob; 10204 10205 switch (I->Kind) { 10206 case CC_JumpTable: { 10207 // FIXME: Optimize away range check based on pivot comparisons. 10208 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 10209 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 10210 10211 // The jump block hasn't been inserted yet; insert it here. 10212 MachineBasicBlock *JumpMBB = JT->MBB; 10213 CurMF->insert(BBI, JumpMBB); 10214 10215 auto JumpProb = I->Prob; 10216 auto FallthroughProb = UnhandledProbs; 10217 10218 // If the default statement is a target of the jump table, we evenly 10219 // distribute the default probability to successors of CurMBB. Also 10220 // update the probability on the edge from JumpMBB to Fallthrough. 10221 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10222 SE = JumpMBB->succ_end(); 10223 SI != SE; ++SI) { 10224 if (*SI == DefaultMBB) { 10225 JumpProb += DefaultProb / 2; 10226 FallthroughProb -= DefaultProb / 2; 10227 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10228 JumpMBB->normalizeSuccProbs(); 10229 break; 10230 } 10231 } 10232 10233 if (FallthroughUnreachable) { 10234 // Skip the range check if the fallthrough block is unreachable. 10235 JTH->OmitRangeCheck = true; 10236 } 10237 10238 if (!JTH->OmitRangeCheck) 10239 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10240 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10241 CurMBB->normalizeSuccProbs(); 10242 10243 // The jump table header will be inserted in our current block, do the 10244 // range check, and fall through to our fallthrough block. 10245 JTH->HeaderBB = CurMBB; 10246 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10247 10248 // If we're in the right place, emit the jump table header right now. 10249 if (CurMBB == SwitchMBB) { 10250 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10251 JTH->Emitted = true; 10252 } 10253 break; 10254 } 10255 case CC_BitTests: { 10256 // FIXME: Optimize away range check based on pivot comparisons. 10257 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 10258 10259 // The bit test blocks haven't been inserted yet; insert them here. 10260 for (BitTestCase &BTC : BTB->Cases) 10261 CurMF->insert(BBI, BTC.ThisBB); 10262 10263 // Fill in fields of the BitTestBlock. 10264 BTB->Parent = CurMBB; 10265 BTB->Default = Fallthrough; 10266 10267 BTB->DefaultProb = UnhandledProbs; 10268 // If the cases in bit test don't form a contiguous range, we evenly 10269 // distribute the probability on the edge to Fallthrough to two 10270 // successors of CurMBB. 10271 if (!BTB->ContiguousRange) { 10272 BTB->Prob += DefaultProb / 2; 10273 BTB->DefaultProb -= DefaultProb / 2; 10274 } 10275 10276 if (FallthroughUnreachable) { 10277 // Skip the range check if the fallthrough block is unreachable. 10278 BTB->OmitRangeCheck = true; 10279 } 10280 10281 // If we're in the right place, emit the bit test header right now. 10282 if (CurMBB == SwitchMBB) { 10283 visitBitTestHeader(*BTB, SwitchMBB); 10284 BTB->Emitted = true; 10285 } 10286 break; 10287 } 10288 case CC_Range: { 10289 const Value *RHS, *LHS, *MHS; 10290 ISD::CondCode CC; 10291 if (I->Low == I->High) { 10292 // Check Cond == I->Low. 10293 CC = ISD::SETEQ; 10294 LHS = Cond; 10295 RHS=I->Low; 10296 MHS = nullptr; 10297 } else { 10298 // Check I->Low <= Cond <= I->High. 10299 CC = ISD::SETLE; 10300 LHS = I->Low; 10301 MHS = Cond; 10302 RHS = I->High; 10303 } 10304 10305 // If Fallthrough is unreachable, fold away the comparison. 10306 if (FallthroughUnreachable) 10307 CC = ISD::SETTRUE; 10308 10309 // The false probability is the sum of all unhandled cases. 10310 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10311 getCurSDLoc(), I->Prob, UnhandledProbs); 10312 10313 if (CurMBB == SwitchMBB) 10314 visitSwitchCase(CB, SwitchMBB); 10315 else 10316 SL->SwitchCases.push_back(CB); 10317 10318 break; 10319 } 10320 } 10321 CurMBB = Fallthrough; 10322 } 10323 } 10324 10325 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10326 CaseClusterIt First, 10327 CaseClusterIt Last) { 10328 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10329 if (X.Prob != CC.Prob) 10330 return X.Prob > CC.Prob; 10331 10332 // Ties are broken by comparing the case value. 10333 return X.Low->getValue().slt(CC.Low->getValue()); 10334 }); 10335 } 10336 10337 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10338 const SwitchWorkListItem &W, 10339 Value *Cond, 10340 MachineBasicBlock *SwitchMBB) { 10341 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10342 "Clusters not sorted?"); 10343 10344 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10345 10346 // Balance the tree based on branch probabilities to create a near-optimal (in 10347 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10348 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10349 CaseClusterIt LastLeft = W.FirstCluster; 10350 CaseClusterIt FirstRight = W.LastCluster; 10351 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10352 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10353 10354 // Move LastLeft and FirstRight towards each other from opposite directions to 10355 // find a partitioning of the clusters which balances the probability on both 10356 // sides. If LeftProb and RightProb are equal, alternate which side is 10357 // taken to ensure 0-probability nodes are distributed evenly. 10358 unsigned I = 0; 10359 while (LastLeft + 1 < FirstRight) { 10360 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10361 LeftProb += (++LastLeft)->Prob; 10362 else 10363 RightProb += (--FirstRight)->Prob; 10364 I++; 10365 } 10366 10367 while (true) { 10368 // Our binary search tree differs from a typical BST in that ours can have up 10369 // to three values in each leaf. The pivot selection above doesn't take that 10370 // into account, which means the tree might require more nodes and be less 10371 // efficient. We compensate for this here. 10372 10373 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10374 unsigned NumRight = W.LastCluster - FirstRight + 1; 10375 10376 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10377 // If one side has less than 3 clusters, and the other has more than 3, 10378 // consider taking a cluster from the other side. 10379 10380 if (NumLeft < NumRight) { 10381 // Consider moving the first cluster on the right to the left side. 10382 CaseCluster &CC = *FirstRight; 10383 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10384 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10385 if (LeftSideRank <= RightSideRank) { 10386 // Moving the cluster to the left does not demote it. 10387 ++LastLeft; 10388 ++FirstRight; 10389 continue; 10390 } 10391 } else { 10392 assert(NumRight < NumLeft); 10393 // Consider moving the last element on the left to the right side. 10394 CaseCluster &CC = *LastLeft; 10395 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10396 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10397 if (RightSideRank <= LeftSideRank) { 10398 // Moving the cluster to the right does not demot it. 10399 --LastLeft; 10400 --FirstRight; 10401 continue; 10402 } 10403 } 10404 } 10405 break; 10406 } 10407 10408 assert(LastLeft + 1 == FirstRight); 10409 assert(LastLeft >= W.FirstCluster); 10410 assert(FirstRight <= W.LastCluster); 10411 10412 // Use the first element on the right as pivot since we will make less-than 10413 // comparisons against it. 10414 CaseClusterIt PivotCluster = FirstRight; 10415 assert(PivotCluster > W.FirstCluster); 10416 assert(PivotCluster <= W.LastCluster); 10417 10418 CaseClusterIt FirstLeft = W.FirstCluster; 10419 CaseClusterIt LastRight = W.LastCluster; 10420 10421 const ConstantInt *Pivot = PivotCluster->Low; 10422 10423 // New blocks will be inserted immediately after the current one. 10424 MachineFunction::iterator BBI(W.MBB); 10425 ++BBI; 10426 10427 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10428 // we can branch to its destination directly if it's squeezed exactly in 10429 // between the known lower bound and Pivot - 1. 10430 MachineBasicBlock *LeftMBB; 10431 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10432 FirstLeft->Low == W.GE && 10433 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10434 LeftMBB = FirstLeft->MBB; 10435 } else { 10436 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10437 FuncInfo.MF->insert(BBI, LeftMBB); 10438 WorkList.push_back( 10439 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10440 // Put Cond in a virtual register to make it available from the new blocks. 10441 ExportFromCurrentBlock(Cond); 10442 } 10443 10444 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10445 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10446 // directly if RHS.High equals the current upper bound. 10447 MachineBasicBlock *RightMBB; 10448 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10449 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10450 RightMBB = FirstRight->MBB; 10451 } else { 10452 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10453 FuncInfo.MF->insert(BBI, RightMBB); 10454 WorkList.push_back( 10455 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10456 // Put Cond in a virtual register to make it available from the new blocks. 10457 ExportFromCurrentBlock(Cond); 10458 } 10459 10460 // Create the CaseBlock record that will be used to lower the branch. 10461 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10462 getCurSDLoc(), LeftProb, RightProb); 10463 10464 if (W.MBB == SwitchMBB) 10465 visitSwitchCase(CB, SwitchMBB); 10466 else 10467 SL->SwitchCases.push_back(CB); 10468 } 10469 10470 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10471 // from the swith statement. 10472 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10473 BranchProbability PeeledCaseProb) { 10474 if (PeeledCaseProb == BranchProbability::getOne()) 10475 return BranchProbability::getZero(); 10476 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10477 10478 uint32_t Numerator = CaseProb.getNumerator(); 10479 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10480 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10481 } 10482 10483 // Try to peel the top probability case if it exceeds the threshold. 10484 // Return current MachineBasicBlock for the switch statement if the peeling 10485 // does not occur. 10486 // If the peeling is performed, return the newly created MachineBasicBlock 10487 // for the peeled switch statement. Also update Clusters to remove the peeled 10488 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10489 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10490 const SwitchInst &SI, CaseClusterVector &Clusters, 10491 BranchProbability &PeeledCaseProb) { 10492 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10493 // Don't perform if there is only one cluster or optimizing for size. 10494 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10495 TM.getOptLevel() == CodeGenOpt::None || 10496 SwitchMBB->getParent()->getFunction().hasMinSize()) 10497 return SwitchMBB; 10498 10499 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10500 unsigned PeeledCaseIndex = 0; 10501 bool SwitchPeeled = false; 10502 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10503 CaseCluster &CC = Clusters[Index]; 10504 if (CC.Prob < TopCaseProb) 10505 continue; 10506 TopCaseProb = CC.Prob; 10507 PeeledCaseIndex = Index; 10508 SwitchPeeled = true; 10509 } 10510 if (!SwitchPeeled) 10511 return SwitchMBB; 10512 10513 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10514 << TopCaseProb << "\n"); 10515 10516 // Record the MBB for the peeled switch statement. 10517 MachineFunction::iterator BBI(SwitchMBB); 10518 ++BBI; 10519 MachineBasicBlock *PeeledSwitchMBB = 10520 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10521 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10522 10523 ExportFromCurrentBlock(SI.getCondition()); 10524 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10525 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10526 nullptr, nullptr, TopCaseProb.getCompl()}; 10527 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10528 10529 Clusters.erase(PeeledCaseIt); 10530 for (CaseCluster &CC : Clusters) { 10531 LLVM_DEBUG( 10532 dbgs() << "Scale the probablity for one cluster, before scaling: " 10533 << CC.Prob << "\n"); 10534 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10535 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10536 } 10537 PeeledCaseProb = TopCaseProb; 10538 return PeeledSwitchMBB; 10539 } 10540 10541 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10542 // Extract cases from the switch. 10543 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10544 CaseClusterVector Clusters; 10545 Clusters.reserve(SI.getNumCases()); 10546 for (auto I : SI.cases()) { 10547 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10548 const ConstantInt *CaseVal = I.getCaseValue(); 10549 BranchProbability Prob = 10550 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10551 : BranchProbability(1, SI.getNumCases() + 1); 10552 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10553 } 10554 10555 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10556 10557 // Cluster adjacent cases with the same destination. We do this at all 10558 // optimization levels because it's cheap to do and will make codegen faster 10559 // if there are many clusters. 10560 sortAndRangeify(Clusters); 10561 10562 // The branch probablity of the peeled case. 10563 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10564 MachineBasicBlock *PeeledSwitchMBB = 10565 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10566 10567 // If there is only the default destination, jump there directly. 10568 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10569 if (Clusters.empty()) { 10570 assert(PeeledSwitchMBB == SwitchMBB); 10571 SwitchMBB->addSuccessor(DefaultMBB); 10572 if (DefaultMBB != NextBlock(SwitchMBB)) { 10573 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10574 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10575 } 10576 return; 10577 } 10578 10579 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 10580 SL->findBitTestClusters(Clusters, &SI); 10581 10582 LLVM_DEBUG({ 10583 dbgs() << "Case clusters: "; 10584 for (const CaseCluster &C : Clusters) { 10585 if (C.Kind == CC_JumpTable) 10586 dbgs() << "JT:"; 10587 if (C.Kind == CC_BitTests) 10588 dbgs() << "BT:"; 10589 10590 C.Low->getValue().print(dbgs(), true); 10591 if (C.Low != C.High) { 10592 dbgs() << '-'; 10593 C.High->getValue().print(dbgs(), true); 10594 } 10595 dbgs() << ' '; 10596 } 10597 dbgs() << '\n'; 10598 }); 10599 10600 assert(!Clusters.empty()); 10601 SwitchWorkList WorkList; 10602 CaseClusterIt First = Clusters.begin(); 10603 CaseClusterIt Last = Clusters.end() - 1; 10604 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10605 // Scale the branchprobability for DefaultMBB if the peel occurs and 10606 // DefaultMBB is not replaced. 10607 if (PeeledCaseProb != BranchProbability::getZero() && 10608 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10609 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10610 WorkList.push_back( 10611 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10612 10613 while (!WorkList.empty()) { 10614 SwitchWorkListItem W = WorkList.back(); 10615 WorkList.pop_back(); 10616 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10617 10618 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10619 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 10620 // For optimized builds, lower large range as a balanced binary tree. 10621 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10622 continue; 10623 } 10624 10625 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10626 } 10627 } 10628 10629 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 10630 SDValue N = getValue(I.getOperand(0)); 10631 setValue(&I, N); 10632 } 10633