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/BranchProbabilityInfo.h" 31 #include "llvm/Analysis/BlockFrequencyInfo.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/LLVMContext.h" 90 #include "llvm/IR/Metadata.h" 91 #include "llvm/IR/Module.h" 92 #include "llvm/IR/Operator.h" 93 #include "llvm/IR/PatternMatch.h" 94 #include "llvm/IR/Statepoint.h" 95 #include "llvm/IR/Type.h" 96 #include "llvm/IR/User.h" 97 #include "llvm/IR/Value.h" 98 #include "llvm/MC/MCContext.h" 99 #include "llvm/MC/MCSymbol.h" 100 #include "llvm/Support/AtomicOrdering.h" 101 #include "llvm/Support/BranchProbability.h" 102 #include "llvm/Support/Casting.h" 103 #include "llvm/Support/CodeGen.h" 104 #include "llvm/Support/CommandLine.h" 105 #include "llvm/Support/Compiler.h" 106 #include "llvm/Support/Debug.h" 107 #include "llvm/Support/ErrorHandling.h" 108 #include "llvm/Support/MachineValueType.h" 109 #include "llvm/Support/MathExtras.h" 110 #include "llvm/Support/raw_ostream.h" 111 #include "llvm/Target/TargetIntrinsicInfo.h" 112 #include "llvm/Target/TargetMachine.h" 113 #include "llvm/Target/TargetOptions.h" 114 #include "llvm/Transforms/Utils/Local.h" 115 #include <algorithm> 116 #include <cassert> 117 #include <cstddef> 118 #include <cstdint> 119 #include <cstring> 120 #include <iterator> 121 #include <limits> 122 #include <numeric> 123 #include <tuple> 124 #include <utility> 125 #include <vector> 126 127 using namespace llvm; 128 using namespace PatternMatch; 129 using namespace SwitchCG; 130 131 #define DEBUG_TYPE "isel" 132 133 /// LimitFloatPrecision - Generate low-precision inline sequences for 134 /// some float libcalls (6, 8 or 12 bits). 135 static unsigned LimitFloatPrecision; 136 137 static cl::opt<unsigned, true> 138 LimitFPPrecision("limit-float-precision", 139 cl::desc("Generate low-precision inline sequences " 140 "for some float libcalls"), 141 cl::location(LimitFloatPrecision), cl::Hidden, 142 cl::init(0)); 143 144 static cl::opt<unsigned> SwitchPeelThreshold( 145 "switch-peel-threshold", cl::Hidden, cl::init(66), 146 cl::desc("Set the case probability threshold for peeling the case from a " 147 "switch statement. A value greater than 100 will void this " 148 "optimization")); 149 150 // Limit the width of DAG chains. This is important in general to prevent 151 // DAG-based analysis from blowing up. For example, alias analysis and 152 // load clustering may not complete in reasonable time. It is difficult to 153 // recognize and avoid this situation within each individual analysis, and 154 // future analyses are likely to have the same behavior. Limiting DAG width is 155 // the safe approach and will be especially important with global DAGs. 156 // 157 // MaxParallelChains default is arbitrarily high to avoid affecting 158 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 159 // sequence over this should have been converted to llvm.memcpy by the 160 // frontend. It is easy to induce this behavior with .ll code such as: 161 // %buffer = alloca [4096 x i8] 162 // %data = load [4096 x i8]* %argPtr 163 // store [4096 x i8] %data, [4096 x i8]* %buffer 164 static const unsigned MaxParallelChains = 64; 165 166 // Return the calling convention if the Value passed requires ABI mangling as it 167 // is a parameter to a function or a return value from a function which is not 168 // an intrinsic. 169 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) { 170 if (auto *R = dyn_cast<ReturnInst>(V)) 171 return R->getParent()->getParent()->getCallingConv(); 172 173 if (auto *CI = dyn_cast<CallInst>(V)) { 174 const bool IsInlineAsm = CI->isInlineAsm(); 175 const bool IsIndirectFunctionCall = 176 !IsInlineAsm && !CI->getCalledFunction(); 177 178 // It is possible that the call instruction is an inline asm statement or an 179 // indirect function call in which case the return value of 180 // getCalledFunction() would be nullptr. 181 const bool IsInstrinsicCall = 182 !IsInlineAsm && !IsIndirectFunctionCall && 183 CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic; 184 185 if (!IsInlineAsm && !IsInstrinsicCall) 186 return CI->getCallingConv(); 187 } 188 189 return None; 190 } 191 192 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 193 const SDValue *Parts, unsigned NumParts, 194 MVT PartVT, EVT ValueVT, const Value *V, 195 Optional<CallingConv::ID> CC); 196 197 /// getCopyFromParts - Create a value that contains the specified legal parts 198 /// combined into the value they represent. If the parts combine to a type 199 /// larger than ValueVT then AssertOp can be used to specify whether the extra 200 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 201 /// (ISD::AssertSext). 202 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 203 const SDValue *Parts, unsigned NumParts, 204 MVT PartVT, EVT ValueVT, const Value *V, 205 Optional<CallingConv::ID> CC = None, 206 Optional<ISD::NodeType> AssertOp = None) { 207 if (ValueVT.isVector()) 208 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 209 CC); 210 211 assert(NumParts > 0 && "No parts to assemble!"); 212 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 213 SDValue Val = Parts[0]; 214 215 if (NumParts > 1) { 216 // Assemble the value from multiple parts. 217 if (ValueVT.isInteger()) { 218 unsigned PartBits = PartVT.getSizeInBits(); 219 unsigned ValueBits = ValueVT.getSizeInBits(); 220 221 // Assemble the power of 2 part. 222 unsigned RoundParts = 223 (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts; 224 unsigned RoundBits = PartBits * RoundParts; 225 EVT RoundVT = RoundBits == ValueBits ? 226 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 227 SDValue Lo, Hi; 228 229 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 230 231 if (RoundParts > 2) { 232 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 233 PartVT, HalfVT, V); 234 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 235 RoundParts / 2, PartVT, HalfVT, V); 236 } else { 237 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 238 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 239 } 240 241 if (DAG.getDataLayout().isBigEndian()) 242 std::swap(Lo, Hi); 243 244 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 245 246 if (RoundParts < NumParts) { 247 // Assemble the trailing non-power-of-2 part. 248 unsigned OddParts = NumParts - RoundParts; 249 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 250 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 251 OddVT, V, CC); 252 253 // Combine the round and odd parts. 254 Lo = Val; 255 if (DAG.getDataLayout().isBigEndian()) 256 std::swap(Lo, Hi); 257 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 258 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 259 Hi = 260 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 261 DAG.getConstant(Lo.getValueSizeInBits(), DL, 262 TLI.getPointerTy(DAG.getDataLayout()))); 263 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 264 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 265 } 266 } else if (PartVT.isFloatingPoint()) { 267 // FP split into multiple FP parts (for ppcf128) 268 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 269 "Unexpected split"); 270 SDValue Lo, Hi; 271 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 272 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 273 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 274 std::swap(Lo, Hi); 275 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 276 } else { 277 // FP split into integer parts (soft fp) 278 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 279 !PartVT.isVector() && "Unexpected split"); 280 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 281 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 282 } 283 } 284 285 // There is now one part, held in Val. Correct it to match ValueVT. 286 // PartEVT is the type of the register class that holds the value. 287 // ValueVT is the type of the inline asm operation. 288 EVT PartEVT = Val.getValueType(); 289 290 if (PartEVT == ValueVT) 291 return Val; 292 293 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 294 ValueVT.bitsLT(PartEVT)) { 295 // For an FP value in an integer part, we need to truncate to the right 296 // width first. 297 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 298 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 299 } 300 301 // Handle types that have the same size. 302 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 303 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 304 305 // Handle types with different sizes. 306 if (PartEVT.isInteger() && ValueVT.isInteger()) { 307 if (ValueVT.bitsLT(PartEVT)) { 308 // For a truncate, see if we have any information to 309 // indicate whether the truncated bits will always be 310 // zero or sign-extension. 311 if (AssertOp.hasValue()) 312 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 313 DAG.getValueType(ValueVT)); 314 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 315 } 316 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 317 } 318 319 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 320 // FP_ROUND's are always exact here. 321 if (ValueVT.bitsLT(Val.getValueType())) 322 return DAG.getNode( 323 ISD::FP_ROUND, DL, ValueVT, Val, 324 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 325 326 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 327 } 328 329 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 330 // then truncating. 331 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 332 ValueVT.bitsLT(PartEVT)) { 333 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 334 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 335 } 336 337 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 338 } 339 340 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 341 const Twine &ErrMsg) { 342 const Instruction *I = dyn_cast_or_null<Instruction>(V); 343 if (!V) 344 return Ctx.emitError(ErrMsg); 345 346 const char *AsmError = ", possible invalid constraint for vector type"; 347 if (const CallInst *CI = dyn_cast<CallInst>(I)) 348 if (isa<InlineAsm>(CI->getCalledValue())) 349 return Ctx.emitError(I, ErrMsg + AsmError); 350 351 return Ctx.emitError(I, ErrMsg); 352 } 353 354 /// getCopyFromPartsVector - Create a value that contains the specified legal 355 /// parts combined into the value they represent. If the parts combine to a 356 /// type larger than ValueVT then AssertOp can be used to specify whether the 357 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 358 /// ValueVT (ISD::AssertSext). 359 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 360 const SDValue *Parts, unsigned NumParts, 361 MVT PartVT, EVT ValueVT, const Value *V, 362 Optional<CallingConv::ID> CallConv) { 363 assert(ValueVT.isVector() && "Not a vector value"); 364 assert(NumParts > 0 && "No parts to assemble!"); 365 const bool IsABIRegCopy = CallConv.hasValue(); 366 367 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 368 SDValue Val = Parts[0]; 369 370 // Handle a multi-element vector. 371 if (NumParts > 1) { 372 EVT IntermediateVT; 373 MVT RegisterVT; 374 unsigned NumIntermediates; 375 unsigned NumRegs; 376 377 if (IsABIRegCopy) { 378 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 379 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 380 NumIntermediates, RegisterVT); 381 } else { 382 NumRegs = 383 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 384 NumIntermediates, RegisterVT); 385 } 386 387 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 388 NumParts = NumRegs; // Silence a compiler warning. 389 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 390 assert(RegisterVT.getSizeInBits() == 391 Parts[0].getSimpleValueType().getSizeInBits() && 392 "Part type sizes don't match!"); 393 394 // Assemble the parts into intermediate operands. 395 SmallVector<SDValue, 8> Ops(NumIntermediates); 396 if (NumIntermediates == NumParts) { 397 // If the register was not expanded, truncate or copy the value, 398 // as appropriate. 399 for (unsigned i = 0; i != NumParts; ++i) 400 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 401 PartVT, IntermediateVT, V); 402 } else if (NumParts > 0) { 403 // If the intermediate type was expanded, build the intermediate 404 // operands from the parts. 405 assert(NumParts % NumIntermediates == 0 && 406 "Must expand into a divisible number of parts!"); 407 unsigned Factor = NumParts / NumIntermediates; 408 for (unsigned i = 0; i != NumIntermediates; ++i) 409 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 410 PartVT, IntermediateVT, V); 411 } 412 413 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 414 // intermediate operands. 415 EVT BuiltVectorTy = 416 EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(), 417 (IntermediateVT.isVector() 418 ? IntermediateVT.getVectorNumElements() * NumParts 419 : NumIntermediates)); 420 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 421 : ISD::BUILD_VECTOR, 422 DL, BuiltVectorTy, Ops); 423 } 424 425 // There is now one part, held in Val. Correct it to match ValueVT. 426 EVT PartEVT = Val.getValueType(); 427 428 if (PartEVT == ValueVT) 429 return Val; 430 431 if (PartEVT.isVector()) { 432 // If the element type of the source/dest vectors are the same, but the 433 // parts vector has more elements than the value vector, then we have a 434 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 435 // elements we want. 436 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { 437 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() && 438 "Cannot narrow, it would be a lossy transformation"); 439 return DAG.getNode( 440 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 441 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 442 } 443 444 // Vector/Vector bitcast. 445 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 446 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 447 448 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() && 449 "Cannot handle this kind of promotion"); 450 // Promoted vector extract 451 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 452 453 } 454 455 // Trivial bitcast if the types are the same size and the destination 456 // vector type is legal. 457 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 458 TLI.isTypeLegal(ValueVT)) 459 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 460 461 if (ValueVT.getVectorNumElements() != 1) { 462 // Certain ABIs require that vectors are passed as integers. For vectors 463 // are the same size, this is an obvious bitcast. 464 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 465 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 466 } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) { 467 // Bitcast Val back the original type and extract the corresponding 468 // vector we want. 469 unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits(); 470 EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(), 471 ValueVT.getVectorElementType(), Elts); 472 Val = DAG.getBitcast(WiderVecType, Val); 473 return DAG.getNode( 474 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 475 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 476 } 477 478 diagnosePossiblyInvalidConstraint( 479 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 480 return DAG.getUNDEF(ValueVT); 481 } 482 483 // Handle cases such as i8 -> <1 x i1> 484 EVT ValueSVT = ValueVT.getVectorElementType(); 485 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) 486 Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 487 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 488 489 return DAG.getBuildVector(ValueVT, DL, Val); 490 } 491 492 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 493 SDValue Val, SDValue *Parts, unsigned NumParts, 494 MVT PartVT, const Value *V, 495 Optional<CallingConv::ID> CallConv); 496 497 /// getCopyToParts - Create a series of nodes that contain the specified value 498 /// split into legal parts. If the parts contain more bits than Val, then, for 499 /// integers, ExtendKind can be used to specify how to generate the extra bits. 500 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 501 SDValue *Parts, unsigned NumParts, MVT PartVT, 502 const Value *V, 503 Optional<CallingConv::ID> CallConv = None, 504 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 505 EVT ValueVT = Val.getValueType(); 506 507 // Handle the vector case separately. 508 if (ValueVT.isVector()) 509 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 510 CallConv); 511 512 unsigned PartBits = PartVT.getSizeInBits(); 513 unsigned OrigNumParts = NumParts; 514 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 515 "Copying to an illegal type!"); 516 517 if (NumParts == 0) 518 return; 519 520 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 521 EVT PartEVT = PartVT; 522 if (PartEVT == ValueVT) { 523 assert(NumParts == 1 && "No-op copy with multiple parts!"); 524 Parts[0] = Val; 525 return; 526 } 527 528 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 529 // If the parts cover more bits than the value has, promote the value. 530 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 531 assert(NumParts == 1 && "Do not know what to promote to!"); 532 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 533 } else { 534 if (ValueVT.isFloatingPoint()) { 535 // FP values need to be bitcast, then extended if they are being put 536 // into a larger container. 537 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 538 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 539 } 540 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 541 ValueVT.isInteger() && 542 "Unknown mismatch!"); 543 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 544 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 545 if (PartVT == MVT::x86mmx) 546 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 547 } 548 } else if (PartBits == ValueVT.getSizeInBits()) { 549 // Different types of the same size. 550 assert(NumParts == 1 && PartEVT != ValueVT); 551 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 552 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 553 // If the parts cover less bits than value has, truncate the value. 554 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 555 ValueVT.isInteger() && 556 "Unknown mismatch!"); 557 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 558 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 559 if (PartVT == MVT::x86mmx) 560 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 561 } 562 563 // The value may have changed - recompute ValueVT. 564 ValueVT = Val.getValueType(); 565 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 566 "Failed to tile the value with PartVT!"); 567 568 if (NumParts == 1) { 569 if (PartEVT != ValueVT) { 570 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 571 "scalar-to-vector conversion failed"); 572 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 573 } 574 575 Parts[0] = Val; 576 return; 577 } 578 579 // Expand the value into multiple parts. 580 if (NumParts & (NumParts - 1)) { 581 // The number of parts is not a power of 2. Split off and copy the tail. 582 assert(PartVT.isInteger() && ValueVT.isInteger() && 583 "Do not know what to expand to!"); 584 unsigned RoundParts = 1 << Log2_32(NumParts); 585 unsigned RoundBits = RoundParts * PartBits; 586 unsigned OddParts = NumParts - RoundParts; 587 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 588 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false)); 589 590 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 591 CallConv); 592 593 if (DAG.getDataLayout().isBigEndian()) 594 // The odd parts were reversed by getCopyToParts - unreverse them. 595 std::reverse(Parts + RoundParts, Parts + NumParts); 596 597 NumParts = RoundParts; 598 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 599 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 600 } 601 602 // The number of parts is a power of 2. Repeatedly bisect the value using 603 // EXTRACT_ELEMENT. 604 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 605 EVT::getIntegerVT(*DAG.getContext(), 606 ValueVT.getSizeInBits()), 607 Val); 608 609 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 610 for (unsigned i = 0; i < NumParts; i += StepSize) { 611 unsigned ThisBits = StepSize * PartBits / 2; 612 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 613 SDValue &Part0 = Parts[i]; 614 SDValue &Part1 = Parts[i+StepSize/2]; 615 616 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 617 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 618 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 619 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 620 621 if (ThisBits == PartBits && ThisVT != PartVT) { 622 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 623 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 624 } 625 } 626 } 627 628 if (DAG.getDataLayout().isBigEndian()) 629 std::reverse(Parts, Parts + OrigNumParts); 630 } 631 632 static SDValue widenVectorToPartType(SelectionDAG &DAG, 633 SDValue Val, const SDLoc &DL, EVT PartVT) { 634 if (!PartVT.isVector()) 635 return SDValue(); 636 637 EVT ValueVT = Val.getValueType(); 638 unsigned PartNumElts = PartVT.getVectorNumElements(); 639 unsigned ValueNumElts = ValueVT.getVectorNumElements(); 640 if (PartNumElts > ValueNumElts && 641 PartVT.getVectorElementType() == ValueVT.getVectorElementType()) { 642 EVT ElementVT = PartVT.getVectorElementType(); 643 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 644 // undef elements. 645 SmallVector<SDValue, 16> Ops; 646 DAG.ExtractVectorElements(Val, Ops); 647 SDValue EltUndef = DAG.getUNDEF(ElementVT); 648 for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i) 649 Ops.push_back(EltUndef); 650 651 // FIXME: Use CONCAT for 2x -> 4x. 652 return DAG.getBuildVector(PartVT, DL, Ops); 653 } 654 655 return SDValue(); 656 } 657 658 /// getCopyToPartsVector - Create a series of nodes that contain the specified 659 /// value split into legal parts. 660 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 661 SDValue Val, SDValue *Parts, unsigned NumParts, 662 MVT PartVT, const Value *V, 663 Optional<CallingConv::ID> CallConv) { 664 EVT ValueVT = Val.getValueType(); 665 assert(ValueVT.isVector() && "Not a vector"); 666 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 667 const bool IsABIRegCopy = CallConv.hasValue(); 668 669 if (NumParts == 1) { 670 EVT PartEVT = PartVT; 671 if (PartEVT == ValueVT) { 672 // Nothing to do. 673 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 674 // Bitconvert vector->vector case. 675 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 676 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 677 Val = Widened; 678 } else if (PartVT.isVector() && 679 PartEVT.getVectorElementType().bitsGE( 680 ValueVT.getVectorElementType()) && 681 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) { 682 683 // Promoted vector extract 684 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 685 } else { 686 if (ValueVT.getVectorNumElements() == 1) { 687 Val = DAG.getNode( 688 ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 689 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 690 } else { 691 assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() && 692 "lossy conversion of vector to scalar type"); 693 EVT IntermediateType = 694 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 695 Val = DAG.getBitcast(IntermediateType, Val); 696 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 697 } 698 } 699 700 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 701 Parts[0] = Val; 702 return; 703 } 704 705 // Handle a multi-element vector. 706 EVT IntermediateVT; 707 MVT RegisterVT; 708 unsigned NumIntermediates; 709 unsigned NumRegs; 710 if (IsABIRegCopy) { 711 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 712 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 713 NumIntermediates, RegisterVT); 714 } else { 715 NumRegs = 716 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 717 NumIntermediates, RegisterVT); 718 } 719 720 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 721 NumParts = NumRegs; // Silence a compiler warning. 722 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 723 724 unsigned IntermediateNumElts = IntermediateVT.isVector() ? 725 IntermediateVT.getVectorNumElements() : 1; 726 727 // Convert the vector to the appropriate type if necessary. 728 unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts; 729 730 EVT BuiltVectorTy = EVT::getVectorVT( 731 *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts); 732 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 733 if (ValueVT != BuiltVectorTy) { 734 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) 735 Val = Widened; 736 737 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 738 } 739 740 // Split the vector into intermediate operands. 741 SmallVector<SDValue, 8> Ops(NumIntermediates); 742 for (unsigned i = 0; i != NumIntermediates; ++i) { 743 if (IntermediateVT.isVector()) { 744 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 745 DAG.getConstant(i * IntermediateNumElts, DL, IdxVT)); 746 } else { 747 Ops[i] = DAG.getNode( 748 ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 749 DAG.getConstant(i, DL, IdxVT)); 750 } 751 } 752 753 // Split the intermediate operands into legal parts. 754 if (NumParts == NumIntermediates) { 755 // If the register was not expanded, promote or copy the value, 756 // as appropriate. 757 for (unsigned i = 0; i != NumParts; ++i) 758 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 759 } else if (NumParts > 0) { 760 // If the intermediate type was expanded, split each the value into 761 // legal parts. 762 assert(NumIntermediates != 0 && "division by zero"); 763 assert(NumParts % NumIntermediates == 0 && 764 "Must expand into a divisible number of parts!"); 765 unsigned Factor = NumParts / NumIntermediates; 766 for (unsigned i = 0; i != NumIntermediates; ++i) 767 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 768 CallConv); 769 } 770 } 771 772 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 773 EVT valuevt, Optional<CallingConv::ID> CC) 774 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 775 RegCount(1, regs.size()), CallConv(CC) {} 776 777 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 778 const DataLayout &DL, unsigned Reg, Type *Ty, 779 Optional<CallingConv::ID> CC) { 780 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 781 782 CallConv = CC; 783 784 for (EVT ValueVT : ValueVTs) { 785 unsigned NumRegs = 786 isABIMangled() 787 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) 788 : TLI.getNumRegisters(Context, ValueVT); 789 MVT RegisterVT = 790 isABIMangled() 791 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) 792 : TLI.getRegisterType(Context, ValueVT); 793 for (unsigned i = 0; i != NumRegs; ++i) 794 Regs.push_back(Reg + i); 795 RegVTs.push_back(RegisterVT); 796 RegCount.push_back(NumRegs); 797 Reg += NumRegs; 798 } 799 } 800 801 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 802 FunctionLoweringInfo &FuncInfo, 803 const SDLoc &dl, SDValue &Chain, 804 SDValue *Flag, const Value *V) const { 805 // A Value with type {} or [0 x %t] needs no registers. 806 if (ValueVTs.empty()) 807 return SDValue(); 808 809 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 810 811 // Assemble the legal parts into the final values. 812 SmallVector<SDValue, 4> Values(ValueVTs.size()); 813 SmallVector<SDValue, 8> Parts; 814 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 815 // Copy the legal parts from the registers. 816 EVT ValueVT = ValueVTs[Value]; 817 unsigned NumRegs = RegCount[Value]; 818 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 819 *DAG.getContext(), 820 CallConv.getValue(), RegVTs[Value]) 821 : RegVTs[Value]; 822 823 Parts.resize(NumRegs); 824 for (unsigned i = 0; i != NumRegs; ++i) { 825 SDValue P; 826 if (!Flag) { 827 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 828 } else { 829 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 830 *Flag = P.getValue(2); 831 } 832 833 Chain = P.getValue(1); 834 Parts[i] = P; 835 836 // If the source register was virtual and if we know something about it, 837 // add an assert node. 838 if (!Register::isVirtualRegister(Regs[Part + i]) || 839 !RegisterVT.isInteger()) 840 continue; 841 842 const FunctionLoweringInfo::LiveOutInfo *LOI = 843 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 844 if (!LOI) 845 continue; 846 847 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 848 unsigned NumSignBits = LOI->NumSignBits; 849 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 850 851 if (NumZeroBits == RegSize) { 852 // The current value is a zero. 853 // Explicitly express that as it would be easier for 854 // optimizations to kick in. 855 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 856 continue; 857 } 858 859 // FIXME: We capture more information than the dag can represent. For 860 // now, just use the tightest assertzext/assertsext possible. 861 bool isSExt; 862 EVT FromVT(MVT::Other); 863 if (NumZeroBits) { 864 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 865 isSExt = false; 866 } else if (NumSignBits > 1) { 867 FromVT = 868 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 869 isSExt = true; 870 } else { 871 continue; 872 } 873 // Add an assertion node. 874 assert(FromVT != MVT::Other); 875 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 876 RegisterVT, P, DAG.getValueType(FromVT)); 877 } 878 879 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 880 RegisterVT, ValueVT, V, CallConv); 881 Part += NumRegs; 882 Parts.clear(); 883 } 884 885 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 886 } 887 888 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 889 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 890 const Value *V, 891 ISD::NodeType PreferredExtendType) const { 892 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 893 ISD::NodeType ExtendKind = PreferredExtendType; 894 895 // Get the list of the values's legal parts. 896 unsigned NumRegs = Regs.size(); 897 SmallVector<SDValue, 8> Parts(NumRegs); 898 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 899 unsigned NumParts = RegCount[Value]; 900 901 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 902 *DAG.getContext(), 903 CallConv.getValue(), RegVTs[Value]) 904 : RegVTs[Value]; 905 906 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 907 ExtendKind = ISD::ZERO_EXTEND; 908 909 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 910 NumParts, RegisterVT, V, CallConv, ExtendKind); 911 Part += NumParts; 912 } 913 914 // Copy the parts into the registers. 915 SmallVector<SDValue, 8> Chains(NumRegs); 916 for (unsigned i = 0; i != NumRegs; ++i) { 917 SDValue Part; 918 if (!Flag) { 919 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 920 } else { 921 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 922 *Flag = Part.getValue(1); 923 } 924 925 Chains[i] = Part.getValue(0); 926 } 927 928 if (NumRegs == 1 || Flag) 929 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 930 // flagged to it. That is the CopyToReg nodes and the user are considered 931 // a single scheduling unit. If we create a TokenFactor and return it as 932 // chain, then the TokenFactor is both a predecessor (operand) of the 933 // user as well as a successor (the TF operands are flagged to the user). 934 // c1, f1 = CopyToReg 935 // c2, f2 = CopyToReg 936 // c3 = TokenFactor c1, c2 937 // ... 938 // = op c3, ..., f2 939 Chain = Chains[NumRegs-1]; 940 else 941 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 942 } 943 944 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 945 unsigned MatchingIdx, const SDLoc &dl, 946 SelectionDAG &DAG, 947 std::vector<SDValue> &Ops) const { 948 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 949 950 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 951 if (HasMatching) 952 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 953 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 954 // Put the register class of the virtual registers in the flag word. That 955 // way, later passes can recompute register class constraints for inline 956 // assembly as well as normal instructions. 957 // Don't do this for tied operands that can use the regclass information 958 // from the def. 959 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 960 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 961 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 962 } 963 964 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 965 Ops.push_back(Res); 966 967 if (Code == InlineAsm::Kind_Clobber) { 968 // Clobbers should always have a 1:1 mapping with registers, and may 969 // reference registers that have illegal (e.g. vector) types. Hence, we 970 // shouldn't try to apply any sort of splitting logic to them. 971 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 972 "No 1:1 mapping from clobbers to regs?"); 973 unsigned SP = TLI.getStackPointerRegisterToSaveRestore(); 974 (void)SP; 975 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 976 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 977 assert( 978 (Regs[I] != SP || 979 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 980 "If we clobbered the stack pointer, MFI should know about it."); 981 } 982 return; 983 } 984 985 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 986 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 987 MVT RegisterVT = RegVTs[Value]; 988 for (unsigned i = 0; i != NumRegs; ++i) { 989 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 990 unsigned TheReg = Regs[Reg++]; 991 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 992 } 993 } 994 } 995 996 SmallVector<std::pair<unsigned, unsigned>, 4> 997 RegsForValue::getRegsAndSizes() const { 998 SmallVector<std::pair<unsigned, unsigned>, 4> OutVec; 999 unsigned I = 0; 1000 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1001 unsigned RegCount = std::get<0>(CountAndVT); 1002 MVT RegisterVT = std::get<1>(CountAndVT); 1003 unsigned RegisterSize = RegisterVT.getSizeInBits(); 1004 for (unsigned E = I + RegCount; I != E; ++I) 1005 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1006 } 1007 return OutVec; 1008 } 1009 1010 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1011 const TargetLibraryInfo *li) { 1012 AA = aa; 1013 GFI = gfi; 1014 LibInfo = li; 1015 DL = &DAG.getDataLayout(); 1016 Context = DAG.getContext(); 1017 LPadToCallSiteMap.clear(); 1018 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1019 } 1020 1021 void SelectionDAGBuilder::clear() { 1022 NodeMap.clear(); 1023 UnusedArgNodeMap.clear(); 1024 PendingLoads.clear(); 1025 PendingExports.clear(); 1026 CurInst = nullptr; 1027 HasTailCall = false; 1028 SDNodeOrder = LowestSDNodeOrder; 1029 StatepointLowering.clear(); 1030 } 1031 1032 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1033 DanglingDebugInfoMap.clear(); 1034 } 1035 1036 SDValue SelectionDAGBuilder::getRoot() { 1037 if (PendingLoads.empty()) 1038 return DAG.getRoot(); 1039 1040 if (PendingLoads.size() == 1) { 1041 SDValue Root = PendingLoads[0]; 1042 DAG.setRoot(Root); 1043 PendingLoads.clear(); 1044 return Root; 1045 } 1046 1047 // Otherwise, we have to make a token factor node. 1048 SDValue Root = DAG.getTokenFactor(getCurSDLoc(), PendingLoads); 1049 PendingLoads.clear(); 1050 DAG.setRoot(Root); 1051 return Root; 1052 } 1053 1054 SDValue SelectionDAGBuilder::getControlRoot() { 1055 SDValue Root = DAG.getRoot(); 1056 1057 if (PendingExports.empty()) 1058 return Root; 1059 1060 // Turn all of the CopyToReg chains into one factored node. 1061 if (Root.getOpcode() != ISD::EntryToken) { 1062 unsigned i = 0, e = PendingExports.size(); 1063 for (; i != e; ++i) { 1064 assert(PendingExports[i].getNode()->getNumOperands() > 1); 1065 if (PendingExports[i].getNode()->getOperand(0) == Root) 1066 break; // Don't add the root if we already indirectly depend on it. 1067 } 1068 1069 if (i == e) 1070 PendingExports.push_back(Root); 1071 } 1072 1073 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, 1074 PendingExports); 1075 PendingExports.clear(); 1076 DAG.setRoot(Root); 1077 return Root; 1078 } 1079 1080 void SelectionDAGBuilder::visit(const Instruction &I) { 1081 // Set up outgoing PHI node register values before emitting the terminator. 1082 if (I.isTerminator()) { 1083 HandlePHINodesInSuccessorBlocks(I.getParent()); 1084 } 1085 1086 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1087 if (!isa<DbgInfoIntrinsic>(I)) 1088 ++SDNodeOrder; 1089 1090 CurInst = &I; 1091 1092 visit(I.getOpcode(), I); 1093 1094 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) { 1095 // Propagate the fast-math-flags of this IR instruction to the DAG node that 1096 // maps to this instruction. 1097 // TODO: We could handle all flags (nsw, etc) here. 1098 // TODO: If an IR instruction maps to >1 node, only the final node will have 1099 // flags set. 1100 if (SDNode *Node = getNodeForIRValue(&I)) { 1101 SDNodeFlags IncomingFlags; 1102 IncomingFlags.copyFMF(*FPMO); 1103 if (!Node->getFlags().isDefined()) 1104 Node->setFlags(IncomingFlags); 1105 else 1106 Node->intersectFlagsWith(IncomingFlags); 1107 } 1108 } 1109 1110 if (!I.isTerminator() && !HasTailCall && 1111 !isStatepoint(&I)) // statepoints handle their exports internally 1112 CopyToExportRegsIfNeeded(&I); 1113 1114 CurInst = nullptr; 1115 } 1116 1117 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1118 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1119 } 1120 1121 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1122 // Note: this doesn't use InstVisitor, because it has to work with 1123 // ConstantExpr's in addition to instructions. 1124 switch (Opcode) { 1125 default: llvm_unreachable("Unknown instruction type encountered!"); 1126 // Build the switch statement using the Instruction.def file. 1127 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1128 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1129 #include "llvm/IR/Instruction.def" 1130 } 1131 } 1132 1133 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1134 const DIExpression *Expr) { 1135 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1136 const DbgValueInst *DI = DDI.getDI(); 1137 DIVariable *DanglingVariable = DI->getVariable(); 1138 DIExpression *DanglingExpr = DI->getExpression(); 1139 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1140 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1141 return true; 1142 } 1143 return false; 1144 }; 1145 1146 for (auto &DDIMI : DanglingDebugInfoMap) { 1147 DanglingDebugInfoVector &DDIV = DDIMI.second; 1148 1149 // If debug info is to be dropped, run it through final checks to see 1150 // whether it can be salvaged. 1151 for (auto &DDI : DDIV) 1152 if (isMatchingDbgValue(DDI)) 1153 salvageUnresolvedDbgValue(DDI); 1154 1155 DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end()); 1156 } 1157 } 1158 1159 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1160 // generate the debug data structures now that we've seen its definition. 1161 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1162 SDValue Val) { 1163 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1164 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1165 return; 1166 1167 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1168 for (auto &DDI : DDIV) { 1169 const DbgValueInst *DI = DDI.getDI(); 1170 assert(DI && "Ill-formed DanglingDebugInfo"); 1171 DebugLoc dl = DDI.getdl(); 1172 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1173 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1174 DILocalVariable *Variable = DI->getVariable(); 1175 DIExpression *Expr = DI->getExpression(); 1176 assert(Variable->isValidLocationForIntrinsic(dl) && 1177 "Expected inlined-at fields to agree"); 1178 SDDbgValue *SDV; 1179 if (Val.getNode()) { 1180 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1181 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1182 // we couldn't resolve it directly when examining the DbgValue intrinsic 1183 // in the first place we should not be more successful here). Unless we 1184 // have some test case that prove this to be correct we should avoid 1185 // calling EmitFuncArgumentDbgValue here. 1186 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1187 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1188 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1189 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1190 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1191 // inserted after the definition of Val when emitting the instructions 1192 // after ISel. An alternative could be to teach 1193 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1194 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1195 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1196 << ValSDNodeOrder << "\n"); 1197 SDV = getDbgValue(Val, Variable, Expr, dl, 1198 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1199 DAG.AddDbgValue(SDV, Val.getNode(), false); 1200 } else 1201 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1202 << "in EmitFuncArgumentDbgValue\n"); 1203 } else { 1204 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1205 auto Undef = 1206 UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1207 auto SDV = 1208 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); 1209 DAG.AddDbgValue(SDV, nullptr, false); 1210 } 1211 } 1212 DDIV.clear(); 1213 } 1214 1215 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1216 Value *V = DDI.getDI()->getValue(); 1217 DILocalVariable *Var = DDI.getDI()->getVariable(); 1218 DIExpression *Expr = DDI.getDI()->getExpression(); 1219 DebugLoc DL = DDI.getdl(); 1220 DebugLoc InstDL = DDI.getDI()->getDebugLoc(); 1221 unsigned SDOrder = DDI.getSDNodeOrder(); 1222 1223 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1224 // that DW_OP_stack_value is desired. 1225 assert(isa<DbgValueInst>(DDI.getDI())); 1226 bool StackValue = true; 1227 1228 // Can this Value can be encoded without any further work? 1229 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) 1230 return; 1231 1232 // Attempt to salvage back through as many instructions as possible. Bail if 1233 // a non-instruction is seen, such as a constant expression or global 1234 // variable. FIXME: Further work could recover those too. 1235 while (isa<Instruction>(V)) { 1236 Instruction &VAsInst = *cast<Instruction>(V); 1237 DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue); 1238 1239 // If we cannot salvage any further, and haven't yet found a suitable debug 1240 // expression, bail out. 1241 if (!NewExpr) 1242 break; 1243 1244 // New value and expr now represent this debuginfo. 1245 V = VAsInst.getOperand(0); 1246 Expr = NewExpr; 1247 1248 // Some kind of simplification occurred: check whether the operand of the 1249 // salvaged debug expression can be encoded in this DAG. 1250 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) { 1251 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n " 1252 << DDI.getDI() << "\nBy stripping back to:\n " << V); 1253 return; 1254 } 1255 } 1256 1257 // This was the final opportunity to salvage this debug information, and it 1258 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1259 // any earlier variable location. 1260 auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1261 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1262 DAG.AddDbgValue(SDV, nullptr, false); 1263 1264 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI() 1265 << "\n"); 1266 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0) 1267 << "\n"); 1268 } 1269 1270 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var, 1271 DIExpression *Expr, DebugLoc dl, 1272 DebugLoc InstDL, unsigned Order) { 1273 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1274 SDDbgValue *SDV; 1275 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1276 isa<ConstantPointerNull>(V)) { 1277 SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder); 1278 DAG.AddDbgValue(SDV, nullptr, false); 1279 return true; 1280 } 1281 1282 // If the Value is a frame index, we can create a FrameIndex debug value 1283 // without relying on the DAG at all. 1284 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1285 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1286 if (SI != FuncInfo.StaticAllocaMap.end()) { 1287 auto SDV = 1288 DAG.getFrameIndexDbgValue(Var, Expr, SI->second, 1289 /*IsIndirect*/ false, dl, SDNodeOrder); 1290 // Do not attach the SDNodeDbgValue to an SDNode: this variable location 1291 // is still available even if the SDNode gets optimized out. 1292 DAG.AddDbgValue(SDV, nullptr, false); 1293 return true; 1294 } 1295 } 1296 1297 // Do not use getValue() in here; we don't want to generate code at 1298 // this point if it hasn't been done yet. 1299 SDValue N = NodeMap[V]; 1300 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1301 N = UnusedArgNodeMap[V]; 1302 if (N.getNode()) { 1303 if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N)) 1304 return true; 1305 SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder); 1306 DAG.AddDbgValue(SDV, N.getNode(), false); 1307 return true; 1308 } 1309 1310 // Special rules apply for the first dbg.values of parameter variables in a 1311 // function. Identify them by the fact they reference Argument Values, that 1312 // they're parameters, and they are parameters of the current function. We 1313 // need to let them dangle until they get an SDNode. 1314 bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() && 1315 !InstDL.getInlinedAt(); 1316 if (!IsParamOfFunc) { 1317 // The value is not used in this block yet (or it would have an SDNode). 1318 // We still want the value to appear for the user if possible -- if it has 1319 // an associated VReg, we can refer to that instead. 1320 auto VMI = FuncInfo.ValueMap.find(V); 1321 if (VMI != FuncInfo.ValueMap.end()) { 1322 unsigned Reg = VMI->second; 1323 // If this is a PHI node, it may be split up into several MI PHI nodes 1324 // (in FunctionLoweringInfo::set). 1325 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1326 V->getType(), None); 1327 if (RFV.occupiesMultipleRegs()) { 1328 unsigned Offset = 0; 1329 unsigned BitsToDescribe = 0; 1330 if (auto VarSize = Var->getSizeInBits()) 1331 BitsToDescribe = *VarSize; 1332 if (auto Fragment = Expr->getFragmentInfo()) 1333 BitsToDescribe = Fragment->SizeInBits; 1334 for (auto RegAndSize : RFV.getRegsAndSizes()) { 1335 unsigned RegisterSize = RegAndSize.second; 1336 // Bail out if all bits are described already. 1337 if (Offset >= BitsToDescribe) 1338 break; 1339 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1340 ? BitsToDescribe - Offset 1341 : RegisterSize; 1342 auto FragmentExpr = DIExpression::createFragmentExpression( 1343 Expr, Offset, FragmentSize); 1344 if (!FragmentExpr) 1345 continue; 1346 SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first, 1347 false, dl, SDNodeOrder); 1348 DAG.AddDbgValue(SDV, nullptr, false); 1349 Offset += RegisterSize; 1350 } 1351 } else { 1352 SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder); 1353 DAG.AddDbgValue(SDV, nullptr, false); 1354 } 1355 return true; 1356 } 1357 } 1358 1359 return false; 1360 } 1361 1362 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1363 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1364 for (auto &Pair : DanglingDebugInfoMap) 1365 for (auto &DDI : Pair.second) 1366 salvageUnresolvedDbgValue(DDI); 1367 clearDanglingDebugInfo(); 1368 } 1369 1370 /// getCopyFromRegs - If there was virtual register allocated for the value V 1371 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1372 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1373 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V); 1374 SDValue Result; 1375 1376 if (It != FuncInfo.ValueMap.end()) { 1377 unsigned InReg = It->second; 1378 1379 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1380 DAG.getDataLayout(), InReg, Ty, 1381 None); // This is not an ABI copy. 1382 SDValue Chain = DAG.getEntryNode(); 1383 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1384 V); 1385 resolveDanglingDebugInfo(V, Result); 1386 } 1387 1388 return Result; 1389 } 1390 1391 /// getValue - Return an SDValue for the given Value. 1392 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1393 // If we already have an SDValue for this value, use it. It's important 1394 // to do this first, so that we don't create a CopyFromReg if we already 1395 // have a regular SDValue. 1396 SDValue &N = NodeMap[V]; 1397 if (N.getNode()) return N; 1398 1399 // If there's a virtual register allocated and initialized for this 1400 // value, use it. 1401 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1402 return copyFromReg; 1403 1404 // Otherwise create a new SDValue and remember it. 1405 SDValue Val = getValueImpl(V); 1406 NodeMap[V] = Val; 1407 resolveDanglingDebugInfo(V, Val); 1408 return Val; 1409 } 1410 1411 // Return true if SDValue exists for the given Value 1412 bool SelectionDAGBuilder::findValue(const Value *V) const { 1413 return (NodeMap.find(V) != NodeMap.end()) || 1414 (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end()); 1415 } 1416 1417 /// getNonRegisterValue - Return an SDValue for the given Value, but 1418 /// don't look in FuncInfo.ValueMap for a virtual register. 1419 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1420 // If we already have an SDValue for this value, use it. 1421 SDValue &N = NodeMap[V]; 1422 if (N.getNode()) { 1423 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1424 // Remove the debug location from the node as the node is about to be used 1425 // in a location which may differ from the original debug location. This 1426 // is relevant to Constant and ConstantFP nodes because they can appear 1427 // as constant expressions inside PHI nodes. 1428 N->setDebugLoc(DebugLoc()); 1429 } 1430 return N; 1431 } 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 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1441 /// Create an SDValue for the given value. 1442 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1443 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1444 1445 if (const Constant *C = dyn_cast<Constant>(V)) { 1446 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1447 1448 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1449 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1450 1451 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1452 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1453 1454 if (isa<ConstantPointerNull>(C)) { 1455 unsigned AS = V->getType()->getPointerAddressSpace(); 1456 return DAG.getConstant(0, getCurSDLoc(), 1457 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1458 } 1459 1460 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1461 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1462 1463 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1464 return DAG.getUNDEF(VT); 1465 1466 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1467 visit(CE->getOpcode(), *CE); 1468 SDValue N1 = NodeMap[V]; 1469 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1470 return N1; 1471 } 1472 1473 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1474 SmallVector<SDValue, 4> Constants; 1475 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 1476 OI != OE; ++OI) { 1477 SDNode *Val = getValue(*OI).getNode(); 1478 // If the operand is an empty aggregate, there are no values. 1479 if (!Val) continue; 1480 // Add each leaf value from the operand to the Constants list 1481 // to form a flattened list of all the values. 1482 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1483 Constants.push_back(SDValue(Val, i)); 1484 } 1485 1486 return DAG.getMergeValues(Constants, getCurSDLoc()); 1487 } 1488 1489 if (const ConstantDataSequential *CDS = 1490 dyn_cast<ConstantDataSequential>(C)) { 1491 SmallVector<SDValue, 4> Ops; 1492 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1493 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1494 // Add each leaf value from the operand to the Constants list 1495 // to form a flattened list of all the values. 1496 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1497 Ops.push_back(SDValue(Val, i)); 1498 } 1499 1500 if (isa<ArrayType>(CDS->getType())) 1501 return DAG.getMergeValues(Ops, getCurSDLoc()); 1502 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1503 } 1504 1505 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1506 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1507 "Unknown struct or array constant!"); 1508 1509 SmallVector<EVT, 4> ValueVTs; 1510 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1511 unsigned NumElts = ValueVTs.size(); 1512 if (NumElts == 0) 1513 return SDValue(); // empty struct 1514 SmallVector<SDValue, 4> Constants(NumElts); 1515 for (unsigned i = 0; i != NumElts; ++i) { 1516 EVT EltVT = ValueVTs[i]; 1517 if (isa<UndefValue>(C)) 1518 Constants[i] = DAG.getUNDEF(EltVT); 1519 else if (EltVT.isFloatingPoint()) 1520 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1521 else 1522 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1523 } 1524 1525 return DAG.getMergeValues(Constants, getCurSDLoc()); 1526 } 1527 1528 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1529 return DAG.getBlockAddress(BA, VT); 1530 1531 VectorType *VecTy = cast<VectorType>(V->getType()); 1532 unsigned NumElements = VecTy->getNumElements(); 1533 1534 // Now that we know the number and type of the elements, get that number of 1535 // elements into the Ops array based on what kind of constant it is. 1536 SmallVector<SDValue, 16> Ops; 1537 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1538 for (unsigned i = 0; i != NumElements; ++i) 1539 Ops.push_back(getValue(CV->getOperand(i))); 1540 } else { 1541 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!"); 1542 EVT EltVT = 1543 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1544 1545 SDValue Op; 1546 if (EltVT.isFloatingPoint()) 1547 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1548 else 1549 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1550 Ops.assign(NumElements, Op); 1551 } 1552 1553 // Create a BUILD_VECTOR node. 1554 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1555 } 1556 1557 // If this is a static alloca, generate it as the frameindex instead of 1558 // computation. 1559 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1560 DenseMap<const AllocaInst*, int>::iterator SI = 1561 FuncInfo.StaticAllocaMap.find(AI); 1562 if (SI != FuncInfo.StaticAllocaMap.end()) 1563 return DAG.getFrameIndex(SI->second, 1564 TLI.getFrameIndexTy(DAG.getDataLayout())); 1565 } 1566 1567 // If this is an instruction which fast-isel has deferred, select it now. 1568 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1569 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1570 1571 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1572 Inst->getType(), getABIRegCopyCC(V)); 1573 SDValue Chain = DAG.getEntryNode(); 1574 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1575 } 1576 1577 llvm_unreachable("Can't get register for value!"); 1578 } 1579 1580 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1581 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1582 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1583 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1584 bool IsSEH = isAsynchronousEHPersonality(Pers); 1585 bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX; 1586 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1587 if (!IsSEH) 1588 CatchPadMBB->setIsEHScopeEntry(); 1589 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1590 if (IsMSVCCXX || IsCoreCLR) 1591 CatchPadMBB->setIsEHFuncletEntry(); 1592 // Wasm does not need catchpads anymore 1593 if (!IsWasmCXX) 1594 DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other, 1595 getControlRoot())); 1596 } 1597 1598 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1599 // Update machine-CFG edge. 1600 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1601 FuncInfo.MBB->addSuccessor(TargetMBB); 1602 1603 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1604 bool IsSEH = isAsynchronousEHPersonality(Pers); 1605 if (IsSEH) { 1606 // If this is not a fall-through branch or optimizations are switched off, 1607 // emit the branch. 1608 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1609 TM.getOptLevel() == CodeGenOpt::None) 1610 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1611 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1612 return; 1613 } 1614 1615 // Figure out the funclet membership for the catchret's successor. 1616 // This will be used by the FuncletLayout pass to determine how to order the 1617 // BB's. 1618 // A 'catchret' returns to the outer scope's color. 1619 Value *ParentPad = I.getCatchSwitchParentPad(); 1620 const BasicBlock *SuccessorColor; 1621 if (isa<ConstantTokenNone>(ParentPad)) 1622 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1623 else 1624 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1625 assert(SuccessorColor && "No parent funclet for catchret!"); 1626 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1627 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1628 1629 // Create the terminator node. 1630 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1631 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1632 DAG.getBasicBlock(SuccessorColorMBB)); 1633 DAG.setRoot(Ret); 1634 } 1635 1636 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1637 // Don't emit any special code for the cleanuppad instruction. It just marks 1638 // the start of an EH scope/funclet. 1639 FuncInfo.MBB->setIsEHScopeEntry(); 1640 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1641 if (Pers != EHPersonality::Wasm_CXX) { 1642 FuncInfo.MBB->setIsEHFuncletEntry(); 1643 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1644 } 1645 } 1646 1647 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and 1648 // the control flow always stops at the single catch pad, as it does for a 1649 // cleanup pad. In case the exception caught is not of the types the catch pad 1650 // catches, it will be rethrown by a rethrow. 1651 static void findWasmUnwindDestinations( 1652 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1653 BranchProbability Prob, 1654 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1655 &UnwindDests) { 1656 while (EHPadBB) { 1657 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1658 if (isa<CleanupPadInst>(Pad)) { 1659 // Stop on cleanup pads. 1660 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1661 UnwindDests.back().first->setIsEHScopeEntry(); 1662 break; 1663 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1664 // Add the catchpad handlers to the possible destinations. We don't 1665 // continue to the unwind destination of the catchswitch for wasm. 1666 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1667 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1668 UnwindDests.back().first->setIsEHScopeEntry(); 1669 } 1670 break; 1671 } else { 1672 continue; 1673 } 1674 } 1675 } 1676 1677 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1678 /// many places it could ultimately go. In the IR, we have a single unwind 1679 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1680 /// This function skips over imaginary basic blocks that hold catchswitch 1681 /// instructions, and finds all the "real" machine 1682 /// basic block destinations. As those destinations may not be successors of 1683 /// EHPadBB, here we also calculate the edge probability to those destinations. 1684 /// The passed-in Prob is the edge probability to EHPadBB. 1685 static void findUnwindDestinations( 1686 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1687 BranchProbability Prob, 1688 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1689 &UnwindDests) { 1690 EHPersonality Personality = 1691 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1692 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1693 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1694 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1695 bool IsSEH = isAsynchronousEHPersonality(Personality); 1696 1697 if (IsWasmCXX) { 1698 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1699 assert(UnwindDests.size() <= 1 && 1700 "There should be at most one unwind destination for wasm"); 1701 return; 1702 } 1703 1704 while (EHPadBB) { 1705 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1706 BasicBlock *NewEHPadBB = nullptr; 1707 if (isa<LandingPadInst>(Pad)) { 1708 // Stop on landingpads. They are not funclets. 1709 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1710 break; 1711 } else if (isa<CleanupPadInst>(Pad)) { 1712 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1713 // personalities. 1714 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1715 UnwindDests.back().first->setIsEHScopeEntry(); 1716 UnwindDests.back().first->setIsEHFuncletEntry(); 1717 break; 1718 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1719 // Add the catchpad handlers to the possible destinations. 1720 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1721 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1722 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1723 if (IsMSVCCXX || IsCoreCLR) 1724 UnwindDests.back().first->setIsEHFuncletEntry(); 1725 if (!IsSEH) 1726 UnwindDests.back().first->setIsEHScopeEntry(); 1727 } 1728 NewEHPadBB = CatchSwitch->getUnwindDest(); 1729 } else { 1730 continue; 1731 } 1732 1733 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1734 if (BPI && NewEHPadBB) 1735 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1736 EHPadBB = NewEHPadBB; 1737 } 1738 } 1739 1740 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1741 // Update successor info. 1742 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1743 auto UnwindDest = I.getUnwindDest(); 1744 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1745 BranchProbability UnwindDestProb = 1746 (BPI && UnwindDest) 1747 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1748 : BranchProbability::getZero(); 1749 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1750 for (auto &UnwindDest : UnwindDests) { 1751 UnwindDest.first->setIsEHPad(); 1752 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1753 } 1754 FuncInfo.MBB->normalizeSuccProbs(); 1755 1756 // Create the terminator node. 1757 SDValue Ret = 1758 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1759 DAG.setRoot(Ret); 1760 } 1761 1762 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1763 report_fatal_error("visitCatchSwitch not yet implemented!"); 1764 } 1765 1766 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1767 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1768 auto &DL = DAG.getDataLayout(); 1769 SDValue Chain = getControlRoot(); 1770 SmallVector<ISD::OutputArg, 8> Outs; 1771 SmallVector<SDValue, 8> OutVals; 1772 1773 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1774 // lower 1775 // 1776 // %val = call <ty> @llvm.experimental.deoptimize() 1777 // ret <ty> %val 1778 // 1779 // differently. 1780 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1781 LowerDeoptimizingReturn(); 1782 return; 1783 } 1784 1785 if (!FuncInfo.CanLowerReturn) { 1786 unsigned DemoteReg = FuncInfo.DemoteRegister; 1787 const Function *F = I.getParent()->getParent(); 1788 1789 // Emit a store of the return value through the virtual register. 1790 // Leave Outs empty so that LowerReturn won't try to load return 1791 // registers the usual way. 1792 SmallVector<EVT, 1> PtrValueVTs; 1793 ComputeValueVTs(TLI, DL, 1794 F->getReturnType()->getPointerTo( 1795 DAG.getDataLayout().getAllocaAddrSpace()), 1796 PtrValueVTs); 1797 1798 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1799 DemoteReg, PtrValueVTs[0]); 1800 SDValue RetOp = getValue(I.getOperand(0)); 1801 1802 SmallVector<EVT, 4> ValueVTs, MemVTs; 1803 SmallVector<uint64_t, 4> Offsets; 1804 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1805 &Offsets); 1806 unsigned NumValues = ValueVTs.size(); 1807 1808 SmallVector<SDValue, 4> Chains(NumValues); 1809 for (unsigned i = 0; i != NumValues; ++i) { 1810 // An aggregate return value cannot wrap around the address space, so 1811 // offsets to its parts don't wrap either. 1812 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]); 1813 1814 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 1815 if (MemVTs[i] != ValueVTs[i]) 1816 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 1817 Chains[i] = DAG.getStore(Chain, getCurSDLoc(), Val, 1818 // FIXME: better loc info would be nice. 1819 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction())); 1820 } 1821 1822 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1823 MVT::Other, Chains); 1824 } else if (I.getNumOperands() != 0) { 1825 SmallVector<EVT, 4> ValueVTs; 1826 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1827 unsigned NumValues = ValueVTs.size(); 1828 if (NumValues) { 1829 SDValue RetOp = getValue(I.getOperand(0)); 1830 1831 const Function *F = I.getParent()->getParent(); 1832 1833 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 1834 I.getOperand(0)->getType(), F->getCallingConv(), 1835 /*IsVarArg*/ false); 1836 1837 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1838 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1839 Attribute::SExt)) 1840 ExtendKind = ISD::SIGN_EXTEND; 1841 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1842 Attribute::ZExt)) 1843 ExtendKind = ISD::ZERO_EXTEND; 1844 1845 LLVMContext &Context = F->getContext(); 1846 bool RetInReg = F->getAttributes().hasAttribute( 1847 AttributeList::ReturnIndex, Attribute::InReg); 1848 1849 for (unsigned j = 0; j != NumValues; ++j) { 1850 EVT VT = ValueVTs[j]; 1851 1852 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1853 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1854 1855 CallingConv::ID CC = F->getCallingConv(); 1856 1857 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1858 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1859 SmallVector<SDValue, 4> Parts(NumParts); 1860 getCopyToParts(DAG, getCurSDLoc(), 1861 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1862 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1863 1864 // 'inreg' on function refers to return value 1865 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1866 if (RetInReg) 1867 Flags.setInReg(); 1868 1869 if (I.getOperand(0)->getType()->isPointerTy()) { 1870 Flags.setPointer(); 1871 Flags.setPointerAddrSpace( 1872 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 1873 } 1874 1875 if (NeedsRegBlock) { 1876 Flags.setInConsecutiveRegs(); 1877 if (j == NumValues - 1) 1878 Flags.setInConsecutiveRegsLast(); 1879 } 1880 1881 // Propagate extension type if any 1882 if (ExtendKind == ISD::SIGN_EXTEND) 1883 Flags.setSExt(); 1884 else if (ExtendKind == ISD::ZERO_EXTEND) 1885 Flags.setZExt(); 1886 1887 for (unsigned i = 0; i < NumParts; ++i) { 1888 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1889 VT, /*isfixed=*/true, 0, 0)); 1890 OutVals.push_back(Parts[i]); 1891 } 1892 } 1893 } 1894 } 1895 1896 // Push in swifterror virtual register as the last element of Outs. This makes 1897 // sure swifterror virtual register will be returned in the swifterror 1898 // physical register. 1899 const Function *F = I.getParent()->getParent(); 1900 if (TLI.supportSwiftError() && 1901 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 1902 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 1903 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1904 Flags.setSwiftError(); 1905 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 1906 EVT(TLI.getPointerTy(DL)) /*argvt*/, 1907 true /*isfixed*/, 1 /*origidx*/, 1908 0 /*partOffs*/)); 1909 // Create SDNode for the swifterror virtual register. 1910 OutVals.push_back( 1911 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 1912 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 1913 EVT(TLI.getPointerTy(DL)))); 1914 } 1915 1916 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 1917 CallingConv::ID CallConv = 1918 DAG.getMachineFunction().getFunction().getCallingConv(); 1919 Chain = DAG.getTargetLoweringInfo().LowerReturn( 1920 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 1921 1922 // Verify that the target's LowerReturn behaved as expected. 1923 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 1924 "LowerReturn didn't return a valid chain!"); 1925 1926 // Update the DAG with the new chain value resulting from return lowering. 1927 DAG.setRoot(Chain); 1928 } 1929 1930 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 1931 /// created for it, emit nodes to copy the value into the virtual 1932 /// registers. 1933 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 1934 // Skip empty types 1935 if (V->getType()->isEmptyTy()) 1936 return; 1937 1938 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 1939 if (VMI != FuncInfo.ValueMap.end()) { 1940 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 1941 CopyValueToVirtualRegister(V, VMI->second); 1942 } 1943 } 1944 1945 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 1946 /// the current basic block, add it to ValueMap now so that we'll get a 1947 /// CopyTo/FromReg. 1948 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 1949 // No need to export constants. 1950 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 1951 1952 // Already exported? 1953 if (FuncInfo.isExportedInst(V)) return; 1954 1955 unsigned Reg = FuncInfo.InitializeRegForValue(V); 1956 CopyValueToVirtualRegister(V, Reg); 1957 } 1958 1959 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 1960 const BasicBlock *FromBB) { 1961 // The operands of the setcc have to be in this block. We don't know 1962 // how to export them from some other block. 1963 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 1964 // Can export from current BB. 1965 if (VI->getParent() == FromBB) 1966 return true; 1967 1968 // Is already exported, noop. 1969 return FuncInfo.isExportedInst(V); 1970 } 1971 1972 // If this is an argument, we can export it if the BB is the entry block or 1973 // if it is already exported. 1974 if (isa<Argument>(V)) { 1975 if (FromBB == &FromBB->getParent()->getEntryBlock()) 1976 return true; 1977 1978 // Otherwise, can only export this if it is already exported. 1979 return FuncInfo.isExportedInst(V); 1980 } 1981 1982 // Otherwise, constants can always be exported. 1983 return true; 1984 } 1985 1986 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 1987 BranchProbability 1988 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 1989 const MachineBasicBlock *Dst) const { 1990 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1991 const BasicBlock *SrcBB = Src->getBasicBlock(); 1992 const BasicBlock *DstBB = Dst->getBasicBlock(); 1993 if (!BPI) { 1994 // If BPI is not available, set the default probability as 1 / N, where N is 1995 // the number of successors. 1996 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 1997 return BranchProbability(1, SuccSize); 1998 } 1999 return BPI->getEdgeProbability(SrcBB, DstBB); 2000 } 2001 2002 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2003 MachineBasicBlock *Dst, 2004 BranchProbability Prob) { 2005 if (!FuncInfo.BPI) 2006 Src->addSuccessorWithoutProb(Dst); 2007 else { 2008 if (Prob.isUnknown()) 2009 Prob = getEdgeProbability(Src, Dst); 2010 Src->addSuccessor(Dst, Prob); 2011 } 2012 } 2013 2014 static bool InBlock(const Value *V, const BasicBlock *BB) { 2015 if (const Instruction *I = dyn_cast<Instruction>(V)) 2016 return I->getParent() == BB; 2017 return true; 2018 } 2019 2020 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2021 /// This function emits a branch and is used at the leaves of an OR or an 2022 /// AND operator tree. 2023 void 2024 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2025 MachineBasicBlock *TBB, 2026 MachineBasicBlock *FBB, 2027 MachineBasicBlock *CurBB, 2028 MachineBasicBlock *SwitchBB, 2029 BranchProbability TProb, 2030 BranchProbability FProb, 2031 bool InvertCond) { 2032 const BasicBlock *BB = CurBB->getBasicBlock(); 2033 2034 // If the leaf of the tree is a comparison, merge the condition into 2035 // the caseblock. 2036 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2037 // The operands of the cmp have to be in this block. We don't know 2038 // how to export them from some other block. If this is the first block 2039 // of the sequence, no exporting is needed. 2040 if (CurBB == SwitchBB || 2041 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2042 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2043 ISD::CondCode Condition; 2044 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2045 ICmpInst::Predicate Pred = 2046 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2047 Condition = getICmpCondCode(Pred); 2048 } else { 2049 const FCmpInst *FC = cast<FCmpInst>(Cond); 2050 FCmpInst::Predicate Pred = 2051 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2052 Condition = getFCmpCondCode(Pred); 2053 if (TM.Options.NoNaNsFPMath) 2054 Condition = getFCmpCodeWithoutNaN(Condition); 2055 } 2056 2057 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2058 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2059 SL->SwitchCases.push_back(CB); 2060 return; 2061 } 2062 } 2063 2064 // Create a CaseBlock record representing this branch. 2065 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2066 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2067 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2068 SL->SwitchCases.push_back(CB); 2069 } 2070 2071 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2072 MachineBasicBlock *TBB, 2073 MachineBasicBlock *FBB, 2074 MachineBasicBlock *CurBB, 2075 MachineBasicBlock *SwitchBB, 2076 Instruction::BinaryOps Opc, 2077 BranchProbability TProb, 2078 BranchProbability FProb, 2079 bool InvertCond) { 2080 // Skip over not part of the tree and remember to invert op and operands at 2081 // next level. 2082 Value *NotCond; 2083 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2084 InBlock(NotCond, CurBB->getBasicBlock())) { 2085 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2086 !InvertCond); 2087 return; 2088 } 2089 2090 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2091 // Compute the effective opcode for Cond, taking into account whether it needs 2092 // to be inverted, e.g. 2093 // and (not (or A, B)), C 2094 // gets lowered as 2095 // and (and (not A, not B), C) 2096 unsigned BOpc = 0; 2097 if (BOp) { 2098 BOpc = BOp->getOpcode(); 2099 if (InvertCond) { 2100 if (BOpc == Instruction::And) 2101 BOpc = Instruction::Or; 2102 else if (BOpc == Instruction::Or) 2103 BOpc = Instruction::And; 2104 } 2105 } 2106 2107 // If this node is not part of the or/and tree, emit it as a branch. 2108 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 2109 BOpc != unsigned(Opc) || !BOp->hasOneUse() || 2110 BOp->getParent() != CurBB->getBasicBlock() || 2111 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 2112 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 2113 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2114 TProb, FProb, InvertCond); 2115 return; 2116 } 2117 2118 // Create TmpBB after CurBB. 2119 MachineFunction::iterator BBI(CurBB); 2120 MachineFunction &MF = DAG.getMachineFunction(); 2121 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2122 CurBB->getParent()->insert(++BBI, TmpBB); 2123 2124 if (Opc == Instruction::Or) { 2125 // Codegen X | Y as: 2126 // BB1: 2127 // jmp_if_X TBB 2128 // jmp TmpBB 2129 // TmpBB: 2130 // jmp_if_Y TBB 2131 // jmp FBB 2132 // 2133 2134 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2135 // The requirement is that 2136 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2137 // = TrueProb for original BB. 2138 // Assuming the original probabilities are A and B, one choice is to set 2139 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2140 // A/(1+B) and 2B/(1+B). This choice assumes that 2141 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2142 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2143 // TmpBB, but the math is more complicated. 2144 2145 auto NewTrueProb = TProb / 2; 2146 auto NewFalseProb = TProb / 2 + FProb; 2147 // Emit the LHS condition. 2148 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc, 2149 NewTrueProb, NewFalseProb, InvertCond); 2150 2151 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2152 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2153 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2154 // Emit the RHS condition into TmpBB. 2155 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2156 Probs[0], Probs[1], InvertCond); 2157 } else { 2158 assert(Opc == Instruction::And && "Unknown merge op!"); 2159 // Codegen X & Y as: 2160 // BB1: 2161 // jmp_if_X TmpBB 2162 // jmp FBB 2163 // TmpBB: 2164 // jmp_if_Y TBB 2165 // jmp FBB 2166 // 2167 // This requires creation of TmpBB after CurBB. 2168 2169 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2170 // The requirement is that 2171 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2172 // = FalseProb for original BB. 2173 // Assuming the original probabilities are A and B, one choice is to set 2174 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2175 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2176 // TrueProb for BB1 * FalseProb for TmpBB. 2177 2178 auto NewTrueProb = TProb + FProb / 2; 2179 auto NewFalseProb = FProb / 2; 2180 // Emit the LHS condition. 2181 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc, 2182 NewTrueProb, NewFalseProb, InvertCond); 2183 2184 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2185 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2186 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2187 // Emit the RHS condition into TmpBB. 2188 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2189 Probs[0], Probs[1], InvertCond); 2190 } 2191 } 2192 2193 /// If the set of cases should be emitted as a series of branches, return true. 2194 /// If we should emit this as a bunch of and/or'd together conditions, return 2195 /// false. 2196 bool 2197 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2198 if (Cases.size() != 2) return true; 2199 2200 // If this is two comparisons of the same values or'd or and'd together, they 2201 // will get folded into a single comparison, so don't emit two blocks. 2202 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2203 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2204 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2205 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2206 return false; 2207 } 2208 2209 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2210 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2211 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2212 Cases[0].CC == Cases[1].CC && 2213 isa<Constant>(Cases[0].CmpRHS) && 2214 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2215 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2216 return false; 2217 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2218 return false; 2219 } 2220 2221 return true; 2222 } 2223 2224 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2225 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2226 2227 // Update machine-CFG edges. 2228 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2229 2230 if (I.isUnconditional()) { 2231 // Update machine-CFG edges. 2232 BrMBB->addSuccessor(Succ0MBB); 2233 2234 // If this is not a fall-through branch or optimizations are switched off, 2235 // emit the branch. 2236 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2237 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2238 MVT::Other, getControlRoot(), 2239 DAG.getBasicBlock(Succ0MBB))); 2240 2241 return; 2242 } 2243 2244 // If this condition is one of the special cases we handle, do special stuff 2245 // now. 2246 const Value *CondVal = I.getCondition(); 2247 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2248 2249 // If this is a series of conditions that are or'd or and'd together, emit 2250 // this as a sequence of branches instead of setcc's with and/or operations. 2251 // As long as jumps are not expensive, this should improve performance. 2252 // For example, instead of something like: 2253 // cmp A, B 2254 // C = seteq 2255 // cmp D, E 2256 // F = setle 2257 // or C, F 2258 // jnz foo 2259 // Emit: 2260 // cmp A, B 2261 // je foo 2262 // cmp D, E 2263 // jle foo 2264 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 2265 Instruction::BinaryOps Opcode = BOp->getOpcode(); 2266 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() && 2267 !I.hasMetadata(LLVMContext::MD_unpredictable) && 2268 (Opcode == Instruction::And || Opcode == Instruction::Or)) { 2269 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, 2270 Opcode, 2271 getEdgeProbability(BrMBB, Succ0MBB), 2272 getEdgeProbability(BrMBB, Succ1MBB), 2273 /*InvertCond=*/false); 2274 // If the compares in later blocks need to use values not currently 2275 // exported from this block, export them now. This block should always 2276 // be the first entry. 2277 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2278 2279 // Allow some cases to be rejected. 2280 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2281 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2282 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2283 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2284 } 2285 2286 // Emit the branch for this block. 2287 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2288 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2289 return; 2290 } 2291 2292 // Okay, we decided not to do this, remove any inserted MBB's and clear 2293 // SwitchCases. 2294 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2295 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2296 2297 SL->SwitchCases.clear(); 2298 } 2299 } 2300 2301 // Create a CaseBlock record representing this branch. 2302 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2303 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2304 2305 // Use visitSwitchCase to actually insert the fast branch sequence for this 2306 // cond branch. 2307 visitSwitchCase(CB, BrMBB); 2308 } 2309 2310 /// visitSwitchCase - Emits the necessary code to represent a single node in 2311 /// the binary search tree resulting from lowering a switch instruction. 2312 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2313 MachineBasicBlock *SwitchBB) { 2314 SDValue Cond; 2315 SDValue CondLHS = getValue(CB.CmpLHS); 2316 SDLoc dl = CB.DL; 2317 2318 if (CB.CC == ISD::SETTRUE) { 2319 // Branch or fall through to TrueBB. 2320 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2321 SwitchBB->normalizeSuccProbs(); 2322 if (CB.TrueBB != NextBlock(SwitchBB)) { 2323 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2324 DAG.getBasicBlock(CB.TrueBB))); 2325 } 2326 return; 2327 } 2328 2329 auto &TLI = DAG.getTargetLoweringInfo(); 2330 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2331 2332 // Build the setcc now. 2333 if (!CB.CmpMHS) { 2334 // Fold "(X == true)" to X and "(X == false)" to !X to 2335 // handle common cases produced by branch lowering. 2336 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2337 CB.CC == ISD::SETEQ) 2338 Cond = CondLHS; 2339 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2340 CB.CC == ISD::SETEQ) { 2341 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2342 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2343 } else { 2344 SDValue CondRHS = getValue(CB.CmpRHS); 2345 2346 // If a pointer's DAG type is larger than its memory type then the DAG 2347 // values are zero-extended. This breaks signed comparisons so truncate 2348 // back to the underlying type before doing the compare. 2349 if (CondLHS.getValueType() != MemVT) { 2350 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2351 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2352 } 2353 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2354 } 2355 } else { 2356 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2357 2358 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2359 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2360 2361 SDValue CmpOp = getValue(CB.CmpMHS); 2362 EVT VT = CmpOp.getValueType(); 2363 2364 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2365 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2366 ISD::SETLE); 2367 } else { 2368 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2369 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2370 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2371 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2372 } 2373 } 2374 2375 // Update successor info 2376 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2377 // TrueBB and FalseBB are always different unless the incoming IR is 2378 // degenerate. This only happens when running llc on weird IR. 2379 if (CB.TrueBB != CB.FalseBB) 2380 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2381 SwitchBB->normalizeSuccProbs(); 2382 2383 // If the lhs block is the next block, invert the condition so that we can 2384 // fall through to the lhs instead of the rhs block. 2385 if (CB.TrueBB == NextBlock(SwitchBB)) { 2386 std::swap(CB.TrueBB, CB.FalseBB); 2387 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2388 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2389 } 2390 2391 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2392 MVT::Other, getControlRoot(), Cond, 2393 DAG.getBasicBlock(CB.TrueBB)); 2394 2395 // Insert the false branch. Do this even if it's a fall through branch, 2396 // this makes it easier to do DAG optimizations which require inverting 2397 // the branch condition. 2398 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2399 DAG.getBasicBlock(CB.FalseBB)); 2400 2401 DAG.setRoot(BrCond); 2402 } 2403 2404 /// visitJumpTable - Emit JumpTable node in the current MBB 2405 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2406 // Emit the code for the jump table 2407 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2408 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2409 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2410 JT.Reg, PTy); 2411 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2412 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2413 MVT::Other, Index.getValue(1), 2414 Table, Index); 2415 DAG.setRoot(BrJumpTable); 2416 } 2417 2418 /// visitJumpTableHeader - This function emits necessary code to produce index 2419 /// in the JumpTable from switch case. 2420 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2421 JumpTableHeader &JTH, 2422 MachineBasicBlock *SwitchBB) { 2423 SDLoc dl = getCurSDLoc(); 2424 2425 // Subtract the lowest switch case value from the value being switched on. 2426 SDValue SwitchOp = getValue(JTH.SValue); 2427 EVT VT = SwitchOp.getValueType(); 2428 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2429 DAG.getConstant(JTH.First, dl, VT)); 2430 2431 // The SDNode we just created, which holds the value being switched on minus 2432 // the smallest case value, needs to be copied to a virtual register so it 2433 // can be used as an index into the jump table in a subsequent basic block. 2434 // This value may be smaller or larger than the target's pointer type, and 2435 // therefore require extension or truncating. 2436 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2437 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2438 2439 unsigned JumpTableReg = 2440 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2441 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2442 JumpTableReg, SwitchOp); 2443 JT.Reg = JumpTableReg; 2444 2445 if (!JTH.OmitRangeCheck) { 2446 // Emit the range check for the jump table, and branch to the default block 2447 // for the switch statement if the value being switched on exceeds the 2448 // largest case in the switch. 2449 SDValue CMP = DAG.getSetCC( 2450 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2451 Sub.getValueType()), 2452 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2453 2454 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2455 MVT::Other, CopyTo, CMP, 2456 DAG.getBasicBlock(JT.Default)); 2457 2458 // Avoid emitting unnecessary branches to the next block. 2459 if (JT.MBB != NextBlock(SwitchBB)) 2460 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2461 DAG.getBasicBlock(JT.MBB)); 2462 2463 DAG.setRoot(BrCond); 2464 } else { 2465 // Avoid emitting unnecessary branches to the next block. 2466 if (JT.MBB != NextBlock(SwitchBB)) 2467 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2468 DAG.getBasicBlock(JT.MBB))); 2469 else 2470 DAG.setRoot(CopyTo); 2471 } 2472 } 2473 2474 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2475 /// variable if there exists one. 2476 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2477 SDValue &Chain) { 2478 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2479 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2480 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2481 MachineFunction &MF = DAG.getMachineFunction(); 2482 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2483 MachineSDNode *Node = 2484 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2485 if (Global) { 2486 MachinePointerInfo MPInfo(Global); 2487 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2488 MachineMemOperand::MODereferenceable; 2489 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2490 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy)); 2491 DAG.setNodeMemRefs(Node, {MemRef}); 2492 } 2493 if (PtrTy != PtrMemTy) 2494 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2495 return SDValue(Node, 0); 2496 } 2497 2498 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2499 /// tail spliced into a stack protector check success bb. 2500 /// 2501 /// For a high level explanation of how this fits into the stack protector 2502 /// generation see the comment on the declaration of class 2503 /// StackProtectorDescriptor. 2504 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2505 MachineBasicBlock *ParentBB) { 2506 2507 // First create the loads to the guard/stack slot for the comparison. 2508 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2509 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2510 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2511 2512 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2513 int FI = MFI.getStackProtectorIndex(); 2514 2515 SDValue Guard; 2516 SDLoc dl = getCurSDLoc(); 2517 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2518 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2519 unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext())); 2520 2521 // Generate code to load the content of the guard slot. 2522 SDValue GuardVal = DAG.getLoad( 2523 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2524 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2525 MachineMemOperand::MOVolatile); 2526 2527 if (TLI.useStackGuardXorFP()) 2528 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2529 2530 // Retrieve guard check function, nullptr if instrumentation is inlined. 2531 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2532 // The target provides a guard check function to validate the guard value. 2533 // Generate a call to that function with the content of the guard slot as 2534 // argument. 2535 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2536 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2537 2538 TargetLowering::ArgListTy Args; 2539 TargetLowering::ArgListEntry Entry; 2540 Entry.Node = GuardVal; 2541 Entry.Ty = FnTy->getParamType(0); 2542 if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg)) 2543 Entry.IsInReg = true; 2544 Args.push_back(Entry); 2545 2546 TargetLowering::CallLoweringInfo CLI(DAG); 2547 CLI.setDebugLoc(getCurSDLoc()) 2548 .setChain(DAG.getEntryNode()) 2549 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2550 getValue(GuardCheckFn), std::move(Args)); 2551 2552 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2553 DAG.setRoot(Result.second); 2554 return; 2555 } 2556 2557 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2558 // Otherwise, emit a volatile load to retrieve the stack guard value. 2559 SDValue Chain = DAG.getEntryNode(); 2560 if (TLI.useLoadStackGuardNode()) { 2561 Guard = getLoadStackGuard(DAG, dl, Chain); 2562 } else { 2563 const Value *IRGuard = TLI.getSDagStackGuard(M); 2564 SDValue GuardPtr = getValue(IRGuard); 2565 2566 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2567 MachinePointerInfo(IRGuard, 0), Align, 2568 MachineMemOperand::MOVolatile); 2569 } 2570 2571 // Perform the comparison via a subtract/getsetcc. 2572 EVT VT = Guard.getValueType(); 2573 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal); 2574 2575 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2576 *DAG.getContext(), 2577 Sub.getValueType()), 2578 Sub, DAG.getConstant(0, dl, VT), ISD::SETNE); 2579 2580 // If the sub is not 0, then we know the guard/stackslot do not equal, so 2581 // branch to failure MBB. 2582 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2583 MVT::Other, GuardVal.getOperand(0), 2584 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2585 // Otherwise branch to success MBB. 2586 SDValue Br = DAG.getNode(ISD::BR, dl, 2587 MVT::Other, BrCond, 2588 DAG.getBasicBlock(SPD.getSuccessMBB())); 2589 2590 DAG.setRoot(Br); 2591 } 2592 2593 /// Codegen the failure basic block for a stack protector check. 2594 /// 2595 /// A failure stack protector machine basic block consists simply of a call to 2596 /// __stack_chk_fail(). 2597 /// 2598 /// For a high level explanation of how this fits into the stack protector 2599 /// generation see the comment on the declaration of class 2600 /// StackProtectorDescriptor. 2601 void 2602 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2603 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2604 TargetLowering::MakeLibCallOptions CallOptions; 2605 CallOptions.setDiscardResult(true); 2606 SDValue Chain = 2607 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2608 None, CallOptions, getCurSDLoc()).second; 2609 // On PS4, the "return address" must still be within the calling function, 2610 // even if it's at the very end, so emit an explicit TRAP here. 2611 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2612 if (TM.getTargetTriple().isPS4CPU()) 2613 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2614 2615 DAG.setRoot(Chain); 2616 } 2617 2618 /// visitBitTestHeader - This function emits necessary code to produce value 2619 /// suitable for "bit tests" 2620 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2621 MachineBasicBlock *SwitchBB) { 2622 SDLoc dl = getCurSDLoc(); 2623 2624 // Subtract the minimum value. 2625 SDValue SwitchOp = getValue(B.SValue); 2626 EVT VT = SwitchOp.getValueType(); 2627 SDValue RangeSub = 2628 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2629 2630 // Determine the type of the test operands. 2631 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2632 bool UsePtrType = false; 2633 if (!TLI.isTypeLegal(VT)) { 2634 UsePtrType = true; 2635 } else { 2636 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2637 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2638 // Switch table case range are encoded into series of masks. 2639 // Just use pointer type, it's guaranteed to fit. 2640 UsePtrType = true; 2641 break; 2642 } 2643 } 2644 SDValue Sub = RangeSub; 2645 if (UsePtrType) { 2646 VT = TLI.getPointerTy(DAG.getDataLayout()); 2647 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2648 } 2649 2650 B.RegVT = VT.getSimpleVT(); 2651 B.Reg = FuncInfo.CreateReg(B.RegVT); 2652 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2653 2654 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2655 2656 if (!B.OmitRangeCheck) 2657 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2658 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2659 SwitchBB->normalizeSuccProbs(); 2660 2661 SDValue Root = CopyTo; 2662 if (!B.OmitRangeCheck) { 2663 // Conditional branch to the default block. 2664 SDValue RangeCmp = DAG.getSetCC(dl, 2665 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2666 RangeSub.getValueType()), 2667 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2668 ISD::SETUGT); 2669 2670 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2671 DAG.getBasicBlock(B.Default)); 2672 } 2673 2674 // Avoid emitting unnecessary branches to the next block. 2675 if (MBB != NextBlock(SwitchBB)) 2676 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2677 2678 DAG.setRoot(Root); 2679 } 2680 2681 /// visitBitTestCase - this function produces one "bit test" 2682 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2683 MachineBasicBlock* NextMBB, 2684 BranchProbability BranchProbToNext, 2685 unsigned Reg, 2686 BitTestCase &B, 2687 MachineBasicBlock *SwitchBB) { 2688 SDLoc dl = getCurSDLoc(); 2689 MVT VT = BB.RegVT; 2690 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2691 SDValue Cmp; 2692 unsigned PopCount = countPopulation(B.Mask); 2693 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2694 if (PopCount == 1) { 2695 // Testing for a single bit; just compare the shift count with what it 2696 // would need to be to shift a 1 bit in that position. 2697 Cmp = DAG.getSetCC( 2698 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2699 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2700 ISD::SETEQ); 2701 } else if (PopCount == BB.Range) { 2702 // There is only one zero bit in the range, test for it directly. 2703 Cmp = DAG.getSetCC( 2704 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2705 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2706 ISD::SETNE); 2707 } else { 2708 // Make desired shift 2709 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2710 DAG.getConstant(1, dl, VT), ShiftOp); 2711 2712 // Emit bit tests and jumps 2713 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2714 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2715 Cmp = DAG.getSetCC( 2716 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2717 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2718 } 2719 2720 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2721 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2722 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2723 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2724 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2725 // one as they are relative probabilities (and thus work more like weights), 2726 // and hence we need to normalize them to let the sum of them become one. 2727 SwitchBB->normalizeSuccProbs(); 2728 2729 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2730 MVT::Other, getControlRoot(), 2731 Cmp, DAG.getBasicBlock(B.TargetBB)); 2732 2733 // Avoid emitting unnecessary branches to the next block. 2734 if (NextMBB != NextBlock(SwitchBB)) 2735 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2736 DAG.getBasicBlock(NextMBB)); 2737 2738 DAG.setRoot(BrAnd); 2739 } 2740 2741 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2742 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2743 2744 // Retrieve successors. Look through artificial IR level blocks like 2745 // catchswitch for successors. 2746 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2747 const BasicBlock *EHPadBB = I.getSuccessor(1); 2748 2749 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2750 // have to do anything here to lower funclet bundles. 2751 assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt, 2752 LLVMContext::OB_funclet, 2753 LLVMContext::OB_cfguardtarget}) && 2754 "Cannot lower invokes with arbitrary operand bundles yet!"); 2755 2756 const Value *Callee(I.getCalledValue()); 2757 const Function *Fn = dyn_cast<Function>(Callee); 2758 if (isa<InlineAsm>(Callee)) 2759 visitInlineAsm(&I); 2760 else if (Fn && Fn->isIntrinsic()) { 2761 switch (Fn->getIntrinsicID()) { 2762 default: 2763 llvm_unreachable("Cannot invoke this intrinsic"); 2764 case Intrinsic::donothing: 2765 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2766 break; 2767 case Intrinsic::experimental_patchpoint_void: 2768 case Intrinsic::experimental_patchpoint_i64: 2769 visitPatchpoint(&I, EHPadBB); 2770 break; 2771 case Intrinsic::experimental_gc_statepoint: 2772 LowerStatepoint(ImmutableStatepoint(&I), EHPadBB); 2773 break; 2774 case Intrinsic::wasm_rethrow_in_catch: { 2775 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2776 // special because it can be invoked, so we manually lower it to a DAG 2777 // node here. 2778 SmallVector<SDValue, 8> Ops; 2779 Ops.push_back(getRoot()); // inchain 2780 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2781 Ops.push_back( 2782 DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(), 2783 TLI.getPointerTy(DAG.getDataLayout()))); 2784 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2785 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2786 break; 2787 } 2788 } 2789 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2790 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2791 // Eventually we will support lowering the @llvm.experimental.deoptimize 2792 // intrinsic, and right now there are no plans to support other intrinsics 2793 // with deopt state. 2794 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2795 } else { 2796 LowerCallTo(&I, getValue(Callee), false, EHPadBB); 2797 } 2798 2799 // If the value of the invoke is used outside of its defining block, make it 2800 // available as a virtual register. 2801 // We already took care of the exported value for the statepoint instruction 2802 // during call to the LowerStatepoint. 2803 if (!isStatepoint(I)) { 2804 CopyToExportRegsIfNeeded(&I); 2805 } 2806 2807 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2808 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2809 BranchProbability EHPadBBProb = 2810 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2811 : BranchProbability::getZero(); 2812 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2813 2814 // Update successor info. 2815 addSuccessorWithProb(InvokeMBB, Return); 2816 for (auto &UnwindDest : UnwindDests) { 2817 UnwindDest.first->setIsEHPad(); 2818 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2819 } 2820 InvokeMBB->normalizeSuccProbs(); 2821 2822 // Drop into normal successor. 2823 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 2824 DAG.getBasicBlock(Return))); 2825 } 2826 2827 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 2828 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 2829 2830 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2831 // have to do anything here to lower funclet bundles. 2832 assert(!I.hasOperandBundlesOtherThan( 2833 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2834 "Cannot lower callbrs with arbitrary operand bundles yet!"); 2835 2836 assert(isa<InlineAsm>(I.getCalledValue()) && 2837 "Only know how to handle inlineasm callbr"); 2838 visitInlineAsm(&I); 2839 2840 // Retrieve successors. 2841 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 2842 2843 // Update successor info. 2844 addSuccessorWithProb(CallBrMBB, Return); 2845 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 2846 MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)]; 2847 addSuccessorWithProb(CallBrMBB, Target); 2848 } 2849 CallBrMBB->normalizeSuccProbs(); 2850 2851 // Drop into default successor. 2852 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2853 MVT::Other, getControlRoot(), 2854 DAG.getBasicBlock(Return))); 2855 } 2856 2857 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2858 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2859 } 2860 2861 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2862 assert(FuncInfo.MBB->isEHPad() && 2863 "Call to landingpad not in landing pad!"); 2864 2865 // If there aren't registers to copy the values into (e.g., during SjLj 2866 // exceptions), then don't bother to create these DAG nodes. 2867 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2868 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2869 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2870 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2871 return; 2872 2873 // If landingpad's return type is token type, we don't create DAG nodes 2874 // for its exception pointer and selector value. The extraction of exception 2875 // pointer or selector value from token type landingpads is not currently 2876 // supported. 2877 if (LP.getType()->isTokenTy()) 2878 return; 2879 2880 SmallVector<EVT, 2> ValueVTs; 2881 SDLoc dl = getCurSDLoc(); 2882 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2883 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2884 2885 // Get the two live-in registers as SDValues. The physregs have already been 2886 // copied into virtual registers. 2887 SDValue Ops[2]; 2888 if (FuncInfo.ExceptionPointerVirtReg) { 2889 Ops[0] = DAG.getZExtOrTrunc( 2890 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2891 FuncInfo.ExceptionPointerVirtReg, 2892 TLI.getPointerTy(DAG.getDataLayout())), 2893 dl, ValueVTs[0]); 2894 } else { 2895 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2896 } 2897 Ops[1] = DAG.getZExtOrTrunc( 2898 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2899 FuncInfo.ExceptionSelectorVirtReg, 2900 TLI.getPointerTy(DAG.getDataLayout())), 2901 dl, ValueVTs[1]); 2902 2903 // Merge into one. 2904 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 2905 DAG.getVTList(ValueVTs), Ops); 2906 setValue(&LP, Res); 2907 } 2908 2909 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2910 MachineBasicBlock *Last) { 2911 // Update JTCases. 2912 for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i) 2913 if (SL->JTCases[i].first.HeaderBB == First) 2914 SL->JTCases[i].first.HeaderBB = Last; 2915 2916 // Update BitTestCases. 2917 for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i) 2918 if (SL->BitTestCases[i].Parent == First) 2919 SL->BitTestCases[i].Parent = Last; 2920 } 2921 2922 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2923 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2924 2925 // Update machine-CFG edges with unique successors. 2926 SmallSet<BasicBlock*, 32> Done; 2927 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 2928 BasicBlock *BB = I.getSuccessor(i); 2929 bool Inserted = Done.insert(BB).second; 2930 if (!Inserted) 2931 continue; 2932 2933 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 2934 addSuccessorWithProb(IndirectBrMBB, Succ); 2935 } 2936 IndirectBrMBB->normalizeSuccProbs(); 2937 2938 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 2939 MVT::Other, getControlRoot(), 2940 getValue(I.getAddress()))); 2941 } 2942 2943 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 2944 if (!DAG.getTarget().Options.TrapUnreachable) 2945 return; 2946 2947 // We may be able to ignore unreachable behind a noreturn call. 2948 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 2949 const BasicBlock &BB = *I.getParent(); 2950 if (&I != &BB.front()) { 2951 BasicBlock::const_iterator PredI = 2952 std::prev(BasicBlock::const_iterator(&I)); 2953 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 2954 if (Call->doesNotReturn()) 2955 return; 2956 } 2957 } 2958 } 2959 2960 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 2961 } 2962 2963 void SelectionDAGBuilder::visitFSub(const User &I) { 2964 // -0.0 - X --> fneg 2965 Type *Ty = I.getType(); 2966 if (isa<Constant>(I.getOperand(0)) && 2967 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) { 2968 SDValue Op2 = getValue(I.getOperand(1)); 2969 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(), 2970 Op2.getValueType(), Op2)); 2971 return; 2972 } 2973 2974 visitBinary(I, ISD::FSUB); 2975 } 2976 2977 /// Checks if the given instruction performs a vector reduction, in which case 2978 /// we have the freedom to alter the elements in the result as long as the 2979 /// reduction of them stays unchanged. 2980 static bool isVectorReductionOp(const User *I) { 2981 const Instruction *Inst = dyn_cast<Instruction>(I); 2982 if (!Inst || !Inst->getType()->isVectorTy()) 2983 return false; 2984 2985 auto OpCode = Inst->getOpcode(); 2986 switch (OpCode) { 2987 case Instruction::Add: 2988 case Instruction::Mul: 2989 case Instruction::And: 2990 case Instruction::Or: 2991 case Instruction::Xor: 2992 break; 2993 case Instruction::FAdd: 2994 case Instruction::FMul: 2995 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 2996 if (FPOp->getFastMathFlags().isFast()) 2997 break; 2998 LLVM_FALLTHROUGH; 2999 default: 3000 return false; 3001 } 3002 3003 unsigned ElemNum = Inst->getType()->getVectorNumElements(); 3004 // Ensure the reduction size is a power of 2. 3005 if (!isPowerOf2_32(ElemNum)) 3006 return false; 3007 3008 unsigned ElemNumToReduce = ElemNum; 3009 3010 // Do DFS search on the def-use chain from the given instruction. We only 3011 // allow four kinds of operations during the search until we reach the 3012 // instruction that extracts the first element from the vector: 3013 // 3014 // 1. The reduction operation of the same opcode as the given instruction. 3015 // 3016 // 2. PHI node. 3017 // 3018 // 3. ShuffleVector instruction together with a reduction operation that 3019 // does a partial reduction. 3020 // 3021 // 4. ExtractElement that extracts the first element from the vector, and we 3022 // stop searching the def-use chain here. 3023 // 3024 // 3 & 4 above perform a reduction on all elements of the vector. We push defs 3025 // from 1-3 to the stack to continue the DFS. The given instruction is not 3026 // a reduction operation if we meet any other instructions other than those 3027 // listed above. 3028 3029 SmallVector<const User *, 16> UsersToVisit{Inst}; 3030 SmallPtrSet<const User *, 16> Visited; 3031 bool ReduxExtracted = false; 3032 3033 while (!UsersToVisit.empty()) { 3034 auto User = UsersToVisit.back(); 3035 UsersToVisit.pop_back(); 3036 if (!Visited.insert(User).second) 3037 continue; 3038 3039 for (const auto &U : User->users()) { 3040 auto Inst = dyn_cast<Instruction>(U); 3041 if (!Inst) 3042 return false; 3043 3044 if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) { 3045 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 3046 if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast()) 3047 return false; 3048 UsersToVisit.push_back(U); 3049 } else if (const ShuffleVectorInst *ShufInst = 3050 dyn_cast<ShuffleVectorInst>(U)) { 3051 // Detect the following pattern: A ShuffleVector instruction together 3052 // with a reduction that do partial reduction on the first and second 3053 // ElemNumToReduce / 2 elements, and store the result in 3054 // ElemNumToReduce / 2 elements in another vector. 3055 3056 unsigned ResultElements = ShufInst->getType()->getVectorNumElements(); 3057 if (ResultElements < ElemNum) 3058 return false; 3059 3060 if (ElemNumToReduce == 1) 3061 return false; 3062 if (!isa<UndefValue>(U->getOperand(1))) 3063 return false; 3064 for (unsigned i = 0; i < ElemNumToReduce / 2; ++i) 3065 if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2)) 3066 return false; 3067 for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i) 3068 if (ShufInst->getMaskValue(i) != -1) 3069 return false; 3070 3071 // There is only one user of this ShuffleVector instruction, which 3072 // must be a reduction operation. 3073 if (!U->hasOneUse()) 3074 return false; 3075 3076 auto U2 = dyn_cast<Instruction>(*U->user_begin()); 3077 if (!U2 || U2->getOpcode() != OpCode) 3078 return false; 3079 3080 // Check operands of the reduction operation. 3081 if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) || 3082 (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) { 3083 UsersToVisit.push_back(U2); 3084 ElemNumToReduce /= 2; 3085 } else 3086 return false; 3087 } else if (isa<ExtractElementInst>(U)) { 3088 // At this moment we should have reduced all elements in the vector. 3089 if (ElemNumToReduce != 1) 3090 return false; 3091 3092 const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1)); 3093 if (!Val || !Val->isZero()) 3094 return false; 3095 3096 ReduxExtracted = true; 3097 } else 3098 return false; 3099 } 3100 } 3101 return ReduxExtracted; 3102 } 3103 3104 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3105 SDNodeFlags Flags; 3106 3107 SDValue Op = getValue(I.getOperand(0)); 3108 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3109 Op, Flags); 3110 setValue(&I, UnNodeValue); 3111 } 3112 3113 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3114 SDNodeFlags Flags; 3115 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3116 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3117 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3118 } 3119 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) { 3120 Flags.setExact(ExactOp->isExact()); 3121 } 3122 if (isVectorReductionOp(&I)) { 3123 Flags.setVectorReduction(true); 3124 LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n"); 3125 } 3126 3127 SDValue Op1 = getValue(I.getOperand(0)); 3128 SDValue Op2 = getValue(I.getOperand(1)); 3129 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3130 Op1, Op2, Flags); 3131 setValue(&I, BinNodeValue); 3132 } 3133 3134 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3135 SDValue Op1 = getValue(I.getOperand(0)); 3136 SDValue Op2 = getValue(I.getOperand(1)); 3137 3138 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3139 Op1.getValueType(), DAG.getDataLayout()); 3140 3141 // Coerce the shift amount to the right type if we can. 3142 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3143 unsigned ShiftSize = ShiftTy.getSizeInBits(); 3144 unsigned Op2Size = Op2.getValueSizeInBits(); 3145 SDLoc DL = getCurSDLoc(); 3146 3147 // If the operand is smaller than the shift count type, promote it. 3148 if (ShiftSize > Op2Size) 3149 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 3150 3151 // If the operand is larger than the shift count type but the shift 3152 // count type has enough bits to represent any shift value, truncate 3153 // it now. This is a common case and it exposes the truncate to 3154 // optimization early. 3155 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 3156 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 3157 // Otherwise we'll need to temporarily settle for some other convenient 3158 // type. Type legalization will make adjustments once the shiftee is split. 3159 else 3160 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 3161 } 3162 3163 bool nuw = false; 3164 bool nsw = false; 3165 bool exact = false; 3166 3167 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3168 3169 if (const OverflowingBinaryOperator *OFBinOp = 3170 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3171 nuw = OFBinOp->hasNoUnsignedWrap(); 3172 nsw = OFBinOp->hasNoSignedWrap(); 3173 } 3174 if (const PossiblyExactOperator *ExactOp = 3175 dyn_cast<const PossiblyExactOperator>(&I)) 3176 exact = ExactOp->isExact(); 3177 } 3178 SDNodeFlags Flags; 3179 Flags.setExact(exact); 3180 Flags.setNoSignedWrap(nsw); 3181 Flags.setNoUnsignedWrap(nuw); 3182 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3183 Flags); 3184 setValue(&I, Res); 3185 } 3186 3187 void SelectionDAGBuilder::visitSDiv(const User &I) { 3188 SDValue Op1 = getValue(I.getOperand(0)); 3189 SDValue Op2 = getValue(I.getOperand(1)); 3190 3191 SDNodeFlags Flags; 3192 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3193 cast<PossiblyExactOperator>(&I)->isExact()); 3194 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3195 Op2, Flags)); 3196 } 3197 3198 void SelectionDAGBuilder::visitICmp(const User &I) { 3199 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3200 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3201 predicate = IC->getPredicate(); 3202 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3203 predicate = ICmpInst::Predicate(IC->getPredicate()); 3204 SDValue Op1 = getValue(I.getOperand(0)); 3205 SDValue Op2 = getValue(I.getOperand(1)); 3206 ISD::CondCode Opcode = getICmpCondCode(predicate); 3207 3208 auto &TLI = DAG.getTargetLoweringInfo(); 3209 EVT MemVT = 3210 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3211 3212 // If a pointer's DAG type is larger than its memory type then the DAG values 3213 // are zero-extended. This breaks signed comparisons so truncate back to the 3214 // underlying type before doing the compare. 3215 if (Op1.getValueType() != MemVT) { 3216 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3217 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3218 } 3219 3220 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3221 I.getType()); 3222 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3223 } 3224 3225 void SelectionDAGBuilder::visitFCmp(const User &I) { 3226 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3227 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3228 predicate = FC->getPredicate(); 3229 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3230 predicate = FCmpInst::Predicate(FC->getPredicate()); 3231 SDValue Op1 = getValue(I.getOperand(0)); 3232 SDValue Op2 = getValue(I.getOperand(1)); 3233 3234 ISD::CondCode Condition = getFCmpCondCode(predicate); 3235 auto *FPMO = dyn_cast<FPMathOperator>(&I); 3236 if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath) 3237 Condition = getFCmpCodeWithoutNaN(Condition); 3238 3239 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3240 I.getType()); 3241 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3242 } 3243 3244 // Check if the condition of the select has one use or two users that are both 3245 // selects with the same condition. 3246 static bool hasOnlySelectUsers(const Value *Cond) { 3247 return llvm::all_of(Cond->users(), [](const Value *V) { 3248 return isa<SelectInst>(V); 3249 }); 3250 } 3251 3252 void SelectionDAGBuilder::visitSelect(const User &I) { 3253 SmallVector<EVT, 4> ValueVTs; 3254 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3255 ValueVTs); 3256 unsigned NumValues = ValueVTs.size(); 3257 if (NumValues == 0) return; 3258 3259 SmallVector<SDValue, 4> Values(NumValues); 3260 SDValue Cond = getValue(I.getOperand(0)); 3261 SDValue LHSVal = getValue(I.getOperand(1)); 3262 SDValue RHSVal = getValue(I.getOperand(2)); 3263 auto BaseOps = {Cond}; 3264 ISD::NodeType OpCode = Cond.getValueType().isVector() ? 3265 ISD::VSELECT : ISD::SELECT; 3266 3267 bool IsUnaryAbs = false; 3268 3269 // Min/max matching is only viable if all output VTs are the same. 3270 if (is_splat(ValueVTs)) { 3271 EVT VT = ValueVTs[0]; 3272 LLVMContext &Ctx = *DAG.getContext(); 3273 auto &TLI = DAG.getTargetLoweringInfo(); 3274 3275 // We care about the legality of the operation after it has been type 3276 // legalized. 3277 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3278 VT = TLI.getTypeToTransformTo(Ctx, VT); 3279 3280 // If the vselect is legal, assume we want to leave this as a vector setcc + 3281 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3282 // min/max is legal on the scalar type. 3283 bool UseScalarMinMax = VT.isVector() && 3284 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3285 3286 Value *LHS, *RHS; 3287 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3288 ISD::NodeType Opc = ISD::DELETED_NODE; 3289 switch (SPR.Flavor) { 3290 case SPF_UMAX: Opc = ISD::UMAX; break; 3291 case SPF_UMIN: Opc = ISD::UMIN; break; 3292 case SPF_SMAX: Opc = ISD::SMAX; break; 3293 case SPF_SMIN: Opc = ISD::SMIN; break; 3294 case SPF_FMINNUM: 3295 switch (SPR.NaNBehavior) { 3296 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3297 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3298 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3299 case SPNB_RETURNS_ANY: { 3300 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3301 Opc = ISD::FMINNUM; 3302 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3303 Opc = ISD::FMINIMUM; 3304 else if (UseScalarMinMax) 3305 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3306 ISD::FMINNUM : ISD::FMINIMUM; 3307 break; 3308 } 3309 } 3310 break; 3311 case SPF_FMAXNUM: 3312 switch (SPR.NaNBehavior) { 3313 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3314 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3315 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3316 case SPNB_RETURNS_ANY: 3317 3318 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3319 Opc = ISD::FMAXNUM; 3320 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3321 Opc = ISD::FMAXIMUM; 3322 else if (UseScalarMinMax) 3323 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3324 ISD::FMAXNUM : ISD::FMAXIMUM; 3325 break; 3326 } 3327 break; 3328 case SPF_ABS: 3329 IsUnaryAbs = true; 3330 Opc = ISD::ABS; 3331 break; 3332 case SPF_NABS: 3333 // TODO: we need to produce sub(0, abs(X)). 3334 default: break; 3335 } 3336 3337 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3338 (TLI.isOperationLegalOrCustom(Opc, VT) || 3339 (UseScalarMinMax && 3340 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3341 // If the underlying comparison instruction is used by any other 3342 // instruction, the consumed instructions won't be destroyed, so it is 3343 // not profitable to convert to a min/max. 3344 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3345 OpCode = Opc; 3346 LHSVal = getValue(LHS); 3347 RHSVal = getValue(RHS); 3348 BaseOps = {}; 3349 } 3350 3351 if (IsUnaryAbs) { 3352 OpCode = Opc; 3353 LHSVal = getValue(LHS); 3354 BaseOps = {}; 3355 } 3356 } 3357 3358 if (IsUnaryAbs) { 3359 for (unsigned i = 0; i != NumValues; ++i) { 3360 Values[i] = 3361 DAG.getNode(OpCode, getCurSDLoc(), 3362 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), 3363 SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3364 } 3365 } else { 3366 for (unsigned i = 0; i != NumValues; ++i) { 3367 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3368 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3369 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3370 Values[i] = DAG.getNode( 3371 OpCode, getCurSDLoc(), 3372 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops); 3373 } 3374 } 3375 3376 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3377 DAG.getVTList(ValueVTs), Values)); 3378 } 3379 3380 void SelectionDAGBuilder::visitTrunc(const User &I) { 3381 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3382 SDValue N = getValue(I.getOperand(0)); 3383 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3384 I.getType()); 3385 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3386 } 3387 3388 void SelectionDAGBuilder::visitZExt(const User &I) { 3389 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3390 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3391 SDValue N = getValue(I.getOperand(0)); 3392 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3393 I.getType()); 3394 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3395 } 3396 3397 void SelectionDAGBuilder::visitSExt(const User &I) { 3398 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3399 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3400 SDValue N = getValue(I.getOperand(0)); 3401 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3402 I.getType()); 3403 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3404 } 3405 3406 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3407 // FPTrunc is never a no-op cast, no need to check 3408 SDValue N = getValue(I.getOperand(0)); 3409 SDLoc dl = getCurSDLoc(); 3410 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3411 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3412 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3413 DAG.getTargetConstant( 3414 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3415 } 3416 3417 void SelectionDAGBuilder::visitFPExt(const User &I) { 3418 // FPExt is never a no-op cast, no need to check 3419 SDValue N = getValue(I.getOperand(0)); 3420 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3421 I.getType()); 3422 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3423 } 3424 3425 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3426 // FPToUI is never a no-op cast, no need to check 3427 SDValue N = getValue(I.getOperand(0)); 3428 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3429 I.getType()); 3430 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3431 } 3432 3433 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3434 // FPToSI is never a no-op cast, no need to check 3435 SDValue N = getValue(I.getOperand(0)); 3436 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3437 I.getType()); 3438 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3439 } 3440 3441 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3442 // UIToFP is never a no-op cast, no need to check 3443 SDValue N = getValue(I.getOperand(0)); 3444 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3445 I.getType()); 3446 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3447 } 3448 3449 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3450 // SIToFP is never a no-op cast, no need to check 3451 SDValue N = getValue(I.getOperand(0)); 3452 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3453 I.getType()); 3454 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3455 } 3456 3457 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3458 // What to do depends on the size of the integer and the size of the pointer. 3459 // We can either truncate, zero extend, or no-op, accordingly. 3460 SDValue N = getValue(I.getOperand(0)); 3461 auto &TLI = DAG.getTargetLoweringInfo(); 3462 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3463 I.getType()); 3464 EVT PtrMemVT = 3465 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3466 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3467 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3468 setValue(&I, N); 3469 } 3470 3471 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3472 // What to do depends on the size of the integer and the size of the pointer. 3473 // We can either truncate, zero extend, or no-op, accordingly. 3474 SDValue N = getValue(I.getOperand(0)); 3475 auto &TLI = DAG.getTargetLoweringInfo(); 3476 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3477 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3478 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3479 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3480 setValue(&I, N); 3481 } 3482 3483 void SelectionDAGBuilder::visitBitCast(const User &I) { 3484 SDValue N = getValue(I.getOperand(0)); 3485 SDLoc dl = getCurSDLoc(); 3486 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3487 I.getType()); 3488 3489 // BitCast assures us that source and destination are the same size so this is 3490 // either a BITCAST or a no-op. 3491 if (DestVT != N.getValueType()) 3492 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3493 DestVT, N)); // convert types. 3494 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3495 // might fold any kind of constant expression to an integer constant and that 3496 // is not what we are looking for. Only recognize a bitcast of a genuine 3497 // constant integer as an opaque constant. 3498 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3499 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3500 /*isOpaque*/true)); 3501 else 3502 setValue(&I, N); // noop cast. 3503 } 3504 3505 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3506 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3507 const Value *SV = I.getOperand(0); 3508 SDValue N = getValue(SV); 3509 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3510 3511 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3512 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3513 3514 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) 3515 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3516 3517 setValue(&I, N); 3518 } 3519 3520 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3521 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3522 SDValue InVec = getValue(I.getOperand(0)); 3523 SDValue InVal = getValue(I.getOperand(1)); 3524 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3525 TLI.getVectorIdxTy(DAG.getDataLayout())); 3526 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3527 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3528 InVec, InVal, InIdx)); 3529 } 3530 3531 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3532 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3533 SDValue InVec = getValue(I.getOperand(0)); 3534 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3535 TLI.getVectorIdxTy(DAG.getDataLayout())); 3536 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3537 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3538 InVec, InIdx)); 3539 } 3540 3541 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3542 SDValue Src1 = getValue(I.getOperand(0)); 3543 SDValue Src2 = getValue(I.getOperand(1)); 3544 Constant *MaskV = cast<Constant>(I.getOperand(2)); 3545 SDLoc DL = getCurSDLoc(); 3546 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3547 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3548 EVT SrcVT = Src1.getValueType(); 3549 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3550 3551 if (MaskV->isNullValue() && VT.isScalableVector()) { 3552 // Canonical splat form of first element of first input vector. 3553 SDValue FirstElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 3554 SrcVT.getScalarType(), Src1, 3555 DAG.getConstant(0, DL, 3556 TLI.getVectorIdxTy(DAG.getDataLayout()))); 3557 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3558 return; 3559 } 3560 3561 // For now, we only handle splats for scalable vectors. 3562 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3563 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3564 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3565 3566 SmallVector<int, 8> Mask; 3567 ShuffleVectorInst::getShuffleMask(MaskV, Mask); 3568 unsigned MaskNumElts = Mask.size(); 3569 3570 if (SrcNumElts == MaskNumElts) { 3571 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3572 return; 3573 } 3574 3575 // Normalize the shuffle vector since mask and vector length don't match. 3576 if (SrcNumElts < MaskNumElts) { 3577 // Mask is longer than the source vectors. We can use concatenate vector to 3578 // make the mask and vectors lengths match. 3579 3580 if (MaskNumElts % SrcNumElts == 0) { 3581 // Mask length is a multiple of the source vector length. 3582 // Check if the shuffle is some kind of concatenation of the input 3583 // vectors. 3584 unsigned NumConcat = MaskNumElts / SrcNumElts; 3585 bool IsConcat = true; 3586 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3587 for (unsigned i = 0; i != MaskNumElts; ++i) { 3588 int Idx = Mask[i]; 3589 if (Idx < 0) 3590 continue; 3591 // Ensure the indices in each SrcVT sized piece are sequential and that 3592 // the same source is used for the whole piece. 3593 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3594 (ConcatSrcs[i / SrcNumElts] >= 0 && 3595 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3596 IsConcat = false; 3597 break; 3598 } 3599 // Remember which source this index came from. 3600 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3601 } 3602 3603 // The shuffle is concatenating multiple vectors together. Just emit 3604 // a CONCAT_VECTORS operation. 3605 if (IsConcat) { 3606 SmallVector<SDValue, 8> ConcatOps; 3607 for (auto Src : ConcatSrcs) { 3608 if (Src < 0) 3609 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3610 else if (Src == 0) 3611 ConcatOps.push_back(Src1); 3612 else 3613 ConcatOps.push_back(Src2); 3614 } 3615 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3616 return; 3617 } 3618 } 3619 3620 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3621 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3622 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3623 PaddedMaskNumElts); 3624 3625 // Pad both vectors with undefs to make them the same length as the mask. 3626 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3627 3628 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3629 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3630 MOps1[0] = Src1; 3631 MOps2[0] = Src2; 3632 3633 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3634 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3635 3636 // Readjust mask for new input vector length. 3637 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3638 for (unsigned i = 0; i != MaskNumElts; ++i) { 3639 int Idx = Mask[i]; 3640 if (Idx >= (int)SrcNumElts) 3641 Idx -= SrcNumElts - PaddedMaskNumElts; 3642 MappedOps[i] = Idx; 3643 } 3644 3645 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3646 3647 // If the concatenated vector was padded, extract a subvector with the 3648 // correct number of elements. 3649 if (MaskNumElts != PaddedMaskNumElts) 3650 Result = DAG.getNode( 3651 ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3652 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 3653 3654 setValue(&I, Result); 3655 return; 3656 } 3657 3658 if (SrcNumElts > MaskNumElts) { 3659 // Analyze the access pattern of the vector to see if we can extract 3660 // two subvectors and do the shuffle. 3661 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3662 bool CanExtract = true; 3663 for (int Idx : Mask) { 3664 unsigned Input = 0; 3665 if (Idx < 0) 3666 continue; 3667 3668 if (Idx >= (int)SrcNumElts) { 3669 Input = 1; 3670 Idx -= SrcNumElts; 3671 } 3672 3673 // If all the indices come from the same MaskNumElts sized portion of 3674 // the sources we can use extract. Also make sure the extract wouldn't 3675 // extract past the end of the source. 3676 int NewStartIdx = alignDown(Idx, MaskNumElts); 3677 if (NewStartIdx + MaskNumElts > SrcNumElts || 3678 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3679 CanExtract = false; 3680 // Make sure we always update StartIdx as we use it to track if all 3681 // elements are undef. 3682 StartIdx[Input] = NewStartIdx; 3683 } 3684 3685 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3686 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3687 return; 3688 } 3689 if (CanExtract) { 3690 // Extract appropriate subvector and generate a vector shuffle 3691 for (unsigned Input = 0; Input < 2; ++Input) { 3692 SDValue &Src = Input == 0 ? Src1 : Src2; 3693 if (StartIdx[Input] < 0) 3694 Src = DAG.getUNDEF(VT); 3695 else { 3696 Src = DAG.getNode( 3697 ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3698 DAG.getConstant(StartIdx[Input], DL, 3699 TLI.getVectorIdxTy(DAG.getDataLayout()))); 3700 } 3701 } 3702 3703 // Calculate new mask. 3704 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3705 for (int &Idx : MappedOps) { 3706 if (Idx >= (int)SrcNumElts) 3707 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3708 else if (Idx >= 0) 3709 Idx -= StartIdx[0]; 3710 } 3711 3712 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3713 return; 3714 } 3715 } 3716 3717 // We can't use either concat vectors or extract subvectors so fall back to 3718 // replacing the shuffle with extract and build vector. 3719 // to insert and build vector. 3720 EVT EltVT = VT.getVectorElementType(); 3721 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 3722 SmallVector<SDValue,8> Ops; 3723 for (int Idx : Mask) { 3724 SDValue Res; 3725 3726 if (Idx < 0) { 3727 Res = DAG.getUNDEF(EltVT); 3728 } else { 3729 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3730 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3731 3732 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 3733 EltVT, Src, DAG.getConstant(Idx, DL, IdxVT)); 3734 } 3735 3736 Ops.push_back(Res); 3737 } 3738 3739 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3740 } 3741 3742 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3743 ArrayRef<unsigned> Indices; 3744 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3745 Indices = IV->getIndices(); 3746 else 3747 Indices = cast<ConstantExpr>(&I)->getIndices(); 3748 3749 const Value *Op0 = I.getOperand(0); 3750 const Value *Op1 = I.getOperand(1); 3751 Type *AggTy = I.getType(); 3752 Type *ValTy = Op1->getType(); 3753 bool IntoUndef = isa<UndefValue>(Op0); 3754 bool FromUndef = isa<UndefValue>(Op1); 3755 3756 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3757 3758 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3759 SmallVector<EVT, 4> AggValueVTs; 3760 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3761 SmallVector<EVT, 4> ValValueVTs; 3762 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3763 3764 unsigned NumAggValues = AggValueVTs.size(); 3765 unsigned NumValValues = ValValueVTs.size(); 3766 SmallVector<SDValue, 4> Values(NumAggValues); 3767 3768 // Ignore an insertvalue that produces an empty object 3769 if (!NumAggValues) { 3770 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3771 return; 3772 } 3773 3774 SDValue Agg = getValue(Op0); 3775 unsigned i = 0; 3776 // Copy the beginning value(s) from the original aggregate. 3777 for (; i != LinearIndex; ++i) 3778 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3779 SDValue(Agg.getNode(), Agg.getResNo() + i); 3780 // Copy values from the inserted value(s). 3781 if (NumValValues) { 3782 SDValue Val = getValue(Op1); 3783 for (; i != LinearIndex + NumValValues; ++i) 3784 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3785 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3786 } 3787 // Copy remaining value(s) from the original aggregate. 3788 for (; i != NumAggValues; ++i) 3789 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3790 SDValue(Agg.getNode(), Agg.getResNo() + i); 3791 3792 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3793 DAG.getVTList(AggValueVTs), Values)); 3794 } 3795 3796 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3797 ArrayRef<unsigned> Indices; 3798 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3799 Indices = EV->getIndices(); 3800 else 3801 Indices = cast<ConstantExpr>(&I)->getIndices(); 3802 3803 const Value *Op0 = I.getOperand(0); 3804 Type *AggTy = Op0->getType(); 3805 Type *ValTy = I.getType(); 3806 bool OutOfUndef = isa<UndefValue>(Op0); 3807 3808 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3809 3810 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3811 SmallVector<EVT, 4> ValValueVTs; 3812 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3813 3814 unsigned NumValValues = ValValueVTs.size(); 3815 3816 // Ignore a extractvalue that produces an empty object 3817 if (!NumValValues) { 3818 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3819 return; 3820 } 3821 3822 SmallVector<SDValue, 4> Values(NumValValues); 3823 3824 SDValue Agg = getValue(Op0); 3825 // Copy out the selected value(s). 3826 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3827 Values[i - LinearIndex] = 3828 OutOfUndef ? 3829 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3830 SDValue(Agg.getNode(), Agg.getResNo() + i); 3831 3832 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3833 DAG.getVTList(ValValueVTs), Values)); 3834 } 3835 3836 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3837 Value *Op0 = I.getOperand(0); 3838 // Note that the pointer operand may be a vector of pointers. Take the scalar 3839 // element which holds a pointer. 3840 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3841 SDValue N = getValue(Op0); 3842 SDLoc dl = getCurSDLoc(); 3843 auto &TLI = DAG.getTargetLoweringInfo(); 3844 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 3845 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 3846 3847 // Normalize Vector GEP - all scalar operands should be converted to the 3848 // splat vector. 3849 unsigned VectorWidth = I.getType()->isVectorTy() ? 3850 I.getType()->getVectorNumElements() : 0; 3851 3852 if (VectorWidth && !N.getValueType().isVector()) { 3853 LLVMContext &Context = *DAG.getContext(); 3854 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth); 3855 N = DAG.getSplatBuildVector(VT, dl, N); 3856 } 3857 3858 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3859 GTI != E; ++GTI) { 3860 const Value *Idx = GTI.getOperand(); 3861 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3862 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3863 if (Field) { 3864 // N = N + Offset 3865 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3866 3867 // In an inbounds GEP with an offset that is nonnegative even when 3868 // interpreted as signed, assume there is no unsigned overflow. 3869 SDNodeFlags Flags; 3870 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3871 Flags.setNoUnsignedWrap(true); 3872 3873 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3874 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3875 } 3876 } else { 3877 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3878 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3879 APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType())); 3880 3881 // If this is a scalar constant or a splat vector of constants, 3882 // handle it quickly. 3883 const auto *C = dyn_cast<Constant>(Idx); 3884 if (C && isa<VectorType>(C->getType())) 3885 C = C->getSplatValue(); 3886 3887 if (const auto *CI = dyn_cast_or_null<ConstantInt>(C)) { 3888 if (CI->isZero()) 3889 continue; 3890 APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize); 3891 LLVMContext &Context = *DAG.getContext(); 3892 SDValue OffsVal = VectorWidth ? 3893 DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) : 3894 DAG.getConstant(Offs, dl, IdxTy); 3895 3896 // In an inbounds GEP with an offset that is nonnegative even when 3897 // interpreted as signed, assume there is no unsigned overflow. 3898 SDNodeFlags Flags; 3899 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3900 Flags.setNoUnsignedWrap(true); 3901 3902 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3903 3904 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3905 continue; 3906 } 3907 3908 // N = N + Idx * ElementSize; 3909 SDValue IdxN = getValue(Idx); 3910 3911 if (!IdxN.getValueType().isVector() && VectorWidth) { 3912 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth); 3913 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3914 } 3915 3916 // If the index is smaller or larger than intptr_t, truncate or extend 3917 // it. 3918 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3919 3920 // If this is a multiply by a power of two, turn it into a shl 3921 // immediately. This is a very common case. 3922 if (ElementSize != 1) { 3923 if (ElementSize.isPowerOf2()) { 3924 unsigned Amt = ElementSize.logBase2(); 3925 IdxN = DAG.getNode(ISD::SHL, dl, 3926 N.getValueType(), IdxN, 3927 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3928 } else { 3929 SDValue Scale = DAG.getConstant(ElementSize.getZExtValue(), dl, 3930 IdxN.getValueType()); 3931 IdxN = DAG.getNode(ISD::MUL, dl, 3932 N.getValueType(), IdxN, Scale); 3933 } 3934 } 3935 3936 N = DAG.getNode(ISD::ADD, dl, 3937 N.getValueType(), N, IdxN); 3938 } 3939 } 3940 3941 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 3942 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 3943 3944 setValue(&I, N); 3945 } 3946 3947 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3948 // If this is a fixed sized alloca in the entry block of the function, 3949 // allocate it statically on the stack. 3950 if (FuncInfo.StaticAllocaMap.count(&I)) 3951 return; // getValue will auto-populate this. 3952 3953 SDLoc dl = getCurSDLoc(); 3954 Type *Ty = I.getAllocatedType(); 3955 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3956 auto &DL = DAG.getDataLayout(); 3957 uint64_t TySize = DL.getTypeAllocSize(Ty); 3958 unsigned Align = 3959 std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment()); 3960 3961 SDValue AllocSize = getValue(I.getArraySize()); 3962 3963 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3964 if (AllocSize.getValueType() != IntPtr) 3965 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3966 3967 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3968 AllocSize, 3969 DAG.getConstant(TySize, dl, IntPtr)); 3970 3971 // Handle alignment. If the requested alignment is less than or equal to 3972 // the stack alignment, ignore it. If the size is greater than or equal to 3973 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3974 unsigned StackAlign = 3975 DAG.getSubtarget().getFrameLowering()->getStackAlignment(); 3976 if (Align <= StackAlign) 3977 Align = 0; 3978 3979 // Round the size of the allocation up to the stack alignment size 3980 // by add SA-1 to the size. This doesn't overflow because we're computing 3981 // an address inside an alloca. 3982 SDNodeFlags Flags; 3983 Flags.setNoUnsignedWrap(true); 3984 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 3985 DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags); 3986 3987 // Mask out the low bits for alignment purposes. 3988 AllocSize = 3989 DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 3990 DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr)); 3991 3992 SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)}; 3993 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 3994 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 3995 setValue(&I, DSA); 3996 DAG.setRoot(DSA.getValue(1)); 3997 3998 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 3999 } 4000 4001 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4002 if (I.isAtomic()) 4003 return visitAtomicLoad(I); 4004 4005 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4006 const Value *SV = I.getOperand(0); 4007 if (TLI.supportSwiftError()) { 4008 // Swifterror values can come from either a function parameter with 4009 // swifterror attribute or an alloca with swifterror attribute. 4010 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4011 if (Arg->hasSwiftErrorAttr()) 4012 return visitLoadFromSwiftError(I); 4013 } 4014 4015 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4016 if (Alloca->isSwiftError()) 4017 return visitLoadFromSwiftError(I); 4018 } 4019 } 4020 4021 SDValue Ptr = getValue(SV); 4022 4023 Type *Ty = I.getType(); 4024 4025 bool isVolatile = I.isVolatile(); 4026 bool isNonTemporal = I.hasMetadata(LLVMContext::MD_nontemporal); 4027 bool isInvariant = I.hasMetadata(LLVMContext::MD_invariant_load); 4028 bool isDereferenceable = 4029 isDereferenceablePointer(SV, I.getType(), DAG.getDataLayout()); 4030 unsigned Alignment = I.getAlignment(); 4031 4032 AAMDNodes AAInfo; 4033 I.getAAMetadata(AAInfo); 4034 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4035 4036 SmallVector<EVT, 4> ValueVTs, MemVTs; 4037 SmallVector<uint64_t, 4> Offsets; 4038 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4039 unsigned NumValues = ValueVTs.size(); 4040 if (NumValues == 0) 4041 return; 4042 4043 SDValue Root; 4044 bool ConstantMemory = false; 4045 if (isVolatile || NumValues > MaxParallelChains) 4046 // Serialize volatile loads with other side effects. 4047 Root = getRoot(); 4048 else if (AA && 4049 AA->pointsToConstantMemory(MemoryLocation( 4050 SV, 4051 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4052 AAInfo))) { 4053 // Do not serialize (non-volatile) loads of constant memory with anything. 4054 Root = DAG.getEntryNode(); 4055 ConstantMemory = true; 4056 } else { 4057 // Do not serialize non-volatile loads against each other. 4058 Root = DAG.getRoot(); 4059 } 4060 4061 SDLoc dl = getCurSDLoc(); 4062 4063 if (isVolatile) 4064 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4065 4066 // An aggregate load cannot wrap around the address space, so offsets to its 4067 // parts don't wrap either. 4068 SDNodeFlags Flags; 4069 Flags.setNoUnsignedWrap(true); 4070 4071 SmallVector<SDValue, 4> Values(NumValues); 4072 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4073 EVT PtrVT = Ptr.getValueType(); 4074 unsigned ChainI = 0; 4075 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4076 // Serializing loads here may result in excessive register pressure, and 4077 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4078 // could recover a bit by hoisting nodes upward in the chain by recognizing 4079 // they are side-effect free or do not alias. The optimizer should really 4080 // avoid this case by converting large object/array copies to llvm.memcpy 4081 // (MaxParallelChains should always remain as failsafe). 4082 if (ChainI == MaxParallelChains) { 4083 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4084 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4085 makeArrayRef(Chains.data(), ChainI)); 4086 Root = Chain; 4087 ChainI = 0; 4088 } 4089 SDValue A = DAG.getNode(ISD::ADD, dl, 4090 PtrVT, Ptr, 4091 DAG.getConstant(Offsets[i], dl, PtrVT), 4092 Flags); 4093 auto MMOFlags = MachineMemOperand::MONone; 4094 if (isVolatile) 4095 MMOFlags |= MachineMemOperand::MOVolatile; 4096 if (isNonTemporal) 4097 MMOFlags |= MachineMemOperand::MONonTemporal; 4098 if (isInvariant) 4099 MMOFlags |= MachineMemOperand::MOInvariant; 4100 if (isDereferenceable) 4101 MMOFlags |= MachineMemOperand::MODereferenceable; 4102 MMOFlags |= TLI.getMMOFlags(I); 4103 4104 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4105 MachinePointerInfo(SV, Offsets[i]), Alignment, 4106 MMOFlags, AAInfo, Ranges); 4107 Chains[ChainI] = L.getValue(1); 4108 4109 if (MemVTs[i] != ValueVTs[i]) 4110 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4111 4112 Values[i] = L; 4113 } 4114 4115 if (!ConstantMemory) { 4116 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4117 makeArrayRef(Chains.data(), ChainI)); 4118 if (isVolatile) 4119 DAG.setRoot(Chain); 4120 else 4121 PendingLoads.push_back(Chain); 4122 } 4123 4124 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4125 DAG.getVTList(ValueVTs), Values)); 4126 } 4127 4128 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4129 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4130 "call visitStoreToSwiftError when backend supports swifterror"); 4131 4132 SmallVector<EVT, 4> ValueVTs; 4133 SmallVector<uint64_t, 4> Offsets; 4134 const Value *SrcV = I.getOperand(0); 4135 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4136 SrcV->getType(), ValueVTs, &Offsets); 4137 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4138 "expect a single EVT for swifterror"); 4139 4140 SDValue Src = getValue(SrcV); 4141 // Create a virtual register, then update the virtual register. 4142 Register VReg = 4143 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4144 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4145 // Chain can be getRoot or getControlRoot. 4146 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4147 SDValue(Src.getNode(), Src.getResNo())); 4148 DAG.setRoot(CopyNode); 4149 } 4150 4151 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4152 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4153 "call visitLoadFromSwiftError when backend supports swifterror"); 4154 4155 assert(!I.isVolatile() && 4156 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4157 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4158 "Support volatile, non temporal, invariant for load_from_swift_error"); 4159 4160 const Value *SV = I.getOperand(0); 4161 Type *Ty = I.getType(); 4162 AAMDNodes AAInfo; 4163 I.getAAMetadata(AAInfo); 4164 assert( 4165 (!AA || 4166 !AA->pointsToConstantMemory(MemoryLocation( 4167 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4168 AAInfo))) && 4169 "load_from_swift_error should not be constant memory"); 4170 4171 SmallVector<EVT, 4> ValueVTs; 4172 SmallVector<uint64_t, 4> Offsets; 4173 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4174 ValueVTs, &Offsets); 4175 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4176 "expect a single EVT for swifterror"); 4177 4178 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4179 SDValue L = DAG.getCopyFromReg( 4180 getRoot(), getCurSDLoc(), 4181 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4182 4183 setValue(&I, L); 4184 } 4185 4186 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4187 if (I.isAtomic()) 4188 return visitAtomicStore(I); 4189 4190 const Value *SrcV = I.getOperand(0); 4191 const Value *PtrV = I.getOperand(1); 4192 4193 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4194 if (TLI.supportSwiftError()) { 4195 // Swifterror values can come from either a function parameter with 4196 // swifterror attribute or an alloca with swifterror attribute. 4197 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4198 if (Arg->hasSwiftErrorAttr()) 4199 return visitStoreToSwiftError(I); 4200 } 4201 4202 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4203 if (Alloca->isSwiftError()) 4204 return visitStoreToSwiftError(I); 4205 } 4206 } 4207 4208 SmallVector<EVT, 4> ValueVTs, MemVTs; 4209 SmallVector<uint64_t, 4> Offsets; 4210 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4211 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4212 unsigned NumValues = ValueVTs.size(); 4213 if (NumValues == 0) 4214 return; 4215 4216 // Get the lowered operands. Note that we do this after 4217 // checking if NumResults is zero, because with zero results 4218 // the operands won't have values in the map. 4219 SDValue Src = getValue(SrcV); 4220 SDValue Ptr = getValue(PtrV); 4221 4222 SDValue Root = getRoot(); 4223 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4224 SDLoc dl = getCurSDLoc(); 4225 EVT PtrVT = Ptr.getValueType(); 4226 unsigned Alignment = I.getAlignment(); 4227 AAMDNodes AAInfo; 4228 I.getAAMetadata(AAInfo); 4229 4230 auto MMOFlags = MachineMemOperand::MONone; 4231 if (I.isVolatile()) 4232 MMOFlags |= MachineMemOperand::MOVolatile; 4233 if (I.hasMetadata(LLVMContext::MD_nontemporal)) 4234 MMOFlags |= MachineMemOperand::MONonTemporal; 4235 MMOFlags |= TLI.getMMOFlags(I); 4236 4237 // An aggregate load cannot wrap around the address space, so offsets to its 4238 // parts don't wrap either. 4239 SDNodeFlags Flags; 4240 Flags.setNoUnsignedWrap(true); 4241 4242 unsigned ChainI = 0; 4243 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4244 // See visitLoad comments. 4245 if (ChainI == MaxParallelChains) { 4246 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4247 makeArrayRef(Chains.data(), ChainI)); 4248 Root = Chain; 4249 ChainI = 0; 4250 } 4251 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, 4252 DAG.getConstant(Offsets[i], dl, PtrVT), Flags); 4253 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4254 if (MemVTs[i] != ValueVTs[i]) 4255 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4256 SDValue St = 4257 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4258 Alignment, MMOFlags, AAInfo); 4259 Chains[ChainI] = St; 4260 } 4261 4262 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4263 makeArrayRef(Chains.data(), ChainI)); 4264 DAG.setRoot(StoreNode); 4265 } 4266 4267 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4268 bool IsCompressing) { 4269 SDLoc sdl = getCurSDLoc(); 4270 4271 auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4272 unsigned& Alignment) { 4273 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4274 Src0 = I.getArgOperand(0); 4275 Ptr = I.getArgOperand(1); 4276 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 4277 Mask = I.getArgOperand(3); 4278 }; 4279 auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4280 unsigned& Alignment) { 4281 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4282 Src0 = I.getArgOperand(0); 4283 Ptr = I.getArgOperand(1); 4284 Mask = I.getArgOperand(2); 4285 Alignment = 0; 4286 }; 4287 4288 Value *PtrOperand, *MaskOperand, *Src0Operand; 4289 unsigned Alignment; 4290 if (IsCompressing) 4291 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4292 else 4293 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4294 4295 SDValue Ptr = getValue(PtrOperand); 4296 SDValue Src0 = getValue(Src0Operand); 4297 SDValue Mask = getValue(MaskOperand); 4298 4299 EVT VT = Src0.getValueType(); 4300 if (!Alignment) 4301 Alignment = DAG.getEVTAlignment(VT); 4302 4303 AAMDNodes AAInfo; 4304 I.getAAMetadata(AAInfo); 4305 4306 MachineMemOperand *MMO = 4307 DAG.getMachineFunction(). 4308 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4309 MachineMemOperand::MOStore, 4310 // TODO: Make MachineMemOperands aware of scalable 4311 // vectors. 4312 VT.getStoreSize().getKnownMinSize(), 4313 Alignment, AAInfo); 4314 SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT, 4315 MMO, false /* Truncating */, 4316 IsCompressing); 4317 DAG.setRoot(StoreNode); 4318 setValue(&I, StoreNode); 4319 } 4320 4321 // Get a uniform base for the Gather/Scatter intrinsic. 4322 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4323 // We try to represent it as a base pointer + vector of indices. 4324 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4325 // The first operand of the GEP may be a single pointer or a vector of pointers 4326 // Example: 4327 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4328 // or 4329 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4330 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4331 // 4332 // When the first GEP operand is a single pointer - it is the uniform base we 4333 // are looking for. If first operand of the GEP is a splat vector - we 4334 // extract the splat value and use it as a uniform base. 4335 // In all other cases the function returns 'false'. 4336 static bool getUniformBase(const Value *&Ptr, SDValue &Base, SDValue &Index, 4337 ISD::MemIndexType &IndexType, SDValue &Scale, 4338 SelectionDAGBuilder *SDB) { 4339 SelectionDAG& DAG = SDB->DAG; 4340 LLVMContext &Context = *DAG.getContext(); 4341 4342 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 4343 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4344 if (!GEP) 4345 return false; 4346 4347 const Value *GEPPtr = GEP->getPointerOperand(); 4348 if (!GEPPtr->getType()->isVectorTy()) 4349 Ptr = GEPPtr; 4350 else if (!(Ptr = getSplatValue(GEPPtr))) 4351 return false; 4352 4353 unsigned FinalIndex = GEP->getNumOperands() - 1; 4354 Value *IndexVal = GEP->getOperand(FinalIndex); 4355 4356 // Ensure all the other indices are 0. 4357 for (unsigned i = 1; i < FinalIndex; ++i) { 4358 auto *C = dyn_cast<Constant>(GEP->getOperand(i)); 4359 if (!C) 4360 return false; 4361 if (isa<VectorType>(C->getType())) 4362 C = C->getSplatValue(); 4363 auto *CI = dyn_cast_or_null<ConstantInt>(C); 4364 if (!CI || !CI->isZero()) 4365 return false; 4366 } 4367 4368 // The operands of the GEP may be defined in another basic block. 4369 // In this case we'll not find nodes for the operands. 4370 if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal)) 4371 return false; 4372 4373 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4374 const DataLayout &DL = DAG.getDataLayout(); 4375 Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()), 4376 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4377 Base = SDB->getValue(Ptr); 4378 Index = SDB->getValue(IndexVal); 4379 IndexType = ISD::SIGNED_SCALED; 4380 4381 if (!Index.getValueType().isVector()) { 4382 unsigned GEPWidth = GEP->getType()->getVectorNumElements(); 4383 EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth); 4384 Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index); 4385 } 4386 return true; 4387 } 4388 4389 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4390 SDLoc sdl = getCurSDLoc(); 4391 4392 // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask) 4393 const Value *Ptr = I.getArgOperand(1); 4394 SDValue Src0 = getValue(I.getArgOperand(0)); 4395 SDValue Mask = getValue(I.getArgOperand(3)); 4396 EVT VT = Src0.getValueType(); 4397 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue(); 4398 if (!Alignment) 4399 Alignment = DAG.getEVTAlignment(VT); 4400 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4401 4402 AAMDNodes AAInfo; 4403 I.getAAMetadata(AAInfo); 4404 4405 SDValue Base; 4406 SDValue Index; 4407 ISD::MemIndexType IndexType; 4408 SDValue Scale; 4409 const Value *BasePtr = Ptr; 4410 bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale, 4411 this); 4412 4413 const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr; 4414 MachineMemOperand *MMO = DAG.getMachineFunction(). 4415 getMachineMemOperand(MachinePointerInfo(MemOpBasePtr), 4416 MachineMemOperand::MOStore, 4417 // TODO: Make MachineMemOperands aware of scalable 4418 // vectors. 4419 VT.getStoreSize().getKnownMinSize(), 4420 Alignment, AAInfo); 4421 if (!UniformBase) { 4422 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4423 Index = getValue(Ptr); 4424 IndexType = ISD::SIGNED_SCALED; 4425 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4426 } 4427 SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale }; 4428 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4429 Ops, MMO, IndexType); 4430 DAG.setRoot(Scatter); 4431 setValue(&I, Scatter); 4432 } 4433 4434 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4435 SDLoc sdl = getCurSDLoc(); 4436 4437 auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4438 unsigned& Alignment) { 4439 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4440 Ptr = I.getArgOperand(0); 4441 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 4442 Mask = I.getArgOperand(2); 4443 Src0 = I.getArgOperand(3); 4444 }; 4445 auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4446 unsigned& Alignment) { 4447 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4448 Ptr = I.getArgOperand(0); 4449 Alignment = 0; 4450 Mask = I.getArgOperand(1); 4451 Src0 = I.getArgOperand(2); 4452 }; 4453 4454 Value *PtrOperand, *MaskOperand, *Src0Operand; 4455 unsigned Alignment; 4456 if (IsExpanding) 4457 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4458 else 4459 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4460 4461 SDValue Ptr = getValue(PtrOperand); 4462 SDValue Src0 = getValue(Src0Operand); 4463 SDValue Mask = getValue(MaskOperand); 4464 4465 EVT VT = Src0.getValueType(); 4466 if (!Alignment) 4467 Alignment = DAG.getEVTAlignment(VT); 4468 4469 AAMDNodes AAInfo; 4470 I.getAAMetadata(AAInfo); 4471 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4472 4473 // Do not serialize masked loads of constant memory with anything. 4474 MemoryLocation ML; 4475 if (VT.isScalableVector()) 4476 ML = MemoryLocation(PtrOperand); 4477 else 4478 ML = MemoryLocation(PtrOperand, LocationSize::precise( 4479 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4480 AAInfo); 4481 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4482 4483 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4484 4485 MachineMemOperand *MMO = 4486 DAG.getMachineFunction(). 4487 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4488 MachineMemOperand::MOLoad, 4489 // TODO: Make MachineMemOperands aware of scalable 4490 // vectors. 4491 VT.getStoreSize().getKnownMinSize(), 4492 Alignment, AAInfo, Ranges); 4493 4494 SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO, 4495 ISD::NON_EXTLOAD, IsExpanding); 4496 if (AddToChain) 4497 PendingLoads.push_back(Load.getValue(1)); 4498 setValue(&I, Load); 4499 } 4500 4501 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4502 SDLoc sdl = getCurSDLoc(); 4503 4504 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4505 const Value *Ptr = I.getArgOperand(0); 4506 SDValue Src0 = getValue(I.getArgOperand(3)); 4507 SDValue Mask = getValue(I.getArgOperand(2)); 4508 4509 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4510 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4511 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue(); 4512 if (!Alignment) 4513 Alignment = DAG.getEVTAlignment(VT); 4514 4515 AAMDNodes AAInfo; 4516 I.getAAMetadata(AAInfo); 4517 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4518 4519 SDValue Root = DAG.getRoot(); 4520 SDValue Base; 4521 SDValue Index; 4522 ISD::MemIndexType IndexType; 4523 SDValue Scale; 4524 const Value *BasePtr = Ptr; 4525 bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale, 4526 this); 4527 bool ConstantMemory = false; 4528 if (UniformBase && AA && 4529 AA->pointsToConstantMemory( 4530 MemoryLocation(BasePtr, 4531 LocationSize::precise( 4532 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4533 AAInfo))) { 4534 // Do not serialize (non-volatile) loads of constant memory with anything. 4535 Root = DAG.getEntryNode(); 4536 ConstantMemory = true; 4537 } 4538 4539 MachineMemOperand *MMO = 4540 DAG.getMachineFunction(). 4541 getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr), 4542 MachineMemOperand::MOLoad, 4543 // TODO: Make MachineMemOperands aware of scalable 4544 // vectors. 4545 VT.getStoreSize().getKnownMinSize(), 4546 Alignment, AAInfo, Ranges); 4547 4548 if (!UniformBase) { 4549 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4550 Index = getValue(Ptr); 4551 IndexType = ISD::SIGNED_SCALED; 4552 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4553 } 4554 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4555 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4556 Ops, MMO, IndexType); 4557 4558 SDValue OutChain = Gather.getValue(1); 4559 if (!ConstantMemory) 4560 PendingLoads.push_back(OutChain); 4561 setValue(&I, Gather); 4562 } 4563 4564 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4565 SDLoc dl = getCurSDLoc(); 4566 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4567 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4568 SyncScope::ID SSID = I.getSyncScopeID(); 4569 4570 SDValue InChain = getRoot(); 4571 4572 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4573 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4574 4575 auto Alignment = DAG.getEVTAlignment(MemVT); 4576 4577 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 4578 if (I.isVolatile()) 4579 Flags |= MachineMemOperand::MOVolatile; 4580 Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I); 4581 4582 MachineFunction &MF = DAG.getMachineFunction(); 4583 MachineMemOperand *MMO = 4584 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4585 Flags, MemVT.getStoreSize(), Alignment, 4586 AAMDNodes(), nullptr, SSID, SuccessOrdering, 4587 FailureOrdering); 4588 4589 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4590 dl, MemVT, VTs, InChain, 4591 getValue(I.getPointerOperand()), 4592 getValue(I.getCompareOperand()), 4593 getValue(I.getNewValOperand()), MMO); 4594 4595 SDValue OutChain = L.getValue(2); 4596 4597 setValue(&I, L); 4598 DAG.setRoot(OutChain); 4599 } 4600 4601 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4602 SDLoc dl = getCurSDLoc(); 4603 ISD::NodeType NT; 4604 switch (I.getOperation()) { 4605 default: llvm_unreachable("Unknown atomicrmw operation"); 4606 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4607 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4608 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4609 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4610 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4611 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4612 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4613 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4614 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4615 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4616 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4617 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4618 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4619 } 4620 AtomicOrdering Ordering = I.getOrdering(); 4621 SyncScope::ID SSID = I.getSyncScopeID(); 4622 4623 SDValue InChain = getRoot(); 4624 4625 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4626 auto Alignment = DAG.getEVTAlignment(MemVT); 4627 4628 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 4629 if (I.isVolatile()) 4630 Flags |= MachineMemOperand::MOVolatile; 4631 Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I); 4632 4633 MachineFunction &MF = DAG.getMachineFunction(); 4634 MachineMemOperand *MMO = 4635 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags, 4636 MemVT.getStoreSize(), Alignment, AAMDNodes(), 4637 nullptr, SSID, Ordering); 4638 4639 SDValue L = 4640 DAG.getAtomic(NT, dl, MemVT, InChain, 4641 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4642 MMO); 4643 4644 SDValue OutChain = L.getValue(1); 4645 4646 setValue(&I, L); 4647 DAG.setRoot(OutChain); 4648 } 4649 4650 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4651 SDLoc dl = getCurSDLoc(); 4652 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4653 SDValue Ops[3]; 4654 Ops[0] = getRoot(); 4655 Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl, 4656 TLI.getFenceOperandTy(DAG.getDataLayout())); 4657 Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl, 4658 TLI.getFenceOperandTy(DAG.getDataLayout())); 4659 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4660 } 4661 4662 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4663 SDLoc dl = getCurSDLoc(); 4664 AtomicOrdering Order = I.getOrdering(); 4665 SyncScope::ID SSID = I.getSyncScopeID(); 4666 4667 SDValue InChain = getRoot(); 4668 4669 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4670 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4671 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4672 4673 if (!TLI.supportsUnalignedAtomics() && 4674 I.getAlignment() < MemVT.getSizeInBits() / 8) 4675 report_fatal_error("Cannot generate unaligned atomic load"); 4676 4677 auto Flags = MachineMemOperand::MOLoad; 4678 if (I.isVolatile()) 4679 Flags |= MachineMemOperand::MOVolatile; 4680 if (I.hasMetadata(LLVMContext::MD_invariant_load)) 4681 Flags |= MachineMemOperand::MOInvariant; 4682 if (isDereferenceablePointer(I.getPointerOperand(), I.getType(), 4683 DAG.getDataLayout())) 4684 Flags |= MachineMemOperand::MODereferenceable; 4685 4686 Flags |= TLI.getMMOFlags(I); 4687 4688 MachineMemOperand *MMO = 4689 DAG.getMachineFunction(). 4690 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4691 Flags, MemVT.getStoreSize(), 4692 I.getAlignment() ? I.getAlignment() : 4693 DAG.getEVTAlignment(MemVT), 4694 AAMDNodes(), nullptr, SSID, Order); 4695 4696 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4697 4698 SDValue Ptr = getValue(I.getPointerOperand()); 4699 4700 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4701 // TODO: Once this is better exercised by tests, it should be merged with 4702 // the normal path for loads to prevent future divergence. 4703 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4704 if (MemVT != VT) 4705 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4706 4707 setValue(&I, L); 4708 SDValue OutChain = L.getValue(1); 4709 if (!I.isUnordered()) 4710 DAG.setRoot(OutChain); 4711 else 4712 PendingLoads.push_back(OutChain); 4713 return; 4714 } 4715 4716 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4717 Ptr, MMO); 4718 4719 SDValue OutChain = L.getValue(1); 4720 if (MemVT != VT) 4721 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4722 4723 setValue(&I, L); 4724 DAG.setRoot(OutChain); 4725 } 4726 4727 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4728 SDLoc dl = getCurSDLoc(); 4729 4730 AtomicOrdering Ordering = I.getOrdering(); 4731 SyncScope::ID SSID = I.getSyncScopeID(); 4732 4733 SDValue InChain = getRoot(); 4734 4735 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4736 EVT MemVT = 4737 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4738 4739 if (I.getAlignment() < MemVT.getSizeInBits() / 8) 4740 report_fatal_error("Cannot generate unaligned atomic store"); 4741 4742 auto Flags = MachineMemOperand::MOStore; 4743 if (I.isVolatile()) 4744 Flags |= MachineMemOperand::MOVolatile; 4745 Flags |= TLI.getMMOFlags(I); 4746 4747 MachineFunction &MF = DAG.getMachineFunction(); 4748 MachineMemOperand *MMO = 4749 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags, 4750 MemVT.getStoreSize(), I.getAlignment(), AAMDNodes(), 4751 nullptr, SSID, Ordering); 4752 4753 SDValue Val = getValue(I.getValueOperand()); 4754 if (Val.getValueType() != MemVT) 4755 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4756 SDValue Ptr = getValue(I.getPointerOperand()); 4757 4758 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4759 // TODO: Once this is better exercised by tests, it should be merged with 4760 // the normal path for stores to prevent future divergence. 4761 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4762 DAG.setRoot(S); 4763 return; 4764 } 4765 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4766 Ptr, Val, MMO); 4767 4768 4769 DAG.setRoot(OutChain); 4770 } 4771 4772 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4773 /// node. 4774 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4775 unsigned Intrinsic) { 4776 // Ignore the callsite's attributes. A specific call site may be marked with 4777 // readnone, but the lowering code will expect the chain based on the 4778 // definition. 4779 const Function *F = I.getCalledFunction(); 4780 bool HasChain = !F->doesNotAccessMemory(); 4781 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4782 4783 // Build the operand list. 4784 SmallVector<SDValue, 8> Ops; 4785 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4786 if (OnlyLoad) { 4787 // We don't need to serialize loads against other loads. 4788 Ops.push_back(DAG.getRoot()); 4789 } else { 4790 Ops.push_back(getRoot()); 4791 } 4792 } 4793 4794 // Info is set by getTgtMemInstrinsic 4795 TargetLowering::IntrinsicInfo Info; 4796 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4797 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4798 DAG.getMachineFunction(), 4799 Intrinsic); 4800 4801 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4802 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4803 Info.opc == ISD::INTRINSIC_W_CHAIN) 4804 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4805 TLI.getPointerTy(DAG.getDataLayout()))); 4806 4807 // Add all operands of the call to the operand list. 4808 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4809 const Value *Arg = I.getArgOperand(i); 4810 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4811 Ops.push_back(getValue(Arg)); 4812 continue; 4813 } 4814 4815 // Use TargetConstant instead of a regular constant for immarg. 4816 EVT VT = TLI.getValueType(*DL, Arg->getType(), true); 4817 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4818 assert(CI->getBitWidth() <= 64 && 4819 "large intrinsic immediates not handled"); 4820 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4821 } else { 4822 Ops.push_back( 4823 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4824 } 4825 } 4826 4827 SmallVector<EVT, 4> ValueVTs; 4828 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4829 4830 if (HasChain) 4831 ValueVTs.push_back(MVT::Other); 4832 4833 SDVTList VTs = DAG.getVTList(ValueVTs); 4834 4835 // Create the node. 4836 SDValue Result; 4837 if (IsTgtIntrinsic) { 4838 // This is target intrinsic that touches memory 4839 AAMDNodes AAInfo; 4840 I.getAAMetadata(AAInfo); 4841 Result = DAG.getMemIntrinsicNode( 4842 Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT, 4843 MachinePointerInfo(Info.ptrVal, Info.offset), 4844 Info.align ? Info.align->value() : 0, Info.flags, Info.size, AAInfo); 4845 } else if (!HasChain) { 4846 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4847 } else if (!I.getType()->isVoidTy()) { 4848 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4849 } else { 4850 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4851 } 4852 4853 if (HasChain) { 4854 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4855 if (OnlyLoad) 4856 PendingLoads.push_back(Chain); 4857 else 4858 DAG.setRoot(Chain); 4859 } 4860 4861 if (!I.getType()->isVoidTy()) { 4862 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4863 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4864 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4865 } else 4866 Result = lowerRangeToAssertZExt(DAG, I, Result); 4867 4868 setValue(&I, Result); 4869 } 4870 } 4871 4872 /// GetSignificand - Get the significand and build it into a floating-point 4873 /// number with exponent of 1: 4874 /// 4875 /// Op = (Op & 0x007fffff) | 0x3f800000; 4876 /// 4877 /// where Op is the hexadecimal representation of floating point value. 4878 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4879 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4880 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4881 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4882 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4883 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4884 } 4885 4886 /// GetExponent - Get the exponent: 4887 /// 4888 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4889 /// 4890 /// where Op is the hexadecimal representation of floating point value. 4891 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4892 const TargetLowering &TLI, const SDLoc &dl) { 4893 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4894 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4895 SDValue t1 = DAG.getNode( 4896 ISD::SRL, dl, MVT::i32, t0, 4897 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4898 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4899 DAG.getConstant(127, dl, MVT::i32)); 4900 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4901 } 4902 4903 /// getF32Constant - Get 32-bit floating point constant. 4904 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4905 const SDLoc &dl) { 4906 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4907 MVT::f32); 4908 } 4909 4910 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4911 SelectionDAG &DAG) { 4912 // TODO: What fast-math-flags should be set on the floating-point nodes? 4913 4914 // IntegerPartOfX = ((int32_t)(t0); 4915 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4916 4917 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4918 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4919 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4920 4921 // IntegerPartOfX <<= 23; 4922 IntegerPartOfX = DAG.getNode( 4923 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4924 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4925 DAG.getDataLayout()))); 4926 4927 SDValue TwoToFractionalPartOfX; 4928 if (LimitFloatPrecision <= 6) { 4929 // For floating-point precision of 6: 4930 // 4931 // TwoToFractionalPartOfX = 4932 // 0.997535578f + 4933 // (0.735607626f + 0.252464424f * x) * x; 4934 // 4935 // error 0.0144103317, which is 6 bits 4936 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4937 getF32Constant(DAG, 0x3e814304, dl)); 4938 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4939 getF32Constant(DAG, 0x3f3c50c8, dl)); 4940 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4941 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4942 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4943 } else if (LimitFloatPrecision <= 12) { 4944 // For floating-point precision of 12: 4945 // 4946 // TwoToFractionalPartOfX = 4947 // 0.999892986f + 4948 // (0.696457318f + 4949 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4950 // 4951 // error 0.000107046256, which is 13 to 14 bits 4952 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4953 getF32Constant(DAG, 0x3da235e3, dl)); 4954 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4955 getF32Constant(DAG, 0x3e65b8f3, dl)); 4956 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4957 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4958 getF32Constant(DAG, 0x3f324b07, dl)); 4959 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4960 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4961 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4962 } else { // LimitFloatPrecision <= 18 4963 // For floating-point precision of 18: 4964 // 4965 // TwoToFractionalPartOfX = 4966 // 0.999999982f + 4967 // (0.693148872f + 4968 // (0.240227044f + 4969 // (0.554906021e-1f + 4970 // (0.961591928e-2f + 4971 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4972 // error 2.47208000*10^(-7), which is better than 18 bits 4973 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4974 getF32Constant(DAG, 0x3924b03e, dl)); 4975 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4976 getF32Constant(DAG, 0x3ab24b87, dl)); 4977 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4978 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4979 getF32Constant(DAG, 0x3c1d8c17, dl)); 4980 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4981 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4982 getF32Constant(DAG, 0x3d634a1d, dl)); 4983 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4984 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4985 getF32Constant(DAG, 0x3e75fe14, dl)); 4986 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4987 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4988 getF32Constant(DAG, 0x3f317234, dl)); 4989 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4990 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4991 getF32Constant(DAG, 0x3f800000, dl)); 4992 } 4993 4994 // Add the exponent into the result in integer domain. 4995 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4996 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4997 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4998 } 4999 5000 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5001 /// limited-precision mode. 5002 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5003 const TargetLowering &TLI) { 5004 if (Op.getValueType() == MVT::f32 && 5005 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5006 5007 // Put the exponent in the right bit position for later addition to the 5008 // final result: 5009 // 5010 // t0 = Op * log2(e) 5011 5012 // TODO: What fast-math-flags should be set here? 5013 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5014 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5015 return getLimitedPrecisionExp2(t0, dl, DAG); 5016 } 5017 5018 // No special expansion. 5019 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op); 5020 } 5021 5022 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5023 /// limited-precision mode. 5024 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5025 const TargetLowering &TLI) { 5026 // TODO: What fast-math-flags should be set on the floating-point nodes? 5027 5028 if (Op.getValueType() == MVT::f32 && 5029 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5030 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5031 5032 // Scale the exponent by log(2). 5033 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5034 SDValue LogOfExponent = 5035 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5036 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5037 5038 // Get the significand and build it into a floating-point number with 5039 // exponent of 1. 5040 SDValue X = GetSignificand(DAG, Op1, dl); 5041 5042 SDValue LogOfMantissa; 5043 if (LimitFloatPrecision <= 6) { 5044 // For floating-point precision of 6: 5045 // 5046 // LogofMantissa = 5047 // -1.1609546f + 5048 // (1.4034025f - 0.23903021f * x) * x; 5049 // 5050 // error 0.0034276066, which is better than 8 bits 5051 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5052 getF32Constant(DAG, 0xbe74c456, dl)); 5053 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5054 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5055 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5056 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5057 getF32Constant(DAG, 0x3f949a29, dl)); 5058 } else if (LimitFloatPrecision <= 12) { 5059 // For floating-point precision of 12: 5060 // 5061 // LogOfMantissa = 5062 // -1.7417939f + 5063 // (2.8212026f + 5064 // (-1.4699568f + 5065 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5066 // 5067 // error 0.000061011436, which is 14 bits 5068 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5069 getF32Constant(DAG, 0xbd67b6d6, dl)); 5070 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5071 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5072 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5073 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5074 getF32Constant(DAG, 0x3fbc278b, dl)); 5075 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5076 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5077 getF32Constant(DAG, 0x40348e95, dl)); 5078 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5079 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5080 getF32Constant(DAG, 0x3fdef31a, dl)); 5081 } else { // LimitFloatPrecision <= 18 5082 // For floating-point precision of 18: 5083 // 5084 // LogOfMantissa = 5085 // -2.1072184f + 5086 // (4.2372794f + 5087 // (-3.7029485f + 5088 // (2.2781945f + 5089 // (-0.87823314f + 5090 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5091 // 5092 // error 0.0000023660568, which is better than 18 bits 5093 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5094 getF32Constant(DAG, 0xbc91e5ac, dl)); 5095 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5096 getF32Constant(DAG, 0x3e4350aa, dl)); 5097 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5098 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5099 getF32Constant(DAG, 0x3f60d3e3, dl)); 5100 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5101 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5102 getF32Constant(DAG, 0x4011cdf0, dl)); 5103 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5104 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5105 getF32Constant(DAG, 0x406cfd1c, dl)); 5106 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5107 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5108 getF32Constant(DAG, 0x408797cb, dl)); 5109 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5110 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5111 getF32Constant(DAG, 0x4006dcab, dl)); 5112 } 5113 5114 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5115 } 5116 5117 // No special expansion. 5118 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op); 5119 } 5120 5121 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5122 /// limited-precision mode. 5123 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5124 const TargetLowering &TLI) { 5125 // TODO: What fast-math-flags should be set on the floating-point nodes? 5126 5127 if (Op.getValueType() == MVT::f32 && 5128 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5129 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5130 5131 // Get the exponent. 5132 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5133 5134 // Get the significand and build it into a floating-point number with 5135 // exponent of 1. 5136 SDValue X = GetSignificand(DAG, Op1, dl); 5137 5138 // Different possible minimax approximations of significand in 5139 // floating-point for various degrees of accuracy over [1,2]. 5140 SDValue Log2ofMantissa; 5141 if (LimitFloatPrecision <= 6) { 5142 // For floating-point precision of 6: 5143 // 5144 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5145 // 5146 // error 0.0049451742, which is more than 7 bits 5147 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5148 getF32Constant(DAG, 0xbeb08fe0, dl)); 5149 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5150 getF32Constant(DAG, 0x40019463, dl)); 5151 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5152 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5153 getF32Constant(DAG, 0x3fd6633d, dl)); 5154 } else if (LimitFloatPrecision <= 12) { 5155 // For floating-point precision of 12: 5156 // 5157 // Log2ofMantissa = 5158 // -2.51285454f + 5159 // (4.07009056f + 5160 // (-2.12067489f + 5161 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5162 // 5163 // error 0.0000876136000, which is better than 13 bits 5164 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5165 getF32Constant(DAG, 0xbda7262e, dl)); 5166 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5167 getF32Constant(DAG, 0x3f25280b, dl)); 5168 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5169 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5170 getF32Constant(DAG, 0x4007b923, dl)); 5171 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5172 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5173 getF32Constant(DAG, 0x40823e2f, dl)); 5174 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5175 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5176 getF32Constant(DAG, 0x4020d29c, dl)); 5177 } else { // LimitFloatPrecision <= 18 5178 // For floating-point precision of 18: 5179 // 5180 // Log2ofMantissa = 5181 // -3.0400495f + 5182 // (6.1129976f + 5183 // (-5.3420409f + 5184 // (3.2865683f + 5185 // (-1.2669343f + 5186 // (0.27515199f - 5187 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5188 // 5189 // error 0.0000018516, which is better than 18 bits 5190 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5191 getF32Constant(DAG, 0xbcd2769e, dl)); 5192 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5193 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5194 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5195 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5196 getF32Constant(DAG, 0x3fa22ae7, dl)); 5197 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5198 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5199 getF32Constant(DAG, 0x40525723, dl)); 5200 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5201 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5202 getF32Constant(DAG, 0x40aaf200, dl)); 5203 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5204 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5205 getF32Constant(DAG, 0x40c39dad, dl)); 5206 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5207 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5208 getF32Constant(DAG, 0x4042902c, dl)); 5209 } 5210 5211 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5212 } 5213 5214 // No special expansion. 5215 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op); 5216 } 5217 5218 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5219 /// limited-precision mode. 5220 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5221 const TargetLowering &TLI) { 5222 // TODO: What fast-math-flags should be set on the floating-point nodes? 5223 5224 if (Op.getValueType() == MVT::f32 && 5225 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5226 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5227 5228 // Scale the exponent by log10(2) [0.30102999f]. 5229 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5230 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5231 getF32Constant(DAG, 0x3e9a209a, dl)); 5232 5233 // Get the significand and build it into a floating-point number with 5234 // exponent of 1. 5235 SDValue X = GetSignificand(DAG, Op1, dl); 5236 5237 SDValue Log10ofMantissa; 5238 if (LimitFloatPrecision <= 6) { 5239 // For floating-point precision of 6: 5240 // 5241 // Log10ofMantissa = 5242 // -0.50419619f + 5243 // (0.60948995f - 0.10380950f * x) * x; 5244 // 5245 // error 0.0014886165, which is 6 bits 5246 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5247 getF32Constant(DAG, 0xbdd49a13, dl)); 5248 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5249 getF32Constant(DAG, 0x3f1c0789, dl)); 5250 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5251 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5252 getF32Constant(DAG, 0x3f011300, dl)); 5253 } else if (LimitFloatPrecision <= 12) { 5254 // For floating-point precision of 12: 5255 // 5256 // Log10ofMantissa = 5257 // -0.64831180f + 5258 // (0.91751397f + 5259 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5260 // 5261 // error 0.00019228036, which is better than 12 bits 5262 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5263 getF32Constant(DAG, 0x3d431f31, dl)); 5264 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5265 getF32Constant(DAG, 0x3ea21fb2, dl)); 5266 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5267 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5268 getF32Constant(DAG, 0x3f6ae232, dl)); 5269 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5270 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5271 getF32Constant(DAG, 0x3f25f7c3, dl)); 5272 } else { // LimitFloatPrecision <= 18 5273 // For floating-point precision of 18: 5274 // 5275 // Log10ofMantissa = 5276 // -0.84299375f + 5277 // (1.5327582f + 5278 // (-1.0688956f + 5279 // (0.49102474f + 5280 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5281 // 5282 // error 0.0000037995730, which is better than 18 bits 5283 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5284 getF32Constant(DAG, 0x3c5d51ce, dl)); 5285 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5286 getF32Constant(DAG, 0x3e00685a, dl)); 5287 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5288 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5289 getF32Constant(DAG, 0x3efb6798, dl)); 5290 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5291 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5292 getF32Constant(DAG, 0x3f88d192, dl)); 5293 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5294 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5295 getF32Constant(DAG, 0x3fc4316c, dl)); 5296 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5297 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5298 getF32Constant(DAG, 0x3f57ce70, dl)); 5299 } 5300 5301 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5302 } 5303 5304 // No special expansion. 5305 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op); 5306 } 5307 5308 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5309 /// limited-precision mode. 5310 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5311 const TargetLowering &TLI) { 5312 if (Op.getValueType() == MVT::f32 && 5313 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5314 return getLimitedPrecisionExp2(Op, dl, DAG); 5315 5316 // No special expansion. 5317 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op); 5318 } 5319 5320 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5321 /// limited-precision mode with x == 10.0f. 5322 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5323 SelectionDAG &DAG, const TargetLowering &TLI) { 5324 bool IsExp10 = false; 5325 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5326 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5327 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5328 APFloat Ten(10.0f); 5329 IsExp10 = LHSC->isExactlyValue(Ten); 5330 } 5331 } 5332 5333 // TODO: What fast-math-flags should be set on the FMUL node? 5334 if (IsExp10) { 5335 // Put the exponent in the right bit position for later addition to the 5336 // final result: 5337 // 5338 // #define LOG2OF10 3.3219281f 5339 // t0 = Op * LOG2OF10; 5340 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5341 getF32Constant(DAG, 0x40549a78, dl)); 5342 return getLimitedPrecisionExp2(t0, dl, DAG); 5343 } 5344 5345 // No special expansion. 5346 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS); 5347 } 5348 5349 /// ExpandPowI - Expand a llvm.powi intrinsic. 5350 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5351 SelectionDAG &DAG) { 5352 // If RHS is a constant, we can expand this out to a multiplication tree, 5353 // otherwise we end up lowering to a call to __powidf2 (for example). When 5354 // optimizing for size, we only want to do this if the expansion would produce 5355 // a small number of multiplies, otherwise we do the full expansion. 5356 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5357 // Get the exponent as a positive value. 5358 unsigned Val = RHSC->getSExtValue(); 5359 if ((int)Val < 0) Val = -Val; 5360 5361 // powi(x, 0) -> 1.0 5362 if (Val == 0) 5363 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5364 5365 bool OptForSize = DAG.shouldOptForSize(); 5366 if (!OptForSize || 5367 // If optimizing for size, don't insert too many multiplies. 5368 // This inserts up to 5 multiplies. 5369 countPopulation(Val) + Log2_32(Val) < 7) { 5370 // We use the simple binary decomposition method to generate the multiply 5371 // sequence. There are more optimal ways to do this (for example, 5372 // powi(x,15) generates one more multiply than it should), but this has 5373 // the benefit of being both really simple and much better than a libcall. 5374 SDValue Res; // Logically starts equal to 1.0 5375 SDValue CurSquare = LHS; 5376 // TODO: Intrinsics should have fast-math-flags that propagate to these 5377 // nodes. 5378 while (Val) { 5379 if (Val & 1) { 5380 if (Res.getNode()) 5381 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 5382 else 5383 Res = CurSquare; // 1.0*CurSquare. 5384 } 5385 5386 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5387 CurSquare, CurSquare); 5388 Val >>= 1; 5389 } 5390 5391 // If the original was negative, invert the result, producing 1/(x*x*x). 5392 if (RHSC->getSExtValue() < 0) 5393 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5394 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5395 return Res; 5396 } 5397 } 5398 5399 // Otherwise, expand to a libcall. 5400 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5401 } 5402 5403 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5404 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5405 static void 5406 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs, 5407 const SDValue &N) { 5408 switch (N.getOpcode()) { 5409 case ISD::CopyFromReg: { 5410 SDValue Op = N.getOperand(1); 5411 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5412 Op.getValueType().getSizeInBits()); 5413 return; 5414 } 5415 case ISD::BITCAST: 5416 case ISD::AssertZext: 5417 case ISD::AssertSext: 5418 case ISD::TRUNCATE: 5419 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5420 return; 5421 case ISD::BUILD_PAIR: 5422 case ISD::BUILD_VECTOR: 5423 case ISD::CONCAT_VECTORS: 5424 for (SDValue Op : N->op_values()) 5425 getUnderlyingArgRegs(Regs, Op); 5426 return; 5427 default: 5428 return; 5429 } 5430 } 5431 5432 /// If the DbgValueInst is a dbg_value of a function argument, create the 5433 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5434 /// instruction selection, they will be inserted to the entry BB. 5435 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5436 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5437 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 5438 const Argument *Arg = dyn_cast<Argument>(V); 5439 if (!Arg) 5440 return false; 5441 5442 if (!IsDbgDeclare) { 5443 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5444 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5445 // the entry block. 5446 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5447 if (!IsInEntryBlock) 5448 return false; 5449 5450 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5451 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5452 // variable that also is a param. 5453 // 5454 // Although, if we are at the top of the entry block already, we can still 5455 // emit using ArgDbgValue. This might catch some situations when the 5456 // dbg.value refers to an argument that isn't used in the entry block, so 5457 // any CopyToReg node would be optimized out and the only way to express 5458 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5459 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5460 // we should only emit as ArgDbgValue if the Variable is an argument to the 5461 // current function, and the dbg.value intrinsic is found in the entry 5462 // block. 5463 bool VariableIsFunctionInputArg = Variable->isParameter() && 5464 !DL->getInlinedAt(); 5465 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5466 if (!IsInPrologue && !VariableIsFunctionInputArg) 5467 return false; 5468 5469 // Here we assume that a function argument on IR level only can be used to 5470 // describe one input parameter on source level. If we for example have 5471 // source code like this 5472 // 5473 // struct A { long x, y; }; 5474 // void foo(struct A a, long b) { 5475 // ... 5476 // b = a.x; 5477 // ... 5478 // } 5479 // 5480 // and IR like this 5481 // 5482 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5483 // entry: 5484 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5485 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5486 // call void @llvm.dbg.value(metadata i32 %b, "b", 5487 // ... 5488 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5489 // ... 5490 // 5491 // then the last dbg.value is describing a parameter "b" using a value that 5492 // is an argument. But since we already has used %a1 to describe a parameter 5493 // we should not handle that last dbg.value here (that would result in an 5494 // incorrect hoisting of the DBG_VALUE to the function entry). 5495 // Notice that we allow one dbg.value per IR level argument, to accommodate 5496 // for the situation with fragments above. 5497 if (VariableIsFunctionInputArg) { 5498 unsigned ArgNo = Arg->getArgNo(); 5499 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5500 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5501 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5502 return false; 5503 FuncInfo.DescribedArgs.set(ArgNo); 5504 } 5505 } 5506 5507 MachineFunction &MF = DAG.getMachineFunction(); 5508 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5509 5510 Optional<MachineOperand> Op; 5511 // Some arguments' frame index is recorded during argument lowering. 5512 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5513 if (FI != std::numeric_limits<int>::max()) 5514 Op = MachineOperand::CreateFI(FI); 5515 5516 SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes; 5517 if (!Op && N.getNode()) { 5518 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5519 Register Reg; 5520 if (ArgRegsAndSizes.size() == 1) 5521 Reg = ArgRegsAndSizes.front().first; 5522 5523 if (Reg && Reg.isVirtual()) { 5524 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5525 Register PR = RegInfo.getLiveInPhysReg(Reg); 5526 if (PR) 5527 Reg = PR; 5528 } 5529 if (Reg) { 5530 Op = MachineOperand::CreateReg(Reg, false); 5531 } 5532 } 5533 5534 if (!Op && N.getNode()) { 5535 // Check if frame index is available. 5536 SDValue LCandidate = peekThroughBitcasts(N); 5537 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5538 if (FrameIndexSDNode *FINode = 5539 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5540 Op = MachineOperand::CreateFI(FINode->getIndex()); 5541 } 5542 5543 if (!Op) { 5544 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5545 auto splitMultiRegDbgValue 5546 = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) { 5547 unsigned Offset = 0; 5548 for (auto RegAndSize : SplitRegs) { 5549 auto FragmentExpr = DIExpression::createFragmentExpression( 5550 Expr, Offset, RegAndSize.second); 5551 if (!FragmentExpr) 5552 continue; 5553 assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?"); 5554 FuncInfo.ArgDbgValues.push_back( 5555 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), false, 5556 RegAndSize.first, Variable, *FragmentExpr)); 5557 Offset += RegAndSize.second; 5558 } 5559 }; 5560 5561 // Check if ValueMap has reg number. 5562 DenseMap<const Value *, unsigned>::const_iterator 5563 VMI = FuncInfo.ValueMap.find(V); 5564 if (VMI != FuncInfo.ValueMap.end()) { 5565 const auto &TLI = DAG.getTargetLoweringInfo(); 5566 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5567 V->getType(), getABIRegCopyCC(V)); 5568 if (RFV.occupiesMultipleRegs()) { 5569 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5570 return true; 5571 } 5572 5573 Op = MachineOperand::CreateReg(VMI->second, false); 5574 } else if (ArgRegsAndSizes.size() > 1) { 5575 // This was split due to the calling convention, and no virtual register 5576 // mapping exists for the value. 5577 splitMultiRegDbgValue(ArgRegsAndSizes); 5578 return true; 5579 } 5580 } 5581 5582 if (!Op) 5583 return false; 5584 5585 assert(Variable->isValidLocationForIntrinsic(DL) && 5586 "Expected inlined-at fields to agree"); 5587 5588 // If the argument arrives in a stack slot, then what the IR thought was a 5589 // normal Value is actually in memory, and we must add a deref to load it. 5590 if (Op->isFI()) { 5591 int FI = Op->getIndex(); 5592 unsigned Size = DAG.getMachineFunction().getFrameInfo().getObjectSize(FI); 5593 if (Expr->isImplicit()) { 5594 SmallVector<uint64_t, 2> Ops = {dwarf::DW_OP_deref_size, Size}; 5595 Expr = DIExpression::prependOpcodes(Expr, Ops); 5596 } else { 5597 Expr = DIExpression::prepend(Expr, DIExpression::DerefBefore); 5598 } 5599 } 5600 5601 // If this location was specified with a dbg.declare, then it and its 5602 // expression calculate the address of the variable. Append a deref to 5603 // force it to be a memory location. 5604 if (IsDbgDeclare) 5605 Expr = DIExpression::append(Expr, {dwarf::DW_OP_deref}); 5606 5607 FuncInfo.ArgDbgValues.push_back( 5608 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), false, 5609 *Op, Variable, Expr)); 5610 5611 return true; 5612 } 5613 5614 /// Return the appropriate SDDbgValue based on N. 5615 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5616 DILocalVariable *Variable, 5617 DIExpression *Expr, 5618 const DebugLoc &dl, 5619 unsigned DbgSDNodeOrder) { 5620 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5621 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5622 // stack slot locations. 5623 // 5624 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5625 // debug values here after optimization: 5626 // 5627 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5628 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5629 // 5630 // Both describe the direct values of their associated variables. 5631 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5632 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5633 } 5634 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5635 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5636 } 5637 5638 // VisualStudio defines setjmp as _setjmp 5639 #if defined(_MSC_VER) && defined(setjmp) && \ 5640 !defined(setjmp_undefined_for_msvc) 5641 # pragma push_macro("setjmp") 5642 # undef setjmp 5643 # define setjmp_undefined_for_msvc 5644 #endif 5645 5646 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5647 switch (Intrinsic) { 5648 case Intrinsic::smul_fix: 5649 return ISD::SMULFIX; 5650 case Intrinsic::umul_fix: 5651 return ISD::UMULFIX; 5652 default: 5653 llvm_unreachable("Unhandled fixed point intrinsic"); 5654 } 5655 } 5656 5657 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5658 const char *FunctionName) { 5659 assert(FunctionName && "FunctionName must not be nullptr"); 5660 SDValue Callee = DAG.getExternalSymbol( 5661 FunctionName, 5662 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5663 LowerCallTo(&I, Callee, I.isTailCall()); 5664 } 5665 5666 /// Lower the call to the specified intrinsic function. 5667 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5668 unsigned Intrinsic) { 5669 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5670 SDLoc sdl = getCurSDLoc(); 5671 DebugLoc dl = getCurDebugLoc(); 5672 SDValue Res; 5673 5674 switch (Intrinsic) { 5675 default: 5676 // By default, turn this into a target intrinsic node. 5677 visitTargetIntrinsic(I, Intrinsic); 5678 return; 5679 case Intrinsic::vastart: visitVAStart(I); return; 5680 case Intrinsic::vaend: visitVAEnd(I); return; 5681 case Intrinsic::vacopy: visitVACopy(I); return; 5682 case Intrinsic::returnaddress: 5683 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5684 TLI.getPointerTy(DAG.getDataLayout()), 5685 getValue(I.getArgOperand(0)))); 5686 return; 5687 case Intrinsic::addressofreturnaddress: 5688 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5689 TLI.getPointerTy(DAG.getDataLayout()))); 5690 return; 5691 case Intrinsic::sponentry: 5692 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5693 TLI.getFrameIndexTy(DAG.getDataLayout()))); 5694 return; 5695 case Intrinsic::frameaddress: 5696 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5697 TLI.getFrameIndexTy(DAG.getDataLayout()), 5698 getValue(I.getArgOperand(0)))); 5699 return; 5700 case Intrinsic::read_register: { 5701 Value *Reg = I.getArgOperand(0); 5702 SDValue Chain = getRoot(); 5703 SDValue RegName = 5704 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5705 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5706 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5707 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5708 setValue(&I, Res); 5709 DAG.setRoot(Res.getValue(1)); 5710 return; 5711 } 5712 case Intrinsic::write_register: { 5713 Value *Reg = I.getArgOperand(0); 5714 Value *RegValue = I.getArgOperand(1); 5715 SDValue Chain = getRoot(); 5716 SDValue RegName = 5717 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5718 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5719 RegName, getValue(RegValue))); 5720 return; 5721 } 5722 case Intrinsic::setjmp: 5723 lowerCallToExternalSymbol(I, &"_setjmp"[!TLI.usesUnderscoreSetJmp()]); 5724 return; 5725 case Intrinsic::longjmp: 5726 lowerCallToExternalSymbol(I, &"_longjmp"[!TLI.usesUnderscoreLongJmp()]); 5727 return; 5728 case Intrinsic::memcpy: { 5729 const auto &MCI = cast<MemCpyInst>(I); 5730 SDValue Op1 = getValue(I.getArgOperand(0)); 5731 SDValue Op2 = getValue(I.getArgOperand(1)); 5732 SDValue Op3 = getValue(I.getArgOperand(2)); 5733 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5734 unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1); 5735 unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1); 5736 unsigned Align = MinAlign(DstAlign, SrcAlign); 5737 bool isVol = MCI.isVolatile(); 5738 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5739 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5740 // node. 5741 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5742 false, isTC, 5743 MachinePointerInfo(I.getArgOperand(0)), 5744 MachinePointerInfo(I.getArgOperand(1))); 5745 updateDAGForMaybeTailCall(MC); 5746 return; 5747 } 5748 case Intrinsic::memset: { 5749 const auto &MSI = cast<MemSetInst>(I); 5750 SDValue Op1 = getValue(I.getArgOperand(0)); 5751 SDValue Op2 = getValue(I.getArgOperand(1)); 5752 SDValue Op3 = getValue(I.getArgOperand(2)); 5753 // @llvm.memset defines 0 and 1 to both mean no alignment. 5754 unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1); 5755 bool isVol = MSI.isVolatile(); 5756 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5757 SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5758 isTC, MachinePointerInfo(I.getArgOperand(0))); 5759 updateDAGForMaybeTailCall(MS); 5760 return; 5761 } 5762 case Intrinsic::memmove: { 5763 const auto &MMI = cast<MemMoveInst>(I); 5764 SDValue Op1 = getValue(I.getArgOperand(0)); 5765 SDValue Op2 = getValue(I.getArgOperand(1)); 5766 SDValue Op3 = getValue(I.getArgOperand(2)); 5767 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5768 unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1); 5769 unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1); 5770 unsigned Align = MinAlign(DstAlign, SrcAlign); 5771 bool isVol = MMI.isVolatile(); 5772 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5773 // FIXME: Support passing different dest/src alignments to the memmove DAG 5774 // node. 5775 SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5776 isTC, MachinePointerInfo(I.getArgOperand(0)), 5777 MachinePointerInfo(I.getArgOperand(1))); 5778 updateDAGForMaybeTailCall(MM); 5779 return; 5780 } 5781 case Intrinsic::memcpy_element_unordered_atomic: { 5782 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5783 SDValue Dst = getValue(MI.getRawDest()); 5784 SDValue Src = getValue(MI.getRawSource()); 5785 SDValue Length = getValue(MI.getLength()); 5786 5787 unsigned DstAlign = MI.getDestAlignment(); 5788 unsigned SrcAlign = MI.getSourceAlignment(); 5789 Type *LengthTy = MI.getLength()->getType(); 5790 unsigned ElemSz = MI.getElementSizeInBytes(); 5791 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5792 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5793 SrcAlign, Length, LengthTy, ElemSz, isTC, 5794 MachinePointerInfo(MI.getRawDest()), 5795 MachinePointerInfo(MI.getRawSource())); 5796 updateDAGForMaybeTailCall(MC); 5797 return; 5798 } 5799 case Intrinsic::memmove_element_unordered_atomic: { 5800 auto &MI = cast<AtomicMemMoveInst>(I); 5801 SDValue Dst = getValue(MI.getRawDest()); 5802 SDValue Src = getValue(MI.getRawSource()); 5803 SDValue Length = getValue(MI.getLength()); 5804 5805 unsigned DstAlign = MI.getDestAlignment(); 5806 unsigned SrcAlign = MI.getSourceAlignment(); 5807 Type *LengthTy = MI.getLength()->getType(); 5808 unsigned ElemSz = MI.getElementSizeInBytes(); 5809 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5810 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5811 SrcAlign, Length, LengthTy, ElemSz, isTC, 5812 MachinePointerInfo(MI.getRawDest()), 5813 MachinePointerInfo(MI.getRawSource())); 5814 updateDAGForMaybeTailCall(MC); 5815 return; 5816 } 5817 case Intrinsic::memset_element_unordered_atomic: { 5818 auto &MI = cast<AtomicMemSetInst>(I); 5819 SDValue Dst = getValue(MI.getRawDest()); 5820 SDValue Val = getValue(MI.getValue()); 5821 SDValue Length = getValue(MI.getLength()); 5822 5823 unsigned DstAlign = MI.getDestAlignment(); 5824 Type *LengthTy = MI.getLength()->getType(); 5825 unsigned ElemSz = MI.getElementSizeInBytes(); 5826 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5827 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5828 LengthTy, ElemSz, isTC, 5829 MachinePointerInfo(MI.getRawDest())); 5830 updateDAGForMaybeTailCall(MC); 5831 return; 5832 } 5833 case Intrinsic::dbg_addr: 5834 case Intrinsic::dbg_declare: { 5835 const auto &DI = cast<DbgVariableIntrinsic>(I); 5836 DILocalVariable *Variable = DI.getVariable(); 5837 DIExpression *Expression = DI.getExpression(); 5838 dropDanglingDebugInfo(Variable, Expression); 5839 assert(Variable && "Missing variable"); 5840 5841 // Check if address has undef value. 5842 const Value *Address = DI.getVariableLocation(); 5843 if (!Address || isa<UndefValue>(Address) || 5844 (Address->use_empty() && !isa<Argument>(Address))) { 5845 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5846 return; 5847 } 5848 5849 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5850 5851 // Check if this variable can be described by a frame index, typically 5852 // either as a static alloca or a byval parameter. 5853 int FI = std::numeric_limits<int>::max(); 5854 if (const auto *AI = 5855 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5856 if (AI->isStaticAlloca()) { 5857 auto I = FuncInfo.StaticAllocaMap.find(AI); 5858 if (I != FuncInfo.StaticAllocaMap.end()) 5859 FI = I->second; 5860 } 5861 } else if (const auto *Arg = dyn_cast<Argument>( 5862 Address->stripInBoundsConstantOffsets())) { 5863 FI = FuncInfo.getArgumentFrameIndex(Arg); 5864 } 5865 5866 // llvm.dbg.addr is control dependent and always generates indirect 5867 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5868 // the MachineFunction variable table. 5869 if (FI != std::numeric_limits<int>::max()) { 5870 if (Intrinsic == Intrinsic::dbg_addr) { 5871 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 5872 Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder); 5873 DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter); 5874 } 5875 return; 5876 } 5877 5878 SDValue &N = NodeMap[Address]; 5879 if (!N.getNode() && isa<Argument>(Address)) 5880 // Check unused arguments map. 5881 N = UnusedArgNodeMap[Address]; 5882 SDDbgValue *SDV; 5883 if (N.getNode()) { 5884 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 5885 Address = BCI->getOperand(0); 5886 // Parameters are handled specially. 5887 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 5888 if (isParameter && FINode) { 5889 // Byval parameter. We have a frame index at this point. 5890 SDV = 5891 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 5892 /*IsIndirect*/ true, dl, SDNodeOrder); 5893 } else if (isa<Argument>(Address)) { 5894 // Address is an argument, so try to emit its dbg value using 5895 // virtual register info from the FuncInfo.ValueMap. 5896 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 5897 return; 5898 } else { 5899 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 5900 true, dl, SDNodeOrder); 5901 } 5902 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 5903 } else { 5904 // If Address is an argument then try to emit its dbg value using 5905 // virtual register info from the FuncInfo.ValueMap. 5906 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 5907 N)) { 5908 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5909 } 5910 } 5911 return; 5912 } 5913 case Intrinsic::dbg_label: { 5914 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 5915 DILabel *Label = DI.getLabel(); 5916 assert(Label && "Missing label"); 5917 5918 SDDbgLabel *SDV; 5919 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 5920 DAG.AddDbgLabel(SDV); 5921 return; 5922 } 5923 case Intrinsic::dbg_value: { 5924 const DbgValueInst &DI = cast<DbgValueInst>(I); 5925 assert(DI.getVariable() && "Missing variable"); 5926 5927 DILocalVariable *Variable = DI.getVariable(); 5928 DIExpression *Expression = DI.getExpression(); 5929 dropDanglingDebugInfo(Variable, Expression); 5930 const Value *V = DI.getValue(); 5931 if (!V) 5932 return; 5933 5934 if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(), 5935 SDNodeOrder)) 5936 return; 5937 5938 // TODO: Dangling debug info will eventually either be resolved or produce 5939 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 5940 // between the original dbg.value location and its resolved DBG_VALUE, which 5941 // we should ideally fill with an extra Undef DBG_VALUE. 5942 5943 DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder); 5944 return; 5945 } 5946 5947 case Intrinsic::eh_typeid_for: { 5948 // Find the type id for the given typeinfo. 5949 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 5950 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 5951 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 5952 setValue(&I, Res); 5953 return; 5954 } 5955 5956 case Intrinsic::eh_return_i32: 5957 case Intrinsic::eh_return_i64: 5958 DAG.getMachineFunction().setCallsEHReturn(true); 5959 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 5960 MVT::Other, 5961 getControlRoot(), 5962 getValue(I.getArgOperand(0)), 5963 getValue(I.getArgOperand(1)))); 5964 return; 5965 case Intrinsic::eh_unwind_init: 5966 DAG.getMachineFunction().setCallsUnwindInit(true); 5967 return; 5968 case Intrinsic::eh_dwarf_cfa: 5969 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 5970 TLI.getPointerTy(DAG.getDataLayout()), 5971 getValue(I.getArgOperand(0)))); 5972 return; 5973 case Intrinsic::eh_sjlj_callsite: { 5974 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5975 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 5976 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 5977 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 5978 5979 MMI.setCurrentCallSite(CI->getZExtValue()); 5980 return; 5981 } 5982 case Intrinsic::eh_sjlj_functioncontext: { 5983 // Get and store the index of the function context. 5984 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5985 AllocaInst *FnCtx = 5986 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 5987 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 5988 MFI.setFunctionContextIndex(FI); 5989 return; 5990 } 5991 case Intrinsic::eh_sjlj_setjmp: { 5992 SDValue Ops[2]; 5993 Ops[0] = getRoot(); 5994 Ops[1] = getValue(I.getArgOperand(0)); 5995 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 5996 DAG.getVTList(MVT::i32, MVT::Other), Ops); 5997 setValue(&I, Op.getValue(0)); 5998 DAG.setRoot(Op.getValue(1)); 5999 return; 6000 } 6001 case Intrinsic::eh_sjlj_longjmp: 6002 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6003 getRoot(), getValue(I.getArgOperand(0)))); 6004 return; 6005 case Intrinsic::eh_sjlj_setup_dispatch: 6006 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6007 getRoot())); 6008 return; 6009 case Intrinsic::masked_gather: 6010 visitMaskedGather(I); 6011 return; 6012 case Intrinsic::masked_load: 6013 visitMaskedLoad(I); 6014 return; 6015 case Intrinsic::masked_scatter: 6016 visitMaskedScatter(I); 6017 return; 6018 case Intrinsic::masked_store: 6019 visitMaskedStore(I); 6020 return; 6021 case Intrinsic::masked_expandload: 6022 visitMaskedLoad(I, true /* IsExpanding */); 6023 return; 6024 case Intrinsic::masked_compressstore: 6025 visitMaskedStore(I, true /* IsCompressing */); 6026 return; 6027 case Intrinsic::powi: 6028 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6029 getValue(I.getArgOperand(1)), DAG)); 6030 return; 6031 case Intrinsic::log: 6032 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6033 return; 6034 case Intrinsic::log2: 6035 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6036 return; 6037 case Intrinsic::log10: 6038 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6039 return; 6040 case Intrinsic::exp: 6041 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6042 return; 6043 case Intrinsic::exp2: 6044 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6045 return; 6046 case Intrinsic::pow: 6047 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6048 getValue(I.getArgOperand(1)), DAG, TLI)); 6049 return; 6050 case Intrinsic::sqrt: 6051 case Intrinsic::fabs: 6052 case Intrinsic::sin: 6053 case Intrinsic::cos: 6054 case Intrinsic::floor: 6055 case Intrinsic::ceil: 6056 case Intrinsic::trunc: 6057 case Intrinsic::rint: 6058 case Intrinsic::nearbyint: 6059 case Intrinsic::round: 6060 case Intrinsic::canonicalize: { 6061 unsigned Opcode; 6062 switch (Intrinsic) { 6063 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6064 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6065 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6066 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6067 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6068 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6069 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6070 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6071 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6072 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6073 case Intrinsic::round: Opcode = ISD::FROUND; break; 6074 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6075 } 6076 6077 setValue(&I, DAG.getNode(Opcode, sdl, 6078 getValue(I.getArgOperand(0)).getValueType(), 6079 getValue(I.getArgOperand(0)))); 6080 return; 6081 } 6082 case Intrinsic::lround: 6083 case Intrinsic::llround: 6084 case Intrinsic::lrint: 6085 case Intrinsic::llrint: { 6086 unsigned Opcode; 6087 switch (Intrinsic) { 6088 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6089 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6090 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6091 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6092 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6093 } 6094 6095 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6096 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6097 getValue(I.getArgOperand(0)))); 6098 return; 6099 } 6100 case Intrinsic::minnum: 6101 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6102 getValue(I.getArgOperand(0)).getValueType(), 6103 getValue(I.getArgOperand(0)), 6104 getValue(I.getArgOperand(1)))); 6105 return; 6106 case Intrinsic::maxnum: 6107 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6108 getValue(I.getArgOperand(0)).getValueType(), 6109 getValue(I.getArgOperand(0)), 6110 getValue(I.getArgOperand(1)))); 6111 return; 6112 case Intrinsic::minimum: 6113 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6114 getValue(I.getArgOperand(0)).getValueType(), 6115 getValue(I.getArgOperand(0)), 6116 getValue(I.getArgOperand(1)))); 6117 return; 6118 case Intrinsic::maximum: 6119 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6120 getValue(I.getArgOperand(0)).getValueType(), 6121 getValue(I.getArgOperand(0)), 6122 getValue(I.getArgOperand(1)))); 6123 return; 6124 case Intrinsic::copysign: 6125 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6126 getValue(I.getArgOperand(0)).getValueType(), 6127 getValue(I.getArgOperand(0)), 6128 getValue(I.getArgOperand(1)))); 6129 return; 6130 case Intrinsic::fma: 6131 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6132 getValue(I.getArgOperand(0)).getValueType(), 6133 getValue(I.getArgOperand(0)), 6134 getValue(I.getArgOperand(1)), 6135 getValue(I.getArgOperand(2)))); 6136 return; 6137 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 6138 case Intrinsic::INTRINSIC: 6139 #include "llvm/IR/ConstrainedOps.def" 6140 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6141 return; 6142 case Intrinsic::fmuladd: { 6143 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6144 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6145 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6146 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6147 getValue(I.getArgOperand(0)).getValueType(), 6148 getValue(I.getArgOperand(0)), 6149 getValue(I.getArgOperand(1)), 6150 getValue(I.getArgOperand(2)))); 6151 } else { 6152 // TODO: Intrinsic calls should have fast-math-flags. 6153 SDValue Mul = DAG.getNode(ISD::FMUL, sdl, 6154 getValue(I.getArgOperand(0)).getValueType(), 6155 getValue(I.getArgOperand(0)), 6156 getValue(I.getArgOperand(1))); 6157 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6158 getValue(I.getArgOperand(0)).getValueType(), 6159 Mul, 6160 getValue(I.getArgOperand(2))); 6161 setValue(&I, Add); 6162 } 6163 return; 6164 } 6165 case Intrinsic::convert_to_fp16: 6166 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6167 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6168 getValue(I.getArgOperand(0)), 6169 DAG.getTargetConstant(0, sdl, 6170 MVT::i32)))); 6171 return; 6172 case Intrinsic::convert_from_fp16: 6173 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6174 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6175 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6176 getValue(I.getArgOperand(0))))); 6177 return; 6178 case Intrinsic::pcmarker: { 6179 SDValue Tmp = getValue(I.getArgOperand(0)); 6180 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6181 return; 6182 } 6183 case Intrinsic::readcyclecounter: { 6184 SDValue Op = getRoot(); 6185 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6186 DAG.getVTList(MVT::i64, MVT::Other), Op); 6187 setValue(&I, Res); 6188 DAG.setRoot(Res.getValue(1)); 6189 return; 6190 } 6191 case Intrinsic::bitreverse: 6192 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6193 getValue(I.getArgOperand(0)).getValueType(), 6194 getValue(I.getArgOperand(0)))); 6195 return; 6196 case Intrinsic::bswap: 6197 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6198 getValue(I.getArgOperand(0)).getValueType(), 6199 getValue(I.getArgOperand(0)))); 6200 return; 6201 case Intrinsic::cttz: { 6202 SDValue Arg = getValue(I.getArgOperand(0)); 6203 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6204 EVT Ty = Arg.getValueType(); 6205 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6206 sdl, Ty, Arg)); 6207 return; 6208 } 6209 case Intrinsic::ctlz: { 6210 SDValue Arg = getValue(I.getArgOperand(0)); 6211 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6212 EVT Ty = Arg.getValueType(); 6213 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6214 sdl, Ty, Arg)); 6215 return; 6216 } 6217 case Intrinsic::ctpop: { 6218 SDValue Arg = getValue(I.getArgOperand(0)); 6219 EVT Ty = Arg.getValueType(); 6220 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6221 return; 6222 } 6223 case Intrinsic::fshl: 6224 case Intrinsic::fshr: { 6225 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6226 SDValue X = getValue(I.getArgOperand(0)); 6227 SDValue Y = getValue(I.getArgOperand(1)); 6228 SDValue Z = getValue(I.getArgOperand(2)); 6229 EVT VT = X.getValueType(); 6230 SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT); 6231 SDValue Zero = DAG.getConstant(0, sdl, VT); 6232 SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC); 6233 6234 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6235 if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) { 6236 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6237 return; 6238 } 6239 6240 // When X == Y, this is rotate. If the data type has a power-of-2 size, we 6241 // avoid the select that is necessary in the general case to filter out 6242 // the 0-shift possibility that leads to UB. 6243 if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) { 6244 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6245 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 6246 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6247 return; 6248 } 6249 6250 // Some targets only rotate one way. Try the opposite direction. 6251 RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL; 6252 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 6253 // Negate the shift amount because it is safe to ignore the high bits. 6254 SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 6255 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt)); 6256 return; 6257 } 6258 6259 // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW)) 6260 // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW)) 6261 SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 6262 SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC); 6263 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt); 6264 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt); 6265 setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY)); 6266 return; 6267 } 6268 6269 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 6270 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 6271 SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt); 6272 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt); 6273 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt); 6274 SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY); 6275 6276 // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth, 6277 // and that is undefined. We must compare and select to avoid UB. 6278 EVT CCVT = MVT::i1; 6279 if (VT.isVector()) 6280 CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements()); 6281 6282 // For fshl, 0-shift returns the 1st arg (X). 6283 // For fshr, 0-shift returns the 2nd arg (Y). 6284 SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ); 6285 setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or)); 6286 return; 6287 } 6288 case Intrinsic::sadd_sat: { 6289 SDValue Op1 = getValue(I.getArgOperand(0)); 6290 SDValue Op2 = getValue(I.getArgOperand(1)); 6291 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6292 return; 6293 } 6294 case Intrinsic::uadd_sat: { 6295 SDValue Op1 = getValue(I.getArgOperand(0)); 6296 SDValue Op2 = getValue(I.getArgOperand(1)); 6297 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6298 return; 6299 } 6300 case Intrinsic::ssub_sat: { 6301 SDValue Op1 = getValue(I.getArgOperand(0)); 6302 SDValue Op2 = getValue(I.getArgOperand(1)); 6303 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6304 return; 6305 } 6306 case Intrinsic::usub_sat: { 6307 SDValue Op1 = getValue(I.getArgOperand(0)); 6308 SDValue Op2 = getValue(I.getArgOperand(1)); 6309 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6310 return; 6311 } 6312 case Intrinsic::smul_fix: 6313 case Intrinsic::umul_fix: { 6314 SDValue Op1 = getValue(I.getArgOperand(0)); 6315 SDValue Op2 = getValue(I.getArgOperand(1)); 6316 SDValue Op3 = getValue(I.getArgOperand(2)); 6317 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6318 Op1.getValueType(), Op1, Op2, Op3)); 6319 return; 6320 } 6321 case Intrinsic::smul_fix_sat: { 6322 SDValue Op1 = getValue(I.getArgOperand(0)); 6323 SDValue Op2 = getValue(I.getArgOperand(1)); 6324 SDValue Op3 = getValue(I.getArgOperand(2)); 6325 setValue(&I, DAG.getNode(ISD::SMULFIXSAT, sdl, Op1.getValueType(), Op1, Op2, 6326 Op3)); 6327 return; 6328 } 6329 case Intrinsic::umul_fix_sat: { 6330 SDValue Op1 = getValue(I.getArgOperand(0)); 6331 SDValue Op2 = getValue(I.getArgOperand(1)); 6332 SDValue Op3 = getValue(I.getArgOperand(2)); 6333 setValue(&I, DAG.getNode(ISD::UMULFIXSAT, sdl, Op1.getValueType(), Op1, Op2, 6334 Op3)); 6335 return; 6336 } 6337 case Intrinsic::stacksave: { 6338 SDValue Op = getRoot(); 6339 Res = DAG.getNode( 6340 ISD::STACKSAVE, sdl, 6341 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op); 6342 setValue(&I, Res); 6343 DAG.setRoot(Res.getValue(1)); 6344 return; 6345 } 6346 case Intrinsic::stackrestore: 6347 Res = getValue(I.getArgOperand(0)); 6348 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6349 return; 6350 case Intrinsic::get_dynamic_area_offset: { 6351 SDValue Op = getRoot(); 6352 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6353 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6354 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6355 // target. 6356 if (PtrTy.getSizeInBits() < ResTy.getSizeInBits()) 6357 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6358 " intrinsic!"); 6359 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6360 Op); 6361 DAG.setRoot(Op); 6362 setValue(&I, Res); 6363 return; 6364 } 6365 case Intrinsic::stackguard: { 6366 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6367 MachineFunction &MF = DAG.getMachineFunction(); 6368 const Module &M = *MF.getFunction().getParent(); 6369 SDValue Chain = getRoot(); 6370 if (TLI.useLoadStackGuardNode()) { 6371 Res = getLoadStackGuard(DAG, sdl, Chain); 6372 } else { 6373 const Value *Global = TLI.getSDagStackGuard(M); 6374 unsigned Align = DL->getPrefTypeAlignment(Global->getType()); 6375 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6376 MachinePointerInfo(Global, 0), Align, 6377 MachineMemOperand::MOVolatile); 6378 } 6379 if (TLI.useStackGuardXorFP()) 6380 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6381 DAG.setRoot(Chain); 6382 setValue(&I, Res); 6383 return; 6384 } 6385 case Intrinsic::stackprotector: { 6386 // Emit code into the DAG to store the stack guard onto the stack. 6387 MachineFunction &MF = DAG.getMachineFunction(); 6388 MachineFrameInfo &MFI = MF.getFrameInfo(); 6389 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6390 SDValue Src, Chain = getRoot(); 6391 6392 if (TLI.useLoadStackGuardNode()) 6393 Src = getLoadStackGuard(DAG, sdl, Chain); 6394 else 6395 Src = getValue(I.getArgOperand(0)); // The guard's value. 6396 6397 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6398 6399 int FI = FuncInfo.StaticAllocaMap[Slot]; 6400 MFI.setStackProtectorIndex(FI); 6401 6402 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6403 6404 // Store the stack protector onto the stack. 6405 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack( 6406 DAG.getMachineFunction(), FI), 6407 /* Alignment = */ 0, MachineMemOperand::MOVolatile); 6408 setValue(&I, Res); 6409 DAG.setRoot(Res); 6410 return; 6411 } 6412 case Intrinsic::objectsize: 6413 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6414 6415 case Intrinsic::is_constant: 6416 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6417 6418 case Intrinsic::annotation: 6419 case Intrinsic::ptr_annotation: 6420 case Intrinsic::launder_invariant_group: 6421 case Intrinsic::strip_invariant_group: 6422 // Drop the intrinsic, but forward the value 6423 setValue(&I, getValue(I.getOperand(0))); 6424 return; 6425 case Intrinsic::assume: 6426 case Intrinsic::var_annotation: 6427 case Intrinsic::sideeffect: 6428 // Discard annotate attributes, assumptions, and artificial side-effects. 6429 return; 6430 6431 case Intrinsic::codeview_annotation: { 6432 // Emit a label associated with this metadata. 6433 MachineFunction &MF = DAG.getMachineFunction(); 6434 MCSymbol *Label = 6435 MF.getMMI().getContext().createTempSymbol("annotation", true); 6436 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6437 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6438 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6439 DAG.setRoot(Res); 6440 return; 6441 } 6442 6443 case Intrinsic::init_trampoline: { 6444 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6445 6446 SDValue Ops[6]; 6447 Ops[0] = getRoot(); 6448 Ops[1] = getValue(I.getArgOperand(0)); 6449 Ops[2] = getValue(I.getArgOperand(1)); 6450 Ops[3] = getValue(I.getArgOperand(2)); 6451 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6452 Ops[5] = DAG.getSrcValue(F); 6453 6454 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6455 6456 DAG.setRoot(Res); 6457 return; 6458 } 6459 case Intrinsic::adjust_trampoline: 6460 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6461 TLI.getPointerTy(DAG.getDataLayout()), 6462 getValue(I.getArgOperand(0)))); 6463 return; 6464 case Intrinsic::gcroot: { 6465 assert(DAG.getMachineFunction().getFunction().hasGC() && 6466 "only valid in functions with gc specified, enforced by Verifier"); 6467 assert(GFI && "implied by previous"); 6468 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6469 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6470 6471 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6472 GFI->addStackRoot(FI->getIndex(), TypeMap); 6473 return; 6474 } 6475 case Intrinsic::gcread: 6476 case Intrinsic::gcwrite: 6477 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6478 case Intrinsic::flt_rounds: 6479 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32)); 6480 return; 6481 6482 case Intrinsic::expect: 6483 // Just replace __builtin_expect(exp, c) with EXP. 6484 setValue(&I, getValue(I.getArgOperand(0))); 6485 return; 6486 6487 case Intrinsic::debugtrap: 6488 case Intrinsic::trap: { 6489 StringRef TrapFuncName = 6490 I.getAttributes() 6491 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6492 .getValueAsString(); 6493 if (TrapFuncName.empty()) { 6494 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 6495 ISD::TRAP : ISD::DEBUGTRAP; 6496 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 6497 return; 6498 } 6499 TargetLowering::ArgListTy Args; 6500 6501 TargetLowering::CallLoweringInfo CLI(DAG); 6502 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6503 CallingConv::C, I.getType(), 6504 DAG.getExternalSymbol(TrapFuncName.data(), 6505 TLI.getPointerTy(DAG.getDataLayout())), 6506 std::move(Args)); 6507 6508 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6509 DAG.setRoot(Result.second); 6510 return; 6511 } 6512 6513 case Intrinsic::uadd_with_overflow: 6514 case Intrinsic::sadd_with_overflow: 6515 case Intrinsic::usub_with_overflow: 6516 case Intrinsic::ssub_with_overflow: 6517 case Intrinsic::umul_with_overflow: 6518 case Intrinsic::smul_with_overflow: { 6519 ISD::NodeType Op; 6520 switch (Intrinsic) { 6521 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6522 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6523 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6524 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6525 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6526 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6527 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6528 } 6529 SDValue Op1 = getValue(I.getArgOperand(0)); 6530 SDValue Op2 = getValue(I.getArgOperand(1)); 6531 6532 EVT ResultVT = Op1.getValueType(); 6533 EVT OverflowVT = MVT::i1; 6534 if (ResultVT.isVector()) 6535 OverflowVT = EVT::getVectorVT( 6536 *Context, OverflowVT, ResultVT.getVectorNumElements()); 6537 6538 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6539 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6540 return; 6541 } 6542 case Intrinsic::prefetch: { 6543 SDValue Ops[5]; 6544 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6545 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6546 Ops[0] = DAG.getRoot(); 6547 Ops[1] = getValue(I.getArgOperand(0)); 6548 Ops[2] = getValue(I.getArgOperand(1)); 6549 Ops[3] = getValue(I.getArgOperand(2)); 6550 Ops[4] = getValue(I.getArgOperand(3)); 6551 SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl, 6552 DAG.getVTList(MVT::Other), Ops, 6553 EVT::getIntegerVT(*Context, 8), 6554 MachinePointerInfo(I.getArgOperand(0)), 6555 0, /* align */ 6556 Flags); 6557 6558 // Chain the prefetch in parallell with any pending loads, to stay out of 6559 // the way of later optimizations. 6560 PendingLoads.push_back(Result); 6561 Result = getRoot(); 6562 DAG.setRoot(Result); 6563 return; 6564 } 6565 case Intrinsic::lifetime_start: 6566 case Intrinsic::lifetime_end: { 6567 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6568 // Stack coloring is not enabled in O0, discard region information. 6569 if (TM.getOptLevel() == CodeGenOpt::None) 6570 return; 6571 6572 const int64_t ObjectSize = 6573 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6574 Value *const ObjectPtr = I.getArgOperand(1); 6575 SmallVector<const Value *, 4> Allocas; 6576 GetUnderlyingObjects(ObjectPtr, Allocas, *DL); 6577 6578 for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(), 6579 E = Allocas.end(); Object != E; ++Object) { 6580 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 6581 6582 // Could not find an Alloca. 6583 if (!LifetimeObject) 6584 continue; 6585 6586 // First check that the Alloca is static, otherwise it won't have a 6587 // valid frame index. 6588 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6589 if (SI == FuncInfo.StaticAllocaMap.end()) 6590 return; 6591 6592 const int FrameIndex = SI->second; 6593 int64_t Offset; 6594 if (GetPointerBaseWithConstantOffset( 6595 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6596 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6597 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6598 Offset); 6599 DAG.setRoot(Res); 6600 } 6601 return; 6602 } 6603 case Intrinsic::invariant_start: 6604 // Discard region information. 6605 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6606 return; 6607 case Intrinsic::invariant_end: 6608 // Discard region information. 6609 return; 6610 case Intrinsic::clear_cache: 6611 /// FunctionName may be null. 6612 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6613 lowerCallToExternalSymbol(I, FunctionName); 6614 return; 6615 case Intrinsic::donothing: 6616 // ignore 6617 return; 6618 case Intrinsic::experimental_stackmap: 6619 visitStackmap(I); 6620 return; 6621 case Intrinsic::experimental_patchpoint_void: 6622 case Intrinsic::experimental_patchpoint_i64: 6623 visitPatchpoint(&I); 6624 return; 6625 case Intrinsic::experimental_gc_statepoint: 6626 LowerStatepoint(ImmutableStatepoint(&I)); 6627 return; 6628 case Intrinsic::experimental_gc_result: 6629 visitGCResult(cast<GCResultInst>(I)); 6630 return; 6631 case Intrinsic::experimental_gc_relocate: 6632 visitGCRelocate(cast<GCRelocateInst>(I)); 6633 return; 6634 case Intrinsic::instrprof_increment: 6635 llvm_unreachable("instrprof failed to lower an increment"); 6636 case Intrinsic::instrprof_value_profile: 6637 llvm_unreachable("instrprof failed to lower a value profiling call"); 6638 case Intrinsic::localescape: { 6639 MachineFunction &MF = DAG.getMachineFunction(); 6640 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6641 6642 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6643 // is the same on all targets. 6644 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6645 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6646 if (isa<ConstantPointerNull>(Arg)) 6647 continue; // Skip null pointers. They represent a hole in index space. 6648 AllocaInst *Slot = cast<AllocaInst>(Arg); 6649 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6650 "can only escape static allocas"); 6651 int FI = FuncInfo.StaticAllocaMap[Slot]; 6652 MCSymbol *FrameAllocSym = 6653 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6654 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6655 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6656 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6657 .addSym(FrameAllocSym) 6658 .addFrameIndex(FI); 6659 } 6660 6661 return; 6662 } 6663 6664 case Intrinsic::localrecover: { 6665 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6666 MachineFunction &MF = DAG.getMachineFunction(); 6667 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0); 6668 6669 // Get the symbol that defines the frame offset. 6670 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6671 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6672 unsigned IdxVal = 6673 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6674 MCSymbol *FrameAllocSym = 6675 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6676 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6677 6678 // Create a MCSymbol for the label to avoid any target lowering 6679 // that would make this PC relative. 6680 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6681 SDValue OffsetVal = 6682 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6683 6684 // Add the offset to the FP. 6685 Value *FP = I.getArgOperand(1); 6686 SDValue FPVal = getValue(FP); 6687 SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal); 6688 setValue(&I, Add); 6689 6690 return; 6691 } 6692 6693 case Intrinsic::eh_exceptionpointer: 6694 case Intrinsic::eh_exceptioncode: { 6695 // Get the exception pointer vreg, copy from it, and resize it to fit. 6696 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6697 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6698 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6699 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6700 SDValue N = 6701 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6702 if (Intrinsic == Intrinsic::eh_exceptioncode) 6703 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6704 setValue(&I, N); 6705 return; 6706 } 6707 case Intrinsic::xray_customevent: { 6708 // Here we want to make sure that the intrinsic behaves as if it has a 6709 // specific calling convention, and only for x86_64. 6710 // FIXME: Support other platforms later. 6711 const auto &Triple = DAG.getTarget().getTargetTriple(); 6712 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6713 return; 6714 6715 SDLoc DL = getCurSDLoc(); 6716 SmallVector<SDValue, 8> Ops; 6717 6718 // We want to say that we always want the arguments in registers. 6719 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6720 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6721 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6722 SDValue Chain = getRoot(); 6723 Ops.push_back(LogEntryVal); 6724 Ops.push_back(StrSizeVal); 6725 Ops.push_back(Chain); 6726 6727 // We need to enforce the calling convention for the callsite, so that 6728 // argument ordering is enforced correctly, and that register allocation can 6729 // see that some registers may be assumed clobbered and have to preserve 6730 // them across calls to the intrinsic. 6731 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6732 DL, NodeTys, Ops); 6733 SDValue patchableNode = SDValue(MN, 0); 6734 DAG.setRoot(patchableNode); 6735 setValue(&I, patchableNode); 6736 return; 6737 } 6738 case Intrinsic::xray_typedevent: { 6739 // Here we want to make sure that the intrinsic behaves as if it has a 6740 // specific calling convention, and only for x86_64. 6741 // FIXME: Support other platforms later. 6742 const auto &Triple = DAG.getTarget().getTargetTriple(); 6743 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6744 return; 6745 6746 SDLoc DL = getCurSDLoc(); 6747 SmallVector<SDValue, 8> Ops; 6748 6749 // We want to say that we always want the arguments in registers. 6750 // It's unclear to me how manipulating the selection DAG here forces callers 6751 // to provide arguments in registers instead of on the stack. 6752 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6753 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6754 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6755 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6756 SDValue Chain = getRoot(); 6757 Ops.push_back(LogTypeId); 6758 Ops.push_back(LogEntryVal); 6759 Ops.push_back(StrSizeVal); 6760 Ops.push_back(Chain); 6761 6762 // We need to enforce the calling convention for the callsite, so that 6763 // argument ordering is enforced correctly, and that register allocation can 6764 // see that some registers may be assumed clobbered and have to preserve 6765 // them across calls to the intrinsic. 6766 MachineSDNode *MN = DAG.getMachineNode( 6767 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6768 SDValue patchableNode = SDValue(MN, 0); 6769 DAG.setRoot(patchableNode); 6770 setValue(&I, patchableNode); 6771 return; 6772 } 6773 case Intrinsic::experimental_deoptimize: 6774 LowerDeoptimizeCall(&I); 6775 return; 6776 6777 case Intrinsic::experimental_vector_reduce_v2_fadd: 6778 case Intrinsic::experimental_vector_reduce_v2_fmul: 6779 case Intrinsic::experimental_vector_reduce_add: 6780 case Intrinsic::experimental_vector_reduce_mul: 6781 case Intrinsic::experimental_vector_reduce_and: 6782 case Intrinsic::experimental_vector_reduce_or: 6783 case Intrinsic::experimental_vector_reduce_xor: 6784 case Intrinsic::experimental_vector_reduce_smax: 6785 case Intrinsic::experimental_vector_reduce_smin: 6786 case Intrinsic::experimental_vector_reduce_umax: 6787 case Intrinsic::experimental_vector_reduce_umin: 6788 case Intrinsic::experimental_vector_reduce_fmax: 6789 case Intrinsic::experimental_vector_reduce_fmin: 6790 visitVectorReduce(I, Intrinsic); 6791 return; 6792 6793 case Intrinsic::icall_branch_funnel: { 6794 SmallVector<SDValue, 16> Ops; 6795 Ops.push_back(getValue(I.getArgOperand(0))); 6796 6797 int64_t Offset; 6798 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6799 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6800 if (!Base) 6801 report_fatal_error( 6802 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6803 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6804 6805 struct BranchFunnelTarget { 6806 int64_t Offset; 6807 SDValue Target; 6808 }; 6809 SmallVector<BranchFunnelTarget, 8> Targets; 6810 6811 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6812 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6813 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6814 if (ElemBase != Base) 6815 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6816 "to the same GlobalValue"); 6817 6818 SDValue Val = getValue(I.getArgOperand(Op + 1)); 6819 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 6820 if (!GA) 6821 report_fatal_error( 6822 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6823 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 6824 GA->getGlobal(), getCurSDLoc(), 6825 Val.getValueType(), GA->getOffset())}); 6826 } 6827 llvm::sort(Targets, 6828 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 6829 return T1.Offset < T2.Offset; 6830 }); 6831 6832 for (auto &T : Targets) { 6833 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 6834 Ops.push_back(T.Target); 6835 } 6836 6837 Ops.push_back(DAG.getRoot()); // Chain 6838 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 6839 getCurSDLoc(), MVT::Other, Ops), 6840 0); 6841 DAG.setRoot(N); 6842 setValue(&I, N); 6843 HasTailCall = true; 6844 return; 6845 } 6846 6847 case Intrinsic::wasm_landingpad_index: 6848 // Information this intrinsic contained has been transferred to 6849 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 6850 // delete it now. 6851 return; 6852 6853 case Intrinsic::aarch64_settag: 6854 case Intrinsic::aarch64_settag_zero: { 6855 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6856 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 6857 SDValue Val = TSI.EmitTargetCodeForSetTag( 6858 DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)), 6859 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 6860 ZeroMemory); 6861 DAG.setRoot(Val); 6862 setValue(&I, Val); 6863 return; 6864 } 6865 case Intrinsic::ptrmask: { 6866 SDValue Ptr = getValue(I.getOperand(0)); 6867 SDValue Const = getValue(I.getOperand(1)); 6868 6869 EVT DestVT = 6870 EVT(DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 6871 6872 setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), DestVT, Ptr, 6873 DAG.getZExtOrTrunc(Const, getCurSDLoc(), DestVT))); 6874 return; 6875 } 6876 } 6877 } 6878 6879 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 6880 const ConstrainedFPIntrinsic &FPI) { 6881 SDLoc sdl = getCurSDLoc(); 6882 6883 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6884 SmallVector<EVT, 4> ValueVTs; 6885 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 6886 ValueVTs.push_back(MVT::Other); // Out chain 6887 6888 SDValue Chain = getRoot(); 6889 SmallVector<SDValue, 4> Opers; 6890 Opers.push_back(Chain); 6891 if (FPI.isUnaryOp()) { 6892 Opers.push_back(getValue(FPI.getArgOperand(0))); 6893 } else if (FPI.isTernaryOp()) { 6894 Opers.push_back(getValue(FPI.getArgOperand(0))); 6895 Opers.push_back(getValue(FPI.getArgOperand(1))); 6896 Opers.push_back(getValue(FPI.getArgOperand(2))); 6897 } else { 6898 Opers.push_back(getValue(FPI.getArgOperand(0))); 6899 Opers.push_back(getValue(FPI.getArgOperand(1))); 6900 } 6901 6902 unsigned Opcode; 6903 switch (FPI.getIntrinsicID()) { 6904 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6905 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 6906 case Intrinsic::INTRINSIC: \ 6907 Opcode = ISD::STRICT_##DAGN; \ 6908 break; 6909 #include "llvm/IR/ConstrainedOps.def" 6910 } 6911 6912 if (Opcode == ISD::STRICT_FP_ROUND) 6913 Opers.push_back( 6914 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 6915 6916 SDVTList VTs = DAG.getVTList(ValueVTs); 6917 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers); 6918 6919 if (FPI.getExceptionBehavior() != fp::ExceptionBehavior::ebIgnore) { 6920 SDNodeFlags Flags; 6921 Flags.setFPExcept(true); 6922 Result->setFlags(Flags); 6923 } 6924 6925 assert(Result.getNode()->getNumValues() == 2); 6926 SDValue OutChain = Result.getValue(1); 6927 DAG.setRoot(OutChain); 6928 SDValue FPResult = Result.getValue(0); 6929 setValue(&FPI, FPResult); 6930 } 6931 6932 std::pair<SDValue, SDValue> 6933 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 6934 const BasicBlock *EHPadBB) { 6935 MachineFunction &MF = DAG.getMachineFunction(); 6936 MachineModuleInfo &MMI = MF.getMMI(); 6937 MCSymbol *BeginLabel = nullptr; 6938 6939 if (EHPadBB) { 6940 // Insert a label before the invoke call to mark the try range. This can be 6941 // used to detect deletion of the invoke via the MachineModuleInfo. 6942 BeginLabel = MMI.getContext().createTempSymbol(); 6943 6944 // For SjLj, keep track of which landing pads go with which invokes 6945 // so as to maintain the ordering of pads in the LSDA. 6946 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 6947 if (CallSiteIndex) { 6948 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 6949 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 6950 6951 // Now that the call site is handled, stop tracking it. 6952 MMI.setCurrentCallSite(0); 6953 } 6954 6955 // Both PendingLoads and PendingExports must be flushed here; 6956 // this call might not return. 6957 (void)getRoot(); 6958 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 6959 6960 CLI.setChain(getRoot()); 6961 } 6962 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6963 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6964 6965 assert((CLI.IsTailCall || Result.second.getNode()) && 6966 "Non-null chain expected with non-tail call!"); 6967 assert((Result.second.getNode() || !Result.first.getNode()) && 6968 "Null value expected with tail call!"); 6969 6970 if (!Result.second.getNode()) { 6971 // As a special case, a null chain means that a tail call has been emitted 6972 // and the DAG root is already updated. 6973 HasTailCall = true; 6974 6975 // Since there's no actual continuation from this block, nothing can be 6976 // relying on us setting vregs for them. 6977 PendingExports.clear(); 6978 } else { 6979 DAG.setRoot(Result.second); 6980 } 6981 6982 if (EHPadBB) { 6983 // Insert a label at the end of the invoke call to mark the try range. This 6984 // can be used to detect deletion of the invoke via the MachineModuleInfo. 6985 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 6986 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 6987 6988 // Inform MachineModuleInfo of range. 6989 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 6990 // There is a platform (e.g. wasm) that uses funclet style IR but does not 6991 // actually use outlined funclets and their LSDA info style. 6992 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 6993 assert(CLI.CS); 6994 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 6995 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()), 6996 BeginLabel, EndLabel); 6997 } else if (!isScopedEHPersonality(Pers)) { 6998 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 6999 } 7000 } 7001 7002 return Result; 7003 } 7004 7005 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee, 7006 bool isTailCall, 7007 const BasicBlock *EHPadBB) { 7008 auto &DL = DAG.getDataLayout(); 7009 FunctionType *FTy = CS.getFunctionType(); 7010 Type *RetTy = CS.getType(); 7011 7012 TargetLowering::ArgListTy Args; 7013 Args.reserve(CS.arg_size()); 7014 7015 const Value *SwiftErrorVal = nullptr; 7016 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7017 7018 // We can't tail call inside a function with a swifterror argument. Lowering 7019 // does not support this yet. It would have to move into the swifterror 7020 // register before the call. 7021 auto *Caller = CS.getInstruction()->getParent()->getParent(); 7022 if (TLI.supportSwiftError() && 7023 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7024 isTailCall = false; 7025 7026 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 7027 i != e; ++i) { 7028 TargetLowering::ArgListEntry Entry; 7029 const Value *V = *i; 7030 7031 // Skip empty types 7032 if (V->getType()->isEmptyTy()) 7033 continue; 7034 7035 SDValue ArgNode = getValue(V); 7036 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7037 7038 Entry.setAttributes(&CS, i - CS.arg_begin()); 7039 7040 // Use swifterror virtual register as input to the call. 7041 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7042 SwiftErrorVal = V; 7043 // We find the virtual register for the actual swifterror argument. 7044 // Instead of using the Value, we use the virtual register instead. 7045 Entry.Node = DAG.getRegister( 7046 SwiftError.getOrCreateVRegUseAt(CS.getInstruction(), FuncInfo.MBB, V), 7047 EVT(TLI.getPointerTy(DL))); 7048 } 7049 7050 Args.push_back(Entry); 7051 7052 // If we have an explicit sret argument that is an Instruction, (i.e., it 7053 // might point to function-local memory), we can't meaningfully tail-call. 7054 if (Entry.IsSRet && isa<Instruction>(V)) 7055 isTailCall = false; 7056 } 7057 7058 // If call site has a cfguardtarget operand bundle, create and add an 7059 // additional ArgListEntry. 7060 if (auto Bundle = CS.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7061 TargetLowering::ArgListEntry Entry; 7062 Value *V = Bundle->Inputs[0]; 7063 SDValue ArgNode = getValue(V); 7064 Entry.Node = ArgNode; 7065 Entry.Ty = V->getType(); 7066 Entry.IsCFGuardTarget = true; 7067 Args.push_back(Entry); 7068 } 7069 7070 // Check if target-independent constraints permit a tail call here. 7071 // Target-dependent constraints are checked within TLI->LowerCallTo. 7072 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget())) 7073 isTailCall = false; 7074 7075 // Disable tail calls if there is an swifterror argument. Targets have not 7076 // been updated to support tail calls. 7077 if (TLI.supportSwiftError() && SwiftErrorVal) 7078 isTailCall = false; 7079 7080 TargetLowering::CallLoweringInfo CLI(DAG); 7081 CLI.setDebugLoc(getCurSDLoc()) 7082 .setChain(getRoot()) 7083 .setCallee(RetTy, FTy, Callee, std::move(Args), CS) 7084 .setTailCall(isTailCall) 7085 .setConvergent(CS.isConvergent()); 7086 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7087 7088 if (Result.first.getNode()) { 7089 const Instruction *Inst = CS.getInstruction(); 7090 Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first); 7091 setValue(Inst, Result.first); 7092 } 7093 7094 // The last element of CLI.InVals has the SDValue for swifterror return. 7095 // Here we copy it to a virtual register and update SwiftErrorMap for 7096 // book-keeping. 7097 if (SwiftErrorVal && TLI.supportSwiftError()) { 7098 // Get the last element of InVals. 7099 SDValue Src = CLI.InVals.back(); 7100 Register VReg = SwiftError.getOrCreateVRegDefAt( 7101 CS.getInstruction(), FuncInfo.MBB, SwiftErrorVal); 7102 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7103 DAG.setRoot(CopyNode); 7104 } 7105 } 7106 7107 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7108 SelectionDAGBuilder &Builder) { 7109 // Check to see if this load can be trivially constant folded, e.g. if the 7110 // input is from a string literal. 7111 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7112 // Cast pointer to the type we really want to load. 7113 Type *LoadTy = 7114 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7115 if (LoadVT.isVector()) 7116 LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7117 7118 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7119 PointerType::getUnqual(LoadTy)); 7120 7121 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 7122 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 7123 return Builder.getValue(LoadCst); 7124 } 7125 7126 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7127 // still constant memory, the input chain can be the entry node. 7128 SDValue Root; 7129 bool ConstantMemory = false; 7130 7131 // Do not serialize (non-volatile) loads of constant memory with anything. 7132 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7133 Root = Builder.DAG.getEntryNode(); 7134 ConstantMemory = true; 7135 } else { 7136 // Do not serialize non-volatile loads against each other. 7137 Root = Builder.DAG.getRoot(); 7138 } 7139 7140 SDValue Ptr = Builder.getValue(PtrVal); 7141 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, 7142 Ptr, MachinePointerInfo(PtrVal), 7143 /* Alignment = */ 1); 7144 7145 if (!ConstantMemory) 7146 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7147 return LoadVal; 7148 } 7149 7150 /// Record the value for an instruction that produces an integer result, 7151 /// converting the type where necessary. 7152 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7153 SDValue Value, 7154 bool IsSigned) { 7155 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7156 I.getType(), true); 7157 if (IsSigned) 7158 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7159 else 7160 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7161 setValue(&I, Value); 7162 } 7163 7164 /// See if we can lower a memcmp call into an optimized form. If so, return 7165 /// true and lower it. Otherwise return false, and it will be lowered like a 7166 /// normal call. 7167 /// The caller already checked that \p I calls the appropriate LibFunc with a 7168 /// correct prototype. 7169 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 7170 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 7171 const Value *Size = I.getArgOperand(2); 7172 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 7173 if (CSize && CSize->getZExtValue() == 0) { 7174 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7175 I.getType(), true); 7176 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 7177 return true; 7178 } 7179 7180 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7181 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 7182 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 7183 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 7184 if (Res.first.getNode()) { 7185 processIntegerCallValue(I, Res.first, true); 7186 PendingLoads.push_back(Res.second); 7187 return true; 7188 } 7189 7190 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 7191 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 7192 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 7193 return false; 7194 7195 // If the target has a fast compare for the given size, it will return a 7196 // preferred load type for that size. Require that the load VT is legal and 7197 // that the target supports unaligned loads of that type. Otherwise, return 7198 // INVALID. 7199 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 7200 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7201 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 7202 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 7203 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 7204 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 7205 // TODO: Check alignment of src and dest ptrs. 7206 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 7207 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 7208 if (!TLI.isTypeLegal(LVT) || 7209 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 7210 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 7211 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 7212 } 7213 7214 return LVT; 7215 }; 7216 7217 // This turns into unaligned loads. We only do this if the target natively 7218 // supports the MVT we'll be loading or if it is small enough (<= 4) that 7219 // we'll only produce a small number of byte loads. 7220 MVT LoadVT; 7221 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 7222 switch (NumBitsToCompare) { 7223 default: 7224 return false; 7225 case 16: 7226 LoadVT = MVT::i16; 7227 break; 7228 case 32: 7229 LoadVT = MVT::i32; 7230 break; 7231 case 64: 7232 case 128: 7233 case 256: 7234 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 7235 break; 7236 } 7237 7238 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 7239 return false; 7240 7241 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 7242 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 7243 7244 // Bitcast to a wide integer type if the loads are vectors. 7245 if (LoadVT.isVector()) { 7246 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 7247 LoadL = DAG.getBitcast(CmpVT, LoadL); 7248 LoadR = DAG.getBitcast(CmpVT, LoadR); 7249 } 7250 7251 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 7252 processIntegerCallValue(I, Cmp, false); 7253 return true; 7254 } 7255 7256 /// See if we can lower a memchr call into an optimized form. If so, return 7257 /// true and lower it. Otherwise return false, and it will be lowered like a 7258 /// normal call. 7259 /// The caller already checked that \p I calls the appropriate LibFunc with a 7260 /// correct prototype. 7261 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 7262 const Value *Src = I.getArgOperand(0); 7263 const Value *Char = I.getArgOperand(1); 7264 const Value *Length = I.getArgOperand(2); 7265 7266 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7267 std::pair<SDValue, SDValue> Res = 7268 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 7269 getValue(Src), getValue(Char), getValue(Length), 7270 MachinePointerInfo(Src)); 7271 if (Res.first.getNode()) { 7272 setValue(&I, Res.first); 7273 PendingLoads.push_back(Res.second); 7274 return true; 7275 } 7276 7277 return false; 7278 } 7279 7280 /// See if we can lower a mempcpy call into an optimized form. If so, return 7281 /// true and lower it. Otherwise return false, and it will be lowered like a 7282 /// normal call. 7283 /// The caller already checked that \p I calls the appropriate LibFunc with a 7284 /// correct prototype. 7285 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 7286 SDValue Dst = getValue(I.getArgOperand(0)); 7287 SDValue Src = getValue(I.getArgOperand(1)); 7288 SDValue Size = getValue(I.getArgOperand(2)); 7289 7290 unsigned DstAlign = DAG.InferPtrAlignment(Dst); 7291 unsigned SrcAlign = DAG.InferPtrAlignment(Src); 7292 unsigned Align = std::min(DstAlign, SrcAlign); 7293 if (Align == 0) // Alignment of one or both could not be inferred. 7294 Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved. 7295 7296 bool isVol = false; 7297 SDLoc sdl = getCurSDLoc(); 7298 7299 // In the mempcpy context we need to pass in a false value for isTailCall 7300 // because the return pointer needs to be adjusted by the size of 7301 // the copied memory. 7302 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol, 7303 false, /*isTailCall=*/false, 7304 MachinePointerInfo(I.getArgOperand(0)), 7305 MachinePointerInfo(I.getArgOperand(1))); 7306 assert(MC.getNode() != nullptr && 7307 "** memcpy should not be lowered as TailCall in mempcpy context **"); 7308 DAG.setRoot(MC); 7309 7310 // Check if Size needs to be truncated or extended. 7311 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 7312 7313 // Adjust return pointer to point just past the last dst byte. 7314 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 7315 Dst, Size); 7316 setValue(&I, DstPlusSize); 7317 return true; 7318 } 7319 7320 /// See if we can lower a strcpy call into an optimized form. If so, return 7321 /// true and lower it, otherwise return false and it will be lowered like a 7322 /// normal call. 7323 /// The caller already checked that \p I calls the appropriate LibFunc with a 7324 /// correct prototype. 7325 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 7326 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7327 7328 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7329 std::pair<SDValue, SDValue> Res = 7330 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 7331 getValue(Arg0), getValue(Arg1), 7332 MachinePointerInfo(Arg0), 7333 MachinePointerInfo(Arg1), isStpcpy); 7334 if (Res.first.getNode()) { 7335 setValue(&I, Res.first); 7336 DAG.setRoot(Res.second); 7337 return true; 7338 } 7339 7340 return false; 7341 } 7342 7343 /// See if we can lower a strcmp call into an optimized form. If so, return 7344 /// true and lower it, otherwise return false and it will be lowered like a 7345 /// normal call. 7346 /// The caller already checked that \p I calls the appropriate LibFunc with a 7347 /// correct prototype. 7348 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 7349 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7350 7351 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7352 std::pair<SDValue, SDValue> Res = 7353 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 7354 getValue(Arg0), getValue(Arg1), 7355 MachinePointerInfo(Arg0), 7356 MachinePointerInfo(Arg1)); 7357 if (Res.first.getNode()) { 7358 processIntegerCallValue(I, Res.first, true); 7359 PendingLoads.push_back(Res.second); 7360 return true; 7361 } 7362 7363 return false; 7364 } 7365 7366 /// See if we can lower a strlen call into an optimized form. If so, return 7367 /// true and lower it, otherwise return false and it will be lowered like a 7368 /// normal call. 7369 /// The caller already checked that \p I calls the appropriate LibFunc with a 7370 /// correct prototype. 7371 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 7372 const Value *Arg0 = I.getArgOperand(0); 7373 7374 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7375 std::pair<SDValue, SDValue> Res = 7376 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 7377 getValue(Arg0), MachinePointerInfo(Arg0)); 7378 if (Res.first.getNode()) { 7379 processIntegerCallValue(I, Res.first, false); 7380 PendingLoads.push_back(Res.second); 7381 return true; 7382 } 7383 7384 return false; 7385 } 7386 7387 /// See if we can lower a strnlen call into an optimized form. If so, return 7388 /// true and lower it, otherwise return false and it will be lowered like a 7389 /// normal call. 7390 /// The caller already checked that \p I calls the appropriate LibFunc with a 7391 /// correct prototype. 7392 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 7393 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7394 7395 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7396 std::pair<SDValue, SDValue> Res = 7397 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 7398 getValue(Arg0), getValue(Arg1), 7399 MachinePointerInfo(Arg0)); 7400 if (Res.first.getNode()) { 7401 processIntegerCallValue(I, Res.first, false); 7402 PendingLoads.push_back(Res.second); 7403 return true; 7404 } 7405 7406 return false; 7407 } 7408 7409 /// See if we can lower a unary floating-point operation into an SDNode with 7410 /// the specified Opcode. If so, return true and lower it, otherwise return 7411 /// false and it will be lowered like a normal call. 7412 /// The caller already checked that \p I calls the appropriate LibFunc with a 7413 /// correct prototype. 7414 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 7415 unsigned Opcode) { 7416 // We already checked this call's prototype; verify it doesn't modify errno. 7417 if (!I.onlyReadsMemory()) 7418 return false; 7419 7420 SDValue Tmp = getValue(I.getArgOperand(0)); 7421 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); 7422 return true; 7423 } 7424 7425 /// See if we can lower a binary floating-point operation into an SDNode with 7426 /// the specified Opcode. If so, return true and lower it. Otherwise return 7427 /// false, and it will be lowered like a normal call. 7428 /// The caller already checked that \p I calls the appropriate LibFunc with a 7429 /// correct prototype. 7430 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 7431 unsigned Opcode) { 7432 // We already checked this call's prototype; verify it doesn't modify errno. 7433 if (!I.onlyReadsMemory()) 7434 return false; 7435 7436 SDValue Tmp0 = getValue(I.getArgOperand(0)); 7437 SDValue Tmp1 = getValue(I.getArgOperand(1)); 7438 EVT VT = Tmp0.getValueType(); 7439 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1)); 7440 return true; 7441 } 7442 7443 void SelectionDAGBuilder::visitCall(const CallInst &I) { 7444 // Handle inline assembly differently. 7445 if (isa<InlineAsm>(I.getCalledValue())) { 7446 visitInlineAsm(&I); 7447 return; 7448 } 7449 7450 if (Function *F = I.getCalledFunction()) { 7451 if (F->isDeclaration()) { 7452 // Is this an LLVM intrinsic or a target-specific intrinsic? 7453 unsigned IID = F->getIntrinsicID(); 7454 if (!IID) 7455 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7456 IID = II->getIntrinsicID(F); 7457 7458 if (IID) { 7459 visitIntrinsicCall(I, IID); 7460 return; 7461 } 7462 } 7463 7464 // Check for well-known libc/libm calls. If the function is internal, it 7465 // can't be a library call. Don't do the check if marked as nobuiltin for 7466 // some reason or the call site requires strict floating point semantics. 7467 LibFunc Func; 7468 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7469 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7470 LibInfo->hasOptimizedCodeGen(Func)) { 7471 switch (Func) { 7472 default: break; 7473 case LibFunc_copysign: 7474 case LibFunc_copysignf: 7475 case LibFunc_copysignl: 7476 // We already checked this call's prototype; verify it doesn't modify 7477 // errno. 7478 if (I.onlyReadsMemory()) { 7479 SDValue LHS = getValue(I.getArgOperand(0)); 7480 SDValue RHS = getValue(I.getArgOperand(1)); 7481 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7482 LHS.getValueType(), LHS, RHS)); 7483 return; 7484 } 7485 break; 7486 case LibFunc_fabs: 7487 case LibFunc_fabsf: 7488 case LibFunc_fabsl: 7489 if (visitUnaryFloatCall(I, ISD::FABS)) 7490 return; 7491 break; 7492 case LibFunc_fmin: 7493 case LibFunc_fminf: 7494 case LibFunc_fminl: 7495 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7496 return; 7497 break; 7498 case LibFunc_fmax: 7499 case LibFunc_fmaxf: 7500 case LibFunc_fmaxl: 7501 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7502 return; 7503 break; 7504 case LibFunc_sin: 7505 case LibFunc_sinf: 7506 case LibFunc_sinl: 7507 if (visitUnaryFloatCall(I, ISD::FSIN)) 7508 return; 7509 break; 7510 case LibFunc_cos: 7511 case LibFunc_cosf: 7512 case LibFunc_cosl: 7513 if (visitUnaryFloatCall(I, ISD::FCOS)) 7514 return; 7515 break; 7516 case LibFunc_sqrt: 7517 case LibFunc_sqrtf: 7518 case LibFunc_sqrtl: 7519 case LibFunc_sqrt_finite: 7520 case LibFunc_sqrtf_finite: 7521 case LibFunc_sqrtl_finite: 7522 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7523 return; 7524 break; 7525 case LibFunc_floor: 7526 case LibFunc_floorf: 7527 case LibFunc_floorl: 7528 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7529 return; 7530 break; 7531 case LibFunc_nearbyint: 7532 case LibFunc_nearbyintf: 7533 case LibFunc_nearbyintl: 7534 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7535 return; 7536 break; 7537 case LibFunc_ceil: 7538 case LibFunc_ceilf: 7539 case LibFunc_ceill: 7540 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7541 return; 7542 break; 7543 case LibFunc_rint: 7544 case LibFunc_rintf: 7545 case LibFunc_rintl: 7546 if (visitUnaryFloatCall(I, ISD::FRINT)) 7547 return; 7548 break; 7549 case LibFunc_round: 7550 case LibFunc_roundf: 7551 case LibFunc_roundl: 7552 if (visitUnaryFloatCall(I, ISD::FROUND)) 7553 return; 7554 break; 7555 case LibFunc_trunc: 7556 case LibFunc_truncf: 7557 case LibFunc_truncl: 7558 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7559 return; 7560 break; 7561 case LibFunc_log2: 7562 case LibFunc_log2f: 7563 case LibFunc_log2l: 7564 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7565 return; 7566 break; 7567 case LibFunc_exp2: 7568 case LibFunc_exp2f: 7569 case LibFunc_exp2l: 7570 if (visitUnaryFloatCall(I, ISD::FEXP2)) 7571 return; 7572 break; 7573 case LibFunc_memcmp: 7574 if (visitMemCmpCall(I)) 7575 return; 7576 break; 7577 case LibFunc_mempcpy: 7578 if (visitMemPCpyCall(I)) 7579 return; 7580 break; 7581 case LibFunc_memchr: 7582 if (visitMemChrCall(I)) 7583 return; 7584 break; 7585 case LibFunc_strcpy: 7586 if (visitStrCpyCall(I, false)) 7587 return; 7588 break; 7589 case LibFunc_stpcpy: 7590 if (visitStrCpyCall(I, true)) 7591 return; 7592 break; 7593 case LibFunc_strcmp: 7594 if (visitStrCmpCall(I)) 7595 return; 7596 break; 7597 case LibFunc_strlen: 7598 if (visitStrLenCall(I)) 7599 return; 7600 break; 7601 case LibFunc_strnlen: 7602 if (visitStrNLenCall(I)) 7603 return; 7604 break; 7605 } 7606 } 7607 } 7608 7609 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 7610 // have to do anything here to lower funclet bundles. 7611 // CFGuardTarget bundles are lowered in LowerCallTo. 7612 assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt, 7613 LLVMContext::OB_funclet, 7614 LLVMContext::OB_cfguardtarget}) && 7615 "Cannot lower calls with arbitrary operand bundles!"); 7616 7617 SDValue Callee = getValue(I.getCalledValue()); 7618 7619 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 7620 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 7621 else 7622 // Check if we can potentially perform a tail call. More detailed checking 7623 // is be done within LowerCallTo, after more information about the call is 7624 // known. 7625 LowerCallTo(&I, Callee, I.isTailCall()); 7626 } 7627 7628 namespace { 7629 7630 /// AsmOperandInfo - This contains information for each constraint that we are 7631 /// lowering. 7632 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 7633 public: 7634 /// CallOperand - If this is the result output operand or a clobber 7635 /// this is null, otherwise it is the incoming operand to the CallInst. 7636 /// This gets modified as the asm is processed. 7637 SDValue CallOperand; 7638 7639 /// AssignedRegs - If this is a register or register class operand, this 7640 /// contains the set of register corresponding to the operand. 7641 RegsForValue AssignedRegs; 7642 7643 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 7644 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 7645 } 7646 7647 /// Whether or not this operand accesses memory 7648 bool hasMemory(const TargetLowering &TLI) const { 7649 // Indirect operand accesses access memory. 7650 if (isIndirect) 7651 return true; 7652 7653 for (const auto &Code : Codes) 7654 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 7655 return true; 7656 7657 return false; 7658 } 7659 7660 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 7661 /// corresponds to. If there is no Value* for this operand, it returns 7662 /// MVT::Other. 7663 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 7664 const DataLayout &DL) const { 7665 if (!CallOperandVal) return MVT::Other; 7666 7667 if (isa<BasicBlock>(CallOperandVal)) 7668 return TLI.getPointerTy(DL); 7669 7670 llvm::Type *OpTy = CallOperandVal->getType(); 7671 7672 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 7673 // If this is an indirect operand, the operand is a pointer to the 7674 // accessed type. 7675 if (isIndirect) { 7676 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 7677 if (!PtrTy) 7678 report_fatal_error("Indirect operand for inline asm not a pointer!"); 7679 OpTy = PtrTy->getElementType(); 7680 } 7681 7682 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 7683 if (StructType *STy = dyn_cast<StructType>(OpTy)) 7684 if (STy->getNumElements() == 1) 7685 OpTy = STy->getElementType(0); 7686 7687 // If OpTy is not a single value, it may be a struct/union that we 7688 // can tile with integers. 7689 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 7690 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 7691 switch (BitSize) { 7692 default: break; 7693 case 1: 7694 case 8: 7695 case 16: 7696 case 32: 7697 case 64: 7698 case 128: 7699 OpTy = IntegerType::get(Context, BitSize); 7700 break; 7701 } 7702 } 7703 7704 return TLI.getValueType(DL, OpTy, true); 7705 } 7706 }; 7707 7708 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>; 7709 7710 } // end anonymous namespace 7711 7712 /// Make sure that the output operand \p OpInfo and its corresponding input 7713 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 7714 /// out). 7715 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 7716 SDISelAsmOperandInfo &MatchingOpInfo, 7717 SelectionDAG &DAG) { 7718 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 7719 return; 7720 7721 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 7722 const auto &TLI = DAG.getTargetLoweringInfo(); 7723 7724 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 7725 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 7726 OpInfo.ConstraintVT); 7727 std::pair<unsigned, const TargetRegisterClass *> InputRC = 7728 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 7729 MatchingOpInfo.ConstraintVT); 7730 if ((OpInfo.ConstraintVT.isInteger() != 7731 MatchingOpInfo.ConstraintVT.isInteger()) || 7732 (MatchRC.second != InputRC.second)) { 7733 // FIXME: error out in a more elegant fashion 7734 report_fatal_error("Unsupported asm: input constraint" 7735 " with a matching output constraint of" 7736 " incompatible type!"); 7737 } 7738 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 7739 } 7740 7741 /// Get a direct memory input to behave well as an indirect operand. 7742 /// This may introduce stores, hence the need for a \p Chain. 7743 /// \return The (possibly updated) chain. 7744 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 7745 SDISelAsmOperandInfo &OpInfo, 7746 SelectionDAG &DAG) { 7747 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7748 7749 // If we don't have an indirect input, put it in the constpool if we can, 7750 // otherwise spill it to a stack slot. 7751 // TODO: This isn't quite right. We need to handle these according to 7752 // the addressing mode that the constraint wants. Also, this may take 7753 // an additional register for the computation and we don't want that 7754 // either. 7755 7756 // If the operand is a float, integer, or vector constant, spill to a 7757 // constant pool entry to get its address. 7758 const Value *OpVal = OpInfo.CallOperandVal; 7759 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 7760 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 7761 OpInfo.CallOperand = DAG.getConstantPool( 7762 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 7763 return Chain; 7764 } 7765 7766 // Otherwise, create a stack slot and emit a store to it before the asm. 7767 Type *Ty = OpVal->getType(); 7768 auto &DL = DAG.getDataLayout(); 7769 uint64_t TySize = DL.getTypeAllocSize(Ty); 7770 unsigned Align = DL.getPrefTypeAlignment(Ty); 7771 MachineFunction &MF = DAG.getMachineFunction(); 7772 int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 7773 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 7774 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 7775 MachinePointerInfo::getFixedStack(MF, SSFI), 7776 TLI.getMemValueType(DL, Ty)); 7777 OpInfo.CallOperand = StackSlot; 7778 7779 return Chain; 7780 } 7781 7782 /// GetRegistersForValue - Assign registers (virtual or physical) for the 7783 /// specified operand. We prefer to assign virtual registers, to allow the 7784 /// register allocator to handle the assignment process. However, if the asm 7785 /// uses features that we can't model on machineinstrs, we have SDISel do the 7786 /// allocation. This produces generally horrible, but correct, code. 7787 /// 7788 /// OpInfo describes the operand 7789 /// RefOpInfo describes the matching operand if any, the operand otherwise 7790 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 7791 SDISelAsmOperandInfo &OpInfo, 7792 SDISelAsmOperandInfo &RefOpInfo) { 7793 LLVMContext &Context = *DAG.getContext(); 7794 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7795 7796 MachineFunction &MF = DAG.getMachineFunction(); 7797 SmallVector<unsigned, 4> Regs; 7798 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 7799 7800 // No work to do for memory operations. 7801 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 7802 return; 7803 7804 // If this is a constraint for a single physreg, or a constraint for a 7805 // register class, find it. 7806 unsigned AssignedReg; 7807 const TargetRegisterClass *RC; 7808 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 7809 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 7810 // RC is unset only on failure. Return immediately. 7811 if (!RC) 7812 return; 7813 7814 // Get the actual register value type. This is important, because the user 7815 // may have asked for (e.g.) the AX register in i32 type. We need to 7816 // remember that AX is actually i16 to get the right extension. 7817 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 7818 7819 if (OpInfo.ConstraintVT != MVT::Other) { 7820 // If this is an FP operand in an integer register (or visa versa), or more 7821 // generally if the operand value disagrees with the register class we plan 7822 // to stick it in, fix the operand type. 7823 // 7824 // If this is an input value, the bitcast to the new type is done now. 7825 // Bitcast for output value is done at the end of visitInlineAsm(). 7826 if ((OpInfo.Type == InlineAsm::isOutput || 7827 OpInfo.Type == InlineAsm::isInput) && 7828 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 7829 // Try to convert to the first EVT that the reg class contains. If the 7830 // types are identical size, use a bitcast to convert (e.g. two differing 7831 // vector types). Note: output bitcast is done at the end of 7832 // visitInlineAsm(). 7833 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 7834 // Exclude indirect inputs while they are unsupported because the code 7835 // to perform the load is missing and thus OpInfo.CallOperand still 7836 // refers to the input address rather than the pointed-to value. 7837 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 7838 OpInfo.CallOperand = 7839 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 7840 OpInfo.ConstraintVT = RegVT; 7841 // If the operand is an FP value and we want it in integer registers, 7842 // use the corresponding integer type. This turns an f64 value into 7843 // i64, which can be passed with two i32 values on a 32-bit machine. 7844 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 7845 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 7846 if (OpInfo.Type == InlineAsm::isInput) 7847 OpInfo.CallOperand = 7848 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 7849 OpInfo.ConstraintVT = VT; 7850 } 7851 } 7852 } 7853 7854 // No need to allocate a matching input constraint since the constraint it's 7855 // matching to has already been allocated. 7856 if (OpInfo.isMatchingInputConstraint()) 7857 return; 7858 7859 EVT ValueVT = OpInfo.ConstraintVT; 7860 if (OpInfo.ConstraintVT == MVT::Other) 7861 ValueVT = RegVT; 7862 7863 // Initialize NumRegs. 7864 unsigned NumRegs = 1; 7865 if (OpInfo.ConstraintVT != MVT::Other) 7866 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 7867 7868 // If this is a constraint for a specific physical register, like {r17}, 7869 // assign it now. 7870 7871 // If this associated to a specific register, initialize iterator to correct 7872 // place. If virtual, make sure we have enough registers 7873 7874 // Initialize iterator if necessary 7875 TargetRegisterClass::iterator I = RC->begin(); 7876 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7877 7878 // Do not check for single registers. 7879 if (AssignedReg) { 7880 for (; *I != AssignedReg; ++I) 7881 assert(I != RC->end() && "AssignedReg should be member of RC"); 7882 } 7883 7884 for (; NumRegs; --NumRegs, ++I) { 7885 assert(I != RC->end() && "Ran out of registers to allocate!"); 7886 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 7887 Regs.push_back(R); 7888 } 7889 7890 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 7891 } 7892 7893 static unsigned 7894 findMatchingInlineAsmOperand(unsigned OperandNo, 7895 const std::vector<SDValue> &AsmNodeOperands) { 7896 // Scan until we find the definition we already emitted of this operand. 7897 unsigned CurOp = InlineAsm::Op_FirstOperand; 7898 for (; OperandNo; --OperandNo) { 7899 // Advance to the next operand. 7900 unsigned OpFlag = 7901 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7902 assert((InlineAsm::isRegDefKind(OpFlag) || 7903 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 7904 InlineAsm::isMemKind(OpFlag)) && 7905 "Skipped past definitions?"); 7906 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 7907 } 7908 return CurOp; 7909 } 7910 7911 namespace { 7912 7913 class ExtraFlags { 7914 unsigned Flags = 0; 7915 7916 public: 7917 explicit ExtraFlags(ImmutableCallSite CS) { 7918 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7919 if (IA->hasSideEffects()) 7920 Flags |= InlineAsm::Extra_HasSideEffects; 7921 if (IA->isAlignStack()) 7922 Flags |= InlineAsm::Extra_IsAlignStack; 7923 if (CS.isConvergent()) 7924 Flags |= InlineAsm::Extra_IsConvergent; 7925 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 7926 } 7927 7928 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 7929 // Ideally, we would only check against memory constraints. However, the 7930 // meaning of an Other constraint can be target-specific and we can't easily 7931 // reason about it. Therefore, be conservative and set MayLoad/MayStore 7932 // for Other constraints as well. 7933 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 7934 OpInfo.ConstraintType == TargetLowering::C_Other) { 7935 if (OpInfo.Type == InlineAsm::isInput) 7936 Flags |= InlineAsm::Extra_MayLoad; 7937 else if (OpInfo.Type == InlineAsm::isOutput) 7938 Flags |= InlineAsm::Extra_MayStore; 7939 else if (OpInfo.Type == InlineAsm::isClobber) 7940 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 7941 } 7942 } 7943 7944 unsigned get() const { return Flags; } 7945 }; 7946 7947 } // end anonymous namespace 7948 7949 /// visitInlineAsm - Handle a call to an InlineAsm object. 7950 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) { 7951 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7952 7953 /// ConstraintOperands - Information about all of the constraints. 7954 SDISelAsmOperandInfoVector ConstraintOperands; 7955 7956 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7957 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 7958 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS); 7959 7960 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 7961 // AsmDialect, MayLoad, MayStore). 7962 bool HasSideEffect = IA->hasSideEffects(); 7963 ExtraFlags ExtraInfo(CS); 7964 7965 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 7966 unsigned ResNo = 0; // ResNo - The result number of the next output. 7967 for (auto &T : TargetConstraints) { 7968 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 7969 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 7970 7971 // Compute the value type for each operand. 7972 if (OpInfo.Type == InlineAsm::isInput || 7973 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 7974 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 7975 7976 // Process the call argument. BasicBlocks are labels, currently appearing 7977 // only in asm's. 7978 const Instruction *I = CS.getInstruction(); 7979 if (isa<CallBrInst>(I) && 7980 (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() - 7981 cast<CallBrInst>(I)->getNumIndirectDests())) { 7982 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal); 7983 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true); 7984 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT); 7985 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 7986 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 7987 } else { 7988 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 7989 } 7990 7991 OpInfo.ConstraintVT = 7992 OpInfo 7993 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout()) 7994 .getSimpleVT(); 7995 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 7996 // The return value of the call is this value. As such, there is no 7997 // corresponding argument. 7998 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 7999 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 8000 OpInfo.ConstraintVT = TLI.getSimpleValueType( 8001 DAG.getDataLayout(), STy->getElementType(ResNo)); 8002 } else { 8003 assert(ResNo == 0 && "Asm only has one result!"); 8004 OpInfo.ConstraintVT = 8005 TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType()); 8006 } 8007 ++ResNo; 8008 } else { 8009 OpInfo.ConstraintVT = MVT::Other; 8010 } 8011 8012 if (!HasSideEffect) 8013 HasSideEffect = OpInfo.hasMemory(TLI); 8014 8015 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8016 // FIXME: Could we compute this on OpInfo rather than T? 8017 8018 // Compute the constraint code and ConstraintType to use. 8019 TLI.ComputeConstraintToUse(T, SDValue()); 8020 8021 if (T.ConstraintType == TargetLowering::C_Immediate && 8022 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8023 // We've delayed emitting a diagnostic like the "n" constraint because 8024 // inlining could cause an integer showing up. 8025 return emitInlineAsmError( 8026 CS, "constraint '" + Twine(T.ConstraintCode) + "' expects an " 8027 "integer constant expression"); 8028 8029 ExtraInfo.update(T); 8030 } 8031 8032 8033 // We won't need to flush pending loads if this asm doesn't touch 8034 // memory and is nonvolatile. 8035 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8036 8037 bool IsCallBr = isa<CallBrInst>(CS.getInstruction()); 8038 if (IsCallBr) { 8039 // If this is a callbr we need to flush pending exports since inlineasm_br 8040 // is a terminator. We need to do this before nodes are glued to 8041 // the inlineasm_br node. 8042 Chain = getControlRoot(); 8043 } 8044 8045 // Second pass over the constraints: compute which constraint option to use. 8046 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8047 // If this is an output operand with a matching input operand, look up the 8048 // matching input. If their types mismatch, e.g. one is an integer, the 8049 // other is floating point, or their sizes are different, flag it as an 8050 // error. 8051 if (OpInfo.hasMatchingInput()) { 8052 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8053 patchMatchingInput(OpInfo, Input, DAG); 8054 } 8055 8056 // Compute the constraint code and ConstraintType to use. 8057 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8058 8059 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8060 OpInfo.Type == InlineAsm::isClobber) 8061 continue; 8062 8063 // If this is a memory input, and if the operand is not indirect, do what we 8064 // need to provide an address for the memory input. 8065 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8066 !OpInfo.isIndirect) { 8067 assert((OpInfo.isMultipleAlternative || 8068 (OpInfo.Type == InlineAsm::isInput)) && 8069 "Can only indirectify direct input operands!"); 8070 8071 // Memory operands really want the address of the value. 8072 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8073 8074 // There is no longer a Value* corresponding to this operand. 8075 OpInfo.CallOperandVal = nullptr; 8076 8077 // It is now an indirect operand. 8078 OpInfo.isIndirect = true; 8079 } 8080 8081 } 8082 8083 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8084 std::vector<SDValue> AsmNodeOperands; 8085 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8086 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8087 IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout()))); 8088 8089 // If we have a !srcloc metadata node associated with it, we want to attach 8090 // this to the ultimately generated inline asm machineinstr. To do this, we 8091 // pass in the third operand as this (potentially null) inline asm MDNode. 8092 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc"); 8093 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8094 8095 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8096 // bits as operand 3. 8097 AsmNodeOperands.push_back(DAG.getTargetConstant( 8098 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8099 8100 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8101 // this, assign virtual and physical registers for inputs and otput. 8102 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8103 // Assign Registers. 8104 SDISelAsmOperandInfo &RefOpInfo = 8105 OpInfo.isMatchingInputConstraint() 8106 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8107 : OpInfo; 8108 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8109 8110 switch (OpInfo.Type) { 8111 case InlineAsm::isOutput: 8112 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8113 ((OpInfo.ConstraintType == TargetLowering::C_Immediate || 8114 OpInfo.ConstraintType == TargetLowering::C_Other) && 8115 OpInfo.isIndirect)) { 8116 unsigned ConstraintID = 8117 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8118 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8119 "Failed to convert memory constraint code to constraint id."); 8120 8121 // Add information to the INLINEASM node to know about this output. 8122 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8123 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8124 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8125 MVT::i32)); 8126 AsmNodeOperands.push_back(OpInfo.CallOperand); 8127 break; 8128 } else if (((OpInfo.ConstraintType == TargetLowering::C_Immediate || 8129 OpInfo.ConstraintType == TargetLowering::C_Other) && 8130 !OpInfo.isIndirect) || 8131 OpInfo.ConstraintType == TargetLowering::C_Register || 8132 OpInfo.ConstraintType == TargetLowering::C_RegisterClass) { 8133 // Otherwise, this outputs to a register (directly for C_Register / 8134 // C_RegisterClass, and a target-defined fashion for 8135 // C_Immediate/C_Other). Find a register that we can use. 8136 if (OpInfo.AssignedRegs.Regs.empty()) { 8137 emitInlineAsmError( 8138 CS, "couldn't allocate output register for constraint '" + 8139 Twine(OpInfo.ConstraintCode) + "'"); 8140 return; 8141 } 8142 8143 // Add information to the INLINEASM node to know that this register is 8144 // set. 8145 OpInfo.AssignedRegs.AddInlineAsmOperands( 8146 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8147 : InlineAsm::Kind_RegDef, 8148 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8149 } 8150 break; 8151 8152 case InlineAsm::isInput: { 8153 SDValue InOperandVal = OpInfo.CallOperand; 8154 8155 if (OpInfo.isMatchingInputConstraint()) { 8156 // If this is required to match an output register we have already set, 8157 // just use its register. 8158 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8159 AsmNodeOperands); 8160 unsigned OpFlag = 8161 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8162 if (InlineAsm::isRegDefKind(OpFlag) || 8163 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8164 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8165 if (OpInfo.isIndirect) { 8166 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8167 emitInlineAsmError(CS, "inline asm not supported yet:" 8168 " don't know how to handle tied " 8169 "indirect register inputs"); 8170 return; 8171 } 8172 8173 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 8174 SmallVector<unsigned, 4> Regs; 8175 8176 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { 8177 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8178 MachineRegisterInfo &RegInfo = 8179 DAG.getMachineFunction().getRegInfo(); 8180 for (unsigned i = 0; i != NumRegs; ++i) 8181 Regs.push_back(RegInfo.createVirtualRegister(RC)); 8182 } else { 8183 emitInlineAsmError(CS, "inline asm error: This value type register " 8184 "class is not natively supported!"); 8185 return; 8186 } 8187 8188 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8189 8190 SDLoc dl = getCurSDLoc(); 8191 // Use the produced MatchedRegs object to 8192 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 8193 CS.getInstruction()); 8194 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8195 true, OpInfo.getMatchedOperand(), dl, 8196 DAG, AsmNodeOperands); 8197 break; 8198 } 8199 8200 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8201 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8202 "Unexpected number of operands"); 8203 // Add information to the INLINEASM node to know about this input. 8204 // See InlineAsm.h isUseOperandTiedToDef. 8205 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8206 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8207 OpInfo.getMatchedOperand()); 8208 AsmNodeOperands.push_back(DAG.getTargetConstant( 8209 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8210 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8211 break; 8212 } 8213 8214 // Treat indirect 'X' constraint as memory. 8215 if ((OpInfo.ConstraintType == TargetLowering::C_Immediate || 8216 OpInfo.ConstraintType == TargetLowering::C_Other) && 8217 OpInfo.isIndirect) 8218 OpInfo.ConstraintType = TargetLowering::C_Memory; 8219 8220 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 8221 OpInfo.ConstraintType == TargetLowering::C_Other) { 8222 std::vector<SDValue> Ops; 8223 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 8224 Ops, DAG); 8225 if (Ops.empty()) { 8226 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 8227 if (isa<ConstantSDNode>(InOperandVal)) { 8228 emitInlineAsmError(CS, "value out of range for constraint '" + 8229 Twine(OpInfo.ConstraintCode) + "'"); 8230 return; 8231 } 8232 8233 emitInlineAsmError(CS, "invalid operand for inline asm constraint '" + 8234 Twine(OpInfo.ConstraintCode) + "'"); 8235 return; 8236 } 8237 8238 // Add information to the INLINEASM node to know about this input. 8239 unsigned ResOpType = 8240 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 8241 AsmNodeOperands.push_back(DAG.getTargetConstant( 8242 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8243 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 8244 break; 8245 } 8246 8247 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8248 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 8249 assert(InOperandVal.getValueType() == 8250 TLI.getPointerTy(DAG.getDataLayout()) && 8251 "Memory operands expect pointer values"); 8252 8253 unsigned ConstraintID = 8254 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8255 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8256 "Failed to convert memory constraint code to constraint id."); 8257 8258 // Add information to the INLINEASM node to know about this input. 8259 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8260 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 8261 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 8262 getCurSDLoc(), 8263 MVT::i32)); 8264 AsmNodeOperands.push_back(InOperandVal); 8265 break; 8266 } 8267 8268 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 8269 OpInfo.ConstraintType == TargetLowering::C_Register || 8270 OpInfo.ConstraintType == TargetLowering::C_Immediate) && 8271 "Unknown constraint type!"); 8272 8273 // TODO: Support this. 8274 if (OpInfo.isIndirect) { 8275 emitInlineAsmError( 8276 CS, "Don't know how to handle indirect register inputs yet " 8277 "for constraint '" + 8278 Twine(OpInfo.ConstraintCode) + "'"); 8279 return; 8280 } 8281 8282 // Copy the input into the appropriate registers. 8283 if (OpInfo.AssignedRegs.Regs.empty()) { 8284 emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" + 8285 Twine(OpInfo.ConstraintCode) + "'"); 8286 return; 8287 } 8288 8289 SDLoc dl = getCurSDLoc(); 8290 8291 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, 8292 Chain, &Flag, CS.getInstruction()); 8293 8294 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 8295 dl, DAG, AsmNodeOperands); 8296 break; 8297 } 8298 case InlineAsm::isClobber: 8299 // Add the clobbered value to the operand list, so that the register 8300 // allocator is aware that the physreg got clobbered. 8301 if (!OpInfo.AssignedRegs.Regs.empty()) 8302 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 8303 false, 0, getCurSDLoc(), DAG, 8304 AsmNodeOperands); 8305 break; 8306 } 8307 } 8308 8309 // Finish up input operands. Set the input chain and add the flag last. 8310 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 8311 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 8312 8313 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 8314 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 8315 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 8316 Flag = Chain.getValue(1); 8317 8318 // Do additional work to generate outputs. 8319 8320 SmallVector<EVT, 1> ResultVTs; 8321 SmallVector<SDValue, 1> ResultValues; 8322 SmallVector<SDValue, 8> OutChains; 8323 8324 llvm::Type *CSResultType = CS.getType(); 8325 ArrayRef<Type *> ResultTypes; 8326 if (StructType *StructResult = dyn_cast<StructType>(CSResultType)) 8327 ResultTypes = StructResult->elements(); 8328 else if (!CSResultType->isVoidTy()) 8329 ResultTypes = makeArrayRef(CSResultType); 8330 8331 auto CurResultType = ResultTypes.begin(); 8332 auto handleRegAssign = [&](SDValue V) { 8333 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 8334 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 8335 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 8336 ++CurResultType; 8337 // If the type of the inline asm call site return value is different but has 8338 // same size as the type of the asm output bitcast it. One example of this 8339 // is for vectors with different width / number of elements. This can 8340 // happen for register classes that can contain multiple different value 8341 // types. The preg or vreg allocated may not have the same VT as was 8342 // expected. 8343 // 8344 // This can also happen for a return value that disagrees with the register 8345 // class it is put in, eg. a double in a general-purpose register on a 8346 // 32-bit machine. 8347 if (ResultVT != V.getValueType() && 8348 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 8349 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 8350 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 8351 V.getValueType().isInteger()) { 8352 // If a result value was tied to an input value, the computed result 8353 // may have a wider width than the expected result. Extract the 8354 // relevant portion. 8355 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 8356 } 8357 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 8358 ResultVTs.push_back(ResultVT); 8359 ResultValues.push_back(V); 8360 }; 8361 8362 // Deal with output operands. 8363 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8364 if (OpInfo.Type == InlineAsm::isOutput) { 8365 SDValue Val; 8366 // Skip trivial output operands. 8367 if (OpInfo.AssignedRegs.Regs.empty()) 8368 continue; 8369 8370 switch (OpInfo.ConstraintType) { 8371 case TargetLowering::C_Register: 8372 case TargetLowering::C_RegisterClass: 8373 Val = OpInfo.AssignedRegs.getCopyFromRegs( 8374 DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction()); 8375 break; 8376 case TargetLowering::C_Immediate: 8377 case TargetLowering::C_Other: 8378 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 8379 OpInfo, DAG); 8380 break; 8381 case TargetLowering::C_Memory: 8382 break; // Already handled. 8383 case TargetLowering::C_Unknown: 8384 assert(false && "Unexpected unknown constraint"); 8385 } 8386 8387 // Indirect output manifest as stores. Record output chains. 8388 if (OpInfo.isIndirect) { 8389 const Value *Ptr = OpInfo.CallOperandVal; 8390 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 8391 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 8392 MachinePointerInfo(Ptr)); 8393 OutChains.push_back(Store); 8394 } else { 8395 // generate CopyFromRegs to associated registers. 8396 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 8397 if (Val.getOpcode() == ISD::MERGE_VALUES) { 8398 for (const SDValue &V : Val->op_values()) 8399 handleRegAssign(V); 8400 } else 8401 handleRegAssign(Val); 8402 } 8403 } 8404 } 8405 8406 // Set results. 8407 if (!ResultValues.empty()) { 8408 assert(CurResultType == ResultTypes.end() && 8409 "Mismatch in number of ResultTypes"); 8410 assert(ResultValues.size() == ResultTypes.size() && 8411 "Mismatch in number of output operands in asm result"); 8412 8413 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 8414 DAG.getVTList(ResultVTs), ResultValues); 8415 setValue(CS.getInstruction(), V); 8416 } 8417 8418 // Collect store chains. 8419 if (!OutChains.empty()) 8420 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 8421 8422 // Only Update Root if inline assembly has a memory effect. 8423 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr) 8424 DAG.setRoot(Chain); 8425 } 8426 8427 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS, 8428 const Twine &Message) { 8429 LLVMContext &Ctx = *DAG.getContext(); 8430 Ctx.emitError(CS.getInstruction(), Message); 8431 8432 // Make sure we leave the DAG in a valid state 8433 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8434 SmallVector<EVT, 1> ValueVTs; 8435 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8436 8437 if (ValueVTs.empty()) 8438 return; 8439 8440 SmallVector<SDValue, 1> Ops; 8441 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 8442 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 8443 8444 setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc())); 8445 } 8446 8447 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 8448 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 8449 MVT::Other, getRoot(), 8450 getValue(I.getArgOperand(0)), 8451 DAG.getSrcValue(I.getArgOperand(0)))); 8452 } 8453 8454 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 8455 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8456 const DataLayout &DL = DAG.getDataLayout(); 8457 SDValue V = DAG.getVAArg( 8458 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 8459 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 8460 DL.getABITypeAlignment(I.getType())); 8461 DAG.setRoot(V.getValue(1)); 8462 8463 if (I.getType()->isPointerTy()) 8464 V = DAG.getPtrExtOrTrunc( 8465 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 8466 setValue(&I, V); 8467 } 8468 8469 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 8470 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 8471 MVT::Other, getRoot(), 8472 getValue(I.getArgOperand(0)), 8473 DAG.getSrcValue(I.getArgOperand(0)))); 8474 } 8475 8476 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 8477 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 8478 MVT::Other, getRoot(), 8479 getValue(I.getArgOperand(0)), 8480 getValue(I.getArgOperand(1)), 8481 DAG.getSrcValue(I.getArgOperand(0)), 8482 DAG.getSrcValue(I.getArgOperand(1)))); 8483 } 8484 8485 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 8486 const Instruction &I, 8487 SDValue Op) { 8488 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 8489 if (!Range) 8490 return Op; 8491 8492 ConstantRange CR = getConstantRangeFromMetadata(*Range); 8493 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 8494 return Op; 8495 8496 APInt Lo = CR.getUnsignedMin(); 8497 if (!Lo.isMinValue()) 8498 return Op; 8499 8500 APInt Hi = CR.getUnsignedMax(); 8501 unsigned Bits = std::max(Hi.getActiveBits(), 8502 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 8503 8504 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8505 8506 SDLoc SL = getCurSDLoc(); 8507 8508 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8509 DAG.getValueType(SmallVT)); 8510 unsigned NumVals = Op.getNode()->getNumValues(); 8511 if (NumVals == 1) 8512 return ZExt; 8513 8514 SmallVector<SDValue, 4> Ops; 8515 8516 Ops.push_back(ZExt); 8517 for (unsigned I = 1; I != NumVals; ++I) 8518 Ops.push_back(Op.getValue(I)); 8519 8520 return DAG.getMergeValues(Ops, SL); 8521 } 8522 8523 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8524 /// the call being lowered. 8525 /// 8526 /// This is a helper for lowering intrinsics that follow a target calling 8527 /// convention or require stack pointer adjustment. Only a subset of the 8528 /// intrinsic's operands need to participate in the calling convention. 8529 void SelectionDAGBuilder::populateCallLoweringInfo( 8530 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 8531 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8532 bool IsPatchPoint) { 8533 TargetLowering::ArgListTy Args; 8534 Args.reserve(NumArgs); 8535 8536 // Populate the argument list. 8537 // Attributes for args start at offset 1, after the return attribute. 8538 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8539 ArgI != ArgE; ++ArgI) { 8540 const Value *V = Call->getOperand(ArgI); 8541 8542 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 8543 8544 TargetLowering::ArgListEntry Entry; 8545 Entry.Node = getValue(V); 8546 Entry.Ty = V->getType(); 8547 Entry.setAttributes(Call, ArgI); 8548 Args.push_back(Entry); 8549 } 8550 8551 CLI.setDebugLoc(getCurSDLoc()) 8552 .setChain(getRoot()) 8553 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 8554 .setDiscardResult(Call->use_empty()) 8555 .setIsPatchPoint(IsPatchPoint); 8556 } 8557 8558 /// Add a stack map intrinsic call's live variable operands to a stackmap 8559 /// or patchpoint target node's operand list. 8560 /// 8561 /// Constants are converted to TargetConstants purely as an optimization to 8562 /// avoid constant materialization and register allocation. 8563 /// 8564 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 8565 /// generate addess computation nodes, and so FinalizeISel can convert the 8566 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 8567 /// address materialization and register allocation, but may also be required 8568 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 8569 /// alloca in the entry block, then the runtime may assume that the alloca's 8570 /// StackMap location can be read immediately after compilation and that the 8571 /// location is valid at any point during execution (this is similar to the 8572 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 8573 /// only available in a register, then the runtime would need to trap when 8574 /// execution reaches the StackMap in order to read the alloca's location. 8575 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx, 8576 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 8577 SelectionDAGBuilder &Builder) { 8578 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) { 8579 SDValue OpVal = Builder.getValue(CS.getArgument(i)); 8580 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 8581 Ops.push_back( 8582 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 8583 Ops.push_back( 8584 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 8585 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 8586 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 8587 Ops.push_back(Builder.DAG.getTargetFrameIndex( 8588 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 8589 } else 8590 Ops.push_back(OpVal); 8591 } 8592 } 8593 8594 /// Lower llvm.experimental.stackmap directly to its target opcode. 8595 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 8596 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 8597 // [live variables...]) 8598 8599 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 8600 8601 SDValue Chain, InFlag, Callee, NullPtr; 8602 SmallVector<SDValue, 32> Ops; 8603 8604 SDLoc DL = getCurSDLoc(); 8605 Callee = getValue(CI.getCalledValue()); 8606 NullPtr = DAG.getIntPtrConstant(0, DL, true); 8607 8608 // The stackmap intrinsic only records the live variables (the arguments 8609 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 8610 // intrinsic, this won't be lowered to a function call. This means we don't 8611 // have to worry about calling conventions and target specific lowering code. 8612 // Instead we perform the call lowering right here. 8613 // 8614 // chain, flag = CALLSEQ_START(chain, 0, 0) 8615 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 8616 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 8617 // 8618 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 8619 InFlag = Chain.getValue(1); 8620 8621 // Add the <id> and <numBytes> constants. 8622 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 8623 Ops.push_back(DAG.getTargetConstant( 8624 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 8625 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 8626 Ops.push_back(DAG.getTargetConstant( 8627 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 8628 MVT::i32)); 8629 8630 // Push live variables for the stack map. 8631 addStackMapLiveVars(&CI, 2, DL, Ops, *this); 8632 8633 // We are not pushing any register mask info here on the operands list, 8634 // because the stackmap doesn't clobber anything. 8635 8636 // Push the chain and the glue flag. 8637 Ops.push_back(Chain); 8638 Ops.push_back(InFlag); 8639 8640 // Create the STACKMAP node. 8641 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8642 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 8643 Chain = SDValue(SM, 0); 8644 InFlag = Chain.getValue(1); 8645 8646 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 8647 8648 // Stackmaps don't generate values, so nothing goes into the NodeMap. 8649 8650 // Set the root to the target-lowered call chain. 8651 DAG.setRoot(Chain); 8652 8653 // Inform the Frame Information that we have a stackmap in this function. 8654 FuncInfo.MF->getFrameInfo().setHasStackMap(); 8655 } 8656 8657 /// Lower llvm.experimental.patchpoint directly to its target opcode. 8658 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS, 8659 const BasicBlock *EHPadBB) { 8660 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 8661 // i32 <numBytes>, 8662 // i8* <target>, 8663 // i32 <numArgs>, 8664 // [Args...], 8665 // [live variables...]) 8666 8667 CallingConv::ID CC = CS.getCallingConv(); 8668 bool IsAnyRegCC = CC == CallingConv::AnyReg; 8669 bool HasDef = !CS->getType()->isVoidTy(); 8670 SDLoc dl = getCurSDLoc(); 8671 SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos)); 8672 8673 // Handle immediate and symbolic callees. 8674 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 8675 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 8676 /*isTarget=*/true); 8677 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 8678 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 8679 SDLoc(SymbolicCallee), 8680 SymbolicCallee->getValueType(0)); 8681 8682 // Get the real number of arguments participating in the call <numArgs> 8683 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos)); 8684 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 8685 8686 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 8687 // Intrinsics include all meta-operands up to but not including CC. 8688 unsigned NumMetaOpers = PatchPointOpers::CCPos; 8689 assert(CS.arg_size() >= NumMetaOpers + NumArgs && 8690 "Not enough arguments provided to the patchpoint intrinsic"); 8691 8692 // For AnyRegCC the arguments are lowered later on manually. 8693 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 8694 Type *ReturnTy = 8695 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType(); 8696 8697 TargetLowering::CallLoweringInfo CLI(DAG); 8698 populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()), 8699 NumMetaOpers, NumCallArgs, Callee, ReturnTy, true); 8700 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8701 8702 SDNode *CallEnd = Result.second.getNode(); 8703 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 8704 CallEnd = CallEnd->getOperand(0).getNode(); 8705 8706 /// Get a call instruction from the call sequence chain. 8707 /// Tail calls are not allowed. 8708 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 8709 "Expected a callseq node."); 8710 SDNode *Call = CallEnd->getOperand(0).getNode(); 8711 bool HasGlue = Call->getGluedNode(); 8712 8713 // Replace the target specific call node with the patchable intrinsic. 8714 SmallVector<SDValue, 8> Ops; 8715 8716 // Add the <id> and <numBytes> constants. 8717 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos)); 8718 Ops.push_back(DAG.getTargetConstant( 8719 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 8720 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos)); 8721 Ops.push_back(DAG.getTargetConstant( 8722 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 8723 MVT::i32)); 8724 8725 // Add the callee. 8726 Ops.push_back(Callee); 8727 8728 // Adjust <numArgs> to account for any arguments that have been passed on the 8729 // stack instead. 8730 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 8731 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 8732 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 8733 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 8734 8735 // Add the calling convention 8736 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 8737 8738 // Add the arguments we omitted previously. The register allocator should 8739 // place these in any free register. 8740 if (IsAnyRegCC) 8741 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 8742 Ops.push_back(getValue(CS.getArgument(i))); 8743 8744 // Push the arguments from the call instruction up to the register mask. 8745 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 8746 Ops.append(Call->op_begin() + 2, e); 8747 8748 // Push live variables for the stack map. 8749 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this); 8750 8751 // Push the register mask info. 8752 if (HasGlue) 8753 Ops.push_back(*(Call->op_end()-2)); 8754 else 8755 Ops.push_back(*(Call->op_end()-1)); 8756 8757 // Push the chain (this is originally the first operand of the call, but 8758 // becomes now the last or second to last operand). 8759 Ops.push_back(*(Call->op_begin())); 8760 8761 // Push the glue flag (last operand). 8762 if (HasGlue) 8763 Ops.push_back(*(Call->op_end()-1)); 8764 8765 SDVTList NodeTys; 8766 if (IsAnyRegCC && HasDef) { 8767 // Create the return types based on the intrinsic definition 8768 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8769 SmallVector<EVT, 3> ValueVTs; 8770 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8771 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 8772 8773 // There is always a chain and a glue type at the end 8774 ValueVTs.push_back(MVT::Other); 8775 ValueVTs.push_back(MVT::Glue); 8776 NodeTys = DAG.getVTList(ValueVTs); 8777 } else 8778 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8779 8780 // Replace the target specific call node with a PATCHPOINT node. 8781 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 8782 dl, NodeTys, Ops); 8783 8784 // Update the NodeMap. 8785 if (HasDef) { 8786 if (IsAnyRegCC) 8787 setValue(CS.getInstruction(), SDValue(MN, 0)); 8788 else 8789 setValue(CS.getInstruction(), Result.first); 8790 } 8791 8792 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 8793 // call sequence. Furthermore the location of the chain and glue can change 8794 // when the AnyReg calling convention is used and the intrinsic returns a 8795 // value. 8796 if (IsAnyRegCC && HasDef) { 8797 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 8798 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 8799 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 8800 } else 8801 DAG.ReplaceAllUsesWith(Call, MN); 8802 DAG.DeleteNode(Call); 8803 8804 // Inform the Frame Information that we have a patchpoint in this function. 8805 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 8806 } 8807 8808 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 8809 unsigned Intrinsic) { 8810 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8811 SDValue Op1 = getValue(I.getArgOperand(0)); 8812 SDValue Op2; 8813 if (I.getNumArgOperands() > 1) 8814 Op2 = getValue(I.getArgOperand(1)); 8815 SDLoc dl = getCurSDLoc(); 8816 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8817 SDValue Res; 8818 FastMathFlags FMF; 8819 if (isa<FPMathOperator>(I)) 8820 FMF = I.getFastMathFlags(); 8821 8822 switch (Intrinsic) { 8823 case Intrinsic::experimental_vector_reduce_v2_fadd: 8824 if (FMF.allowReassoc()) 8825 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 8826 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2)); 8827 else 8828 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2); 8829 break; 8830 case Intrinsic::experimental_vector_reduce_v2_fmul: 8831 if (FMF.allowReassoc()) 8832 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 8833 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2)); 8834 else 8835 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2); 8836 break; 8837 case Intrinsic::experimental_vector_reduce_add: 8838 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 8839 break; 8840 case Intrinsic::experimental_vector_reduce_mul: 8841 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 8842 break; 8843 case Intrinsic::experimental_vector_reduce_and: 8844 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 8845 break; 8846 case Intrinsic::experimental_vector_reduce_or: 8847 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 8848 break; 8849 case Intrinsic::experimental_vector_reduce_xor: 8850 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 8851 break; 8852 case Intrinsic::experimental_vector_reduce_smax: 8853 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 8854 break; 8855 case Intrinsic::experimental_vector_reduce_smin: 8856 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 8857 break; 8858 case Intrinsic::experimental_vector_reduce_umax: 8859 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 8860 break; 8861 case Intrinsic::experimental_vector_reduce_umin: 8862 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 8863 break; 8864 case Intrinsic::experimental_vector_reduce_fmax: 8865 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1); 8866 break; 8867 case Intrinsic::experimental_vector_reduce_fmin: 8868 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1); 8869 break; 8870 default: 8871 llvm_unreachable("Unhandled vector reduce intrinsic"); 8872 } 8873 setValue(&I, Res); 8874 } 8875 8876 /// Returns an AttributeList representing the attributes applied to the return 8877 /// value of the given call. 8878 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 8879 SmallVector<Attribute::AttrKind, 2> Attrs; 8880 if (CLI.RetSExt) 8881 Attrs.push_back(Attribute::SExt); 8882 if (CLI.RetZExt) 8883 Attrs.push_back(Attribute::ZExt); 8884 if (CLI.IsInReg) 8885 Attrs.push_back(Attribute::InReg); 8886 8887 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 8888 Attrs); 8889 } 8890 8891 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 8892 /// implementation, which just calls LowerCall. 8893 /// FIXME: When all targets are 8894 /// migrated to using LowerCall, this hook should be integrated into SDISel. 8895 std::pair<SDValue, SDValue> 8896 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 8897 // Handle the incoming return values from the call. 8898 CLI.Ins.clear(); 8899 Type *OrigRetTy = CLI.RetTy; 8900 SmallVector<EVT, 4> RetTys; 8901 SmallVector<uint64_t, 4> Offsets; 8902 auto &DL = CLI.DAG.getDataLayout(); 8903 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 8904 8905 if (CLI.IsPostTypeLegalization) { 8906 // If we are lowering a libcall after legalization, split the return type. 8907 SmallVector<EVT, 4> OldRetTys; 8908 SmallVector<uint64_t, 4> OldOffsets; 8909 RetTys.swap(OldRetTys); 8910 Offsets.swap(OldOffsets); 8911 8912 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 8913 EVT RetVT = OldRetTys[i]; 8914 uint64_t Offset = OldOffsets[i]; 8915 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 8916 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 8917 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 8918 RetTys.append(NumRegs, RegisterVT); 8919 for (unsigned j = 0; j != NumRegs; ++j) 8920 Offsets.push_back(Offset + j * RegisterVTByteSZ); 8921 } 8922 } 8923 8924 SmallVector<ISD::OutputArg, 4> Outs; 8925 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 8926 8927 bool CanLowerReturn = 8928 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 8929 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 8930 8931 SDValue DemoteStackSlot; 8932 int DemoteStackIdx = -100; 8933 if (!CanLowerReturn) { 8934 // FIXME: equivalent assert? 8935 // assert(!CS.hasInAllocaArgument() && 8936 // "sret demotion is incompatible with inalloca"); 8937 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 8938 unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy); 8939 MachineFunction &MF = CLI.DAG.getMachineFunction(); 8940 DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 8941 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 8942 DL.getAllocaAddrSpace()); 8943 8944 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 8945 ArgListEntry Entry; 8946 Entry.Node = DemoteStackSlot; 8947 Entry.Ty = StackSlotPtrType; 8948 Entry.IsSExt = false; 8949 Entry.IsZExt = false; 8950 Entry.IsInReg = false; 8951 Entry.IsSRet = true; 8952 Entry.IsNest = false; 8953 Entry.IsByVal = false; 8954 Entry.IsReturned = false; 8955 Entry.IsSwiftSelf = false; 8956 Entry.IsSwiftError = false; 8957 Entry.IsCFGuardTarget = false; 8958 Entry.Alignment = Align; 8959 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 8960 CLI.NumFixedArgs += 1; 8961 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 8962 8963 // sret demotion isn't compatible with tail-calls, since the sret argument 8964 // points into the callers stack frame. 8965 CLI.IsTailCall = false; 8966 } else { 8967 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 8968 CLI.RetTy, CLI.CallConv, CLI.IsVarArg); 8969 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 8970 ISD::ArgFlagsTy Flags; 8971 if (NeedsRegBlock) { 8972 Flags.setInConsecutiveRegs(); 8973 if (I == RetTys.size() - 1) 8974 Flags.setInConsecutiveRegsLast(); 8975 } 8976 EVT VT = RetTys[I]; 8977 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 8978 CLI.CallConv, VT); 8979 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 8980 CLI.CallConv, VT); 8981 for (unsigned i = 0; i != NumRegs; ++i) { 8982 ISD::InputArg MyFlags; 8983 MyFlags.Flags = Flags; 8984 MyFlags.VT = RegisterVT; 8985 MyFlags.ArgVT = VT; 8986 MyFlags.Used = CLI.IsReturnValueUsed; 8987 if (CLI.RetTy->isPointerTy()) { 8988 MyFlags.Flags.setPointer(); 8989 MyFlags.Flags.setPointerAddrSpace( 8990 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 8991 } 8992 if (CLI.RetSExt) 8993 MyFlags.Flags.setSExt(); 8994 if (CLI.RetZExt) 8995 MyFlags.Flags.setZExt(); 8996 if (CLI.IsInReg) 8997 MyFlags.Flags.setInReg(); 8998 CLI.Ins.push_back(MyFlags); 8999 } 9000 } 9001 } 9002 9003 // We push in swifterror return as the last element of CLI.Ins. 9004 ArgListTy &Args = CLI.getArgs(); 9005 if (supportSwiftError()) { 9006 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9007 if (Args[i].IsSwiftError) { 9008 ISD::InputArg MyFlags; 9009 MyFlags.VT = getPointerTy(DL); 9010 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9011 MyFlags.Flags.setSwiftError(); 9012 CLI.Ins.push_back(MyFlags); 9013 } 9014 } 9015 } 9016 9017 // Handle all of the outgoing arguments. 9018 CLI.Outs.clear(); 9019 CLI.OutVals.clear(); 9020 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9021 SmallVector<EVT, 4> ValueVTs; 9022 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9023 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9024 Type *FinalType = Args[i].Ty; 9025 if (Args[i].IsByVal) 9026 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 9027 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9028 FinalType, CLI.CallConv, CLI.IsVarArg); 9029 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9030 ++Value) { 9031 EVT VT = ValueVTs[Value]; 9032 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9033 SDValue Op = SDValue(Args[i].Node.getNode(), 9034 Args[i].Node.getResNo() + Value); 9035 ISD::ArgFlagsTy Flags; 9036 9037 // Certain targets (such as MIPS), may have a different ABI alignment 9038 // for a type depending on the context. Give the target a chance to 9039 // specify the alignment it wants. 9040 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 9041 9042 if (Args[i].Ty->isPointerTy()) { 9043 Flags.setPointer(); 9044 Flags.setPointerAddrSpace( 9045 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9046 } 9047 if (Args[i].IsZExt) 9048 Flags.setZExt(); 9049 if (Args[i].IsSExt) 9050 Flags.setSExt(); 9051 if (Args[i].IsInReg) { 9052 // If we are using vectorcall calling convention, a structure that is 9053 // passed InReg - is surely an HVA 9054 if (CLI.CallConv == CallingConv::X86_VectorCall && 9055 isa<StructType>(FinalType)) { 9056 // The first value of a structure is marked 9057 if (0 == Value) 9058 Flags.setHvaStart(); 9059 Flags.setHva(); 9060 } 9061 // Set InReg Flag 9062 Flags.setInReg(); 9063 } 9064 if (Args[i].IsSRet) 9065 Flags.setSRet(); 9066 if (Args[i].IsSwiftSelf) 9067 Flags.setSwiftSelf(); 9068 if (Args[i].IsSwiftError) 9069 Flags.setSwiftError(); 9070 if (Args[i].IsCFGuardTarget) 9071 Flags.setCFGuardTarget(); 9072 if (Args[i].IsByVal) 9073 Flags.setByVal(); 9074 if (Args[i].IsInAlloca) { 9075 Flags.setInAlloca(); 9076 // Set the byval flag for CCAssignFn callbacks that don't know about 9077 // inalloca. This way we can know how many bytes we should've allocated 9078 // and how many bytes a callee cleanup function will pop. If we port 9079 // inalloca to more targets, we'll have to add custom inalloca handling 9080 // in the various CC lowering callbacks. 9081 Flags.setByVal(); 9082 } 9083 if (Args[i].IsByVal || Args[i].IsInAlloca) { 9084 PointerType *Ty = cast<PointerType>(Args[i].Ty); 9085 Type *ElementTy = Ty->getElementType(); 9086 9087 unsigned FrameSize = DL.getTypeAllocSize( 9088 Args[i].ByValType ? Args[i].ByValType : ElementTy); 9089 Flags.setByValSize(FrameSize); 9090 9091 // info is not there but there are cases it cannot get right. 9092 unsigned FrameAlign; 9093 if (Args[i].Alignment) 9094 FrameAlign = Args[i].Alignment; 9095 else 9096 FrameAlign = getByValTypeAlignment(ElementTy, DL); 9097 Flags.setByValAlign(Align(FrameAlign)); 9098 } 9099 if (Args[i].IsNest) 9100 Flags.setNest(); 9101 if (NeedsRegBlock) 9102 Flags.setInConsecutiveRegs(); 9103 Flags.setOrigAlign(OriginalAlignment); 9104 9105 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9106 CLI.CallConv, VT); 9107 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9108 CLI.CallConv, VT); 9109 SmallVector<SDValue, 4> Parts(NumParts); 9110 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9111 9112 if (Args[i].IsSExt) 9113 ExtendKind = ISD::SIGN_EXTEND; 9114 else if (Args[i].IsZExt) 9115 ExtendKind = ISD::ZERO_EXTEND; 9116 9117 // Conservatively only handle 'returned' on non-vectors that can be lowered, 9118 // for now. 9119 if (Args[i].IsReturned && !Op.getValueType().isVector() && 9120 CanLowerReturn) { 9121 assert((CLI.RetTy == Args[i].Ty || 9122 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 9123 CLI.RetTy->getPointerAddressSpace() == 9124 Args[i].Ty->getPointerAddressSpace())) && 9125 RetTys.size() == NumValues && "unexpected use of 'returned'"); 9126 // Before passing 'returned' to the target lowering code, ensure that 9127 // either the register MVT and the actual EVT are the same size or that 9128 // the return value and argument are extended in the same way; in these 9129 // cases it's safe to pass the argument register value unchanged as the 9130 // return register value (although it's at the target's option whether 9131 // to do so) 9132 // TODO: allow code generation to take advantage of partially preserved 9133 // registers rather than clobbering the entire register when the 9134 // parameter extension method is not compatible with the return 9135 // extension method 9136 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9137 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9138 CLI.RetZExt == Args[i].IsZExt)) 9139 Flags.setReturned(); 9140 } 9141 9142 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, 9143 CLI.CS.getInstruction(), CLI.CallConv, ExtendKind); 9144 9145 for (unsigned j = 0; j != NumParts; ++j) { 9146 // if it isn't first piece, alignment must be 1 9147 // For scalable vectors the scalable part is currently handled 9148 // by individual targets, so we just use the known minimum size here. 9149 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 9150 i < CLI.NumFixedArgs, i, 9151 j*Parts[j].getValueType().getStoreSize().getKnownMinSize()); 9152 if (NumParts > 1 && j == 0) 9153 MyFlags.Flags.setSplit(); 9154 else if (j != 0) { 9155 MyFlags.Flags.setOrigAlign(Align::None()); 9156 if (j == NumParts - 1) 9157 MyFlags.Flags.setSplitEnd(); 9158 } 9159 9160 CLI.Outs.push_back(MyFlags); 9161 CLI.OutVals.push_back(Parts[j]); 9162 } 9163 9164 if (NeedsRegBlock && Value == NumValues - 1) 9165 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 9166 } 9167 } 9168 9169 SmallVector<SDValue, 4> InVals; 9170 CLI.Chain = LowerCall(CLI, InVals); 9171 9172 // Update CLI.InVals to use outside of this function. 9173 CLI.InVals = InVals; 9174 9175 // Verify that the target's LowerCall behaved as expected. 9176 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 9177 "LowerCall didn't return a valid chain!"); 9178 assert((!CLI.IsTailCall || InVals.empty()) && 9179 "LowerCall emitted a return value for a tail call!"); 9180 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9181 "LowerCall didn't emit the correct number of values!"); 9182 9183 // For a tail call, the return value is merely live-out and there aren't 9184 // any nodes in the DAG representing it. Return a special value to 9185 // indicate that a tail call has been emitted and no more Instructions 9186 // should be processed in the current block. 9187 if (CLI.IsTailCall) { 9188 CLI.DAG.setRoot(CLI.Chain); 9189 return std::make_pair(SDValue(), SDValue()); 9190 } 9191 9192 #ifndef NDEBUG 9193 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 9194 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 9195 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 9196 "LowerCall emitted a value with the wrong type!"); 9197 } 9198 #endif 9199 9200 SmallVector<SDValue, 4> ReturnValues; 9201 if (!CanLowerReturn) { 9202 // The instruction result is the result of loading from the 9203 // hidden sret parameter. 9204 SmallVector<EVT, 1> PVTs; 9205 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 9206 9207 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 9208 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 9209 EVT PtrVT = PVTs[0]; 9210 9211 unsigned NumValues = RetTys.size(); 9212 ReturnValues.resize(NumValues); 9213 SmallVector<SDValue, 4> Chains(NumValues); 9214 9215 // An aggregate return value cannot wrap around the address space, so 9216 // offsets to its parts don't wrap either. 9217 SDNodeFlags Flags; 9218 Flags.setNoUnsignedWrap(true); 9219 9220 for (unsigned i = 0; i < NumValues; ++i) { 9221 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 9222 CLI.DAG.getConstant(Offsets[i], CLI.DL, 9223 PtrVT), Flags); 9224 SDValue L = CLI.DAG.getLoad( 9225 RetTys[i], CLI.DL, CLI.Chain, Add, 9226 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 9227 DemoteStackIdx, Offsets[i]), 9228 /* Alignment = */ 1); 9229 ReturnValues[i] = L; 9230 Chains[i] = L.getValue(1); 9231 } 9232 9233 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 9234 } else { 9235 // Collect the legal value parts into potentially illegal values 9236 // that correspond to the original function's return values. 9237 Optional<ISD::NodeType> AssertOp; 9238 if (CLI.RetSExt) 9239 AssertOp = ISD::AssertSext; 9240 else if (CLI.RetZExt) 9241 AssertOp = ISD::AssertZext; 9242 unsigned CurReg = 0; 9243 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9244 EVT VT = RetTys[I]; 9245 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9246 CLI.CallConv, VT); 9247 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9248 CLI.CallConv, VT); 9249 9250 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 9251 NumRegs, RegisterVT, VT, nullptr, 9252 CLI.CallConv, AssertOp)); 9253 CurReg += NumRegs; 9254 } 9255 9256 // For a function returning void, there is no return value. We can't create 9257 // such a node, so we just return a null return value in that case. In 9258 // that case, nothing will actually look at the value. 9259 if (ReturnValues.empty()) 9260 return std::make_pair(SDValue(), CLI.Chain); 9261 } 9262 9263 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 9264 CLI.DAG.getVTList(RetTys), ReturnValues); 9265 return std::make_pair(Res, CLI.Chain); 9266 } 9267 9268 void TargetLowering::LowerOperationWrapper(SDNode *N, 9269 SmallVectorImpl<SDValue> &Results, 9270 SelectionDAG &DAG) const { 9271 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG)) 9272 Results.push_back(Res); 9273 } 9274 9275 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9276 llvm_unreachable("LowerOperation not implemented for this target!"); 9277 } 9278 9279 void 9280 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 9281 SDValue Op = getNonRegisterValue(V); 9282 assert((Op.getOpcode() != ISD::CopyFromReg || 9283 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 9284 "Copy from a reg to the same reg!"); 9285 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 9286 9287 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9288 // If this is an InlineAsm we have to match the registers required, not the 9289 // notional registers required by the type. 9290 9291 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 9292 None); // This is not an ABI copy. 9293 SDValue Chain = DAG.getEntryNode(); 9294 9295 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 9296 FuncInfo.PreferredExtendType.end()) 9297 ? ISD::ANY_EXTEND 9298 : FuncInfo.PreferredExtendType[V]; 9299 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 9300 PendingExports.push_back(Chain); 9301 } 9302 9303 #include "llvm/CodeGen/SelectionDAGISel.h" 9304 9305 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 9306 /// entry block, return true. This includes arguments used by switches, since 9307 /// the switch may expand into multiple basic blocks. 9308 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 9309 // With FastISel active, we may be splitting blocks, so force creation 9310 // of virtual registers for all non-dead arguments. 9311 if (FastISel) 9312 return A->use_empty(); 9313 9314 const BasicBlock &Entry = A->getParent()->front(); 9315 for (const User *U : A->users()) 9316 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 9317 return false; // Use not in entry block. 9318 9319 return true; 9320 } 9321 9322 using ArgCopyElisionMapTy = 9323 DenseMap<const Argument *, 9324 std::pair<const AllocaInst *, const StoreInst *>>; 9325 9326 /// Scan the entry block of the function in FuncInfo for arguments that look 9327 /// like copies into a local alloca. Record any copied arguments in 9328 /// ArgCopyElisionCandidates. 9329 static void 9330 findArgumentCopyElisionCandidates(const DataLayout &DL, 9331 FunctionLoweringInfo *FuncInfo, 9332 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 9333 // Record the state of every static alloca used in the entry block. Argument 9334 // allocas are all used in the entry block, so we need approximately as many 9335 // entries as we have arguments. 9336 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 9337 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 9338 unsigned NumArgs = FuncInfo->Fn->arg_size(); 9339 StaticAllocas.reserve(NumArgs * 2); 9340 9341 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 9342 if (!V) 9343 return nullptr; 9344 V = V->stripPointerCasts(); 9345 const auto *AI = dyn_cast<AllocaInst>(V); 9346 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 9347 return nullptr; 9348 auto Iter = StaticAllocas.insert({AI, Unknown}); 9349 return &Iter.first->second; 9350 }; 9351 9352 // Look for stores of arguments to static allocas. Look through bitcasts and 9353 // GEPs to handle type coercions, as long as the alloca is fully initialized 9354 // by the store. Any non-store use of an alloca escapes it and any subsequent 9355 // unanalyzed store might write it. 9356 // FIXME: Handle structs initialized with multiple stores. 9357 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 9358 // Look for stores, and handle non-store uses conservatively. 9359 const auto *SI = dyn_cast<StoreInst>(&I); 9360 if (!SI) { 9361 // We will look through cast uses, so ignore them completely. 9362 if (I.isCast()) 9363 continue; 9364 // Ignore debug info intrinsics, they don't escape or store to allocas. 9365 if (isa<DbgInfoIntrinsic>(I)) 9366 continue; 9367 // This is an unknown instruction. Assume it escapes or writes to all 9368 // static alloca operands. 9369 for (const Use &U : I.operands()) { 9370 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 9371 *Info = StaticAllocaInfo::Clobbered; 9372 } 9373 continue; 9374 } 9375 9376 // If the stored value is a static alloca, mark it as escaped. 9377 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 9378 *Info = StaticAllocaInfo::Clobbered; 9379 9380 // Check if the destination is a static alloca. 9381 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 9382 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 9383 if (!Info) 9384 continue; 9385 const AllocaInst *AI = cast<AllocaInst>(Dst); 9386 9387 // Skip allocas that have been initialized or clobbered. 9388 if (*Info != StaticAllocaInfo::Unknown) 9389 continue; 9390 9391 // Check if the stored value is an argument, and that this store fully 9392 // initializes the alloca. Don't elide copies from the same argument twice. 9393 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 9394 const auto *Arg = dyn_cast<Argument>(Val); 9395 if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() || 9396 Arg->getType()->isEmptyTy() || 9397 DL.getTypeStoreSize(Arg->getType()) != 9398 DL.getTypeAllocSize(AI->getAllocatedType()) || 9399 ArgCopyElisionCandidates.count(Arg)) { 9400 *Info = StaticAllocaInfo::Clobbered; 9401 continue; 9402 } 9403 9404 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 9405 << '\n'); 9406 9407 // Mark this alloca and store for argument copy elision. 9408 *Info = StaticAllocaInfo::Elidable; 9409 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 9410 9411 // Stop scanning if we've seen all arguments. This will happen early in -O0 9412 // builds, which is useful, because -O0 builds have large entry blocks and 9413 // many allocas. 9414 if (ArgCopyElisionCandidates.size() == NumArgs) 9415 break; 9416 } 9417 } 9418 9419 /// Try to elide argument copies from memory into a local alloca. Succeeds if 9420 /// ArgVal is a load from a suitable fixed stack object. 9421 static void tryToElideArgumentCopy( 9422 FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains, 9423 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 9424 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 9425 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 9426 SDValue ArgVal, bool &ArgHasUses) { 9427 // Check if this is a load from a fixed stack object. 9428 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 9429 if (!LNode) 9430 return; 9431 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 9432 if (!FINode) 9433 return; 9434 9435 // Check that the fixed stack object is the right size and alignment. 9436 // Look at the alignment that the user wrote on the alloca instead of looking 9437 // at the stack object. 9438 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 9439 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 9440 const AllocaInst *AI = ArgCopyIter->second.first; 9441 int FixedIndex = FINode->getIndex(); 9442 int &AllocaIndex = FuncInfo->StaticAllocaMap[AI]; 9443 int OldIndex = AllocaIndex; 9444 MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo(); 9445 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 9446 LLVM_DEBUG( 9447 dbgs() << " argument copy elision failed due to bad fixed stack " 9448 "object size\n"); 9449 return; 9450 } 9451 unsigned RequiredAlignment = AI->getAlignment(); 9452 if (!RequiredAlignment) { 9453 RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment( 9454 AI->getAllocatedType()); 9455 } 9456 if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) { 9457 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 9458 "greater than stack argument alignment (" 9459 << RequiredAlignment << " vs " 9460 << MFI.getObjectAlignment(FixedIndex) << ")\n"); 9461 return; 9462 } 9463 9464 // Perform the elision. Delete the old stack object and replace its only use 9465 // in the variable info map. Mark the stack object as mutable. 9466 LLVM_DEBUG({ 9467 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 9468 << " Replacing frame index " << OldIndex << " with " << FixedIndex 9469 << '\n'; 9470 }); 9471 MFI.RemoveStackObject(OldIndex); 9472 MFI.setIsImmutableObjectIndex(FixedIndex, false); 9473 AllocaIndex = FixedIndex; 9474 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 9475 Chains.push_back(ArgVal.getValue(1)); 9476 9477 // Avoid emitting code for the store implementing the copy. 9478 const StoreInst *SI = ArgCopyIter->second.second; 9479 ElidedArgCopyInstrs.insert(SI); 9480 9481 // Check for uses of the argument again so that we can avoid exporting ArgVal 9482 // if it is't used by anything other than the store. 9483 for (const Value *U : Arg.users()) { 9484 if (U != SI) { 9485 ArgHasUses = true; 9486 break; 9487 } 9488 } 9489 } 9490 9491 void SelectionDAGISel::LowerArguments(const Function &F) { 9492 SelectionDAG &DAG = SDB->DAG; 9493 SDLoc dl = SDB->getCurSDLoc(); 9494 const DataLayout &DL = DAG.getDataLayout(); 9495 SmallVector<ISD::InputArg, 16> Ins; 9496 9497 if (!FuncInfo->CanLowerReturn) { 9498 // Put in an sret pointer parameter before all the other parameters. 9499 SmallVector<EVT, 1> ValueVTs; 9500 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9501 F.getReturnType()->getPointerTo( 9502 DAG.getDataLayout().getAllocaAddrSpace()), 9503 ValueVTs); 9504 9505 // NOTE: Assuming that a pointer will never break down to more than one VT 9506 // or one register. 9507 ISD::ArgFlagsTy Flags; 9508 Flags.setSRet(); 9509 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 9510 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 9511 ISD::InputArg::NoArgIndex, 0); 9512 Ins.push_back(RetArg); 9513 } 9514 9515 // Look for stores of arguments to static allocas. Mark such arguments with a 9516 // flag to ask the target to give us the memory location of that argument if 9517 // available. 9518 ArgCopyElisionMapTy ArgCopyElisionCandidates; 9519 findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates); 9520 9521 // Set up the incoming argument description vector. 9522 for (const Argument &Arg : F.args()) { 9523 unsigned ArgNo = Arg.getArgNo(); 9524 SmallVector<EVT, 4> ValueVTs; 9525 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9526 bool isArgValueUsed = !Arg.use_empty(); 9527 unsigned PartBase = 0; 9528 Type *FinalType = Arg.getType(); 9529 if (Arg.hasAttribute(Attribute::ByVal)) 9530 FinalType = Arg.getParamByValType(); 9531 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 9532 FinalType, F.getCallingConv(), F.isVarArg()); 9533 for (unsigned Value = 0, NumValues = ValueVTs.size(); 9534 Value != NumValues; ++Value) { 9535 EVT VT = ValueVTs[Value]; 9536 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 9537 ISD::ArgFlagsTy Flags; 9538 9539 // Certain targets (such as MIPS), may have a different ABI alignment 9540 // for a type depending on the context. Give the target a chance to 9541 // specify the alignment it wants. 9542 const Align OriginalAlignment( 9543 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 9544 9545 if (Arg.getType()->isPointerTy()) { 9546 Flags.setPointer(); 9547 Flags.setPointerAddrSpace( 9548 cast<PointerType>(Arg.getType())->getAddressSpace()); 9549 } 9550 if (Arg.hasAttribute(Attribute::ZExt)) 9551 Flags.setZExt(); 9552 if (Arg.hasAttribute(Attribute::SExt)) 9553 Flags.setSExt(); 9554 if (Arg.hasAttribute(Attribute::InReg)) { 9555 // If we are using vectorcall calling convention, a structure that is 9556 // passed InReg - is surely an HVA 9557 if (F.getCallingConv() == CallingConv::X86_VectorCall && 9558 isa<StructType>(Arg.getType())) { 9559 // The first value of a structure is marked 9560 if (0 == Value) 9561 Flags.setHvaStart(); 9562 Flags.setHva(); 9563 } 9564 // Set InReg Flag 9565 Flags.setInReg(); 9566 } 9567 if (Arg.hasAttribute(Attribute::StructRet)) 9568 Flags.setSRet(); 9569 if (Arg.hasAttribute(Attribute::SwiftSelf)) 9570 Flags.setSwiftSelf(); 9571 if (Arg.hasAttribute(Attribute::SwiftError)) 9572 Flags.setSwiftError(); 9573 if (Arg.hasAttribute(Attribute::ByVal)) 9574 Flags.setByVal(); 9575 if (Arg.hasAttribute(Attribute::InAlloca)) { 9576 Flags.setInAlloca(); 9577 // Set the byval flag for CCAssignFn callbacks that don't know about 9578 // inalloca. This way we can know how many bytes we should've allocated 9579 // and how many bytes a callee cleanup function will pop. If we port 9580 // inalloca to more targets, we'll have to add custom inalloca handling 9581 // in the various CC lowering callbacks. 9582 Flags.setByVal(); 9583 } 9584 if (F.getCallingConv() == CallingConv::X86_INTR) { 9585 // IA Interrupt passes frame (1st parameter) by value in the stack. 9586 if (ArgNo == 0) 9587 Flags.setByVal(); 9588 } 9589 if (Flags.isByVal() || Flags.isInAlloca()) { 9590 Type *ElementTy = Arg.getParamByValType(); 9591 9592 // For ByVal, size and alignment should be passed from FE. BE will 9593 // guess if this info is not there but there are cases it cannot get 9594 // right. 9595 unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType()); 9596 Flags.setByValSize(FrameSize); 9597 9598 unsigned FrameAlign; 9599 if (Arg.getParamAlignment()) 9600 FrameAlign = Arg.getParamAlignment(); 9601 else 9602 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL); 9603 Flags.setByValAlign(Align(FrameAlign)); 9604 } 9605 if (Arg.hasAttribute(Attribute::Nest)) 9606 Flags.setNest(); 9607 if (NeedsRegBlock) 9608 Flags.setInConsecutiveRegs(); 9609 Flags.setOrigAlign(OriginalAlignment); 9610 if (ArgCopyElisionCandidates.count(&Arg)) 9611 Flags.setCopyElisionCandidate(); 9612 if (Arg.hasAttribute(Attribute::Returned)) 9613 Flags.setReturned(); 9614 9615 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 9616 *CurDAG->getContext(), F.getCallingConv(), VT); 9617 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 9618 *CurDAG->getContext(), F.getCallingConv(), VT); 9619 for (unsigned i = 0; i != NumRegs; ++i) { 9620 // For scalable vectors, use the minimum size; individual targets 9621 // are responsible for handling scalable vector arguments and 9622 // return values. 9623 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 9624 ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize()); 9625 if (NumRegs > 1 && i == 0) 9626 MyFlags.Flags.setSplit(); 9627 // if it isn't first piece, alignment must be 1 9628 else if (i > 0) { 9629 MyFlags.Flags.setOrigAlign(Align::None()); 9630 if (i == NumRegs - 1) 9631 MyFlags.Flags.setSplitEnd(); 9632 } 9633 Ins.push_back(MyFlags); 9634 } 9635 if (NeedsRegBlock && Value == NumValues - 1) 9636 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 9637 PartBase += VT.getStoreSize().getKnownMinSize(); 9638 } 9639 } 9640 9641 // Call the target to set up the argument values. 9642 SmallVector<SDValue, 8> InVals; 9643 SDValue NewRoot = TLI->LowerFormalArguments( 9644 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 9645 9646 // Verify that the target's LowerFormalArguments behaved as expected. 9647 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 9648 "LowerFormalArguments didn't return a valid chain!"); 9649 assert(InVals.size() == Ins.size() && 9650 "LowerFormalArguments didn't emit the correct number of values!"); 9651 LLVM_DEBUG({ 9652 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 9653 assert(InVals[i].getNode() && 9654 "LowerFormalArguments emitted a null value!"); 9655 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 9656 "LowerFormalArguments emitted a value with the wrong type!"); 9657 } 9658 }); 9659 9660 // Update the DAG with the new chain value resulting from argument lowering. 9661 DAG.setRoot(NewRoot); 9662 9663 // Set up the argument values. 9664 unsigned i = 0; 9665 if (!FuncInfo->CanLowerReturn) { 9666 // Create a virtual register for the sret pointer, and put in a copy 9667 // from the sret argument into it. 9668 SmallVector<EVT, 1> ValueVTs; 9669 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9670 F.getReturnType()->getPointerTo( 9671 DAG.getDataLayout().getAllocaAddrSpace()), 9672 ValueVTs); 9673 MVT VT = ValueVTs[0].getSimpleVT(); 9674 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 9675 Optional<ISD::NodeType> AssertOp = None; 9676 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 9677 nullptr, F.getCallingConv(), AssertOp); 9678 9679 MachineFunction& MF = SDB->DAG.getMachineFunction(); 9680 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 9681 Register SRetReg = 9682 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 9683 FuncInfo->DemoteRegister = SRetReg; 9684 NewRoot = 9685 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 9686 DAG.setRoot(NewRoot); 9687 9688 // i indexes lowered arguments. Bump it past the hidden sret argument. 9689 ++i; 9690 } 9691 9692 SmallVector<SDValue, 4> Chains; 9693 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 9694 for (const Argument &Arg : F.args()) { 9695 SmallVector<SDValue, 4> ArgValues; 9696 SmallVector<EVT, 4> ValueVTs; 9697 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9698 unsigned NumValues = ValueVTs.size(); 9699 if (NumValues == 0) 9700 continue; 9701 9702 bool ArgHasUses = !Arg.use_empty(); 9703 9704 // Elide the copying store if the target loaded this argument from a 9705 // suitable fixed stack object. 9706 if (Ins[i].Flags.isCopyElisionCandidate()) { 9707 tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 9708 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 9709 InVals[i], ArgHasUses); 9710 } 9711 9712 // If this argument is unused then remember its value. It is used to generate 9713 // debugging information. 9714 bool isSwiftErrorArg = 9715 TLI->supportSwiftError() && 9716 Arg.hasAttribute(Attribute::SwiftError); 9717 if (!ArgHasUses && !isSwiftErrorArg) { 9718 SDB->setUnusedArgValue(&Arg, InVals[i]); 9719 9720 // Also remember any frame index for use in FastISel. 9721 if (FrameIndexSDNode *FI = 9722 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 9723 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9724 } 9725 9726 for (unsigned Val = 0; Val != NumValues; ++Val) { 9727 EVT VT = ValueVTs[Val]; 9728 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 9729 F.getCallingConv(), VT); 9730 unsigned NumParts = TLI->getNumRegistersForCallingConv( 9731 *CurDAG->getContext(), F.getCallingConv(), VT); 9732 9733 // Even an apparent 'unused' swifterror argument needs to be returned. So 9734 // we do generate a copy for it that can be used on return from the 9735 // function. 9736 if (ArgHasUses || isSwiftErrorArg) { 9737 Optional<ISD::NodeType> AssertOp; 9738 if (Arg.hasAttribute(Attribute::SExt)) 9739 AssertOp = ISD::AssertSext; 9740 else if (Arg.hasAttribute(Attribute::ZExt)) 9741 AssertOp = ISD::AssertZext; 9742 9743 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 9744 PartVT, VT, nullptr, 9745 F.getCallingConv(), AssertOp)); 9746 } 9747 9748 i += NumParts; 9749 } 9750 9751 // We don't need to do anything else for unused arguments. 9752 if (ArgValues.empty()) 9753 continue; 9754 9755 // Note down frame index. 9756 if (FrameIndexSDNode *FI = 9757 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 9758 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9759 9760 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 9761 SDB->getCurSDLoc()); 9762 9763 SDB->setValue(&Arg, Res); 9764 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 9765 // We want to associate the argument with the frame index, among 9766 // involved operands, that correspond to the lowest address. The 9767 // getCopyFromParts function, called earlier, is swapping the order of 9768 // the operands to BUILD_PAIR depending on endianness. The result of 9769 // that swapping is that the least significant bits of the argument will 9770 // be in the first operand of the BUILD_PAIR node, and the most 9771 // significant bits will be in the second operand. 9772 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 9773 if (LoadSDNode *LNode = 9774 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 9775 if (FrameIndexSDNode *FI = 9776 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 9777 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9778 } 9779 9780 // Analyses past this point are naive and don't expect an assertion. 9781 if (Res.getOpcode() == ISD::AssertZext) 9782 Res = Res.getOperand(0); 9783 9784 // Update the SwiftErrorVRegDefMap. 9785 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 9786 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9787 if (Register::isVirtualRegister(Reg)) 9788 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 9789 Reg); 9790 } 9791 9792 // If this argument is live outside of the entry block, insert a copy from 9793 // wherever we got it to the vreg that other BB's will reference it as. 9794 if (Res.getOpcode() == ISD::CopyFromReg) { 9795 // If we can, though, try to skip creating an unnecessary vreg. 9796 // FIXME: This isn't very clean... it would be nice to make this more 9797 // general. 9798 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9799 if (Register::isVirtualRegister(Reg)) { 9800 FuncInfo->ValueMap[&Arg] = Reg; 9801 continue; 9802 } 9803 } 9804 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 9805 FuncInfo->InitializeRegForValue(&Arg); 9806 SDB->CopyToExportRegsIfNeeded(&Arg); 9807 } 9808 } 9809 9810 if (!Chains.empty()) { 9811 Chains.push_back(NewRoot); 9812 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 9813 } 9814 9815 DAG.setRoot(NewRoot); 9816 9817 assert(i == InVals.size() && "Argument register count mismatch!"); 9818 9819 // If any argument copy elisions occurred and we have debug info, update the 9820 // stale frame indices used in the dbg.declare variable info table. 9821 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 9822 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 9823 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 9824 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 9825 if (I != ArgCopyElisionFrameIndexMap.end()) 9826 VI.Slot = I->second; 9827 } 9828 } 9829 9830 // Finally, if the target has anything special to do, allow it to do so. 9831 EmitFunctionEntryCode(); 9832 } 9833 9834 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 9835 /// ensure constants are generated when needed. Remember the virtual registers 9836 /// that need to be added to the Machine PHI nodes as input. We cannot just 9837 /// directly add them, because expansion might result in multiple MBB's for one 9838 /// BB. As such, the start of the BB might correspond to a different MBB than 9839 /// the end. 9840 void 9841 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 9842 const Instruction *TI = LLVMBB->getTerminator(); 9843 9844 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 9845 9846 // Check PHI nodes in successors that expect a value to be available from this 9847 // block. 9848 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 9849 const BasicBlock *SuccBB = TI->getSuccessor(succ); 9850 if (!isa<PHINode>(SuccBB->begin())) continue; 9851 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 9852 9853 // If this terminator has multiple identical successors (common for 9854 // switches), only handle each succ once. 9855 if (!SuccsHandled.insert(SuccMBB).second) 9856 continue; 9857 9858 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 9859 9860 // At this point we know that there is a 1-1 correspondence between LLVM PHI 9861 // nodes and Machine PHI nodes, but the incoming operands have not been 9862 // emitted yet. 9863 for (const PHINode &PN : SuccBB->phis()) { 9864 // Ignore dead phi's. 9865 if (PN.use_empty()) 9866 continue; 9867 9868 // Skip empty types 9869 if (PN.getType()->isEmptyTy()) 9870 continue; 9871 9872 unsigned Reg; 9873 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 9874 9875 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 9876 unsigned &RegOut = ConstantsOut[C]; 9877 if (RegOut == 0) { 9878 RegOut = FuncInfo.CreateRegs(C); 9879 CopyValueToVirtualRegister(C, RegOut); 9880 } 9881 Reg = RegOut; 9882 } else { 9883 DenseMap<const Value *, unsigned>::iterator I = 9884 FuncInfo.ValueMap.find(PHIOp); 9885 if (I != FuncInfo.ValueMap.end()) 9886 Reg = I->second; 9887 else { 9888 assert(isa<AllocaInst>(PHIOp) && 9889 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 9890 "Didn't codegen value into a register!??"); 9891 Reg = FuncInfo.CreateRegs(PHIOp); 9892 CopyValueToVirtualRegister(PHIOp, Reg); 9893 } 9894 } 9895 9896 // Remember that this register needs to added to the machine PHI node as 9897 // the input for this MBB. 9898 SmallVector<EVT, 4> ValueVTs; 9899 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9900 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 9901 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 9902 EVT VT = ValueVTs[vti]; 9903 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 9904 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 9905 FuncInfo.PHINodesToUpdate.push_back( 9906 std::make_pair(&*MBBI++, Reg + i)); 9907 Reg += NumRegisters; 9908 } 9909 } 9910 } 9911 9912 ConstantsOut.clear(); 9913 } 9914 9915 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 9916 /// is 0. 9917 MachineBasicBlock * 9918 SelectionDAGBuilder::StackProtectorDescriptor:: 9919 AddSuccessorMBB(const BasicBlock *BB, 9920 MachineBasicBlock *ParentMBB, 9921 bool IsLikely, 9922 MachineBasicBlock *SuccMBB) { 9923 // If SuccBB has not been created yet, create it. 9924 if (!SuccMBB) { 9925 MachineFunction *MF = ParentMBB->getParent(); 9926 MachineFunction::iterator BBI(ParentMBB); 9927 SuccMBB = MF->CreateMachineBasicBlock(BB); 9928 MF->insert(++BBI, SuccMBB); 9929 } 9930 // Add it as a successor of ParentMBB. 9931 ParentMBB->addSuccessor( 9932 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 9933 return SuccMBB; 9934 } 9935 9936 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 9937 MachineFunction::iterator I(MBB); 9938 if (++I == FuncInfo.MF->end()) 9939 return nullptr; 9940 return &*I; 9941 } 9942 9943 /// During lowering new call nodes can be created (such as memset, etc.). 9944 /// Those will become new roots of the current DAG, but complications arise 9945 /// when they are tail calls. In such cases, the call lowering will update 9946 /// the root, but the builder still needs to know that a tail call has been 9947 /// lowered in order to avoid generating an additional return. 9948 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 9949 // If the node is null, we do have a tail call. 9950 if (MaybeTC.getNode() != nullptr) 9951 DAG.setRoot(MaybeTC); 9952 else 9953 HasTailCall = true; 9954 } 9955 9956 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 9957 MachineBasicBlock *SwitchMBB, 9958 MachineBasicBlock *DefaultMBB) { 9959 MachineFunction *CurMF = FuncInfo.MF; 9960 MachineBasicBlock *NextMBB = nullptr; 9961 MachineFunction::iterator BBI(W.MBB); 9962 if (++BBI != FuncInfo.MF->end()) 9963 NextMBB = &*BBI; 9964 9965 unsigned Size = W.LastCluster - W.FirstCluster + 1; 9966 9967 BranchProbabilityInfo *BPI = FuncInfo.BPI; 9968 9969 if (Size == 2 && W.MBB == SwitchMBB) { 9970 // If any two of the cases has the same destination, and if one value 9971 // is the same as the other, but has one bit unset that the other has set, 9972 // use bit manipulation to do two compares at once. For example: 9973 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 9974 // TODO: This could be extended to merge any 2 cases in switches with 3 9975 // cases. 9976 // TODO: Handle cases where W.CaseBB != SwitchBB. 9977 CaseCluster &Small = *W.FirstCluster; 9978 CaseCluster &Big = *W.LastCluster; 9979 9980 if (Small.Low == Small.High && Big.Low == Big.High && 9981 Small.MBB == Big.MBB) { 9982 const APInt &SmallValue = Small.Low->getValue(); 9983 const APInt &BigValue = Big.Low->getValue(); 9984 9985 // Check that there is only one bit different. 9986 APInt CommonBit = BigValue ^ SmallValue; 9987 if (CommonBit.isPowerOf2()) { 9988 SDValue CondLHS = getValue(Cond); 9989 EVT VT = CondLHS.getValueType(); 9990 SDLoc DL = getCurSDLoc(); 9991 9992 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 9993 DAG.getConstant(CommonBit, DL, VT)); 9994 SDValue Cond = DAG.getSetCC( 9995 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 9996 ISD::SETEQ); 9997 9998 // Update successor info. 9999 // Both Small and Big will jump to Small.BB, so we sum up the 10000 // probabilities. 10001 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10002 if (BPI) 10003 addSuccessorWithProb( 10004 SwitchMBB, DefaultMBB, 10005 // The default destination is the first successor in IR. 10006 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10007 else 10008 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10009 10010 // Insert the true branch. 10011 SDValue BrCond = 10012 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10013 DAG.getBasicBlock(Small.MBB)); 10014 // Insert the false branch. 10015 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10016 DAG.getBasicBlock(DefaultMBB)); 10017 10018 DAG.setRoot(BrCond); 10019 return; 10020 } 10021 } 10022 } 10023 10024 if (TM.getOptLevel() != CodeGenOpt::None) { 10025 // Here, we order cases by probability so the most likely case will be 10026 // checked first. However, two clusters can have the same probability in 10027 // which case their relative ordering is non-deterministic. So we use Low 10028 // as a tie-breaker as clusters are guaranteed to never overlap. 10029 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10030 [](const CaseCluster &a, const CaseCluster &b) { 10031 return a.Prob != b.Prob ? 10032 a.Prob > b.Prob : 10033 a.Low->getValue().slt(b.Low->getValue()); 10034 }); 10035 10036 // Rearrange the case blocks so that the last one falls through if possible 10037 // without changing the order of probabilities. 10038 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10039 --I; 10040 if (I->Prob > W.LastCluster->Prob) 10041 break; 10042 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10043 std::swap(*I, *W.LastCluster); 10044 break; 10045 } 10046 } 10047 } 10048 10049 // Compute total probability. 10050 BranchProbability DefaultProb = W.DefaultProb; 10051 BranchProbability UnhandledProbs = DefaultProb; 10052 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10053 UnhandledProbs += I->Prob; 10054 10055 MachineBasicBlock *CurMBB = W.MBB; 10056 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10057 bool FallthroughUnreachable = false; 10058 MachineBasicBlock *Fallthrough; 10059 if (I == W.LastCluster) { 10060 // For the last cluster, fall through to the default destination. 10061 Fallthrough = DefaultMBB; 10062 FallthroughUnreachable = isa<UnreachableInst>( 10063 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10064 } else { 10065 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10066 CurMF->insert(BBI, Fallthrough); 10067 // Put Cond in a virtual register to make it available from the new blocks. 10068 ExportFromCurrentBlock(Cond); 10069 } 10070 UnhandledProbs -= I->Prob; 10071 10072 switch (I->Kind) { 10073 case CC_JumpTable: { 10074 // FIXME: Optimize away range check based on pivot comparisons. 10075 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 10076 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 10077 10078 // The jump block hasn't been inserted yet; insert it here. 10079 MachineBasicBlock *JumpMBB = JT->MBB; 10080 CurMF->insert(BBI, JumpMBB); 10081 10082 auto JumpProb = I->Prob; 10083 auto FallthroughProb = UnhandledProbs; 10084 10085 // If the default statement is a target of the jump table, we evenly 10086 // distribute the default probability to successors of CurMBB. Also 10087 // update the probability on the edge from JumpMBB to Fallthrough. 10088 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10089 SE = JumpMBB->succ_end(); 10090 SI != SE; ++SI) { 10091 if (*SI == DefaultMBB) { 10092 JumpProb += DefaultProb / 2; 10093 FallthroughProb -= DefaultProb / 2; 10094 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10095 JumpMBB->normalizeSuccProbs(); 10096 break; 10097 } 10098 } 10099 10100 if (FallthroughUnreachable) { 10101 // Skip the range check if the fallthrough block is unreachable. 10102 JTH->OmitRangeCheck = true; 10103 } 10104 10105 if (!JTH->OmitRangeCheck) 10106 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10107 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10108 CurMBB->normalizeSuccProbs(); 10109 10110 // The jump table header will be inserted in our current block, do the 10111 // range check, and fall through to our fallthrough block. 10112 JTH->HeaderBB = CurMBB; 10113 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10114 10115 // If we're in the right place, emit the jump table header right now. 10116 if (CurMBB == SwitchMBB) { 10117 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10118 JTH->Emitted = true; 10119 } 10120 break; 10121 } 10122 case CC_BitTests: { 10123 // FIXME: Optimize away range check based on pivot comparisons. 10124 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 10125 10126 // The bit test blocks haven't been inserted yet; insert them here. 10127 for (BitTestCase &BTC : BTB->Cases) 10128 CurMF->insert(BBI, BTC.ThisBB); 10129 10130 // Fill in fields of the BitTestBlock. 10131 BTB->Parent = CurMBB; 10132 BTB->Default = Fallthrough; 10133 10134 BTB->DefaultProb = UnhandledProbs; 10135 // If the cases in bit test don't form a contiguous range, we evenly 10136 // distribute the probability on the edge to Fallthrough to two 10137 // successors of CurMBB. 10138 if (!BTB->ContiguousRange) { 10139 BTB->Prob += DefaultProb / 2; 10140 BTB->DefaultProb -= DefaultProb / 2; 10141 } 10142 10143 if (FallthroughUnreachable) { 10144 // Skip the range check if the fallthrough block is unreachable. 10145 BTB->OmitRangeCheck = true; 10146 } 10147 10148 // If we're in the right place, emit the bit test header right now. 10149 if (CurMBB == SwitchMBB) { 10150 visitBitTestHeader(*BTB, SwitchMBB); 10151 BTB->Emitted = true; 10152 } 10153 break; 10154 } 10155 case CC_Range: { 10156 const Value *RHS, *LHS, *MHS; 10157 ISD::CondCode CC; 10158 if (I->Low == I->High) { 10159 // Check Cond == I->Low. 10160 CC = ISD::SETEQ; 10161 LHS = Cond; 10162 RHS=I->Low; 10163 MHS = nullptr; 10164 } else { 10165 // Check I->Low <= Cond <= I->High. 10166 CC = ISD::SETLE; 10167 LHS = I->Low; 10168 MHS = Cond; 10169 RHS = I->High; 10170 } 10171 10172 // If Fallthrough is unreachable, fold away the comparison. 10173 if (FallthroughUnreachable) 10174 CC = ISD::SETTRUE; 10175 10176 // The false probability is the sum of all unhandled cases. 10177 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10178 getCurSDLoc(), I->Prob, UnhandledProbs); 10179 10180 if (CurMBB == SwitchMBB) 10181 visitSwitchCase(CB, SwitchMBB); 10182 else 10183 SL->SwitchCases.push_back(CB); 10184 10185 break; 10186 } 10187 } 10188 CurMBB = Fallthrough; 10189 } 10190 } 10191 10192 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10193 CaseClusterIt First, 10194 CaseClusterIt Last) { 10195 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10196 if (X.Prob != CC.Prob) 10197 return X.Prob > CC.Prob; 10198 10199 // Ties are broken by comparing the case value. 10200 return X.Low->getValue().slt(CC.Low->getValue()); 10201 }); 10202 } 10203 10204 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10205 const SwitchWorkListItem &W, 10206 Value *Cond, 10207 MachineBasicBlock *SwitchMBB) { 10208 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10209 "Clusters not sorted?"); 10210 10211 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10212 10213 // Balance the tree based on branch probabilities to create a near-optimal (in 10214 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10215 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10216 CaseClusterIt LastLeft = W.FirstCluster; 10217 CaseClusterIt FirstRight = W.LastCluster; 10218 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10219 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10220 10221 // Move LastLeft and FirstRight towards each other from opposite directions to 10222 // find a partitioning of the clusters which balances the probability on both 10223 // sides. If LeftProb and RightProb are equal, alternate which side is 10224 // taken to ensure 0-probability nodes are distributed evenly. 10225 unsigned I = 0; 10226 while (LastLeft + 1 < FirstRight) { 10227 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10228 LeftProb += (++LastLeft)->Prob; 10229 else 10230 RightProb += (--FirstRight)->Prob; 10231 I++; 10232 } 10233 10234 while (true) { 10235 // Our binary search tree differs from a typical BST in that ours can have up 10236 // to three values in each leaf. The pivot selection above doesn't take that 10237 // into account, which means the tree might require more nodes and be less 10238 // efficient. We compensate for this here. 10239 10240 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10241 unsigned NumRight = W.LastCluster - FirstRight + 1; 10242 10243 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10244 // If one side has less than 3 clusters, and the other has more than 3, 10245 // consider taking a cluster from the other side. 10246 10247 if (NumLeft < NumRight) { 10248 // Consider moving the first cluster on the right to the left side. 10249 CaseCluster &CC = *FirstRight; 10250 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10251 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10252 if (LeftSideRank <= RightSideRank) { 10253 // Moving the cluster to the left does not demote it. 10254 ++LastLeft; 10255 ++FirstRight; 10256 continue; 10257 } 10258 } else { 10259 assert(NumRight < NumLeft); 10260 // Consider moving the last element on the left to the right side. 10261 CaseCluster &CC = *LastLeft; 10262 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10263 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10264 if (RightSideRank <= LeftSideRank) { 10265 // Moving the cluster to the right does not demot it. 10266 --LastLeft; 10267 --FirstRight; 10268 continue; 10269 } 10270 } 10271 } 10272 break; 10273 } 10274 10275 assert(LastLeft + 1 == FirstRight); 10276 assert(LastLeft >= W.FirstCluster); 10277 assert(FirstRight <= W.LastCluster); 10278 10279 // Use the first element on the right as pivot since we will make less-than 10280 // comparisons against it. 10281 CaseClusterIt PivotCluster = FirstRight; 10282 assert(PivotCluster > W.FirstCluster); 10283 assert(PivotCluster <= W.LastCluster); 10284 10285 CaseClusterIt FirstLeft = W.FirstCluster; 10286 CaseClusterIt LastRight = W.LastCluster; 10287 10288 const ConstantInt *Pivot = PivotCluster->Low; 10289 10290 // New blocks will be inserted immediately after the current one. 10291 MachineFunction::iterator BBI(W.MBB); 10292 ++BBI; 10293 10294 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10295 // we can branch to its destination directly if it's squeezed exactly in 10296 // between the known lower bound and Pivot - 1. 10297 MachineBasicBlock *LeftMBB; 10298 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10299 FirstLeft->Low == W.GE && 10300 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10301 LeftMBB = FirstLeft->MBB; 10302 } else { 10303 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10304 FuncInfo.MF->insert(BBI, LeftMBB); 10305 WorkList.push_back( 10306 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10307 // Put Cond in a virtual register to make it available from the new blocks. 10308 ExportFromCurrentBlock(Cond); 10309 } 10310 10311 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10312 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10313 // directly if RHS.High equals the current upper bound. 10314 MachineBasicBlock *RightMBB; 10315 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10316 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10317 RightMBB = FirstRight->MBB; 10318 } else { 10319 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10320 FuncInfo.MF->insert(BBI, RightMBB); 10321 WorkList.push_back( 10322 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10323 // Put Cond in a virtual register to make it available from the new blocks. 10324 ExportFromCurrentBlock(Cond); 10325 } 10326 10327 // Create the CaseBlock record that will be used to lower the branch. 10328 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10329 getCurSDLoc(), LeftProb, RightProb); 10330 10331 if (W.MBB == SwitchMBB) 10332 visitSwitchCase(CB, SwitchMBB); 10333 else 10334 SL->SwitchCases.push_back(CB); 10335 } 10336 10337 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10338 // from the swith statement. 10339 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10340 BranchProbability PeeledCaseProb) { 10341 if (PeeledCaseProb == BranchProbability::getOne()) 10342 return BranchProbability::getZero(); 10343 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10344 10345 uint32_t Numerator = CaseProb.getNumerator(); 10346 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10347 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10348 } 10349 10350 // Try to peel the top probability case if it exceeds the threshold. 10351 // Return current MachineBasicBlock for the switch statement if the peeling 10352 // does not occur. 10353 // If the peeling is performed, return the newly created MachineBasicBlock 10354 // for the peeled switch statement. Also update Clusters to remove the peeled 10355 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10356 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10357 const SwitchInst &SI, CaseClusterVector &Clusters, 10358 BranchProbability &PeeledCaseProb) { 10359 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10360 // Don't perform if there is only one cluster or optimizing for size. 10361 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10362 TM.getOptLevel() == CodeGenOpt::None || 10363 SwitchMBB->getParent()->getFunction().hasMinSize()) 10364 return SwitchMBB; 10365 10366 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10367 unsigned PeeledCaseIndex = 0; 10368 bool SwitchPeeled = false; 10369 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10370 CaseCluster &CC = Clusters[Index]; 10371 if (CC.Prob < TopCaseProb) 10372 continue; 10373 TopCaseProb = CC.Prob; 10374 PeeledCaseIndex = Index; 10375 SwitchPeeled = true; 10376 } 10377 if (!SwitchPeeled) 10378 return SwitchMBB; 10379 10380 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10381 << TopCaseProb << "\n"); 10382 10383 // Record the MBB for the peeled switch statement. 10384 MachineFunction::iterator BBI(SwitchMBB); 10385 ++BBI; 10386 MachineBasicBlock *PeeledSwitchMBB = 10387 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10388 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10389 10390 ExportFromCurrentBlock(SI.getCondition()); 10391 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10392 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10393 nullptr, nullptr, TopCaseProb.getCompl()}; 10394 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10395 10396 Clusters.erase(PeeledCaseIt); 10397 for (CaseCluster &CC : Clusters) { 10398 LLVM_DEBUG( 10399 dbgs() << "Scale the probablity for one cluster, before scaling: " 10400 << CC.Prob << "\n"); 10401 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10402 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10403 } 10404 PeeledCaseProb = TopCaseProb; 10405 return PeeledSwitchMBB; 10406 } 10407 10408 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10409 // Extract cases from the switch. 10410 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10411 CaseClusterVector Clusters; 10412 Clusters.reserve(SI.getNumCases()); 10413 for (auto I : SI.cases()) { 10414 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10415 const ConstantInt *CaseVal = I.getCaseValue(); 10416 BranchProbability Prob = 10417 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10418 : BranchProbability(1, SI.getNumCases() + 1); 10419 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10420 } 10421 10422 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10423 10424 // Cluster adjacent cases with the same destination. We do this at all 10425 // optimization levels because it's cheap to do and will make codegen faster 10426 // if there are many clusters. 10427 sortAndRangeify(Clusters); 10428 10429 // The branch probablity of the peeled case. 10430 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10431 MachineBasicBlock *PeeledSwitchMBB = 10432 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10433 10434 // If there is only the default destination, jump there directly. 10435 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10436 if (Clusters.empty()) { 10437 assert(PeeledSwitchMBB == SwitchMBB); 10438 SwitchMBB->addSuccessor(DefaultMBB); 10439 if (DefaultMBB != NextBlock(SwitchMBB)) { 10440 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10441 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10442 } 10443 return; 10444 } 10445 10446 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 10447 SL->findBitTestClusters(Clusters, &SI); 10448 10449 LLVM_DEBUG({ 10450 dbgs() << "Case clusters: "; 10451 for (const CaseCluster &C : Clusters) { 10452 if (C.Kind == CC_JumpTable) 10453 dbgs() << "JT:"; 10454 if (C.Kind == CC_BitTests) 10455 dbgs() << "BT:"; 10456 10457 C.Low->getValue().print(dbgs(), true); 10458 if (C.Low != C.High) { 10459 dbgs() << '-'; 10460 C.High->getValue().print(dbgs(), true); 10461 } 10462 dbgs() << ' '; 10463 } 10464 dbgs() << '\n'; 10465 }); 10466 10467 assert(!Clusters.empty()); 10468 SwitchWorkList WorkList; 10469 CaseClusterIt First = Clusters.begin(); 10470 CaseClusterIt Last = Clusters.end() - 1; 10471 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10472 // Scale the branchprobability for DefaultMBB if the peel occurs and 10473 // DefaultMBB is not replaced. 10474 if (PeeledCaseProb != BranchProbability::getZero() && 10475 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10476 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10477 WorkList.push_back( 10478 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10479 10480 while (!WorkList.empty()) { 10481 SwitchWorkListItem W = WorkList.back(); 10482 WorkList.pop_back(); 10483 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10484 10485 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10486 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 10487 // For optimized builds, lower large range as a balanced binary tree. 10488 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10489 continue; 10490 } 10491 10492 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10493 } 10494 } 10495 10496 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 10497 SDValue N = getValue(I.getOperand(0)); 10498 setValue(&I, N); 10499 } 10500