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 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4299 4300 EVT VT = Src0.getValueType(); 4301 if (!Alignment) 4302 Alignment = DAG.getEVTAlignment(VT); 4303 4304 AAMDNodes AAInfo; 4305 I.getAAMetadata(AAInfo); 4306 4307 MachineMemOperand *MMO = 4308 DAG.getMachineFunction(). 4309 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4310 MachineMemOperand::MOStore, 4311 // TODO: Make MachineMemOperands aware of scalable 4312 // vectors. 4313 VT.getStoreSize().getKnownMinSize(), 4314 Alignment, AAInfo); 4315 SDValue StoreNode = 4316 DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4317 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4318 DAG.setRoot(StoreNode); 4319 setValue(&I, StoreNode); 4320 } 4321 4322 // Get a uniform base for the Gather/Scatter intrinsic. 4323 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4324 // We try to represent it as a base pointer + vector of indices. 4325 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4326 // The first operand of the GEP may be a single pointer or a vector of pointers 4327 // Example: 4328 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4329 // or 4330 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4331 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4332 // 4333 // When the first GEP operand is a single pointer - it is the uniform base we 4334 // are looking for. If first operand of the GEP is a splat vector - we 4335 // extract the splat value and use it as a uniform base. 4336 // In all other cases the function returns 'false'. 4337 static bool getUniformBase(const Value *&Ptr, SDValue &Base, SDValue &Index, 4338 ISD::MemIndexType &IndexType, SDValue &Scale, 4339 SelectionDAGBuilder *SDB) { 4340 SelectionDAG& DAG = SDB->DAG; 4341 LLVMContext &Context = *DAG.getContext(); 4342 4343 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 4344 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4345 if (!GEP) 4346 return false; 4347 4348 const Value *GEPPtr = GEP->getPointerOperand(); 4349 if (!GEPPtr->getType()->isVectorTy()) 4350 Ptr = GEPPtr; 4351 else if (!(Ptr = getSplatValue(GEPPtr))) 4352 return false; 4353 4354 unsigned FinalIndex = GEP->getNumOperands() - 1; 4355 Value *IndexVal = GEP->getOperand(FinalIndex); 4356 4357 // Ensure all the other indices are 0. 4358 for (unsigned i = 1; i < FinalIndex; ++i) { 4359 auto *C = dyn_cast<Constant>(GEP->getOperand(i)); 4360 if (!C) 4361 return false; 4362 if (isa<VectorType>(C->getType())) 4363 C = C->getSplatValue(); 4364 auto *CI = dyn_cast_or_null<ConstantInt>(C); 4365 if (!CI || !CI->isZero()) 4366 return false; 4367 } 4368 4369 // The operands of the GEP may be defined in another basic block. 4370 // In this case we'll not find nodes for the operands. 4371 if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal)) 4372 return false; 4373 4374 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4375 const DataLayout &DL = DAG.getDataLayout(); 4376 Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()), 4377 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4378 Base = SDB->getValue(Ptr); 4379 Index = SDB->getValue(IndexVal); 4380 IndexType = ISD::SIGNED_SCALED; 4381 4382 if (!Index.getValueType().isVector()) { 4383 unsigned GEPWidth = GEP->getType()->getVectorNumElements(); 4384 EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth); 4385 Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index); 4386 } 4387 return true; 4388 } 4389 4390 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4391 SDLoc sdl = getCurSDLoc(); 4392 4393 // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask) 4394 const Value *Ptr = I.getArgOperand(1); 4395 SDValue Src0 = getValue(I.getArgOperand(0)); 4396 SDValue Mask = getValue(I.getArgOperand(3)); 4397 EVT VT = Src0.getValueType(); 4398 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue(); 4399 if (!Alignment) 4400 Alignment = DAG.getEVTAlignment(VT); 4401 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4402 4403 AAMDNodes AAInfo; 4404 I.getAAMetadata(AAInfo); 4405 4406 SDValue Base; 4407 SDValue Index; 4408 ISD::MemIndexType IndexType; 4409 SDValue Scale; 4410 const Value *BasePtr = Ptr; 4411 bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale, 4412 this); 4413 4414 const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr; 4415 MachineMemOperand *MMO = DAG.getMachineFunction(). 4416 getMachineMemOperand(MachinePointerInfo(MemOpBasePtr), 4417 MachineMemOperand::MOStore, 4418 // TODO: Make MachineMemOperands aware of scalable 4419 // vectors. 4420 VT.getStoreSize().getKnownMinSize(), 4421 Alignment, AAInfo); 4422 if (!UniformBase) { 4423 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4424 Index = getValue(Ptr); 4425 IndexType = ISD::SIGNED_SCALED; 4426 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4427 } 4428 SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale }; 4429 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4430 Ops, MMO, IndexType); 4431 DAG.setRoot(Scatter); 4432 setValue(&I, Scatter); 4433 } 4434 4435 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4436 SDLoc sdl = getCurSDLoc(); 4437 4438 auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4439 unsigned& Alignment) { 4440 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4441 Ptr = I.getArgOperand(0); 4442 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 4443 Mask = I.getArgOperand(2); 4444 Src0 = I.getArgOperand(3); 4445 }; 4446 auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4447 unsigned& Alignment) { 4448 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4449 Ptr = I.getArgOperand(0); 4450 Alignment = 0; 4451 Mask = I.getArgOperand(1); 4452 Src0 = I.getArgOperand(2); 4453 }; 4454 4455 Value *PtrOperand, *MaskOperand, *Src0Operand; 4456 unsigned Alignment; 4457 if (IsExpanding) 4458 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4459 else 4460 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4461 4462 SDValue Ptr = getValue(PtrOperand); 4463 SDValue Src0 = getValue(Src0Operand); 4464 SDValue Mask = getValue(MaskOperand); 4465 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4466 4467 EVT VT = Src0.getValueType(); 4468 if (!Alignment) 4469 Alignment = DAG.getEVTAlignment(VT); 4470 4471 AAMDNodes AAInfo; 4472 I.getAAMetadata(AAInfo); 4473 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4474 4475 // Do not serialize masked loads of constant memory with anything. 4476 MemoryLocation ML; 4477 if (VT.isScalableVector()) 4478 ML = MemoryLocation(PtrOperand); 4479 else 4480 ML = MemoryLocation(PtrOperand, LocationSize::precise( 4481 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4482 AAInfo); 4483 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4484 4485 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4486 4487 MachineMemOperand *MMO = 4488 DAG.getMachineFunction(). 4489 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4490 MachineMemOperand::MOLoad, 4491 // TODO: Make MachineMemOperands aware of scalable 4492 // vectors. 4493 VT.getStoreSize().getKnownMinSize(), 4494 Alignment, AAInfo, Ranges); 4495 4496 SDValue Load = 4497 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4498 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4499 if (AddToChain) 4500 PendingLoads.push_back(Load.getValue(1)); 4501 setValue(&I, Load); 4502 } 4503 4504 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4505 SDLoc sdl = getCurSDLoc(); 4506 4507 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4508 const Value *Ptr = I.getArgOperand(0); 4509 SDValue Src0 = getValue(I.getArgOperand(3)); 4510 SDValue Mask = getValue(I.getArgOperand(2)); 4511 4512 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4513 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4514 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue(); 4515 if (!Alignment) 4516 Alignment = DAG.getEVTAlignment(VT); 4517 4518 AAMDNodes AAInfo; 4519 I.getAAMetadata(AAInfo); 4520 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4521 4522 SDValue Root = DAG.getRoot(); 4523 SDValue Base; 4524 SDValue Index; 4525 ISD::MemIndexType IndexType; 4526 SDValue Scale; 4527 const Value *BasePtr = Ptr; 4528 bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale, 4529 this); 4530 bool ConstantMemory = false; 4531 if (UniformBase && AA && 4532 AA->pointsToConstantMemory( 4533 MemoryLocation(BasePtr, 4534 LocationSize::precise( 4535 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4536 AAInfo))) { 4537 // Do not serialize (non-volatile) loads of constant memory with anything. 4538 Root = DAG.getEntryNode(); 4539 ConstantMemory = true; 4540 } 4541 4542 MachineMemOperand *MMO = 4543 DAG.getMachineFunction(). 4544 getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr), 4545 MachineMemOperand::MOLoad, 4546 // TODO: Make MachineMemOperands aware of scalable 4547 // vectors. 4548 VT.getStoreSize().getKnownMinSize(), 4549 Alignment, AAInfo, Ranges); 4550 4551 if (!UniformBase) { 4552 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4553 Index = getValue(Ptr); 4554 IndexType = ISD::SIGNED_SCALED; 4555 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4556 } 4557 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4558 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4559 Ops, MMO, IndexType); 4560 4561 SDValue OutChain = Gather.getValue(1); 4562 if (!ConstantMemory) 4563 PendingLoads.push_back(OutChain); 4564 setValue(&I, Gather); 4565 } 4566 4567 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4568 SDLoc dl = getCurSDLoc(); 4569 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4570 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4571 SyncScope::ID SSID = I.getSyncScopeID(); 4572 4573 SDValue InChain = getRoot(); 4574 4575 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4576 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4577 4578 auto Alignment = DAG.getEVTAlignment(MemVT); 4579 4580 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 4581 if (I.isVolatile()) 4582 Flags |= MachineMemOperand::MOVolatile; 4583 Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I); 4584 4585 MachineFunction &MF = DAG.getMachineFunction(); 4586 MachineMemOperand *MMO = 4587 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4588 Flags, MemVT.getStoreSize(), Alignment, 4589 AAMDNodes(), nullptr, SSID, SuccessOrdering, 4590 FailureOrdering); 4591 4592 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4593 dl, MemVT, VTs, InChain, 4594 getValue(I.getPointerOperand()), 4595 getValue(I.getCompareOperand()), 4596 getValue(I.getNewValOperand()), MMO); 4597 4598 SDValue OutChain = L.getValue(2); 4599 4600 setValue(&I, L); 4601 DAG.setRoot(OutChain); 4602 } 4603 4604 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4605 SDLoc dl = getCurSDLoc(); 4606 ISD::NodeType NT; 4607 switch (I.getOperation()) { 4608 default: llvm_unreachable("Unknown atomicrmw operation"); 4609 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4610 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4611 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4612 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4613 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4614 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4615 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4616 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4617 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4618 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4619 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4620 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4621 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4622 } 4623 AtomicOrdering Ordering = I.getOrdering(); 4624 SyncScope::ID SSID = I.getSyncScopeID(); 4625 4626 SDValue InChain = getRoot(); 4627 4628 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4629 auto Alignment = DAG.getEVTAlignment(MemVT); 4630 4631 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 4632 if (I.isVolatile()) 4633 Flags |= MachineMemOperand::MOVolatile; 4634 Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I); 4635 4636 MachineFunction &MF = DAG.getMachineFunction(); 4637 MachineMemOperand *MMO = 4638 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags, 4639 MemVT.getStoreSize(), Alignment, AAMDNodes(), 4640 nullptr, SSID, Ordering); 4641 4642 SDValue L = 4643 DAG.getAtomic(NT, dl, MemVT, InChain, 4644 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4645 MMO); 4646 4647 SDValue OutChain = L.getValue(1); 4648 4649 setValue(&I, L); 4650 DAG.setRoot(OutChain); 4651 } 4652 4653 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4654 SDLoc dl = getCurSDLoc(); 4655 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4656 SDValue Ops[3]; 4657 Ops[0] = getRoot(); 4658 Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl, 4659 TLI.getFenceOperandTy(DAG.getDataLayout())); 4660 Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl, 4661 TLI.getFenceOperandTy(DAG.getDataLayout())); 4662 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4663 } 4664 4665 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4666 SDLoc dl = getCurSDLoc(); 4667 AtomicOrdering Order = I.getOrdering(); 4668 SyncScope::ID SSID = I.getSyncScopeID(); 4669 4670 SDValue InChain = getRoot(); 4671 4672 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4673 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4674 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4675 4676 if (!TLI.supportsUnalignedAtomics() && 4677 I.getAlignment() < MemVT.getSizeInBits() / 8) 4678 report_fatal_error("Cannot generate unaligned atomic load"); 4679 4680 auto Flags = MachineMemOperand::MOLoad; 4681 if (I.isVolatile()) 4682 Flags |= MachineMemOperand::MOVolatile; 4683 if (I.hasMetadata(LLVMContext::MD_invariant_load)) 4684 Flags |= MachineMemOperand::MOInvariant; 4685 if (isDereferenceablePointer(I.getPointerOperand(), I.getType(), 4686 DAG.getDataLayout())) 4687 Flags |= MachineMemOperand::MODereferenceable; 4688 4689 Flags |= TLI.getMMOFlags(I); 4690 4691 MachineMemOperand *MMO = 4692 DAG.getMachineFunction(). 4693 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4694 Flags, MemVT.getStoreSize(), 4695 I.getAlignment() ? I.getAlignment() : 4696 DAG.getEVTAlignment(MemVT), 4697 AAMDNodes(), nullptr, SSID, Order); 4698 4699 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4700 4701 SDValue Ptr = getValue(I.getPointerOperand()); 4702 4703 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4704 // TODO: Once this is better exercised by tests, it should be merged with 4705 // the normal path for loads to prevent future divergence. 4706 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4707 if (MemVT != VT) 4708 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4709 4710 setValue(&I, L); 4711 SDValue OutChain = L.getValue(1); 4712 if (!I.isUnordered()) 4713 DAG.setRoot(OutChain); 4714 else 4715 PendingLoads.push_back(OutChain); 4716 return; 4717 } 4718 4719 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4720 Ptr, MMO); 4721 4722 SDValue OutChain = L.getValue(1); 4723 if (MemVT != VT) 4724 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4725 4726 setValue(&I, L); 4727 DAG.setRoot(OutChain); 4728 } 4729 4730 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4731 SDLoc dl = getCurSDLoc(); 4732 4733 AtomicOrdering Ordering = I.getOrdering(); 4734 SyncScope::ID SSID = I.getSyncScopeID(); 4735 4736 SDValue InChain = getRoot(); 4737 4738 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4739 EVT MemVT = 4740 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4741 4742 if (I.getAlignment() < MemVT.getSizeInBits() / 8) 4743 report_fatal_error("Cannot generate unaligned atomic store"); 4744 4745 auto Flags = MachineMemOperand::MOStore; 4746 if (I.isVolatile()) 4747 Flags |= MachineMemOperand::MOVolatile; 4748 Flags |= TLI.getMMOFlags(I); 4749 4750 MachineFunction &MF = DAG.getMachineFunction(); 4751 MachineMemOperand *MMO = 4752 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags, 4753 MemVT.getStoreSize(), I.getAlignment(), AAMDNodes(), 4754 nullptr, SSID, Ordering); 4755 4756 SDValue Val = getValue(I.getValueOperand()); 4757 if (Val.getValueType() != MemVT) 4758 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4759 SDValue Ptr = getValue(I.getPointerOperand()); 4760 4761 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4762 // TODO: Once this is better exercised by tests, it should be merged with 4763 // the normal path for stores to prevent future divergence. 4764 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4765 DAG.setRoot(S); 4766 return; 4767 } 4768 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4769 Ptr, Val, MMO); 4770 4771 4772 DAG.setRoot(OutChain); 4773 } 4774 4775 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4776 /// node. 4777 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4778 unsigned Intrinsic) { 4779 // Ignore the callsite's attributes. A specific call site may be marked with 4780 // readnone, but the lowering code will expect the chain based on the 4781 // definition. 4782 const Function *F = I.getCalledFunction(); 4783 bool HasChain = !F->doesNotAccessMemory(); 4784 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4785 4786 // Build the operand list. 4787 SmallVector<SDValue, 8> Ops; 4788 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4789 if (OnlyLoad) { 4790 // We don't need to serialize loads against other loads. 4791 Ops.push_back(DAG.getRoot()); 4792 } else { 4793 Ops.push_back(getRoot()); 4794 } 4795 } 4796 4797 // Info is set by getTgtMemInstrinsic 4798 TargetLowering::IntrinsicInfo Info; 4799 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4800 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4801 DAG.getMachineFunction(), 4802 Intrinsic); 4803 4804 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4805 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4806 Info.opc == ISD::INTRINSIC_W_CHAIN) 4807 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4808 TLI.getPointerTy(DAG.getDataLayout()))); 4809 4810 // Add all operands of the call to the operand list. 4811 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4812 const Value *Arg = I.getArgOperand(i); 4813 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4814 Ops.push_back(getValue(Arg)); 4815 continue; 4816 } 4817 4818 // Use TargetConstant instead of a regular constant for immarg. 4819 EVT VT = TLI.getValueType(*DL, Arg->getType(), true); 4820 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4821 assert(CI->getBitWidth() <= 64 && 4822 "large intrinsic immediates not handled"); 4823 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4824 } else { 4825 Ops.push_back( 4826 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4827 } 4828 } 4829 4830 SmallVector<EVT, 4> ValueVTs; 4831 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4832 4833 if (HasChain) 4834 ValueVTs.push_back(MVT::Other); 4835 4836 SDVTList VTs = DAG.getVTList(ValueVTs); 4837 4838 // Create the node. 4839 SDValue Result; 4840 if (IsTgtIntrinsic) { 4841 // This is target intrinsic that touches memory 4842 AAMDNodes AAInfo; 4843 I.getAAMetadata(AAInfo); 4844 Result = DAG.getMemIntrinsicNode( 4845 Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT, 4846 MachinePointerInfo(Info.ptrVal, Info.offset), 4847 Info.align ? Info.align->value() : 0, Info.flags, Info.size, AAInfo); 4848 } else if (!HasChain) { 4849 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4850 } else if (!I.getType()->isVoidTy()) { 4851 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4852 } else { 4853 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4854 } 4855 4856 if (HasChain) { 4857 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4858 if (OnlyLoad) 4859 PendingLoads.push_back(Chain); 4860 else 4861 DAG.setRoot(Chain); 4862 } 4863 4864 if (!I.getType()->isVoidTy()) { 4865 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4866 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4867 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4868 } else 4869 Result = lowerRangeToAssertZExt(DAG, I, Result); 4870 4871 setValue(&I, Result); 4872 } 4873 } 4874 4875 /// GetSignificand - Get the significand and build it into a floating-point 4876 /// number with exponent of 1: 4877 /// 4878 /// Op = (Op & 0x007fffff) | 0x3f800000; 4879 /// 4880 /// where Op is the hexadecimal representation of floating point value. 4881 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4882 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4883 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4884 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4885 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4886 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4887 } 4888 4889 /// GetExponent - Get the exponent: 4890 /// 4891 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4892 /// 4893 /// where Op is the hexadecimal representation of floating point value. 4894 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4895 const TargetLowering &TLI, const SDLoc &dl) { 4896 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4897 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4898 SDValue t1 = DAG.getNode( 4899 ISD::SRL, dl, MVT::i32, t0, 4900 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4901 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4902 DAG.getConstant(127, dl, MVT::i32)); 4903 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4904 } 4905 4906 /// getF32Constant - Get 32-bit floating point constant. 4907 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4908 const SDLoc &dl) { 4909 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4910 MVT::f32); 4911 } 4912 4913 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4914 SelectionDAG &DAG) { 4915 // TODO: What fast-math-flags should be set on the floating-point nodes? 4916 4917 // IntegerPartOfX = ((int32_t)(t0); 4918 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4919 4920 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4921 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4922 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4923 4924 // IntegerPartOfX <<= 23; 4925 IntegerPartOfX = DAG.getNode( 4926 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4927 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4928 DAG.getDataLayout()))); 4929 4930 SDValue TwoToFractionalPartOfX; 4931 if (LimitFloatPrecision <= 6) { 4932 // For floating-point precision of 6: 4933 // 4934 // TwoToFractionalPartOfX = 4935 // 0.997535578f + 4936 // (0.735607626f + 0.252464424f * x) * x; 4937 // 4938 // error 0.0144103317, which is 6 bits 4939 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4940 getF32Constant(DAG, 0x3e814304, dl)); 4941 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4942 getF32Constant(DAG, 0x3f3c50c8, dl)); 4943 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4944 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4945 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4946 } else if (LimitFloatPrecision <= 12) { 4947 // For floating-point precision of 12: 4948 // 4949 // TwoToFractionalPartOfX = 4950 // 0.999892986f + 4951 // (0.696457318f + 4952 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4953 // 4954 // error 0.000107046256, which is 13 to 14 bits 4955 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4956 getF32Constant(DAG, 0x3da235e3, dl)); 4957 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4958 getF32Constant(DAG, 0x3e65b8f3, dl)); 4959 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4960 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4961 getF32Constant(DAG, 0x3f324b07, dl)); 4962 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4963 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4964 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4965 } else { // LimitFloatPrecision <= 18 4966 // For floating-point precision of 18: 4967 // 4968 // TwoToFractionalPartOfX = 4969 // 0.999999982f + 4970 // (0.693148872f + 4971 // (0.240227044f + 4972 // (0.554906021e-1f + 4973 // (0.961591928e-2f + 4974 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4975 // error 2.47208000*10^(-7), which is better than 18 bits 4976 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4977 getF32Constant(DAG, 0x3924b03e, dl)); 4978 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4979 getF32Constant(DAG, 0x3ab24b87, dl)); 4980 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4981 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4982 getF32Constant(DAG, 0x3c1d8c17, dl)); 4983 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4984 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4985 getF32Constant(DAG, 0x3d634a1d, dl)); 4986 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4987 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4988 getF32Constant(DAG, 0x3e75fe14, dl)); 4989 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4990 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4991 getF32Constant(DAG, 0x3f317234, dl)); 4992 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4993 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4994 getF32Constant(DAG, 0x3f800000, dl)); 4995 } 4996 4997 // Add the exponent into the result in integer domain. 4998 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4999 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5000 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 5001 } 5002 5003 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5004 /// limited-precision mode. 5005 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5006 const TargetLowering &TLI) { 5007 if (Op.getValueType() == MVT::f32 && 5008 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5009 5010 // Put the exponent in the right bit position for later addition to the 5011 // final result: 5012 // 5013 // t0 = Op * log2(e) 5014 5015 // TODO: What fast-math-flags should be set here? 5016 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5017 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5018 return getLimitedPrecisionExp2(t0, dl, DAG); 5019 } 5020 5021 // No special expansion. 5022 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op); 5023 } 5024 5025 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5026 /// limited-precision mode. 5027 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5028 const TargetLowering &TLI) { 5029 // TODO: What fast-math-flags should be set on the floating-point nodes? 5030 5031 if (Op.getValueType() == MVT::f32 && 5032 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5033 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5034 5035 // Scale the exponent by log(2). 5036 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5037 SDValue LogOfExponent = 5038 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5039 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5040 5041 // Get the significand and build it into a floating-point number with 5042 // exponent of 1. 5043 SDValue X = GetSignificand(DAG, Op1, dl); 5044 5045 SDValue LogOfMantissa; 5046 if (LimitFloatPrecision <= 6) { 5047 // For floating-point precision of 6: 5048 // 5049 // LogofMantissa = 5050 // -1.1609546f + 5051 // (1.4034025f - 0.23903021f * x) * x; 5052 // 5053 // error 0.0034276066, which is better than 8 bits 5054 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5055 getF32Constant(DAG, 0xbe74c456, dl)); 5056 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5057 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5058 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5059 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5060 getF32Constant(DAG, 0x3f949a29, dl)); 5061 } else if (LimitFloatPrecision <= 12) { 5062 // For floating-point precision of 12: 5063 // 5064 // LogOfMantissa = 5065 // -1.7417939f + 5066 // (2.8212026f + 5067 // (-1.4699568f + 5068 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5069 // 5070 // error 0.000061011436, which is 14 bits 5071 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5072 getF32Constant(DAG, 0xbd67b6d6, dl)); 5073 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5074 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5075 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5076 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5077 getF32Constant(DAG, 0x3fbc278b, dl)); 5078 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5079 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5080 getF32Constant(DAG, 0x40348e95, dl)); 5081 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5082 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5083 getF32Constant(DAG, 0x3fdef31a, dl)); 5084 } else { // LimitFloatPrecision <= 18 5085 // For floating-point precision of 18: 5086 // 5087 // LogOfMantissa = 5088 // -2.1072184f + 5089 // (4.2372794f + 5090 // (-3.7029485f + 5091 // (2.2781945f + 5092 // (-0.87823314f + 5093 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5094 // 5095 // error 0.0000023660568, which is better than 18 bits 5096 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5097 getF32Constant(DAG, 0xbc91e5ac, dl)); 5098 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5099 getF32Constant(DAG, 0x3e4350aa, dl)); 5100 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5101 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5102 getF32Constant(DAG, 0x3f60d3e3, dl)); 5103 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5104 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5105 getF32Constant(DAG, 0x4011cdf0, dl)); 5106 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5107 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5108 getF32Constant(DAG, 0x406cfd1c, dl)); 5109 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5110 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5111 getF32Constant(DAG, 0x408797cb, dl)); 5112 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5113 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5114 getF32Constant(DAG, 0x4006dcab, dl)); 5115 } 5116 5117 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5118 } 5119 5120 // No special expansion. 5121 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op); 5122 } 5123 5124 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5125 /// limited-precision mode. 5126 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5127 const TargetLowering &TLI) { 5128 // TODO: What fast-math-flags should be set on the floating-point nodes? 5129 5130 if (Op.getValueType() == MVT::f32 && 5131 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5132 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5133 5134 // Get the exponent. 5135 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5136 5137 // Get the significand and build it into a floating-point number with 5138 // exponent of 1. 5139 SDValue X = GetSignificand(DAG, Op1, dl); 5140 5141 // Different possible minimax approximations of significand in 5142 // floating-point for various degrees of accuracy over [1,2]. 5143 SDValue Log2ofMantissa; 5144 if (LimitFloatPrecision <= 6) { 5145 // For floating-point precision of 6: 5146 // 5147 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5148 // 5149 // error 0.0049451742, which is more than 7 bits 5150 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5151 getF32Constant(DAG, 0xbeb08fe0, dl)); 5152 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5153 getF32Constant(DAG, 0x40019463, dl)); 5154 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5155 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5156 getF32Constant(DAG, 0x3fd6633d, dl)); 5157 } else if (LimitFloatPrecision <= 12) { 5158 // For floating-point precision of 12: 5159 // 5160 // Log2ofMantissa = 5161 // -2.51285454f + 5162 // (4.07009056f + 5163 // (-2.12067489f + 5164 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5165 // 5166 // error 0.0000876136000, which is better than 13 bits 5167 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5168 getF32Constant(DAG, 0xbda7262e, dl)); 5169 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5170 getF32Constant(DAG, 0x3f25280b, dl)); 5171 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5172 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5173 getF32Constant(DAG, 0x4007b923, dl)); 5174 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5175 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5176 getF32Constant(DAG, 0x40823e2f, dl)); 5177 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5178 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5179 getF32Constant(DAG, 0x4020d29c, dl)); 5180 } else { // LimitFloatPrecision <= 18 5181 // For floating-point precision of 18: 5182 // 5183 // Log2ofMantissa = 5184 // -3.0400495f + 5185 // (6.1129976f + 5186 // (-5.3420409f + 5187 // (3.2865683f + 5188 // (-1.2669343f + 5189 // (0.27515199f - 5190 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5191 // 5192 // error 0.0000018516, which is better than 18 bits 5193 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5194 getF32Constant(DAG, 0xbcd2769e, dl)); 5195 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5196 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5197 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5198 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5199 getF32Constant(DAG, 0x3fa22ae7, dl)); 5200 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5201 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5202 getF32Constant(DAG, 0x40525723, dl)); 5203 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5204 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5205 getF32Constant(DAG, 0x40aaf200, dl)); 5206 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5207 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5208 getF32Constant(DAG, 0x40c39dad, dl)); 5209 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5210 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5211 getF32Constant(DAG, 0x4042902c, dl)); 5212 } 5213 5214 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5215 } 5216 5217 // No special expansion. 5218 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op); 5219 } 5220 5221 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5222 /// limited-precision mode. 5223 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5224 const TargetLowering &TLI) { 5225 // TODO: What fast-math-flags should be set on the floating-point nodes? 5226 5227 if (Op.getValueType() == MVT::f32 && 5228 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5229 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5230 5231 // Scale the exponent by log10(2) [0.30102999f]. 5232 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5233 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5234 getF32Constant(DAG, 0x3e9a209a, dl)); 5235 5236 // Get the significand and build it into a floating-point number with 5237 // exponent of 1. 5238 SDValue X = GetSignificand(DAG, Op1, dl); 5239 5240 SDValue Log10ofMantissa; 5241 if (LimitFloatPrecision <= 6) { 5242 // For floating-point precision of 6: 5243 // 5244 // Log10ofMantissa = 5245 // -0.50419619f + 5246 // (0.60948995f - 0.10380950f * x) * x; 5247 // 5248 // error 0.0014886165, which is 6 bits 5249 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5250 getF32Constant(DAG, 0xbdd49a13, dl)); 5251 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5252 getF32Constant(DAG, 0x3f1c0789, dl)); 5253 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5254 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5255 getF32Constant(DAG, 0x3f011300, dl)); 5256 } else if (LimitFloatPrecision <= 12) { 5257 // For floating-point precision of 12: 5258 // 5259 // Log10ofMantissa = 5260 // -0.64831180f + 5261 // (0.91751397f + 5262 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5263 // 5264 // error 0.00019228036, which is better than 12 bits 5265 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5266 getF32Constant(DAG, 0x3d431f31, dl)); 5267 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5268 getF32Constant(DAG, 0x3ea21fb2, dl)); 5269 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5270 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5271 getF32Constant(DAG, 0x3f6ae232, dl)); 5272 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5273 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5274 getF32Constant(DAG, 0x3f25f7c3, dl)); 5275 } else { // LimitFloatPrecision <= 18 5276 // For floating-point precision of 18: 5277 // 5278 // Log10ofMantissa = 5279 // -0.84299375f + 5280 // (1.5327582f + 5281 // (-1.0688956f + 5282 // (0.49102474f + 5283 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5284 // 5285 // error 0.0000037995730, which is better than 18 bits 5286 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5287 getF32Constant(DAG, 0x3c5d51ce, dl)); 5288 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5289 getF32Constant(DAG, 0x3e00685a, dl)); 5290 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5291 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5292 getF32Constant(DAG, 0x3efb6798, dl)); 5293 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5294 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5295 getF32Constant(DAG, 0x3f88d192, dl)); 5296 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5297 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5298 getF32Constant(DAG, 0x3fc4316c, dl)); 5299 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5300 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5301 getF32Constant(DAG, 0x3f57ce70, dl)); 5302 } 5303 5304 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5305 } 5306 5307 // No special expansion. 5308 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op); 5309 } 5310 5311 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5312 /// limited-precision mode. 5313 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5314 const TargetLowering &TLI) { 5315 if (Op.getValueType() == MVT::f32 && 5316 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5317 return getLimitedPrecisionExp2(Op, dl, DAG); 5318 5319 // No special expansion. 5320 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op); 5321 } 5322 5323 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5324 /// limited-precision mode with x == 10.0f. 5325 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5326 SelectionDAG &DAG, const TargetLowering &TLI) { 5327 bool IsExp10 = false; 5328 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5329 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5330 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5331 APFloat Ten(10.0f); 5332 IsExp10 = LHSC->isExactlyValue(Ten); 5333 } 5334 } 5335 5336 // TODO: What fast-math-flags should be set on the FMUL node? 5337 if (IsExp10) { 5338 // Put the exponent in the right bit position for later addition to the 5339 // final result: 5340 // 5341 // #define LOG2OF10 3.3219281f 5342 // t0 = Op * LOG2OF10; 5343 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5344 getF32Constant(DAG, 0x40549a78, dl)); 5345 return getLimitedPrecisionExp2(t0, dl, DAG); 5346 } 5347 5348 // No special expansion. 5349 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS); 5350 } 5351 5352 /// ExpandPowI - Expand a llvm.powi intrinsic. 5353 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5354 SelectionDAG &DAG) { 5355 // If RHS is a constant, we can expand this out to a multiplication tree, 5356 // otherwise we end up lowering to a call to __powidf2 (for example). When 5357 // optimizing for size, we only want to do this if the expansion would produce 5358 // a small number of multiplies, otherwise we do the full expansion. 5359 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5360 // Get the exponent as a positive value. 5361 unsigned Val = RHSC->getSExtValue(); 5362 if ((int)Val < 0) Val = -Val; 5363 5364 // powi(x, 0) -> 1.0 5365 if (Val == 0) 5366 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5367 5368 bool OptForSize = DAG.shouldOptForSize(); 5369 if (!OptForSize || 5370 // If optimizing for size, don't insert too many multiplies. 5371 // This inserts up to 5 multiplies. 5372 countPopulation(Val) + Log2_32(Val) < 7) { 5373 // We use the simple binary decomposition method to generate the multiply 5374 // sequence. There are more optimal ways to do this (for example, 5375 // powi(x,15) generates one more multiply than it should), but this has 5376 // the benefit of being both really simple and much better than a libcall. 5377 SDValue Res; // Logically starts equal to 1.0 5378 SDValue CurSquare = LHS; 5379 // TODO: Intrinsics should have fast-math-flags that propagate to these 5380 // nodes. 5381 while (Val) { 5382 if (Val & 1) { 5383 if (Res.getNode()) 5384 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 5385 else 5386 Res = CurSquare; // 1.0*CurSquare. 5387 } 5388 5389 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5390 CurSquare, CurSquare); 5391 Val >>= 1; 5392 } 5393 5394 // If the original was negative, invert the result, producing 1/(x*x*x). 5395 if (RHSC->getSExtValue() < 0) 5396 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5397 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5398 return Res; 5399 } 5400 } 5401 5402 // Otherwise, expand to a libcall. 5403 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5404 } 5405 5406 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5407 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5408 static void 5409 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs, 5410 const SDValue &N) { 5411 switch (N.getOpcode()) { 5412 case ISD::CopyFromReg: { 5413 SDValue Op = N.getOperand(1); 5414 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5415 Op.getValueType().getSizeInBits()); 5416 return; 5417 } 5418 case ISD::BITCAST: 5419 case ISD::AssertZext: 5420 case ISD::AssertSext: 5421 case ISD::TRUNCATE: 5422 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5423 return; 5424 case ISD::BUILD_PAIR: 5425 case ISD::BUILD_VECTOR: 5426 case ISD::CONCAT_VECTORS: 5427 for (SDValue Op : N->op_values()) 5428 getUnderlyingArgRegs(Regs, Op); 5429 return; 5430 default: 5431 return; 5432 } 5433 } 5434 5435 /// If the DbgValueInst is a dbg_value of a function argument, create the 5436 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5437 /// instruction selection, they will be inserted to the entry BB. 5438 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5439 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5440 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 5441 const Argument *Arg = dyn_cast<Argument>(V); 5442 if (!Arg) 5443 return false; 5444 5445 if (!IsDbgDeclare) { 5446 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5447 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5448 // the entry block. 5449 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5450 if (!IsInEntryBlock) 5451 return false; 5452 5453 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5454 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5455 // variable that also is a param. 5456 // 5457 // Although, if we are at the top of the entry block already, we can still 5458 // emit using ArgDbgValue. This might catch some situations when the 5459 // dbg.value refers to an argument that isn't used in the entry block, so 5460 // any CopyToReg node would be optimized out and the only way to express 5461 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5462 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5463 // we should only emit as ArgDbgValue if the Variable is an argument to the 5464 // current function, and the dbg.value intrinsic is found in the entry 5465 // block. 5466 bool VariableIsFunctionInputArg = Variable->isParameter() && 5467 !DL->getInlinedAt(); 5468 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5469 if (!IsInPrologue && !VariableIsFunctionInputArg) 5470 return false; 5471 5472 // Here we assume that a function argument on IR level only can be used to 5473 // describe one input parameter on source level. If we for example have 5474 // source code like this 5475 // 5476 // struct A { long x, y; }; 5477 // void foo(struct A a, long b) { 5478 // ... 5479 // b = a.x; 5480 // ... 5481 // } 5482 // 5483 // and IR like this 5484 // 5485 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5486 // entry: 5487 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5488 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5489 // call void @llvm.dbg.value(metadata i32 %b, "b", 5490 // ... 5491 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5492 // ... 5493 // 5494 // then the last dbg.value is describing a parameter "b" using a value that 5495 // is an argument. But since we already has used %a1 to describe a parameter 5496 // we should not handle that last dbg.value here (that would result in an 5497 // incorrect hoisting of the DBG_VALUE to the function entry). 5498 // Notice that we allow one dbg.value per IR level argument, to accommodate 5499 // for the situation with fragments above. 5500 if (VariableIsFunctionInputArg) { 5501 unsigned ArgNo = Arg->getArgNo(); 5502 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5503 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5504 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5505 return false; 5506 FuncInfo.DescribedArgs.set(ArgNo); 5507 } 5508 } 5509 5510 MachineFunction &MF = DAG.getMachineFunction(); 5511 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5512 5513 Optional<MachineOperand> Op; 5514 // Some arguments' frame index is recorded during argument lowering. 5515 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5516 if (FI != std::numeric_limits<int>::max()) 5517 Op = MachineOperand::CreateFI(FI); 5518 5519 SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes; 5520 if (!Op && N.getNode()) { 5521 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5522 Register Reg; 5523 if (ArgRegsAndSizes.size() == 1) 5524 Reg = ArgRegsAndSizes.front().first; 5525 5526 if (Reg && Reg.isVirtual()) { 5527 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5528 Register PR = RegInfo.getLiveInPhysReg(Reg); 5529 if (PR) 5530 Reg = PR; 5531 } 5532 if (Reg) { 5533 Op = MachineOperand::CreateReg(Reg, false); 5534 } 5535 } 5536 5537 if (!Op && N.getNode()) { 5538 // Check if frame index is available. 5539 SDValue LCandidate = peekThroughBitcasts(N); 5540 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5541 if (FrameIndexSDNode *FINode = 5542 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5543 Op = MachineOperand::CreateFI(FINode->getIndex()); 5544 } 5545 5546 if (!Op) { 5547 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5548 auto splitMultiRegDbgValue 5549 = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) { 5550 unsigned Offset = 0; 5551 for (auto RegAndSize : SplitRegs) { 5552 auto FragmentExpr = DIExpression::createFragmentExpression( 5553 Expr, Offset, RegAndSize.second); 5554 if (!FragmentExpr) 5555 continue; 5556 assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?"); 5557 FuncInfo.ArgDbgValues.push_back( 5558 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), false, 5559 RegAndSize.first, Variable, *FragmentExpr)); 5560 Offset += RegAndSize.second; 5561 } 5562 }; 5563 5564 // Check if ValueMap has reg number. 5565 DenseMap<const Value *, unsigned>::const_iterator 5566 VMI = FuncInfo.ValueMap.find(V); 5567 if (VMI != FuncInfo.ValueMap.end()) { 5568 const auto &TLI = DAG.getTargetLoweringInfo(); 5569 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5570 V->getType(), getABIRegCopyCC(V)); 5571 if (RFV.occupiesMultipleRegs()) { 5572 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5573 return true; 5574 } 5575 5576 Op = MachineOperand::CreateReg(VMI->second, false); 5577 } else if (ArgRegsAndSizes.size() > 1) { 5578 // This was split due to the calling convention, and no virtual register 5579 // mapping exists for the value. 5580 splitMultiRegDbgValue(ArgRegsAndSizes); 5581 return true; 5582 } 5583 } 5584 5585 if (!Op) 5586 return false; 5587 5588 assert(Variable->isValidLocationForIntrinsic(DL) && 5589 "Expected inlined-at fields to agree"); 5590 5591 // If the argument arrives in a stack slot, then what the IR thought was a 5592 // normal Value is actually in memory, and we must add a deref to load it. 5593 if (Op->isFI()) { 5594 int FI = Op->getIndex(); 5595 unsigned Size = DAG.getMachineFunction().getFrameInfo().getObjectSize(FI); 5596 if (Expr->isImplicit()) { 5597 SmallVector<uint64_t, 2> Ops = {dwarf::DW_OP_deref_size, Size}; 5598 Expr = DIExpression::prependOpcodes(Expr, Ops); 5599 } else { 5600 Expr = DIExpression::prepend(Expr, DIExpression::DerefBefore); 5601 } 5602 } 5603 5604 // If this location was specified with a dbg.declare, then it and its 5605 // expression calculate the address of the variable. Append a deref to 5606 // force it to be a memory location. 5607 if (IsDbgDeclare) 5608 Expr = DIExpression::append(Expr, {dwarf::DW_OP_deref}); 5609 5610 FuncInfo.ArgDbgValues.push_back( 5611 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), false, 5612 *Op, Variable, Expr)); 5613 5614 return true; 5615 } 5616 5617 /// Return the appropriate SDDbgValue based on N. 5618 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5619 DILocalVariable *Variable, 5620 DIExpression *Expr, 5621 const DebugLoc &dl, 5622 unsigned DbgSDNodeOrder) { 5623 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5624 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5625 // stack slot locations. 5626 // 5627 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5628 // debug values here after optimization: 5629 // 5630 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5631 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5632 // 5633 // Both describe the direct values of their associated variables. 5634 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5635 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5636 } 5637 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5638 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5639 } 5640 5641 // VisualStudio defines setjmp as _setjmp 5642 #if defined(_MSC_VER) && defined(setjmp) && \ 5643 !defined(setjmp_undefined_for_msvc) 5644 # pragma push_macro("setjmp") 5645 # undef setjmp 5646 # define setjmp_undefined_for_msvc 5647 #endif 5648 5649 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5650 switch (Intrinsic) { 5651 case Intrinsic::smul_fix: 5652 return ISD::SMULFIX; 5653 case Intrinsic::umul_fix: 5654 return ISD::UMULFIX; 5655 default: 5656 llvm_unreachable("Unhandled fixed point intrinsic"); 5657 } 5658 } 5659 5660 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5661 const char *FunctionName) { 5662 assert(FunctionName && "FunctionName must not be nullptr"); 5663 SDValue Callee = DAG.getExternalSymbol( 5664 FunctionName, 5665 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5666 LowerCallTo(&I, Callee, I.isTailCall()); 5667 } 5668 5669 /// Lower the call to the specified intrinsic function. 5670 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5671 unsigned Intrinsic) { 5672 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5673 SDLoc sdl = getCurSDLoc(); 5674 DebugLoc dl = getCurDebugLoc(); 5675 SDValue Res; 5676 5677 switch (Intrinsic) { 5678 default: 5679 // By default, turn this into a target intrinsic node. 5680 visitTargetIntrinsic(I, Intrinsic); 5681 return; 5682 case Intrinsic::vastart: visitVAStart(I); return; 5683 case Intrinsic::vaend: visitVAEnd(I); return; 5684 case Intrinsic::vacopy: visitVACopy(I); return; 5685 case Intrinsic::returnaddress: 5686 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5687 TLI.getPointerTy(DAG.getDataLayout()), 5688 getValue(I.getArgOperand(0)))); 5689 return; 5690 case Intrinsic::addressofreturnaddress: 5691 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5692 TLI.getPointerTy(DAG.getDataLayout()))); 5693 return; 5694 case Intrinsic::sponentry: 5695 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5696 TLI.getFrameIndexTy(DAG.getDataLayout()))); 5697 return; 5698 case Intrinsic::frameaddress: 5699 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5700 TLI.getFrameIndexTy(DAG.getDataLayout()), 5701 getValue(I.getArgOperand(0)))); 5702 return; 5703 case Intrinsic::read_register: { 5704 Value *Reg = I.getArgOperand(0); 5705 SDValue Chain = getRoot(); 5706 SDValue RegName = 5707 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5708 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5709 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5710 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5711 setValue(&I, Res); 5712 DAG.setRoot(Res.getValue(1)); 5713 return; 5714 } 5715 case Intrinsic::write_register: { 5716 Value *Reg = I.getArgOperand(0); 5717 Value *RegValue = I.getArgOperand(1); 5718 SDValue Chain = getRoot(); 5719 SDValue RegName = 5720 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5721 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5722 RegName, getValue(RegValue))); 5723 return; 5724 } 5725 case Intrinsic::setjmp: 5726 lowerCallToExternalSymbol(I, &"_setjmp"[!TLI.usesUnderscoreSetJmp()]); 5727 return; 5728 case Intrinsic::longjmp: 5729 lowerCallToExternalSymbol(I, &"_longjmp"[!TLI.usesUnderscoreLongJmp()]); 5730 return; 5731 case Intrinsic::memcpy: { 5732 const auto &MCI = cast<MemCpyInst>(I); 5733 SDValue Op1 = getValue(I.getArgOperand(0)); 5734 SDValue Op2 = getValue(I.getArgOperand(1)); 5735 SDValue Op3 = getValue(I.getArgOperand(2)); 5736 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5737 unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1); 5738 unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1); 5739 unsigned Align = MinAlign(DstAlign, SrcAlign); 5740 bool isVol = MCI.isVolatile(); 5741 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5742 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5743 // node. 5744 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5745 false, isTC, 5746 MachinePointerInfo(I.getArgOperand(0)), 5747 MachinePointerInfo(I.getArgOperand(1))); 5748 updateDAGForMaybeTailCall(MC); 5749 return; 5750 } 5751 case Intrinsic::memset: { 5752 const auto &MSI = cast<MemSetInst>(I); 5753 SDValue Op1 = getValue(I.getArgOperand(0)); 5754 SDValue Op2 = getValue(I.getArgOperand(1)); 5755 SDValue Op3 = getValue(I.getArgOperand(2)); 5756 // @llvm.memset defines 0 and 1 to both mean no alignment. 5757 unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1); 5758 bool isVol = MSI.isVolatile(); 5759 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5760 SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5761 isTC, MachinePointerInfo(I.getArgOperand(0))); 5762 updateDAGForMaybeTailCall(MS); 5763 return; 5764 } 5765 case Intrinsic::memmove: { 5766 const auto &MMI = cast<MemMoveInst>(I); 5767 SDValue Op1 = getValue(I.getArgOperand(0)); 5768 SDValue Op2 = getValue(I.getArgOperand(1)); 5769 SDValue Op3 = getValue(I.getArgOperand(2)); 5770 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5771 unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1); 5772 unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1); 5773 unsigned Align = MinAlign(DstAlign, SrcAlign); 5774 bool isVol = MMI.isVolatile(); 5775 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5776 // FIXME: Support passing different dest/src alignments to the memmove DAG 5777 // node. 5778 SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5779 isTC, MachinePointerInfo(I.getArgOperand(0)), 5780 MachinePointerInfo(I.getArgOperand(1))); 5781 updateDAGForMaybeTailCall(MM); 5782 return; 5783 } 5784 case Intrinsic::memcpy_element_unordered_atomic: { 5785 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5786 SDValue Dst = getValue(MI.getRawDest()); 5787 SDValue Src = getValue(MI.getRawSource()); 5788 SDValue Length = getValue(MI.getLength()); 5789 5790 unsigned DstAlign = MI.getDestAlignment(); 5791 unsigned SrcAlign = MI.getSourceAlignment(); 5792 Type *LengthTy = MI.getLength()->getType(); 5793 unsigned ElemSz = MI.getElementSizeInBytes(); 5794 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5795 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5796 SrcAlign, Length, LengthTy, ElemSz, isTC, 5797 MachinePointerInfo(MI.getRawDest()), 5798 MachinePointerInfo(MI.getRawSource())); 5799 updateDAGForMaybeTailCall(MC); 5800 return; 5801 } 5802 case Intrinsic::memmove_element_unordered_atomic: { 5803 auto &MI = cast<AtomicMemMoveInst>(I); 5804 SDValue Dst = getValue(MI.getRawDest()); 5805 SDValue Src = getValue(MI.getRawSource()); 5806 SDValue Length = getValue(MI.getLength()); 5807 5808 unsigned DstAlign = MI.getDestAlignment(); 5809 unsigned SrcAlign = MI.getSourceAlignment(); 5810 Type *LengthTy = MI.getLength()->getType(); 5811 unsigned ElemSz = MI.getElementSizeInBytes(); 5812 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5813 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5814 SrcAlign, Length, LengthTy, ElemSz, isTC, 5815 MachinePointerInfo(MI.getRawDest()), 5816 MachinePointerInfo(MI.getRawSource())); 5817 updateDAGForMaybeTailCall(MC); 5818 return; 5819 } 5820 case Intrinsic::memset_element_unordered_atomic: { 5821 auto &MI = cast<AtomicMemSetInst>(I); 5822 SDValue Dst = getValue(MI.getRawDest()); 5823 SDValue Val = getValue(MI.getValue()); 5824 SDValue Length = getValue(MI.getLength()); 5825 5826 unsigned DstAlign = MI.getDestAlignment(); 5827 Type *LengthTy = MI.getLength()->getType(); 5828 unsigned ElemSz = MI.getElementSizeInBytes(); 5829 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5830 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5831 LengthTy, ElemSz, isTC, 5832 MachinePointerInfo(MI.getRawDest())); 5833 updateDAGForMaybeTailCall(MC); 5834 return; 5835 } 5836 case Intrinsic::dbg_addr: 5837 case Intrinsic::dbg_declare: { 5838 const auto &DI = cast<DbgVariableIntrinsic>(I); 5839 DILocalVariable *Variable = DI.getVariable(); 5840 DIExpression *Expression = DI.getExpression(); 5841 dropDanglingDebugInfo(Variable, Expression); 5842 assert(Variable && "Missing variable"); 5843 5844 // Check if address has undef value. 5845 const Value *Address = DI.getVariableLocation(); 5846 if (!Address || isa<UndefValue>(Address) || 5847 (Address->use_empty() && !isa<Argument>(Address))) { 5848 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5849 return; 5850 } 5851 5852 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5853 5854 // Check if this variable can be described by a frame index, typically 5855 // either as a static alloca or a byval parameter. 5856 int FI = std::numeric_limits<int>::max(); 5857 if (const auto *AI = 5858 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5859 if (AI->isStaticAlloca()) { 5860 auto I = FuncInfo.StaticAllocaMap.find(AI); 5861 if (I != FuncInfo.StaticAllocaMap.end()) 5862 FI = I->second; 5863 } 5864 } else if (const auto *Arg = dyn_cast<Argument>( 5865 Address->stripInBoundsConstantOffsets())) { 5866 FI = FuncInfo.getArgumentFrameIndex(Arg); 5867 } 5868 5869 // llvm.dbg.addr is control dependent and always generates indirect 5870 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5871 // the MachineFunction variable table. 5872 if (FI != std::numeric_limits<int>::max()) { 5873 if (Intrinsic == Intrinsic::dbg_addr) { 5874 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 5875 Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder); 5876 DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter); 5877 } 5878 return; 5879 } 5880 5881 SDValue &N = NodeMap[Address]; 5882 if (!N.getNode() && isa<Argument>(Address)) 5883 // Check unused arguments map. 5884 N = UnusedArgNodeMap[Address]; 5885 SDDbgValue *SDV; 5886 if (N.getNode()) { 5887 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 5888 Address = BCI->getOperand(0); 5889 // Parameters are handled specially. 5890 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 5891 if (isParameter && FINode) { 5892 // Byval parameter. We have a frame index at this point. 5893 SDV = 5894 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 5895 /*IsIndirect*/ true, dl, SDNodeOrder); 5896 } else if (isa<Argument>(Address)) { 5897 // Address is an argument, so try to emit its dbg value using 5898 // virtual register info from the FuncInfo.ValueMap. 5899 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 5900 return; 5901 } else { 5902 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 5903 true, dl, SDNodeOrder); 5904 } 5905 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 5906 } else { 5907 // If Address is an argument then try to emit its dbg value using 5908 // virtual register info from the FuncInfo.ValueMap. 5909 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 5910 N)) { 5911 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5912 } 5913 } 5914 return; 5915 } 5916 case Intrinsic::dbg_label: { 5917 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 5918 DILabel *Label = DI.getLabel(); 5919 assert(Label && "Missing label"); 5920 5921 SDDbgLabel *SDV; 5922 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 5923 DAG.AddDbgLabel(SDV); 5924 return; 5925 } 5926 case Intrinsic::dbg_value: { 5927 const DbgValueInst &DI = cast<DbgValueInst>(I); 5928 assert(DI.getVariable() && "Missing variable"); 5929 5930 DILocalVariable *Variable = DI.getVariable(); 5931 DIExpression *Expression = DI.getExpression(); 5932 dropDanglingDebugInfo(Variable, Expression); 5933 const Value *V = DI.getValue(); 5934 if (!V) 5935 return; 5936 5937 if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(), 5938 SDNodeOrder)) 5939 return; 5940 5941 // TODO: Dangling debug info will eventually either be resolved or produce 5942 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 5943 // between the original dbg.value location and its resolved DBG_VALUE, which 5944 // we should ideally fill with an extra Undef DBG_VALUE. 5945 5946 DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder); 5947 return; 5948 } 5949 5950 case Intrinsic::eh_typeid_for: { 5951 // Find the type id for the given typeinfo. 5952 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 5953 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 5954 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 5955 setValue(&I, Res); 5956 return; 5957 } 5958 5959 case Intrinsic::eh_return_i32: 5960 case Intrinsic::eh_return_i64: 5961 DAG.getMachineFunction().setCallsEHReturn(true); 5962 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 5963 MVT::Other, 5964 getControlRoot(), 5965 getValue(I.getArgOperand(0)), 5966 getValue(I.getArgOperand(1)))); 5967 return; 5968 case Intrinsic::eh_unwind_init: 5969 DAG.getMachineFunction().setCallsUnwindInit(true); 5970 return; 5971 case Intrinsic::eh_dwarf_cfa: 5972 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 5973 TLI.getPointerTy(DAG.getDataLayout()), 5974 getValue(I.getArgOperand(0)))); 5975 return; 5976 case Intrinsic::eh_sjlj_callsite: { 5977 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5978 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 5979 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 5980 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 5981 5982 MMI.setCurrentCallSite(CI->getZExtValue()); 5983 return; 5984 } 5985 case Intrinsic::eh_sjlj_functioncontext: { 5986 // Get and store the index of the function context. 5987 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5988 AllocaInst *FnCtx = 5989 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 5990 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 5991 MFI.setFunctionContextIndex(FI); 5992 return; 5993 } 5994 case Intrinsic::eh_sjlj_setjmp: { 5995 SDValue Ops[2]; 5996 Ops[0] = getRoot(); 5997 Ops[1] = getValue(I.getArgOperand(0)); 5998 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 5999 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6000 setValue(&I, Op.getValue(0)); 6001 DAG.setRoot(Op.getValue(1)); 6002 return; 6003 } 6004 case Intrinsic::eh_sjlj_longjmp: 6005 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6006 getRoot(), getValue(I.getArgOperand(0)))); 6007 return; 6008 case Intrinsic::eh_sjlj_setup_dispatch: 6009 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6010 getRoot())); 6011 return; 6012 case Intrinsic::masked_gather: 6013 visitMaskedGather(I); 6014 return; 6015 case Intrinsic::masked_load: 6016 visitMaskedLoad(I); 6017 return; 6018 case Intrinsic::masked_scatter: 6019 visitMaskedScatter(I); 6020 return; 6021 case Intrinsic::masked_store: 6022 visitMaskedStore(I); 6023 return; 6024 case Intrinsic::masked_expandload: 6025 visitMaskedLoad(I, true /* IsExpanding */); 6026 return; 6027 case Intrinsic::masked_compressstore: 6028 visitMaskedStore(I, true /* IsCompressing */); 6029 return; 6030 case Intrinsic::powi: 6031 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6032 getValue(I.getArgOperand(1)), DAG)); 6033 return; 6034 case Intrinsic::log: 6035 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6036 return; 6037 case Intrinsic::log2: 6038 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6039 return; 6040 case Intrinsic::log10: 6041 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6042 return; 6043 case Intrinsic::exp: 6044 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6045 return; 6046 case Intrinsic::exp2: 6047 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6048 return; 6049 case Intrinsic::pow: 6050 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6051 getValue(I.getArgOperand(1)), DAG, TLI)); 6052 return; 6053 case Intrinsic::sqrt: 6054 case Intrinsic::fabs: 6055 case Intrinsic::sin: 6056 case Intrinsic::cos: 6057 case Intrinsic::floor: 6058 case Intrinsic::ceil: 6059 case Intrinsic::trunc: 6060 case Intrinsic::rint: 6061 case Intrinsic::nearbyint: 6062 case Intrinsic::round: 6063 case Intrinsic::canonicalize: { 6064 unsigned Opcode; 6065 switch (Intrinsic) { 6066 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6067 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6068 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6069 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6070 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6071 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6072 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6073 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6074 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6075 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6076 case Intrinsic::round: Opcode = ISD::FROUND; break; 6077 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6078 } 6079 6080 setValue(&I, DAG.getNode(Opcode, sdl, 6081 getValue(I.getArgOperand(0)).getValueType(), 6082 getValue(I.getArgOperand(0)))); 6083 return; 6084 } 6085 case Intrinsic::lround: 6086 case Intrinsic::llround: 6087 case Intrinsic::lrint: 6088 case Intrinsic::llrint: { 6089 unsigned Opcode; 6090 switch (Intrinsic) { 6091 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6092 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6093 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6094 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6095 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6096 } 6097 6098 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6099 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6100 getValue(I.getArgOperand(0)))); 6101 return; 6102 } 6103 case Intrinsic::minnum: 6104 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6105 getValue(I.getArgOperand(0)).getValueType(), 6106 getValue(I.getArgOperand(0)), 6107 getValue(I.getArgOperand(1)))); 6108 return; 6109 case Intrinsic::maxnum: 6110 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6111 getValue(I.getArgOperand(0)).getValueType(), 6112 getValue(I.getArgOperand(0)), 6113 getValue(I.getArgOperand(1)))); 6114 return; 6115 case Intrinsic::minimum: 6116 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6117 getValue(I.getArgOperand(0)).getValueType(), 6118 getValue(I.getArgOperand(0)), 6119 getValue(I.getArgOperand(1)))); 6120 return; 6121 case Intrinsic::maximum: 6122 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6123 getValue(I.getArgOperand(0)).getValueType(), 6124 getValue(I.getArgOperand(0)), 6125 getValue(I.getArgOperand(1)))); 6126 return; 6127 case Intrinsic::copysign: 6128 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6129 getValue(I.getArgOperand(0)).getValueType(), 6130 getValue(I.getArgOperand(0)), 6131 getValue(I.getArgOperand(1)))); 6132 return; 6133 case Intrinsic::fma: 6134 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6135 getValue(I.getArgOperand(0)).getValueType(), 6136 getValue(I.getArgOperand(0)), 6137 getValue(I.getArgOperand(1)), 6138 getValue(I.getArgOperand(2)))); 6139 return; 6140 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 6141 case Intrinsic::INTRINSIC: 6142 #include "llvm/IR/ConstrainedOps.def" 6143 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6144 return; 6145 case Intrinsic::fmuladd: { 6146 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6147 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6148 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6149 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6150 getValue(I.getArgOperand(0)).getValueType(), 6151 getValue(I.getArgOperand(0)), 6152 getValue(I.getArgOperand(1)), 6153 getValue(I.getArgOperand(2)))); 6154 } else { 6155 // TODO: Intrinsic calls should have fast-math-flags. 6156 SDValue Mul = DAG.getNode(ISD::FMUL, sdl, 6157 getValue(I.getArgOperand(0)).getValueType(), 6158 getValue(I.getArgOperand(0)), 6159 getValue(I.getArgOperand(1))); 6160 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6161 getValue(I.getArgOperand(0)).getValueType(), 6162 Mul, 6163 getValue(I.getArgOperand(2))); 6164 setValue(&I, Add); 6165 } 6166 return; 6167 } 6168 case Intrinsic::convert_to_fp16: 6169 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6170 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6171 getValue(I.getArgOperand(0)), 6172 DAG.getTargetConstant(0, sdl, 6173 MVT::i32)))); 6174 return; 6175 case Intrinsic::convert_from_fp16: 6176 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6177 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6178 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6179 getValue(I.getArgOperand(0))))); 6180 return; 6181 case Intrinsic::pcmarker: { 6182 SDValue Tmp = getValue(I.getArgOperand(0)); 6183 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6184 return; 6185 } 6186 case Intrinsic::readcyclecounter: { 6187 SDValue Op = getRoot(); 6188 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6189 DAG.getVTList(MVT::i64, MVT::Other), Op); 6190 setValue(&I, Res); 6191 DAG.setRoot(Res.getValue(1)); 6192 return; 6193 } 6194 case Intrinsic::bitreverse: 6195 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6196 getValue(I.getArgOperand(0)).getValueType(), 6197 getValue(I.getArgOperand(0)))); 6198 return; 6199 case Intrinsic::bswap: 6200 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6201 getValue(I.getArgOperand(0)).getValueType(), 6202 getValue(I.getArgOperand(0)))); 6203 return; 6204 case Intrinsic::cttz: { 6205 SDValue Arg = getValue(I.getArgOperand(0)); 6206 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6207 EVT Ty = Arg.getValueType(); 6208 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6209 sdl, Ty, Arg)); 6210 return; 6211 } 6212 case Intrinsic::ctlz: { 6213 SDValue Arg = getValue(I.getArgOperand(0)); 6214 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6215 EVT Ty = Arg.getValueType(); 6216 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6217 sdl, Ty, Arg)); 6218 return; 6219 } 6220 case Intrinsic::ctpop: { 6221 SDValue Arg = getValue(I.getArgOperand(0)); 6222 EVT Ty = Arg.getValueType(); 6223 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6224 return; 6225 } 6226 case Intrinsic::fshl: 6227 case Intrinsic::fshr: { 6228 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6229 SDValue X = getValue(I.getArgOperand(0)); 6230 SDValue Y = getValue(I.getArgOperand(1)); 6231 SDValue Z = getValue(I.getArgOperand(2)); 6232 EVT VT = X.getValueType(); 6233 SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT); 6234 SDValue Zero = DAG.getConstant(0, sdl, VT); 6235 SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC); 6236 6237 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6238 if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) { 6239 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6240 return; 6241 } 6242 6243 // When X == Y, this is rotate. If the data type has a power-of-2 size, we 6244 // avoid the select that is necessary in the general case to filter out 6245 // the 0-shift possibility that leads to UB. 6246 if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) { 6247 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6248 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 6249 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6250 return; 6251 } 6252 6253 // Some targets only rotate one way. Try the opposite direction. 6254 RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL; 6255 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 6256 // Negate the shift amount because it is safe to ignore the high bits. 6257 SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 6258 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt)); 6259 return; 6260 } 6261 6262 // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW)) 6263 // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW)) 6264 SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 6265 SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC); 6266 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt); 6267 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt); 6268 setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY)); 6269 return; 6270 } 6271 6272 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 6273 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 6274 SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt); 6275 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt); 6276 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt); 6277 SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY); 6278 6279 // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth, 6280 // and that is undefined. We must compare and select to avoid UB. 6281 EVT CCVT = MVT::i1; 6282 if (VT.isVector()) 6283 CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements()); 6284 6285 // For fshl, 0-shift returns the 1st arg (X). 6286 // For fshr, 0-shift returns the 2nd arg (Y). 6287 SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ); 6288 setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or)); 6289 return; 6290 } 6291 case Intrinsic::sadd_sat: { 6292 SDValue Op1 = getValue(I.getArgOperand(0)); 6293 SDValue Op2 = getValue(I.getArgOperand(1)); 6294 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6295 return; 6296 } 6297 case Intrinsic::uadd_sat: { 6298 SDValue Op1 = getValue(I.getArgOperand(0)); 6299 SDValue Op2 = getValue(I.getArgOperand(1)); 6300 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6301 return; 6302 } 6303 case Intrinsic::ssub_sat: { 6304 SDValue Op1 = getValue(I.getArgOperand(0)); 6305 SDValue Op2 = getValue(I.getArgOperand(1)); 6306 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6307 return; 6308 } 6309 case Intrinsic::usub_sat: { 6310 SDValue Op1 = getValue(I.getArgOperand(0)); 6311 SDValue Op2 = getValue(I.getArgOperand(1)); 6312 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6313 return; 6314 } 6315 case Intrinsic::smul_fix: 6316 case Intrinsic::umul_fix: { 6317 SDValue Op1 = getValue(I.getArgOperand(0)); 6318 SDValue Op2 = getValue(I.getArgOperand(1)); 6319 SDValue Op3 = getValue(I.getArgOperand(2)); 6320 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6321 Op1.getValueType(), Op1, Op2, Op3)); 6322 return; 6323 } 6324 case Intrinsic::smul_fix_sat: { 6325 SDValue Op1 = getValue(I.getArgOperand(0)); 6326 SDValue Op2 = getValue(I.getArgOperand(1)); 6327 SDValue Op3 = getValue(I.getArgOperand(2)); 6328 setValue(&I, DAG.getNode(ISD::SMULFIXSAT, sdl, Op1.getValueType(), Op1, Op2, 6329 Op3)); 6330 return; 6331 } 6332 case Intrinsic::umul_fix_sat: { 6333 SDValue Op1 = getValue(I.getArgOperand(0)); 6334 SDValue Op2 = getValue(I.getArgOperand(1)); 6335 SDValue Op3 = getValue(I.getArgOperand(2)); 6336 setValue(&I, DAG.getNode(ISD::UMULFIXSAT, sdl, Op1.getValueType(), Op1, Op2, 6337 Op3)); 6338 return; 6339 } 6340 case Intrinsic::stacksave: { 6341 SDValue Op = getRoot(); 6342 Res = DAG.getNode( 6343 ISD::STACKSAVE, sdl, 6344 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op); 6345 setValue(&I, Res); 6346 DAG.setRoot(Res.getValue(1)); 6347 return; 6348 } 6349 case Intrinsic::stackrestore: 6350 Res = getValue(I.getArgOperand(0)); 6351 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6352 return; 6353 case Intrinsic::get_dynamic_area_offset: { 6354 SDValue Op = getRoot(); 6355 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6356 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6357 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6358 // target. 6359 if (PtrTy.getSizeInBits() < ResTy.getSizeInBits()) 6360 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6361 " intrinsic!"); 6362 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6363 Op); 6364 DAG.setRoot(Op); 6365 setValue(&I, Res); 6366 return; 6367 } 6368 case Intrinsic::stackguard: { 6369 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6370 MachineFunction &MF = DAG.getMachineFunction(); 6371 const Module &M = *MF.getFunction().getParent(); 6372 SDValue Chain = getRoot(); 6373 if (TLI.useLoadStackGuardNode()) { 6374 Res = getLoadStackGuard(DAG, sdl, Chain); 6375 } else { 6376 const Value *Global = TLI.getSDagStackGuard(M); 6377 unsigned Align = DL->getPrefTypeAlignment(Global->getType()); 6378 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6379 MachinePointerInfo(Global, 0), Align, 6380 MachineMemOperand::MOVolatile); 6381 } 6382 if (TLI.useStackGuardXorFP()) 6383 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6384 DAG.setRoot(Chain); 6385 setValue(&I, Res); 6386 return; 6387 } 6388 case Intrinsic::stackprotector: { 6389 // Emit code into the DAG to store the stack guard onto the stack. 6390 MachineFunction &MF = DAG.getMachineFunction(); 6391 MachineFrameInfo &MFI = MF.getFrameInfo(); 6392 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6393 SDValue Src, Chain = getRoot(); 6394 6395 if (TLI.useLoadStackGuardNode()) 6396 Src = getLoadStackGuard(DAG, sdl, Chain); 6397 else 6398 Src = getValue(I.getArgOperand(0)); // The guard's value. 6399 6400 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6401 6402 int FI = FuncInfo.StaticAllocaMap[Slot]; 6403 MFI.setStackProtectorIndex(FI); 6404 6405 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6406 6407 // Store the stack protector onto the stack. 6408 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack( 6409 DAG.getMachineFunction(), FI), 6410 /* Alignment = */ 0, MachineMemOperand::MOVolatile); 6411 setValue(&I, Res); 6412 DAG.setRoot(Res); 6413 return; 6414 } 6415 case Intrinsic::objectsize: 6416 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6417 6418 case Intrinsic::is_constant: 6419 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6420 6421 case Intrinsic::annotation: 6422 case Intrinsic::ptr_annotation: 6423 case Intrinsic::launder_invariant_group: 6424 case Intrinsic::strip_invariant_group: 6425 // Drop the intrinsic, but forward the value 6426 setValue(&I, getValue(I.getOperand(0))); 6427 return; 6428 case Intrinsic::assume: 6429 case Intrinsic::var_annotation: 6430 case Intrinsic::sideeffect: 6431 // Discard annotate attributes, assumptions, and artificial side-effects. 6432 return; 6433 6434 case Intrinsic::codeview_annotation: { 6435 // Emit a label associated with this metadata. 6436 MachineFunction &MF = DAG.getMachineFunction(); 6437 MCSymbol *Label = 6438 MF.getMMI().getContext().createTempSymbol("annotation", true); 6439 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6440 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6441 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6442 DAG.setRoot(Res); 6443 return; 6444 } 6445 6446 case Intrinsic::init_trampoline: { 6447 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6448 6449 SDValue Ops[6]; 6450 Ops[0] = getRoot(); 6451 Ops[1] = getValue(I.getArgOperand(0)); 6452 Ops[2] = getValue(I.getArgOperand(1)); 6453 Ops[3] = getValue(I.getArgOperand(2)); 6454 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6455 Ops[5] = DAG.getSrcValue(F); 6456 6457 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6458 6459 DAG.setRoot(Res); 6460 return; 6461 } 6462 case Intrinsic::adjust_trampoline: 6463 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6464 TLI.getPointerTy(DAG.getDataLayout()), 6465 getValue(I.getArgOperand(0)))); 6466 return; 6467 case Intrinsic::gcroot: { 6468 assert(DAG.getMachineFunction().getFunction().hasGC() && 6469 "only valid in functions with gc specified, enforced by Verifier"); 6470 assert(GFI && "implied by previous"); 6471 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6472 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6473 6474 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6475 GFI->addStackRoot(FI->getIndex(), TypeMap); 6476 return; 6477 } 6478 case Intrinsic::gcread: 6479 case Intrinsic::gcwrite: 6480 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6481 case Intrinsic::flt_rounds: 6482 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32)); 6483 return; 6484 6485 case Intrinsic::expect: 6486 // Just replace __builtin_expect(exp, c) with EXP. 6487 setValue(&I, getValue(I.getArgOperand(0))); 6488 return; 6489 6490 case Intrinsic::debugtrap: 6491 case Intrinsic::trap: { 6492 StringRef TrapFuncName = 6493 I.getAttributes() 6494 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6495 .getValueAsString(); 6496 if (TrapFuncName.empty()) { 6497 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 6498 ISD::TRAP : ISD::DEBUGTRAP; 6499 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 6500 return; 6501 } 6502 TargetLowering::ArgListTy Args; 6503 6504 TargetLowering::CallLoweringInfo CLI(DAG); 6505 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6506 CallingConv::C, I.getType(), 6507 DAG.getExternalSymbol(TrapFuncName.data(), 6508 TLI.getPointerTy(DAG.getDataLayout())), 6509 std::move(Args)); 6510 6511 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6512 DAG.setRoot(Result.second); 6513 return; 6514 } 6515 6516 case Intrinsic::uadd_with_overflow: 6517 case Intrinsic::sadd_with_overflow: 6518 case Intrinsic::usub_with_overflow: 6519 case Intrinsic::ssub_with_overflow: 6520 case Intrinsic::umul_with_overflow: 6521 case Intrinsic::smul_with_overflow: { 6522 ISD::NodeType Op; 6523 switch (Intrinsic) { 6524 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6525 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6526 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6527 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6528 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6529 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6530 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6531 } 6532 SDValue Op1 = getValue(I.getArgOperand(0)); 6533 SDValue Op2 = getValue(I.getArgOperand(1)); 6534 6535 EVT ResultVT = Op1.getValueType(); 6536 EVT OverflowVT = MVT::i1; 6537 if (ResultVT.isVector()) 6538 OverflowVT = EVT::getVectorVT( 6539 *Context, OverflowVT, ResultVT.getVectorNumElements()); 6540 6541 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6542 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6543 return; 6544 } 6545 case Intrinsic::prefetch: { 6546 SDValue Ops[5]; 6547 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6548 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6549 Ops[0] = DAG.getRoot(); 6550 Ops[1] = getValue(I.getArgOperand(0)); 6551 Ops[2] = getValue(I.getArgOperand(1)); 6552 Ops[3] = getValue(I.getArgOperand(2)); 6553 Ops[4] = getValue(I.getArgOperand(3)); 6554 SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl, 6555 DAG.getVTList(MVT::Other), Ops, 6556 EVT::getIntegerVT(*Context, 8), 6557 MachinePointerInfo(I.getArgOperand(0)), 6558 0, /* align */ 6559 Flags); 6560 6561 // Chain the prefetch in parallell with any pending loads, to stay out of 6562 // the way of later optimizations. 6563 PendingLoads.push_back(Result); 6564 Result = getRoot(); 6565 DAG.setRoot(Result); 6566 return; 6567 } 6568 case Intrinsic::lifetime_start: 6569 case Intrinsic::lifetime_end: { 6570 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6571 // Stack coloring is not enabled in O0, discard region information. 6572 if (TM.getOptLevel() == CodeGenOpt::None) 6573 return; 6574 6575 const int64_t ObjectSize = 6576 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6577 Value *const ObjectPtr = I.getArgOperand(1); 6578 SmallVector<const Value *, 4> Allocas; 6579 GetUnderlyingObjects(ObjectPtr, Allocas, *DL); 6580 6581 for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(), 6582 E = Allocas.end(); Object != E; ++Object) { 6583 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 6584 6585 // Could not find an Alloca. 6586 if (!LifetimeObject) 6587 continue; 6588 6589 // First check that the Alloca is static, otherwise it won't have a 6590 // valid frame index. 6591 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6592 if (SI == FuncInfo.StaticAllocaMap.end()) 6593 return; 6594 6595 const int FrameIndex = SI->second; 6596 int64_t Offset; 6597 if (GetPointerBaseWithConstantOffset( 6598 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6599 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6600 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6601 Offset); 6602 DAG.setRoot(Res); 6603 } 6604 return; 6605 } 6606 case Intrinsic::invariant_start: 6607 // Discard region information. 6608 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6609 return; 6610 case Intrinsic::invariant_end: 6611 // Discard region information. 6612 return; 6613 case Intrinsic::clear_cache: 6614 /// FunctionName may be null. 6615 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6616 lowerCallToExternalSymbol(I, FunctionName); 6617 return; 6618 case Intrinsic::donothing: 6619 // ignore 6620 return; 6621 case Intrinsic::experimental_stackmap: 6622 visitStackmap(I); 6623 return; 6624 case Intrinsic::experimental_patchpoint_void: 6625 case Intrinsic::experimental_patchpoint_i64: 6626 visitPatchpoint(&I); 6627 return; 6628 case Intrinsic::experimental_gc_statepoint: 6629 LowerStatepoint(ImmutableStatepoint(&I)); 6630 return; 6631 case Intrinsic::experimental_gc_result: 6632 visitGCResult(cast<GCResultInst>(I)); 6633 return; 6634 case Intrinsic::experimental_gc_relocate: 6635 visitGCRelocate(cast<GCRelocateInst>(I)); 6636 return; 6637 case Intrinsic::instrprof_increment: 6638 llvm_unreachable("instrprof failed to lower an increment"); 6639 case Intrinsic::instrprof_value_profile: 6640 llvm_unreachable("instrprof failed to lower a value profiling call"); 6641 case Intrinsic::localescape: { 6642 MachineFunction &MF = DAG.getMachineFunction(); 6643 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6644 6645 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6646 // is the same on all targets. 6647 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6648 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6649 if (isa<ConstantPointerNull>(Arg)) 6650 continue; // Skip null pointers. They represent a hole in index space. 6651 AllocaInst *Slot = cast<AllocaInst>(Arg); 6652 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6653 "can only escape static allocas"); 6654 int FI = FuncInfo.StaticAllocaMap[Slot]; 6655 MCSymbol *FrameAllocSym = 6656 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6657 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6658 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6659 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6660 .addSym(FrameAllocSym) 6661 .addFrameIndex(FI); 6662 } 6663 6664 return; 6665 } 6666 6667 case Intrinsic::localrecover: { 6668 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6669 MachineFunction &MF = DAG.getMachineFunction(); 6670 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0); 6671 6672 // Get the symbol that defines the frame offset. 6673 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6674 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6675 unsigned IdxVal = 6676 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6677 MCSymbol *FrameAllocSym = 6678 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6679 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6680 6681 // Create a MCSymbol for the label to avoid any target lowering 6682 // that would make this PC relative. 6683 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6684 SDValue OffsetVal = 6685 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6686 6687 // Add the offset to the FP. 6688 Value *FP = I.getArgOperand(1); 6689 SDValue FPVal = getValue(FP); 6690 SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal); 6691 setValue(&I, Add); 6692 6693 return; 6694 } 6695 6696 case Intrinsic::eh_exceptionpointer: 6697 case Intrinsic::eh_exceptioncode: { 6698 // Get the exception pointer vreg, copy from it, and resize it to fit. 6699 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6700 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6701 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6702 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6703 SDValue N = 6704 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6705 if (Intrinsic == Intrinsic::eh_exceptioncode) 6706 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6707 setValue(&I, N); 6708 return; 6709 } 6710 case Intrinsic::xray_customevent: { 6711 // Here we want to make sure that the intrinsic behaves as if it has a 6712 // specific calling convention, and only for x86_64. 6713 // FIXME: Support other platforms later. 6714 const auto &Triple = DAG.getTarget().getTargetTriple(); 6715 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6716 return; 6717 6718 SDLoc DL = getCurSDLoc(); 6719 SmallVector<SDValue, 8> Ops; 6720 6721 // We want to say that we always want the arguments in registers. 6722 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6723 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6724 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6725 SDValue Chain = getRoot(); 6726 Ops.push_back(LogEntryVal); 6727 Ops.push_back(StrSizeVal); 6728 Ops.push_back(Chain); 6729 6730 // We need to enforce the calling convention for the callsite, so that 6731 // argument ordering is enforced correctly, and that register allocation can 6732 // see that some registers may be assumed clobbered and have to preserve 6733 // them across calls to the intrinsic. 6734 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6735 DL, NodeTys, Ops); 6736 SDValue patchableNode = SDValue(MN, 0); 6737 DAG.setRoot(patchableNode); 6738 setValue(&I, patchableNode); 6739 return; 6740 } 6741 case Intrinsic::xray_typedevent: { 6742 // Here we want to make sure that the intrinsic behaves as if it has a 6743 // specific calling convention, and only for x86_64. 6744 // FIXME: Support other platforms later. 6745 const auto &Triple = DAG.getTarget().getTargetTriple(); 6746 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6747 return; 6748 6749 SDLoc DL = getCurSDLoc(); 6750 SmallVector<SDValue, 8> Ops; 6751 6752 // We want to say that we always want the arguments in registers. 6753 // It's unclear to me how manipulating the selection DAG here forces callers 6754 // to provide arguments in registers instead of on the stack. 6755 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6756 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6757 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6758 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6759 SDValue Chain = getRoot(); 6760 Ops.push_back(LogTypeId); 6761 Ops.push_back(LogEntryVal); 6762 Ops.push_back(StrSizeVal); 6763 Ops.push_back(Chain); 6764 6765 // We need to enforce the calling convention for the callsite, so that 6766 // argument ordering is enforced correctly, and that register allocation can 6767 // see that some registers may be assumed clobbered and have to preserve 6768 // them across calls to the intrinsic. 6769 MachineSDNode *MN = DAG.getMachineNode( 6770 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6771 SDValue patchableNode = SDValue(MN, 0); 6772 DAG.setRoot(patchableNode); 6773 setValue(&I, patchableNode); 6774 return; 6775 } 6776 case Intrinsic::experimental_deoptimize: 6777 LowerDeoptimizeCall(&I); 6778 return; 6779 6780 case Intrinsic::experimental_vector_reduce_v2_fadd: 6781 case Intrinsic::experimental_vector_reduce_v2_fmul: 6782 case Intrinsic::experimental_vector_reduce_add: 6783 case Intrinsic::experimental_vector_reduce_mul: 6784 case Intrinsic::experimental_vector_reduce_and: 6785 case Intrinsic::experimental_vector_reduce_or: 6786 case Intrinsic::experimental_vector_reduce_xor: 6787 case Intrinsic::experimental_vector_reduce_smax: 6788 case Intrinsic::experimental_vector_reduce_smin: 6789 case Intrinsic::experimental_vector_reduce_umax: 6790 case Intrinsic::experimental_vector_reduce_umin: 6791 case Intrinsic::experimental_vector_reduce_fmax: 6792 case Intrinsic::experimental_vector_reduce_fmin: 6793 visitVectorReduce(I, Intrinsic); 6794 return; 6795 6796 case Intrinsic::icall_branch_funnel: { 6797 SmallVector<SDValue, 16> Ops; 6798 Ops.push_back(getValue(I.getArgOperand(0))); 6799 6800 int64_t Offset; 6801 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6802 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6803 if (!Base) 6804 report_fatal_error( 6805 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6806 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6807 6808 struct BranchFunnelTarget { 6809 int64_t Offset; 6810 SDValue Target; 6811 }; 6812 SmallVector<BranchFunnelTarget, 8> Targets; 6813 6814 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6815 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6816 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6817 if (ElemBase != Base) 6818 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6819 "to the same GlobalValue"); 6820 6821 SDValue Val = getValue(I.getArgOperand(Op + 1)); 6822 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 6823 if (!GA) 6824 report_fatal_error( 6825 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6826 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 6827 GA->getGlobal(), getCurSDLoc(), 6828 Val.getValueType(), GA->getOffset())}); 6829 } 6830 llvm::sort(Targets, 6831 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 6832 return T1.Offset < T2.Offset; 6833 }); 6834 6835 for (auto &T : Targets) { 6836 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 6837 Ops.push_back(T.Target); 6838 } 6839 6840 Ops.push_back(DAG.getRoot()); // Chain 6841 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 6842 getCurSDLoc(), MVT::Other, Ops), 6843 0); 6844 DAG.setRoot(N); 6845 setValue(&I, N); 6846 HasTailCall = true; 6847 return; 6848 } 6849 6850 case Intrinsic::wasm_landingpad_index: 6851 // Information this intrinsic contained has been transferred to 6852 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 6853 // delete it now. 6854 return; 6855 6856 case Intrinsic::aarch64_settag: 6857 case Intrinsic::aarch64_settag_zero: { 6858 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6859 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 6860 SDValue Val = TSI.EmitTargetCodeForSetTag( 6861 DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)), 6862 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 6863 ZeroMemory); 6864 DAG.setRoot(Val); 6865 setValue(&I, Val); 6866 return; 6867 } 6868 case Intrinsic::ptrmask: { 6869 SDValue Ptr = getValue(I.getOperand(0)); 6870 SDValue Const = getValue(I.getOperand(1)); 6871 6872 EVT DestVT = 6873 EVT(DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 6874 6875 setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), DestVT, Ptr, 6876 DAG.getZExtOrTrunc(Const, getCurSDLoc(), DestVT))); 6877 return; 6878 } 6879 } 6880 } 6881 6882 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 6883 const ConstrainedFPIntrinsic &FPI) { 6884 SDLoc sdl = getCurSDLoc(); 6885 6886 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6887 SmallVector<EVT, 4> ValueVTs; 6888 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 6889 ValueVTs.push_back(MVT::Other); // Out chain 6890 6891 SDValue Chain = getRoot(); 6892 SmallVector<SDValue, 4> Opers; 6893 Opers.push_back(Chain); 6894 if (FPI.isUnaryOp()) { 6895 Opers.push_back(getValue(FPI.getArgOperand(0))); 6896 } else if (FPI.isTernaryOp()) { 6897 Opers.push_back(getValue(FPI.getArgOperand(0))); 6898 Opers.push_back(getValue(FPI.getArgOperand(1))); 6899 Opers.push_back(getValue(FPI.getArgOperand(2))); 6900 } else { 6901 Opers.push_back(getValue(FPI.getArgOperand(0))); 6902 Opers.push_back(getValue(FPI.getArgOperand(1))); 6903 } 6904 6905 unsigned Opcode; 6906 switch (FPI.getIntrinsicID()) { 6907 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6908 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 6909 case Intrinsic::INTRINSIC: \ 6910 Opcode = ISD::STRICT_##DAGN; \ 6911 break; 6912 #include "llvm/IR/ConstrainedOps.def" 6913 } 6914 6915 if (Opcode == ISD::STRICT_FP_ROUND) 6916 Opers.push_back( 6917 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 6918 6919 SDVTList VTs = DAG.getVTList(ValueVTs); 6920 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers); 6921 6922 if (FPI.getExceptionBehavior() != fp::ExceptionBehavior::ebIgnore) { 6923 SDNodeFlags Flags; 6924 Flags.setFPExcept(true); 6925 Result->setFlags(Flags); 6926 } 6927 6928 assert(Result.getNode()->getNumValues() == 2); 6929 SDValue OutChain = Result.getValue(1); 6930 DAG.setRoot(OutChain); 6931 SDValue FPResult = Result.getValue(0); 6932 setValue(&FPI, FPResult); 6933 } 6934 6935 std::pair<SDValue, SDValue> 6936 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 6937 const BasicBlock *EHPadBB) { 6938 MachineFunction &MF = DAG.getMachineFunction(); 6939 MachineModuleInfo &MMI = MF.getMMI(); 6940 MCSymbol *BeginLabel = nullptr; 6941 6942 if (EHPadBB) { 6943 // Insert a label before the invoke call to mark the try range. This can be 6944 // used to detect deletion of the invoke via the MachineModuleInfo. 6945 BeginLabel = MMI.getContext().createTempSymbol(); 6946 6947 // For SjLj, keep track of which landing pads go with which invokes 6948 // so as to maintain the ordering of pads in the LSDA. 6949 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 6950 if (CallSiteIndex) { 6951 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 6952 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 6953 6954 // Now that the call site is handled, stop tracking it. 6955 MMI.setCurrentCallSite(0); 6956 } 6957 6958 // Both PendingLoads and PendingExports must be flushed here; 6959 // this call might not return. 6960 (void)getRoot(); 6961 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 6962 6963 CLI.setChain(getRoot()); 6964 } 6965 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6966 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6967 6968 assert((CLI.IsTailCall || Result.second.getNode()) && 6969 "Non-null chain expected with non-tail call!"); 6970 assert((Result.second.getNode() || !Result.first.getNode()) && 6971 "Null value expected with tail call!"); 6972 6973 if (!Result.second.getNode()) { 6974 // As a special case, a null chain means that a tail call has been emitted 6975 // and the DAG root is already updated. 6976 HasTailCall = true; 6977 6978 // Since there's no actual continuation from this block, nothing can be 6979 // relying on us setting vregs for them. 6980 PendingExports.clear(); 6981 } else { 6982 DAG.setRoot(Result.second); 6983 } 6984 6985 if (EHPadBB) { 6986 // Insert a label at the end of the invoke call to mark the try range. This 6987 // can be used to detect deletion of the invoke via the MachineModuleInfo. 6988 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 6989 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 6990 6991 // Inform MachineModuleInfo of range. 6992 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 6993 // There is a platform (e.g. wasm) that uses funclet style IR but does not 6994 // actually use outlined funclets and their LSDA info style. 6995 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 6996 assert(CLI.CS); 6997 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 6998 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()), 6999 BeginLabel, EndLabel); 7000 } else if (!isScopedEHPersonality(Pers)) { 7001 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7002 } 7003 } 7004 7005 return Result; 7006 } 7007 7008 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee, 7009 bool isTailCall, 7010 const BasicBlock *EHPadBB) { 7011 auto &DL = DAG.getDataLayout(); 7012 FunctionType *FTy = CS.getFunctionType(); 7013 Type *RetTy = CS.getType(); 7014 7015 TargetLowering::ArgListTy Args; 7016 Args.reserve(CS.arg_size()); 7017 7018 const Value *SwiftErrorVal = nullptr; 7019 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7020 7021 // We can't tail call inside a function with a swifterror argument. Lowering 7022 // does not support this yet. It would have to move into the swifterror 7023 // register before the call. 7024 auto *Caller = CS.getInstruction()->getParent()->getParent(); 7025 if (TLI.supportSwiftError() && 7026 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7027 isTailCall = false; 7028 7029 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 7030 i != e; ++i) { 7031 TargetLowering::ArgListEntry Entry; 7032 const Value *V = *i; 7033 7034 // Skip empty types 7035 if (V->getType()->isEmptyTy()) 7036 continue; 7037 7038 SDValue ArgNode = getValue(V); 7039 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7040 7041 Entry.setAttributes(&CS, i - CS.arg_begin()); 7042 7043 // Use swifterror virtual register as input to the call. 7044 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7045 SwiftErrorVal = V; 7046 // We find the virtual register for the actual swifterror argument. 7047 // Instead of using the Value, we use the virtual register instead. 7048 Entry.Node = DAG.getRegister( 7049 SwiftError.getOrCreateVRegUseAt(CS.getInstruction(), FuncInfo.MBB, V), 7050 EVT(TLI.getPointerTy(DL))); 7051 } 7052 7053 Args.push_back(Entry); 7054 7055 // If we have an explicit sret argument that is an Instruction, (i.e., it 7056 // might point to function-local memory), we can't meaningfully tail-call. 7057 if (Entry.IsSRet && isa<Instruction>(V)) 7058 isTailCall = false; 7059 } 7060 7061 // If call site has a cfguardtarget operand bundle, create and add an 7062 // additional ArgListEntry. 7063 if (auto Bundle = CS.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7064 TargetLowering::ArgListEntry Entry; 7065 Value *V = Bundle->Inputs[0]; 7066 SDValue ArgNode = getValue(V); 7067 Entry.Node = ArgNode; 7068 Entry.Ty = V->getType(); 7069 Entry.IsCFGuardTarget = true; 7070 Args.push_back(Entry); 7071 } 7072 7073 // Check if target-independent constraints permit a tail call here. 7074 // Target-dependent constraints are checked within TLI->LowerCallTo. 7075 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget())) 7076 isTailCall = false; 7077 7078 // Disable tail calls if there is an swifterror argument. Targets have not 7079 // been updated to support tail calls. 7080 if (TLI.supportSwiftError() && SwiftErrorVal) 7081 isTailCall = false; 7082 7083 TargetLowering::CallLoweringInfo CLI(DAG); 7084 CLI.setDebugLoc(getCurSDLoc()) 7085 .setChain(getRoot()) 7086 .setCallee(RetTy, FTy, Callee, std::move(Args), CS) 7087 .setTailCall(isTailCall) 7088 .setConvergent(CS.isConvergent()); 7089 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7090 7091 if (Result.first.getNode()) { 7092 const Instruction *Inst = CS.getInstruction(); 7093 Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first); 7094 setValue(Inst, Result.first); 7095 } 7096 7097 // The last element of CLI.InVals has the SDValue for swifterror return. 7098 // Here we copy it to a virtual register and update SwiftErrorMap for 7099 // book-keeping. 7100 if (SwiftErrorVal && TLI.supportSwiftError()) { 7101 // Get the last element of InVals. 7102 SDValue Src = CLI.InVals.back(); 7103 Register VReg = SwiftError.getOrCreateVRegDefAt( 7104 CS.getInstruction(), FuncInfo.MBB, SwiftErrorVal); 7105 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7106 DAG.setRoot(CopyNode); 7107 } 7108 } 7109 7110 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7111 SelectionDAGBuilder &Builder) { 7112 // Check to see if this load can be trivially constant folded, e.g. if the 7113 // input is from a string literal. 7114 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7115 // Cast pointer to the type we really want to load. 7116 Type *LoadTy = 7117 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7118 if (LoadVT.isVector()) 7119 LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7120 7121 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7122 PointerType::getUnqual(LoadTy)); 7123 7124 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 7125 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 7126 return Builder.getValue(LoadCst); 7127 } 7128 7129 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7130 // still constant memory, the input chain can be the entry node. 7131 SDValue Root; 7132 bool ConstantMemory = false; 7133 7134 // Do not serialize (non-volatile) loads of constant memory with anything. 7135 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7136 Root = Builder.DAG.getEntryNode(); 7137 ConstantMemory = true; 7138 } else { 7139 // Do not serialize non-volatile loads against each other. 7140 Root = Builder.DAG.getRoot(); 7141 } 7142 7143 SDValue Ptr = Builder.getValue(PtrVal); 7144 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, 7145 Ptr, MachinePointerInfo(PtrVal), 7146 /* Alignment = */ 1); 7147 7148 if (!ConstantMemory) 7149 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7150 return LoadVal; 7151 } 7152 7153 /// Record the value for an instruction that produces an integer result, 7154 /// converting the type where necessary. 7155 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7156 SDValue Value, 7157 bool IsSigned) { 7158 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7159 I.getType(), true); 7160 if (IsSigned) 7161 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7162 else 7163 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7164 setValue(&I, Value); 7165 } 7166 7167 /// See if we can lower a memcmp call into an optimized form. If so, return 7168 /// true and lower it. Otherwise return false, and it will be lowered like a 7169 /// normal call. 7170 /// The caller already checked that \p I calls the appropriate LibFunc with a 7171 /// correct prototype. 7172 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 7173 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 7174 const Value *Size = I.getArgOperand(2); 7175 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 7176 if (CSize && CSize->getZExtValue() == 0) { 7177 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7178 I.getType(), true); 7179 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 7180 return true; 7181 } 7182 7183 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7184 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 7185 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 7186 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 7187 if (Res.first.getNode()) { 7188 processIntegerCallValue(I, Res.first, true); 7189 PendingLoads.push_back(Res.second); 7190 return true; 7191 } 7192 7193 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 7194 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 7195 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 7196 return false; 7197 7198 // If the target has a fast compare for the given size, it will return a 7199 // preferred load type for that size. Require that the load VT is legal and 7200 // that the target supports unaligned loads of that type. Otherwise, return 7201 // INVALID. 7202 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 7203 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7204 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 7205 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 7206 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 7207 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 7208 // TODO: Check alignment of src and dest ptrs. 7209 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 7210 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 7211 if (!TLI.isTypeLegal(LVT) || 7212 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 7213 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 7214 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 7215 } 7216 7217 return LVT; 7218 }; 7219 7220 // This turns into unaligned loads. We only do this if the target natively 7221 // supports the MVT we'll be loading or if it is small enough (<= 4) that 7222 // we'll only produce a small number of byte loads. 7223 MVT LoadVT; 7224 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 7225 switch (NumBitsToCompare) { 7226 default: 7227 return false; 7228 case 16: 7229 LoadVT = MVT::i16; 7230 break; 7231 case 32: 7232 LoadVT = MVT::i32; 7233 break; 7234 case 64: 7235 case 128: 7236 case 256: 7237 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 7238 break; 7239 } 7240 7241 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 7242 return false; 7243 7244 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 7245 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 7246 7247 // Bitcast to a wide integer type if the loads are vectors. 7248 if (LoadVT.isVector()) { 7249 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 7250 LoadL = DAG.getBitcast(CmpVT, LoadL); 7251 LoadR = DAG.getBitcast(CmpVT, LoadR); 7252 } 7253 7254 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 7255 processIntegerCallValue(I, Cmp, false); 7256 return true; 7257 } 7258 7259 /// See if we can lower a memchr call into an optimized form. If so, return 7260 /// true and lower it. Otherwise return false, and it will be lowered like a 7261 /// normal call. 7262 /// The caller already checked that \p I calls the appropriate LibFunc with a 7263 /// correct prototype. 7264 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 7265 const Value *Src = I.getArgOperand(0); 7266 const Value *Char = I.getArgOperand(1); 7267 const Value *Length = I.getArgOperand(2); 7268 7269 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7270 std::pair<SDValue, SDValue> Res = 7271 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 7272 getValue(Src), getValue(Char), getValue(Length), 7273 MachinePointerInfo(Src)); 7274 if (Res.first.getNode()) { 7275 setValue(&I, Res.first); 7276 PendingLoads.push_back(Res.second); 7277 return true; 7278 } 7279 7280 return false; 7281 } 7282 7283 /// See if we can lower a mempcpy call into an optimized form. If so, return 7284 /// true and lower it. Otherwise return false, and it will be lowered like a 7285 /// normal call. 7286 /// The caller already checked that \p I calls the appropriate LibFunc with a 7287 /// correct prototype. 7288 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 7289 SDValue Dst = getValue(I.getArgOperand(0)); 7290 SDValue Src = getValue(I.getArgOperand(1)); 7291 SDValue Size = getValue(I.getArgOperand(2)); 7292 7293 unsigned DstAlign = DAG.InferPtrAlignment(Dst); 7294 unsigned SrcAlign = DAG.InferPtrAlignment(Src); 7295 unsigned Align = std::min(DstAlign, SrcAlign); 7296 if (Align == 0) // Alignment of one or both could not be inferred. 7297 Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved. 7298 7299 bool isVol = false; 7300 SDLoc sdl = getCurSDLoc(); 7301 7302 // In the mempcpy context we need to pass in a false value for isTailCall 7303 // because the return pointer needs to be adjusted by the size of 7304 // the copied memory. 7305 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol, 7306 false, /*isTailCall=*/false, 7307 MachinePointerInfo(I.getArgOperand(0)), 7308 MachinePointerInfo(I.getArgOperand(1))); 7309 assert(MC.getNode() != nullptr && 7310 "** memcpy should not be lowered as TailCall in mempcpy context **"); 7311 DAG.setRoot(MC); 7312 7313 // Check if Size needs to be truncated or extended. 7314 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 7315 7316 // Adjust return pointer to point just past the last dst byte. 7317 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 7318 Dst, Size); 7319 setValue(&I, DstPlusSize); 7320 return true; 7321 } 7322 7323 /// See if we can lower a strcpy call into an optimized form. If so, return 7324 /// true and lower it, otherwise return false and it will be lowered like a 7325 /// normal call. 7326 /// The caller already checked that \p I calls the appropriate LibFunc with a 7327 /// correct prototype. 7328 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 7329 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7330 7331 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7332 std::pair<SDValue, SDValue> Res = 7333 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 7334 getValue(Arg0), getValue(Arg1), 7335 MachinePointerInfo(Arg0), 7336 MachinePointerInfo(Arg1), isStpcpy); 7337 if (Res.first.getNode()) { 7338 setValue(&I, Res.first); 7339 DAG.setRoot(Res.second); 7340 return true; 7341 } 7342 7343 return false; 7344 } 7345 7346 /// See if we can lower a strcmp call into an optimized form. If so, return 7347 /// true and lower it, otherwise return false and it will be lowered like a 7348 /// normal call. 7349 /// The caller already checked that \p I calls the appropriate LibFunc with a 7350 /// correct prototype. 7351 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 7352 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7353 7354 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7355 std::pair<SDValue, SDValue> Res = 7356 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 7357 getValue(Arg0), getValue(Arg1), 7358 MachinePointerInfo(Arg0), 7359 MachinePointerInfo(Arg1)); 7360 if (Res.first.getNode()) { 7361 processIntegerCallValue(I, Res.first, true); 7362 PendingLoads.push_back(Res.second); 7363 return true; 7364 } 7365 7366 return false; 7367 } 7368 7369 /// See if we can lower a strlen call into an optimized form. If so, return 7370 /// true and lower it, otherwise return false and it will be lowered like a 7371 /// normal call. 7372 /// The caller already checked that \p I calls the appropriate LibFunc with a 7373 /// correct prototype. 7374 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 7375 const Value *Arg0 = I.getArgOperand(0); 7376 7377 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7378 std::pair<SDValue, SDValue> Res = 7379 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 7380 getValue(Arg0), MachinePointerInfo(Arg0)); 7381 if (Res.first.getNode()) { 7382 processIntegerCallValue(I, Res.first, false); 7383 PendingLoads.push_back(Res.second); 7384 return true; 7385 } 7386 7387 return false; 7388 } 7389 7390 /// See if we can lower a strnlen call into an optimized form. If so, return 7391 /// true and lower it, otherwise return false and it will be lowered like a 7392 /// normal call. 7393 /// The caller already checked that \p I calls the appropriate LibFunc with a 7394 /// correct prototype. 7395 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 7396 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7397 7398 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7399 std::pair<SDValue, SDValue> Res = 7400 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 7401 getValue(Arg0), getValue(Arg1), 7402 MachinePointerInfo(Arg0)); 7403 if (Res.first.getNode()) { 7404 processIntegerCallValue(I, Res.first, false); 7405 PendingLoads.push_back(Res.second); 7406 return true; 7407 } 7408 7409 return false; 7410 } 7411 7412 /// See if we can lower a unary floating-point operation into an SDNode with 7413 /// the specified Opcode. If so, return true and lower it, otherwise return 7414 /// false and it will be lowered like a normal call. 7415 /// The caller already checked that \p I calls the appropriate LibFunc with a 7416 /// correct prototype. 7417 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 7418 unsigned Opcode) { 7419 // We already checked this call's prototype; verify it doesn't modify errno. 7420 if (!I.onlyReadsMemory()) 7421 return false; 7422 7423 SDValue Tmp = getValue(I.getArgOperand(0)); 7424 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); 7425 return true; 7426 } 7427 7428 /// See if we can lower a binary floating-point operation into an SDNode with 7429 /// the specified Opcode. If so, return true and lower it. Otherwise return 7430 /// false, and it will be lowered like a normal call. 7431 /// The caller already checked that \p I calls the appropriate LibFunc with a 7432 /// correct prototype. 7433 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 7434 unsigned Opcode) { 7435 // We already checked this call's prototype; verify it doesn't modify errno. 7436 if (!I.onlyReadsMemory()) 7437 return false; 7438 7439 SDValue Tmp0 = getValue(I.getArgOperand(0)); 7440 SDValue Tmp1 = getValue(I.getArgOperand(1)); 7441 EVT VT = Tmp0.getValueType(); 7442 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1)); 7443 return true; 7444 } 7445 7446 void SelectionDAGBuilder::visitCall(const CallInst &I) { 7447 // Handle inline assembly differently. 7448 if (isa<InlineAsm>(I.getCalledValue())) { 7449 visitInlineAsm(&I); 7450 return; 7451 } 7452 7453 if (Function *F = I.getCalledFunction()) { 7454 if (F->isDeclaration()) { 7455 // Is this an LLVM intrinsic or a target-specific intrinsic? 7456 unsigned IID = F->getIntrinsicID(); 7457 if (!IID) 7458 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7459 IID = II->getIntrinsicID(F); 7460 7461 if (IID) { 7462 visitIntrinsicCall(I, IID); 7463 return; 7464 } 7465 } 7466 7467 // Check for well-known libc/libm calls. If the function is internal, it 7468 // can't be a library call. Don't do the check if marked as nobuiltin for 7469 // some reason or the call site requires strict floating point semantics. 7470 LibFunc Func; 7471 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7472 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7473 LibInfo->hasOptimizedCodeGen(Func)) { 7474 switch (Func) { 7475 default: break; 7476 case LibFunc_copysign: 7477 case LibFunc_copysignf: 7478 case LibFunc_copysignl: 7479 // We already checked this call's prototype; verify it doesn't modify 7480 // errno. 7481 if (I.onlyReadsMemory()) { 7482 SDValue LHS = getValue(I.getArgOperand(0)); 7483 SDValue RHS = getValue(I.getArgOperand(1)); 7484 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7485 LHS.getValueType(), LHS, RHS)); 7486 return; 7487 } 7488 break; 7489 case LibFunc_fabs: 7490 case LibFunc_fabsf: 7491 case LibFunc_fabsl: 7492 if (visitUnaryFloatCall(I, ISD::FABS)) 7493 return; 7494 break; 7495 case LibFunc_fmin: 7496 case LibFunc_fminf: 7497 case LibFunc_fminl: 7498 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7499 return; 7500 break; 7501 case LibFunc_fmax: 7502 case LibFunc_fmaxf: 7503 case LibFunc_fmaxl: 7504 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7505 return; 7506 break; 7507 case LibFunc_sin: 7508 case LibFunc_sinf: 7509 case LibFunc_sinl: 7510 if (visitUnaryFloatCall(I, ISD::FSIN)) 7511 return; 7512 break; 7513 case LibFunc_cos: 7514 case LibFunc_cosf: 7515 case LibFunc_cosl: 7516 if (visitUnaryFloatCall(I, ISD::FCOS)) 7517 return; 7518 break; 7519 case LibFunc_sqrt: 7520 case LibFunc_sqrtf: 7521 case LibFunc_sqrtl: 7522 case LibFunc_sqrt_finite: 7523 case LibFunc_sqrtf_finite: 7524 case LibFunc_sqrtl_finite: 7525 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7526 return; 7527 break; 7528 case LibFunc_floor: 7529 case LibFunc_floorf: 7530 case LibFunc_floorl: 7531 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7532 return; 7533 break; 7534 case LibFunc_nearbyint: 7535 case LibFunc_nearbyintf: 7536 case LibFunc_nearbyintl: 7537 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7538 return; 7539 break; 7540 case LibFunc_ceil: 7541 case LibFunc_ceilf: 7542 case LibFunc_ceill: 7543 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7544 return; 7545 break; 7546 case LibFunc_rint: 7547 case LibFunc_rintf: 7548 case LibFunc_rintl: 7549 if (visitUnaryFloatCall(I, ISD::FRINT)) 7550 return; 7551 break; 7552 case LibFunc_round: 7553 case LibFunc_roundf: 7554 case LibFunc_roundl: 7555 if (visitUnaryFloatCall(I, ISD::FROUND)) 7556 return; 7557 break; 7558 case LibFunc_trunc: 7559 case LibFunc_truncf: 7560 case LibFunc_truncl: 7561 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7562 return; 7563 break; 7564 case LibFunc_log2: 7565 case LibFunc_log2f: 7566 case LibFunc_log2l: 7567 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7568 return; 7569 break; 7570 case LibFunc_exp2: 7571 case LibFunc_exp2f: 7572 case LibFunc_exp2l: 7573 if (visitUnaryFloatCall(I, ISD::FEXP2)) 7574 return; 7575 break; 7576 case LibFunc_memcmp: 7577 if (visitMemCmpCall(I)) 7578 return; 7579 break; 7580 case LibFunc_mempcpy: 7581 if (visitMemPCpyCall(I)) 7582 return; 7583 break; 7584 case LibFunc_memchr: 7585 if (visitMemChrCall(I)) 7586 return; 7587 break; 7588 case LibFunc_strcpy: 7589 if (visitStrCpyCall(I, false)) 7590 return; 7591 break; 7592 case LibFunc_stpcpy: 7593 if (visitStrCpyCall(I, true)) 7594 return; 7595 break; 7596 case LibFunc_strcmp: 7597 if (visitStrCmpCall(I)) 7598 return; 7599 break; 7600 case LibFunc_strlen: 7601 if (visitStrLenCall(I)) 7602 return; 7603 break; 7604 case LibFunc_strnlen: 7605 if (visitStrNLenCall(I)) 7606 return; 7607 break; 7608 } 7609 } 7610 } 7611 7612 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 7613 // have to do anything here to lower funclet bundles. 7614 // CFGuardTarget bundles are lowered in LowerCallTo. 7615 assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt, 7616 LLVMContext::OB_funclet, 7617 LLVMContext::OB_cfguardtarget}) && 7618 "Cannot lower calls with arbitrary operand bundles!"); 7619 7620 SDValue Callee = getValue(I.getCalledValue()); 7621 7622 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 7623 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 7624 else 7625 // Check if we can potentially perform a tail call. More detailed checking 7626 // is be done within LowerCallTo, after more information about the call is 7627 // known. 7628 LowerCallTo(&I, Callee, I.isTailCall()); 7629 } 7630 7631 namespace { 7632 7633 /// AsmOperandInfo - This contains information for each constraint that we are 7634 /// lowering. 7635 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 7636 public: 7637 /// CallOperand - If this is the result output operand or a clobber 7638 /// this is null, otherwise it is the incoming operand to the CallInst. 7639 /// This gets modified as the asm is processed. 7640 SDValue CallOperand; 7641 7642 /// AssignedRegs - If this is a register or register class operand, this 7643 /// contains the set of register corresponding to the operand. 7644 RegsForValue AssignedRegs; 7645 7646 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 7647 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 7648 } 7649 7650 /// Whether or not this operand accesses memory 7651 bool hasMemory(const TargetLowering &TLI) const { 7652 // Indirect operand accesses access memory. 7653 if (isIndirect) 7654 return true; 7655 7656 for (const auto &Code : Codes) 7657 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 7658 return true; 7659 7660 return false; 7661 } 7662 7663 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 7664 /// corresponds to. If there is no Value* for this operand, it returns 7665 /// MVT::Other. 7666 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 7667 const DataLayout &DL) const { 7668 if (!CallOperandVal) return MVT::Other; 7669 7670 if (isa<BasicBlock>(CallOperandVal)) 7671 return TLI.getPointerTy(DL); 7672 7673 llvm::Type *OpTy = CallOperandVal->getType(); 7674 7675 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 7676 // If this is an indirect operand, the operand is a pointer to the 7677 // accessed type. 7678 if (isIndirect) { 7679 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 7680 if (!PtrTy) 7681 report_fatal_error("Indirect operand for inline asm not a pointer!"); 7682 OpTy = PtrTy->getElementType(); 7683 } 7684 7685 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 7686 if (StructType *STy = dyn_cast<StructType>(OpTy)) 7687 if (STy->getNumElements() == 1) 7688 OpTy = STy->getElementType(0); 7689 7690 // If OpTy is not a single value, it may be a struct/union that we 7691 // can tile with integers. 7692 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 7693 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 7694 switch (BitSize) { 7695 default: break; 7696 case 1: 7697 case 8: 7698 case 16: 7699 case 32: 7700 case 64: 7701 case 128: 7702 OpTy = IntegerType::get(Context, BitSize); 7703 break; 7704 } 7705 } 7706 7707 return TLI.getValueType(DL, OpTy, true); 7708 } 7709 }; 7710 7711 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>; 7712 7713 } // end anonymous namespace 7714 7715 /// Make sure that the output operand \p OpInfo and its corresponding input 7716 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 7717 /// out). 7718 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 7719 SDISelAsmOperandInfo &MatchingOpInfo, 7720 SelectionDAG &DAG) { 7721 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 7722 return; 7723 7724 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 7725 const auto &TLI = DAG.getTargetLoweringInfo(); 7726 7727 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 7728 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 7729 OpInfo.ConstraintVT); 7730 std::pair<unsigned, const TargetRegisterClass *> InputRC = 7731 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 7732 MatchingOpInfo.ConstraintVT); 7733 if ((OpInfo.ConstraintVT.isInteger() != 7734 MatchingOpInfo.ConstraintVT.isInteger()) || 7735 (MatchRC.second != InputRC.second)) { 7736 // FIXME: error out in a more elegant fashion 7737 report_fatal_error("Unsupported asm: input constraint" 7738 " with a matching output constraint of" 7739 " incompatible type!"); 7740 } 7741 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 7742 } 7743 7744 /// Get a direct memory input to behave well as an indirect operand. 7745 /// This may introduce stores, hence the need for a \p Chain. 7746 /// \return The (possibly updated) chain. 7747 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 7748 SDISelAsmOperandInfo &OpInfo, 7749 SelectionDAG &DAG) { 7750 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7751 7752 // If we don't have an indirect input, put it in the constpool if we can, 7753 // otherwise spill it to a stack slot. 7754 // TODO: This isn't quite right. We need to handle these according to 7755 // the addressing mode that the constraint wants. Also, this may take 7756 // an additional register for the computation and we don't want that 7757 // either. 7758 7759 // If the operand is a float, integer, or vector constant, spill to a 7760 // constant pool entry to get its address. 7761 const Value *OpVal = OpInfo.CallOperandVal; 7762 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 7763 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 7764 OpInfo.CallOperand = DAG.getConstantPool( 7765 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 7766 return Chain; 7767 } 7768 7769 // Otherwise, create a stack slot and emit a store to it before the asm. 7770 Type *Ty = OpVal->getType(); 7771 auto &DL = DAG.getDataLayout(); 7772 uint64_t TySize = DL.getTypeAllocSize(Ty); 7773 unsigned Align = DL.getPrefTypeAlignment(Ty); 7774 MachineFunction &MF = DAG.getMachineFunction(); 7775 int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 7776 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 7777 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 7778 MachinePointerInfo::getFixedStack(MF, SSFI), 7779 TLI.getMemValueType(DL, Ty)); 7780 OpInfo.CallOperand = StackSlot; 7781 7782 return Chain; 7783 } 7784 7785 /// GetRegistersForValue - Assign registers (virtual or physical) for the 7786 /// specified operand. We prefer to assign virtual registers, to allow the 7787 /// register allocator to handle the assignment process. However, if the asm 7788 /// uses features that we can't model on machineinstrs, we have SDISel do the 7789 /// allocation. This produces generally horrible, but correct, code. 7790 /// 7791 /// OpInfo describes the operand 7792 /// RefOpInfo describes the matching operand if any, the operand otherwise 7793 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 7794 SDISelAsmOperandInfo &OpInfo, 7795 SDISelAsmOperandInfo &RefOpInfo) { 7796 LLVMContext &Context = *DAG.getContext(); 7797 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7798 7799 MachineFunction &MF = DAG.getMachineFunction(); 7800 SmallVector<unsigned, 4> Regs; 7801 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 7802 7803 // No work to do for memory operations. 7804 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 7805 return; 7806 7807 // If this is a constraint for a single physreg, or a constraint for a 7808 // register class, find it. 7809 unsigned AssignedReg; 7810 const TargetRegisterClass *RC; 7811 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 7812 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 7813 // RC is unset only on failure. Return immediately. 7814 if (!RC) 7815 return; 7816 7817 // Get the actual register value type. This is important, because the user 7818 // may have asked for (e.g.) the AX register in i32 type. We need to 7819 // remember that AX is actually i16 to get the right extension. 7820 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 7821 7822 if (OpInfo.ConstraintVT != MVT::Other) { 7823 // If this is an FP operand in an integer register (or visa versa), or more 7824 // generally if the operand value disagrees with the register class we plan 7825 // to stick it in, fix the operand type. 7826 // 7827 // If this is an input value, the bitcast to the new type is done now. 7828 // Bitcast for output value is done at the end of visitInlineAsm(). 7829 if ((OpInfo.Type == InlineAsm::isOutput || 7830 OpInfo.Type == InlineAsm::isInput) && 7831 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 7832 // Try to convert to the first EVT that the reg class contains. If the 7833 // types are identical size, use a bitcast to convert (e.g. two differing 7834 // vector types). Note: output bitcast is done at the end of 7835 // visitInlineAsm(). 7836 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 7837 // Exclude indirect inputs while they are unsupported because the code 7838 // to perform the load is missing and thus OpInfo.CallOperand still 7839 // refers to the input address rather than the pointed-to value. 7840 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 7841 OpInfo.CallOperand = 7842 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 7843 OpInfo.ConstraintVT = RegVT; 7844 // If the operand is an FP value and we want it in integer registers, 7845 // use the corresponding integer type. This turns an f64 value into 7846 // i64, which can be passed with two i32 values on a 32-bit machine. 7847 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 7848 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 7849 if (OpInfo.Type == InlineAsm::isInput) 7850 OpInfo.CallOperand = 7851 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 7852 OpInfo.ConstraintVT = VT; 7853 } 7854 } 7855 } 7856 7857 // No need to allocate a matching input constraint since the constraint it's 7858 // matching to has already been allocated. 7859 if (OpInfo.isMatchingInputConstraint()) 7860 return; 7861 7862 EVT ValueVT = OpInfo.ConstraintVT; 7863 if (OpInfo.ConstraintVT == MVT::Other) 7864 ValueVT = RegVT; 7865 7866 // Initialize NumRegs. 7867 unsigned NumRegs = 1; 7868 if (OpInfo.ConstraintVT != MVT::Other) 7869 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 7870 7871 // If this is a constraint for a specific physical register, like {r17}, 7872 // assign it now. 7873 7874 // If this associated to a specific register, initialize iterator to correct 7875 // place. If virtual, make sure we have enough registers 7876 7877 // Initialize iterator if necessary 7878 TargetRegisterClass::iterator I = RC->begin(); 7879 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7880 7881 // Do not check for single registers. 7882 if (AssignedReg) { 7883 for (; *I != AssignedReg; ++I) 7884 assert(I != RC->end() && "AssignedReg should be member of RC"); 7885 } 7886 7887 for (; NumRegs; --NumRegs, ++I) { 7888 assert(I != RC->end() && "Ran out of registers to allocate!"); 7889 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 7890 Regs.push_back(R); 7891 } 7892 7893 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 7894 } 7895 7896 static unsigned 7897 findMatchingInlineAsmOperand(unsigned OperandNo, 7898 const std::vector<SDValue> &AsmNodeOperands) { 7899 // Scan until we find the definition we already emitted of this operand. 7900 unsigned CurOp = InlineAsm::Op_FirstOperand; 7901 for (; OperandNo; --OperandNo) { 7902 // Advance to the next operand. 7903 unsigned OpFlag = 7904 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7905 assert((InlineAsm::isRegDefKind(OpFlag) || 7906 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 7907 InlineAsm::isMemKind(OpFlag)) && 7908 "Skipped past definitions?"); 7909 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 7910 } 7911 return CurOp; 7912 } 7913 7914 namespace { 7915 7916 class ExtraFlags { 7917 unsigned Flags = 0; 7918 7919 public: 7920 explicit ExtraFlags(ImmutableCallSite CS) { 7921 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7922 if (IA->hasSideEffects()) 7923 Flags |= InlineAsm::Extra_HasSideEffects; 7924 if (IA->isAlignStack()) 7925 Flags |= InlineAsm::Extra_IsAlignStack; 7926 if (CS.isConvergent()) 7927 Flags |= InlineAsm::Extra_IsConvergent; 7928 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 7929 } 7930 7931 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 7932 // Ideally, we would only check against memory constraints. However, the 7933 // meaning of an Other constraint can be target-specific and we can't easily 7934 // reason about it. Therefore, be conservative and set MayLoad/MayStore 7935 // for Other constraints as well. 7936 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 7937 OpInfo.ConstraintType == TargetLowering::C_Other) { 7938 if (OpInfo.Type == InlineAsm::isInput) 7939 Flags |= InlineAsm::Extra_MayLoad; 7940 else if (OpInfo.Type == InlineAsm::isOutput) 7941 Flags |= InlineAsm::Extra_MayStore; 7942 else if (OpInfo.Type == InlineAsm::isClobber) 7943 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 7944 } 7945 } 7946 7947 unsigned get() const { return Flags; } 7948 }; 7949 7950 } // end anonymous namespace 7951 7952 /// visitInlineAsm - Handle a call to an InlineAsm object. 7953 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) { 7954 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7955 7956 /// ConstraintOperands - Information about all of the constraints. 7957 SDISelAsmOperandInfoVector ConstraintOperands; 7958 7959 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7960 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 7961 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS); 7962 7963 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 7964 // AsmDialect, MayLoad, MayStore). 7965 bool HasSideEffect = IA->hasSideEffects(); 7966 ExtraFlags ExtraInfo(CS); 7967 7968 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 7969 unsigned ResNo = 0; // ResNo - The result number of the next output. 7970 for (auto &T : TargetConstraints) { 7971 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 7972 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 7973 7974 // Compute the value type for each operand. 7975 if (OpInfo.Type == InlineAsm::isInput || 7976 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 7977 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 7978 7979 // Process the call argument. BasicBlocks are labels, currently appearing 7980 // only in asm's. 7981 const Instruction *I = CS.getInstruction(); 7982 if (isa<CallBrInst>(I) && 7983 (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() - 7984 cast<CallBrInst>(I)->getNumIndirectDests())) { 7985 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal); 7986 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true); 7987 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT); 7988 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 7989 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 7990 } else { 7991 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 7992 } 7993 7994 OpInfo.ConstraintVT = 7995 OpInfo 7996 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout()) 7997 .getSimpleVT(); 7998 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 7999 // The return value of the call is this value. As such, there is no 8000 // corresponding argument. 8001 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 8002 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 8003 OpInfo.ConstraintVT = TLI.getSimpleValueType( 8004 DAG.getDataLayout(), STy->getElementType(ResNo)); 8005 } else { 8006 assert(ResNo == 0 && "Asm only has one result!"); 8007 OpInfo.ConstraintVT = 8008 TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType()); 8009 } 8010 ++ResNo; 8011 } else { 8012 OpInfo.ConstraintVT = MVT::Other; 8013 } 8014 8015 if (!HasSideEffect) 8016 HasSideEffect = OpInfo.hasMemory(TLI); 8017 8018 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8019 // FIXME: Could we compute this on OpInfo rather than T? 8020 8021 // Compute the constraint code and ConstraintType to use. 8022 TLI.ComputeConstraintToUse(T, SDValue()); 8023 8024 if (T.ConstraintType == TargetLowering::C_Immediate && 8025 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8026 // We've delayed emitting a diagnostic like the "n" constraint because 8027 // inlining could cause an integer showing up. 8028 return emitInlineAsmError( 8029 CS, "constraint '" + Twine(T.ConstraintCode) + "' expects an " 8030 "integer constant expression"); 8031 8032 ExtraInfo.update(T); 8033 } 8034 8035 8036 // We won't need to flush pending loads if this asm doesn't touch 8037 // memory and is nonvolatile. 8038 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8039 8040 bool IsCallBr = isa<CallBrInst>(CS.getInstruction()); 8041 if (IsCallBr) { 8042 // If this is a callbr we need to flush pending exports since inlineasm_br 8043 // is a terminator. We need to do this before nodes are glued to 8044 // the inlineasm_br node. 8045 Chain = getControlRoot(); 8046 } 8047 8048 // Second pass over the constraints: compute which constraint option to use. 8049 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8050 // If this is an output operand with a matching input operand, look up the 8051 // matching input. If their types mismatch, e.g. one is an integer, the 8052 // other is floating point, or their sizes are different, flag it as an 8053 // error. 8054 if (OpInfo.hasMatchingInput()) { 8055 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8056 patchMatchingInput(OpInfo, Input, DAG); 8057 } 8058 8059 // Compute the constraint code and ConstraintType to use. 8060 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8061 8062 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8063 OpInfo.Type == InlineAsm::isClobber) 8064 continue; 8065 8066 // If this is a memory input, and if the operand is not indirect, do what we 8067 // need to provide an address for the memory input. 8068 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8069 !OpInfo.isIndirect) { 8070 assert((OpInfo.isMultipleAlternative || 8071 (OpInfo.Type == InlineAsm::isInput)) && 8072 "Can only indirectify direct input operands!"); 8073 8074 // Memory operands really want the address of the value. 8075 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8076 8077 // There is no longer a Value* corresponding to this operand. 8078 OpInfo.CallOperandVal = nullptr; 8079 8080 // It is now an indirect operand. 8081 OpInfo.isIndirect = true; 8082 } 8083 8084 } 8085 8086 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8087 std::vector<SDValue> AsmNodeOperands; 8088 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8089 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8090 IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout()))); 8091 8092 // If we have a !srcloc metadata node associated with it, we want to attach 8093 // this to the ultimately generated inline asm machineinstr. To do this, we 8094 // pass in the third operand as this (potentially null) inline asm MDNode. 8095 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc"); 8096 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8097 8098 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8099 // bits as operand 3. 8100 AsmNodeOperands.push_back(DAG.getTargetConstant( 8101 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8102 8103 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8104 // this, assign virtual and physical registers for inputs and otput. 8105 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8106 // Assign Registers. 8107 SDISelAsmOperandInfo &RefOpInfo = 8108 OpInfo.isMatchingInputConstraint() 8109 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8110 : OpInfo; 8111 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8112 8113 switch (OpInfo.Type) { 8114 case InlineAsm::isOutput: 8115 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8116 ((OpInfo.ConstraintType == TargetLowering::C_Immediate || 8117 OpInfo.ConstraintType == TargetLowering::C_Other) && 8118 OpInfo.isIndirect)) { 8119 unsigned ConstraintID = 8120 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8121 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8122 "Failed to convert memory constraint code to constraint id."); 8123 8124 // Add information to the INLINEASM node to know about this output. 8125 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8126 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8127 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8128 MVT::i32)); 8129 AsmNodeOperands.push_back(OpInfo.CallOperand); 8130 break; 8131 } else if (((OpInfo.ConstraintType == TargetLowering::C_Immediate || 8132 OpInfo.ConstraintType == TargetLowering::C_Other) && 8133 !OpInfo.isIndirect) || 8134 OpInfo.ConstraintType == TargetLowering::C_Register || 8135 OpInfo.ConstraintType == TargetLowering::C_RegisterClass) { 8136 // Otherwise, this outputs to a register (directly for C_Register / 8137 // C_RegisterClass, and a target-defined fashion for 8138 // C_Immediate/C_Other). Find a register that we can use. 8139 if (OpInfo.AssignedRegs.Regs.empty()) { 8140 emitInlineAsmError( 8141 CS, "couldn't allocate output register for constraint '" + 8142 Twine(OpInfo.ConstraintCode) + "'"); 8143 return; 8144 } 8145 8146 // Add information to the INLINEASM node to know that this register is 8147 // set. 8148 OpInfo.AssignedRegs.AddInlineAsmOperands( 8149 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8150 : InlineAsm::Kind_RegDef, 8151 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8152 } 8153 break; 8154 8155 case InlineAsm::isInput: { 8156 SDValue InOperandVal = OpInfo.CallOperand; 8157 8158 if (OpInfo.isMatchingInputConstraint()) { 8159 // If this is required to match an output register we have already set, 8160 // just use its register. 8161 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8162 AsmNodeOperands); 8163 unsigned OpFlag = 8164 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8165 if (InlineAsm::isRegDefKind(OpFlag) || 8166 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8167 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8168 if (OpInfo.isIndirect) { 8169 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8170 emitInlineAsmError(CS, "inline asm not supported yet:" 8171 " don't know how to handle tied " 8172 "indirect register inputs"); 8173 return; 8174 } 8175 8176 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 8177 SmallVector<unsigned, 4> Regs; 8178 8179 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { 8180 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8181 MachineRegisterInfo &RegInfo = 8182 DAG.getMachineFunction().getRegInfo(); 8183 for (unsigned i = 0; i != NumRegs; ++i) 8184 Regs.push_back(RegInfo.createVirtualRegister(RC)); 8185 } else { 8186 emitInlineAsmError(CS, "inline asm error: This value type register " 8187 "class is not natively supported!"); 8188 return; 8189 } 8190 8191 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8192 8193 SDLoc dl = getCurSDLoc(); 8194 // Use the produced MatchedRegs object to 8195 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 8196 CS.getInstruction()); 8197 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8198 true, OpInfo.getMatchedOperand(), dl, 8199 DAG, AsmNodeOperands); 8200 break; 8201 } 8202 8203 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8204 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8205 "Unexpected number of operands"); 8206 // Add information to the INLINEASM node to know about this input. 8207 // See InlineAsm.h isUseOperandTiedToDef. 8208 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8209 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8210 OpInfo.getMatchedOperand()); 8211 AsmNodeOperands.push_back(DAG.getTargetConstant( 8212 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8213 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8214 break; 8215 } 8216 8217 // Treat indirect 'X' constraint as memory. 8218 if ((OpInfo.ConstraintType == TargetLowering::C_Immediate || 8219 OpInfo.ConstraintType == TargetLowering::C_Other) && 8220 OpInfo.isIndirect) 8221 OpInfo.ConstraintType = TargetLowering::C_Memory; 8222 8223 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 8224 OpInfo.ConstraintType == TargetLowering::C_Other) { 8225 std::vector<SDValue> Ops; 8226 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 8227 Ops, DAG); 8228 if (Ops.empty()) { 8229 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 8230 if (isa<ConstantSDNode>(InOperandVal)) { 8231 emitInlineAsmError(CS, "value out of range for constraint '" + 8232 Twine(OpInfo.ConstraintCode) + "'"); 8233 return; 8234 } 8235 8236 emitInlineAsmError(CS, "invalid operand for inline asm constraint '" + 8237 Twine(OpInfo.ConstraintCode) + "'"); 8238 return; 8239 } 8240 8241 // Add information to the INLINEASM node to know about this input. 8242 unsigned ResOpType = 8243 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 8244 AsmNodeOperands.push_back(DAG.getTargetConstant( 8245 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8246 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 8247 break; 8248 } 8249 8250 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8251 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 8252 assert(InOperandVal.getValueType() == 8253 TLI.getPointerTy(DAG.getDataLayout()) && 8254 "Memory operands expect pointer values"); 8255 8256 unsigned ConstraintID = 8257 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8258 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8259 "Failed to convert memory constraint code to constraint id."); 8260 8261 // Add information to the INLINEASM node to know about this input. 8262 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8263 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 8264 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 8265 getCurSDLoc(), 8266 MVT::i32)); 8267 AsmNodeOperands.push_back(InOperandVal); 8268 break; 8269 } 8270 8271 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 8272 OpInfo.ConstraintType == TargetLowering::C_Register || 8273 OpInfo.ConstraintType == TargetLowering::C_Immediate) && 8274 "Unknown constraint type!"); 8275 8276 // TODO: Support this. 8277 if (OpInfo.isIndirect) { 8278 emitInlineAsmError( 8279 CS, "Don't know how to handle indirect register inputs yet " 8280 "for constraint '" + 8281 Twine(OpInfo.ConstraintCode) + "'"); 8282 return; 8283 } 8284 8285 // Copy the input into the appropriate registers. 8286 if (OpInfo.AssignedRegs.Regs.empty()) { 8287 emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" + 8288 Twine(OpInfo.ConstraintCode) + "'"); 8289 return; 8290 } 8291 8292 SDLoc dl = getCurSDLoc(); 8293 8294 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, 8295 Chain, &Flag, CS.getInstruction()); 8296 8297 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 8298 dl, DAG, AsmNodeOperands); 8299 break; 8300 } 8301 case InlineAsm::isClobber: 8302 // Add the clobbered value to the operand list, so that the register 8303 // allocator is aware that the physreg got clobbered. 8304 if (!OpInfo.AssignedRegs.Regs.empty()) 8305 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 8306 false, 0, getCurSDLoc(), DAG, 8307 AsmNodeOperands); 8308 break; 8309 } 8310 } 8311 8312 // Finish up input operands. Set the input chain and add the flag last. 8313 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 8314 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 8315 8316 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 8317 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 8318 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 8319 Flag = Chain.getValue(1); 8320 8321 // Do additional work to generate outputs. 8322 8323 SmallVector<EVT, 1> ResultVTs; 8324 SmallVector<SDValue, 1> ResultValues; 8325 SmallVector<SDValue, 8> OutChains; 8326 8327 llvm::Type *CSResultType = CS.getType(); 8328 ArrayRef<Type *> ResultTypes; 8329 if (StructType *StructResult = dyn_cast<StructType>(CSResultType)) 8330 ResultTypes = StructResult->elements(); 8331 else if (!CSResultType->isVoidTy()) 8332 ResultTypes = makeArrayRef(CSResultType); 8333 8334 auto CurResultType = ResultTypes.begin(); 8335 auto handleRegAssign = [&](SDValue V) { 8336 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 8337 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 8338 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 8339 ++CurResultType; 8340 // If the type of the inline asm call site return value is different but has 8341 // same size as the type of the asm output bitcast it. One example of this 8342 // is for vectors with different width / number of elements. This can 8343 // happen for register classes that can contain multiple different value 8344 // types. The preg or vreg allocated may not have the same VT as was 8345 // expected. 8346 // 8347 // This can also happen for a return value that disagrees with the register 8348 // class it is put in, eg. a double in a general-purpose register on a 8349 // 32-bit machine. 8350 if (ResultVT != V.getValueType() && 8351 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 8352 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 8353 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 8354 V.getValueType().isInteger()) { 8355 // If a result value was tied to an input value, the computed result 8356 // may have a wider width than the expected result. Extract the 8357 // relevant portion. 8358 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 8359 } 8360 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 8361 ResultVTs.push_back(ResultVT); 8362 ResultValues.push_back(V); 8363 }; 8364 8365 // Deal with output operands. 8366 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8367 if (OpInfo.Type == InlineAsm::isOutput) { 8368 SDValue Val; 8369 // Skip trivial output operands. 8370 if (OpInfo.AssignedRegs.Regs.empty()) 8371 continue; 8372 8373 switch (OpInfo.ConstraintType) { 8374 case TargetLowering::C_Register: 8375 case TargetLowering::C_RegisterClass: 8376 Val = OpInfo.AssignedRegs.getCopyFromRegs( 8377 DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction()); 8378 break; 8379 case TargetLowering::C_Immediate: 8380 case TargetLowering::C_Other: 8381 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 8382 OpInfo, DAG); 8383 break; 8384 case TargetLowering::C_Memory: 8385 break; // Already handled. 8386 case TargetLowering::C_Unknown: 8387 assert(false && "Unexpected unknown constraint"); 8388 } 8389 8390 // Indirect output manifest as stores. Record output chains. 8391 if (OpInfo.isIndirect) { 8392 const Value *Ptr = OpInfo.CallOperandVal; 8393 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 8394 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 8395 MachinePointerInfo(Ptr)); 8396 OutChains.push_back(Store); 8397 } else { 8398 // generate CopyFromRegs to associated registers. 8399 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 8400 if (Val.getOpcode() == ISD::MERGE_VALUES) { 8401 for (const SDValue &V : Val->op_values()) 8402 handleRegAssign(V); 8403 } else 8404 handleRegAssign(Val); 8405 } 8406 } 8407 } 8408 8409 // Set results. 8410 if (!ResultValues.empty()) { 8411 assert(CurResultType == ResultTypes.end() && 8412 "Mismatch in number of ResultTypes"); 8413 assert(ResultValues.size() == ResultTypes.size() && 8414 "Mismatch in number of output operands in asm result"); 8415 8416 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 8417 DAG.getVTList(ResultVTs), ResultValues); 8418 setValue(CS.getInstruction(), V); 8419 } 8420 8421 // Collect store chains. 8422 if (!OutChains.empty()) 8423 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 8424 8425 // Only Update Root if inline assembly has a memory effect. 8426 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr) 8427 DAG.setRoot(Chain); 8428 } 8429 8430 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS, 8431 const Twine &Message) { 8432 LLVMContext &Ctx = *DAG.getContext(); 8433 Ctx.emitError(CS.getInstruction(), Message); 8434 8435 // Make sure we leave the DAG in a valid state 8436 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8437 SmallVector<EVT, 1> ValueVTs; 8438 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8439 8440 if (ValueVTs.empty()) 8441 return; 8442 8443 SmallVector<SDValue, 1> Ops; 8444 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 8445 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 8446 8447 setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc())); 8448 } 8449 8450 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 8451 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 8452 MVT::Other, getRoot(), 8453 getValue(I.getArgOperand(0)), 8454 DAG.getSrcValue(I.getArgOperand(0)))); 8455 } 8456 8457 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 8458 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8459 const DataLayout &DL = DAG.getDataLayout(); 8460 SDValue V = DAG.getVAArg( 8461 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 8462 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 8463 DL.getABITypeAlignment(I.getType())); 8464 DAG.setRoot(V.getValue(1)); 8465 8466 if (I.getType()->isPointerTy()) 8467 V = DAG.getPtrExtOrTrunc( 8468 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 8469 setValue(&I, V); 8470 } 8471 8472 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 8473 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 8474 MVT::Other, getRoot(), 8475 getValue(I.getArgOperand(0)), 8476 DAG.getSrcValue(I.getArgOperand(0)))); 8477 } 8478 8479 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 8480 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 8481 MVT::Other, getRoot(), 8482 getValue(I.getArgOperand(0)), 8483 getValue(I.getArgOperand(1)), 8484 DAG.getSrcValue(I.getArgOperand(0)), 8485 DAG.getSrcValue(I.getArgOperand(1)))); 8486 } 8487 8488 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 8489 const Instruction &I, 8490 SDValue Op) { 8491 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 8492 if (!Range) 8493 return Op; 8494 8495 ConstantRange CR = getConstantRangeFromMetadata(*Range); 8496 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 8497 return Op; 8498 8499 APInt Lo = CR.getUnsignedMin(); 8500 if (!Lo.isMinValue()) 8501 return Op; 8502 8503 APInt Hi = CR.getUnsignedMax(); 8504 unsigned Bits = std::max(Hi.getActiveBits(), 8505 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 8506 8507 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8508 8509 SDLoc SL = getCurSDLoc(); 8510 8511 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8512 DAG.getValueType(SmallVT)); 8513 unsigned NumVals = Op.getNode()->getNumValues(); 8514 if (NumVals == 1) 8515 return ZExt; 8516 8517 SmallVector<SDValue, 4> Ops; 8518 8519 Ops.push_back(ZExt); 8520 for (unsigned I = 1; I != NumVals; ++I) 8521 Ops.push_back(Op.getValue(I)); 8522 8523 return DAG.getMergeValues(Ops, SL); 8524 } 8525 8526 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8527 /// the call being lowered. 8528 /// 8529 /// This is a helper for lowering intrinsics that follow a target calling 8530 /// convention or require stack pointer adjustment. Only a subset of the 8531 /// intrinsic's operands need to participate in the calling convention. 8532 void SelectionDAGBuilder::populateCallLoweringInfo( 8533 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 8534 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8535 bool IsPatchPoint) { 8536 TargetLowering::ArgListTy Args; 8537 Args.reserve(NumArgs); 8538 8539 // Populate the argument list. 8540 // Attributes for args start at offset 1, after the return attribute. 8541 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8542 ArgI != ArgE; ++ArgI) { 8543 const Value *V = Call->getOperand(ArgI); 8544 8545 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 8546 8547 TargetLowering::ArgListEntry Entry; 8548 Entry.Node = getValue(V); 8549 Entry.Ty = V->getType(); 8550 Entry.setAttributes(Call, ArgI); 8551 Args.push_back(Entry); 8552 } 8553 8554 CLI.setDebugLoc(getCurSDLoc()) 8555 .setChain(getRoot()) 8556 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 8557 .setDiscardResult(Call->use_empty()) 8558 .setIsPatchPoint(IsPatchPoint); 8559 } 8560 8561 /// Add a stack map intrinsic call's live variable operands to a stackmap 8562 /// or patchpoint target node's operand list. 8563 /// 8564 /// Constants are converted to TargetConstants purely as an optimization to 8565 /// avoid constant materialization and register allocation. 8566 /// 8567 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 8568 /// generate addess computation nodes, and so FinalizeISel can convert the 8569 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 8570 /// address materialization and register allocation, but may also be required 8571 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 8572 /// alloca in the entry block, then the runtime may assume that the alloca's 8573 /// StackMap location can be read immediately after compilation and that the 8574 /// location is valid at any point during execution (this is similar to the 8575 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 8576 /// only available in a register, then the runtime would need to trap when 8577 /// execution reaches the StackMap in order to read the alloca's location. 8578 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx, 8579 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 8580 SelectionDAGBuilder &Builder) { 8581 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) { 8582 SDValue OpVal = Builder.getValue(CS.getArgument(i)); 8583 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 8584 Ops.push_back( 8585 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 8586 Ops.push_back( 8587 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 8588 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 8589 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 8590 Ops.push_back(Builder.DAG.getTargetFrameIndex( 8591 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 8592 } else 8593 Ops.push_back(OpVal); 8594 } 8595 } 8596 8597 /// Lower llvm.experimental.stackmap directly to its target opcode. 8598 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 8599 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 8600 // [live variables...]) 8601 8602 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 8603 8604 SDValue Chain, InFlag, Callee, NullPtr; 8605 SmallVector<SDValue, 32> Ops; 8606 8607 SDLoc DL = getCurSDLoc(); 8608 Callee = getValue(CI.getCalledValue()); 8609 NullPtr = DAG.getIntPtrConstant(0, DL, true); 8610 8611 // The stackmap intrinsic only records the live variables (the arguments 8612 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 8613 // intrinsic, this won't be lowered to a function call. This means we don't 8614 // have to worry about calling conventions and target specific lowering code. 8615 // Instead we perform the call lowering right here. 8616 // 8617 // chain, flag = CALLSEQ_START(chain, 0, 0) 8618 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 8619 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 8620 // 8621 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 8622 InFlag = Chain.getValue(1); 8623 8624 // Add the <id> and <numBytes> constants. 8625 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 8626 Ops.push_back(DAG.getTargetConstant( 8627 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 8628 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 8629 Ops.push_back(DAG.getTargetConstant( 8630 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 8631 MVT::i32)); 8632 8633 // Push live variables for the stack map. 8634 addStackMapLiveVars(&CI, 2, DL, Ops, *this); 8635 8636 // We are not pushing any register mask info here on the operands list, 8637 // because the stackmap doesn't clobber anything. 8638 8639 // Push the chain and the glue flag. 8640 Ops.push_back(Chain); 8641 Ops.push_back(InFlag); 8642 8643 // Create the STACKMAP node. 8644 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8645 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 8646 Chain = SDValue(SM, 0); 8647 InFlag = Chain.getValue(1); 8648 8649 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 8650 8651 // Stackmaps don't generate values, so nothing goes into the NodeMap. 8652 8653 // Set the root to the target-lowered call chain. 8654 DAG.setRoot(Chain); 8655 8656 // Inform the Frame Information that we have a stackmap in this function. 8657 FuncInfo.MF->getFrameInfo().setHasStackMap(); 8658 } 8659 8660 /// Lower llvm.experimental.patchpoint directly to its target opcode. 8661 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS, 8662 const BasicBlock *EHPadBB) { 8663 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 8664 // i32 <numBytes>, 8665 // i8* <target>, 8666 // i32 <numArgs>, 8667 // [Args...], 8668 // [live variables...]) 8669 8670 CallingConv::ID CC = CS.getCallingConv(); 8671 bool IsAnyRegCC = CC == CallingConv::AnyReg; 8672 bool HasDef = !CS->getType()->isVoidTy(); 8673 SDLoc dl = getCurSDLoc(); 8674 SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos)); 8675 8676 // Handle immediate and symbolic callees. 8677 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 8678 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 8679 /*isTarget=*/true); 8680 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 8681 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 8682 SDLoc(SymbolicCallee), 8683 SymbolicCallee->getValueType(0)); 8684 8685 // Get the real number of arguments participating in the call <numArgs> 8686 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos)); 8687 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 8688 8689 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 8690 // Intrinsics include all meta-operands up to but not including CC. 8691 unsigned NumMetaOpers = PatchPointOpers::CCPos; 8692 assert(CS.arg_size() >= NumMetaOpers + NumArgs && 8693 "Not enough arguments provided to the patchpoint intrinsic"); 8694 8695 // For AnyRegCC the arguments are lowered later on manually. 8696 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 8697 Type *ReturnTy = 8698 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType(); 8699 8700 TargetLowering::CallLoweringInfo CLI(DAG); 8701 populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()), 8702 NumMetaOpers, NumCallArgs, Callee, ReturnTy, true); 8703 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8704 8705 SDNode *CallEnd = Result.second.getNode(); 8706 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 8707 CallEnd = CallEnd->getOperand(0).getNode(); 8708 8709 /// Get a call instruction from the call sequence chain. 8710 /// Tail calls are not allowed. 8711 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 8712 "Expected a callseq node."); 8713 SDNode *Call = CallEnd->getOperand(0).getNode(); 8714 bool HasGlue = Call->getGluedNode(); 8715 8716 // Replace the target specific call node with the patchable intrinsic. 8717 SmallVector<SDValue, 8> Ops; 8718 8719 // Add the <id> and <numBytes> constants. 8720 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos)); 8721 Ops.push_back(DAG.getTargetConstant( 8722 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 8723 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos)); 8724 Ops.push_back(DAG.getTargetConstant( 8725 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 8726 MVT::i32)); 8727 8728 // Add the callee. 8729 Ops.push_back(Callee); 8730 8731 // Adjust <numArgs> to account for any arguments that have been passed on the 8732 // stack instead. 8733 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 8734 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 8735 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 8736 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 8737 8738 // Add the calling convention 8739 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 8740 8741 // Add the arguments we omitted previously. The register allocator should 8742 // place these in any free register. 8743 if (IsAnyRegCC) 8744 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 8745 Ops.push_back(getValue(CS.getArgument(i))); 8746 8747 // Push the arguments from the call instruction up to the register mask. 8748 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 8749 Ops.append(Call->op_begin() + 2, e); 8750 8751 // Push live variables for the stack map. 8752 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this); 8753 8754 // Push the register mask info. 8755 if (HasGlue) 8756 Ops.push_back(*(Call->op_end()-2)); 8757 else 8758 Ops.push_back(*(Call->op_end()-1)); 8759 8760 // Push the chain (this is originally the first operand of the call, but 8761 // becomes now the last or second to last operand). 8762 Ops.push_back(*(Call->op_begin())); 8763 8764 // Push the glue flag (last operand). 8765 if (HasGlue) 8766 Ops.push_back(*(Call->op_end()-1)); 8767 8768 SDVTList NodeTys; 8769 if (IsAnyRegCC && HasDef) { 8770 // Create the return types based on the intrinsic definition 8771 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8772 SmallVector<EVT, 3> ValueVTs; 8773 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8774 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 8775 8776 // There is always a chain and a glue type at the end 8777 ValueVTs.push_back(MVT::Other); 8778 ValueVTs.push_back(MVT::Glue); 8779 NodeTys = DAG.getVTList(ValueVTs); 8780 } else 8781 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8782 8783 // Replace the target specific call node with a PATCHPOINT node. 8784 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 8785 dl, NodeTys, Ops); 8786 8787 // Update the NodeMap. 8788 if (HasDef) { 8789 if (IsAnyRegCC) 8790 setValue(CS.getInstruction(), SDValue(MN, 0)); 8791 else 8792 setValue(CS.getInstruction(), Result.first); 8793 } 8794 8795 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 8796 // call sequence. Furthermore the location of the chain and glue can change 8797 // when the AnyReg calling convention is used and the intrinsic returns a 8798 // value. 8799 if (IsAnyRegCC && HasDef) { 8800 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 8801 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 8802 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 8803 } else 8804 DAG.ReplaceAllUsesWith(Call, MN); 8805 DAG.DeleteNode(Call); 8806 8807 // Inform the Frame Information that we have a patchpoint in this function. 8808 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 8809 } 8810 8811 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 8812 unsigned Intrinsic) { 8813 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8814 SDValue Op1 = getValue(I.getArgOperand(0)); 8815 SDValue Op2; 8816 if (I.getNumArgOperands() > 1) 8817 Op2 = getValue(I.getArgOperand(1)); 8818 SDLoc dl = getCurSDLoc(); 8819 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8820 SDValue Res; 8821 FastMathFlags FMF; 8822 if (isa<FPMathOperator>(I)) 8823 FMF = I.getFastMathFlags(); 8824 8825 switch (Intrinsic) { 8826 case Intrinsic::experimental_vector_reduce_v2_fadd: 8827 if (FMF.allowReassoc()) 8828 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 8829 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2)); 8830 else 8831 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2); 8832 break; 8833 case Intrinsic::experimental_vector_reduce_v2_fmul: 8834 if (FMF.allowReassoc()) 8835 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 8836 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2)); 8837 else 8838 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2); 8839 break; 8840 case Intrinsic::experimental_vector_reduce_add: 8841 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 8842 break; 8843 case Intrinsic::experimental_vector_reduce_mul: 8844 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 8845 break; 8846 case Intrinsic::experimental_vector_reduce_and: 8847 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 8848 break; 8849 case Intrinsic::experimental_vector_reduce_or: 8850 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 8851 break; 8852 case Intrinsic::experimental_vector_reduce_xor: 8853 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 8854 break; 8855 case Intrinsic::experimental_vector_reduce_smax: 8856 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 8857 break; 8858 case Intrinsic::experimental_vector_reduce_smin: 8859 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 8860 break; 8861 case Intrinsic::experimental_vector_reduce_umax: 8862 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 8863 break; 8864 case Intrinsic::experimental_vector_reduce_umin: 8865 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 8866 break; 8867 case Intrinsic::experimental_vector_reduce_fmax: 8868 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1); 8869 break; 8870 case Intrinsic::experimental_vector_reduce_fmin: 8871 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1); 8872 break; 8873 default: 8874 llvm_unreachable("Unhandled vector reduce intrinsic"); 8875 } 8876 setValue(&I, Res); 8877 } 8878 8879 /// Returns an AttributeList representing the attributes applied to the return 8880 /// value of the given call. 8881 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 8882 SmallVector<Attribute::AttrKind, 2> Attrs; 8883 if (CLI.RetSExt) 8884 Attrs.push_back(Attribute::SExt); 8885 if (CLI.RetZExt) 8886 Attrs.push_back(Attribute::ZExt); 8887 if (CLI.IsInReg) 8888 Attrs.push_back(Attribute::InReg); 8889 8890 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 8891 Attrs); 8892 } 8893 8894 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 8895 /// implementation, which just calls LowerCall. 8896 /// FIXME: When all targets are 8897 /// migrated to using LowerCall, this hook should be integrated into SDISel. 8898 std::pair<SDValue, SDValue> 8899 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 8900 // Handle the incoming return values from the call. 8901 CLI.Ins.clear(); 8902 Type *OrigRetTy = CLI.RetTy; 8903 SmallVector<EVT, 4> RetTys; 8904 SmallVector<uint64_t, 4> Offsets; 8905 auto &DL = CLI.DAG.getDataLayout(); 8906 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 8907 8908 if (CLI.IsPostTypeLegalization) { 8909 // If we are lowering a libcall after legalization, split the return type. 8910 SmallVector<EVT, 4> OldRetTys; 8911 SmallVector<uint64_t, 4> OldOffsets; 8912 RetTys.swap(OldRetTys); 8913 Offsets.swap(OldOffsets); 8914 8915 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 8916 EVT RetVT = OldRetTys[i]; 8917 uint64_t Offset = OldOffsets[i]; 8918 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 8919 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 8920 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 8921 RetTys.append(NumRegs, RegisterVT); 8922 for (unsigned j = 0; j != NumRegs; ++j) 8923 Offsets.push_back(Offset + j * RegisterVTByteSZ); 8924 } 8925 } 8926 8927 SmallVector<ISD::OutputArg, 4> Outs; 8928 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 8929 8930 bool CanLowerReturn = 8931 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 8932 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 8933 8934 SDValue DemoteStackSlot; 8935 int DemoteStackIdx = -100; 8936 if (!CanLowerReturn) { 8937 // FIXME: equivalent assert? 8938 // assert(!CS.hasInAllocaArgument() && 8939 // "sret demotion is incompatible with inalloca"); 8940 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 8941 unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy); 8942 MachineFunction &MF = CLI.DAG.getMachineFunction(); 8943 DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 8944 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 8945 DL.getAllocaAddrSpace()); 8946 8947 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 8948 ArgListEntry Entry; 8949 Entry.Node = DemoteStackSlot; 8950 Entry.Ty = StackSlotPtrType; 8951 Entry.IsSExt = false; 8952 Entry.IsZExt = false; 8953 Entry.IsInReg = false; 8954 Entry.IsSRet = true; 8955 Entry.IsNest = false; 8956 Entry.IsByVal = false; 8957 Entry.IsReturned = false; 8958 Entry.IsSwiftSelf = false; 8959 Entry.IsSwiftError = false; 8960 Entry.IsCFGuardTarget = false; 8961 Entry.Alignment = Align; 8962 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 8963 CLI.NumFixedArgs += 1; 8964 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 8965 8966 // sret demotion isn't compatible with tail-calls, since the sret argument 8967 // points into the callers stack frame. 8968 CLI.IsTailCall = false; 8969 } else { 8970 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 8971 CLI.RetTy, CLI.CallConv, CLI.IsVarArg); 8972 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 8973 ISD::ArgFlagsTy Flags; 8974 if (NeedsRegBlock) { 8975 Flags.setInConsecutiveRegs(); 8976 if (I == RetTys.size() - 1) 8977 Flags.setInConsecutiveRegsLast(); 8978 } 8979 EVT VT = RetTys[I]; 8980 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 8981 CLI.CallConv, VT); 8982 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 8983 CLI.CallConv, VT); 8984 for (unsigned i = 0; i != NumRegs; ++i) { 8985 ISD::InputArg MyFlags; 8986 MyFlags.Flags = Flags; 8987 MyFlags.VT = RegisterVT; 8988 MyFlags.ArgVT = VT; 8989 MyFlags.Used = CLI.IsReturnValueUsed; 8990 if (CLI.RetTy->isPointerTy()) { 8991 MyFlags.Flags.setPointer(); 8992 MyFlags.Flags.setPointerAddrSpace( 8993 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 8994 } 8995 if (CLI.RetSExt) 8996 MyFlags.Flags.setSExt(); 8997 if (CLI.RetZExt) 8998 MyFlags.Flags.setZExt(); 8999 if (CLI.IsInReg) 9000 MyFlags.Flags.setInReg(); 9001 CLI.Ins.push_back(MyFlags); 9002 } 9003 } 9004 } 9005 9006 // We push in swifterror return as the last element of CLI.Ins. 9007 ArgListTy &Args = CLI.getArgs(); 9008 if (supportSwiftError()) { 9009 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9010 if (Args[i].IsSwiftError) { 9011 ISD::InputArg MyFlags; 9012 MyFlags.VT = getPointerTy(DL); 9013 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9014 MyFlags.Flags.setSwiftError(); 9015 CLI.Ins.push_back(MyFlags); 9016 } 9017 } 9018 } 9019 9020 // Handle all of the outgoing arguments. 9021 CLI.Outs.clear(); 9022 CLI.OutVals.clear(); 9023 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9024 SmallVector<EVT, 4> ValueVTs; 9025 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9026 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9027 Type *FinalType = Args[i].Ty; 9028 if (Args[i].IsByVal) 9029 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 9030 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9031 FinalType, CLI.CallConv, CLI.IsVarArg); 9032 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9033 ++Value) { 9034 EVT VT = ValueVTs[Value]; 9035 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9036 SDValue Op = SDValue(Args[i].Node.getNode(), 9037 Args[i].Node.getResNo() + Value); 9038 ISD::ArgFlagsTy Flags; 9039 9040 // Certain targets (such as MIPS), may have a different ABI alignment 9041 // for a type depending on the context. Give the target a chance to 9042 // specify the alignment it wants. 9043 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 9044 9045 if (Args[i].Ty->isPointerTy()) { 9046 Flags.setPointer(); 9047 Flags.setPointerAddrSpace( 9048 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9049 } 9050 if (Args[i].IsZExt) 9051 Flags.setZExt(); 9052 if (Args[i].IsSExt) 9053 Flags.setSExt(); 9054 if (Args[i].IsInReg) { 9055 // If we are using vectorcall calling convention, a structure that is 9056 // passed InReg - is surely an HVA 9057 if (CLI.CallConv == CallingConv::X86_VectorCall && 9058 isa<StructType>(FinalType)) { 9059 // The first value of a structure is marked 9060 if (0 == Value) 9061 Flags.setHvaStart(); 9062 Flags.setHva(); 9063 } 9064 // Set InReg Flag 9065 Flags.setInReg(); 9066 } 9067 if (Args[i].IsSRet) 9068 Flags.setSRet(); 9069 if (Args[i].IsSwiftSelf) 9070 Flags.setSwiftSelf(); 9071 if (Args[i].IsSwiftError) 9072 Flags.setSwiftError(); 9073 if (Args[i].IsCFGuardTarget) 9074 Flags.setCFGuardTarget(); 9075 if (Args[i].IsByVal) 9076 Flags.setByVal(); 9077 if (Args[i].IsInAlloca) { 9078 Flags.setInAlloca(); 9079 // Set the byval flag for CCAssignFn callbacks that don't know about 9080 // inalloca. This way we can know how many bytes we should've allocated 9081 // and how many bytes a callee cleanup function will pop. If we port 9082 // inalloca to more targets, we'll have to add custom inalloca handling 9083 // in the various CC lowering callbacks. 9084 Flags.setByVal(); 9085 } 9086 if (Args[i].IsByVal || Args[i].IsInAlloca) { 9087 PointerType *Ty = cast<PointerType>(Args[i].Ty); 9088 Type *ElementTy = Ty->getElementType(); 9089 9090 unsigned FrameSize = DL.getTypeAllocSize( 9091 Args[i].ByValType ? Args[i].ByValType : ElementTy); 9092 Flags.setByValSize(FrameSize); 9093 9094 // info is not there but there are cases it cannot get right. 9095 unsigned FrameAlign; 9096 if (Args[i].Alignment) 9097 FrameAlign = Args[i].Alignment; 9098 else 9099 FrameAlign = getByValTypeAlignment(ElementTy, DL); 9100 Flags.setByValAlign(Align(FrameAlign)); 9101 } 9102 if (Args[i].IsNest) 9103 Flags.setNest(); 9104 if (NeedsRegBlock) 9105 Flags.setInConsecutiveRegs(); 9106 Flags.setOrigAlign(OriginalAlignment); 9107 9108 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9109 CLI.CallConv, VT); 9110 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9111 CLI.CallConv, VT); 9112 SmallVector<SDValue, 4> Parts(NumParts); 9113 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9114 9115 if (Args[i].IsSExt) 9116 ExtendKind = ISD::SIGN_EXTEND; 9117 else if (Args[i].IsZExt) 9118 ExtendKind = ISD::ZERO_EXTEND; 9119 9120 // Conservatively only handle 'returned' on non-vectors that can be lowered, 9121 // for now. 9122 if (Args[i].IsReturned && !Op.getValueType().isVector() && 9123 CanLowerReturn) { 9124 assert((CLI.RetTy == Args[i].Ty || 9125 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 9126 CLI.RetTy->getPointerAddressSpace() == 9127 Args[i].Ty->getPointerAddressSpace())) && 9128 RetTys.size() == NumValues && "unexpected use of 'returned'"); 9129 // Before passing 'returned' to the target lowering code, ensure that 9130 // either the register MVT and the actual EVT are the same size or that 9131 // the return value and argument are extended in the same way; in these 9132 // cases it's safe to pass the argument register value unchanged as the 9133 // return register value (although it's at the target's option whether 9134 // to do so) 9135 // TODO: allow code generation to take advantage of partially preserved 9136 // registers rather than clobbering the entire register when the 9137 // parameter extension method is not compatible with the return 9138 // extension method 9139 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9140 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9141 CLI.RetZExt == Args[i].IsZExt)) 9142 Flags.setReturned(); 9143 } 9144 9145 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, 9146 CLI.CS.getInstruction(), CLI.CallConv, ExtendKind); 9147 9148 for (unsigned j = 0; j != NumParts; ++j) { 9149 // if it isn't first piece, alignment must be 1 9150 // For scalable vectors the scalable part is currently handled 9151 // by individual targets, so we just use the known minimum size here. 9152 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 9153 i < CLI.NumFixedArgs, i, 9154 j*Parts[j].getValueType().getStoreSize().getKnownMinSize()); 9155 if (NumParts > 1 && j == 0) 9156 MyFlags.Flags.setSplit(); 9157 else if (j != 0) { 9158 MyFlags.Flags.setOrigAlign(Align::None()); 9159 if (j == NumParts - 1) 9160 MyFlags.Flags.setSplitEnd(); 9161 } 9162 9163 CLI.Outs.push_back(MyFlags); 9164 CLI.OutVals.push_back(Parts[j]); 9165 } 9166 9167 if (NeedsRegBlock && Value == NumValues - 1) 9168 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 9169 } 9170 } 9171 9172 SmallVector<SDValue, 4> InVals; 9173 CLI.Chain = LowerCall(CLI, InVals); 9174 9175 // Update CLI.InVals to use outside of this function. 9176 CLI.InVals = InVals; 9177 9178 // Verify that the target's LowerCall behaved as expected. 9179 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 9180 "LowerCall didn't return a valid chain!"); 9181 assert((!CLI.IsTailCall || InVals.empty()) && 9182 "LowerCall emitted a return value for a tail call!"); 9183 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9184 "LowerCall didn't emit the correct number of values!"); 9185 9186 // For a tail call, the return value is merely live-out and there aren't 9187 // any nodes in the DAG representing it. Return a special value to 9188 // indicate that a tail call has been emitted and no more Instructions 9189 // should be processed in the current block. 9190 if (CLI.IsTailCall) { 9191 CLI.DAG.setRoot(CLI.Chain); 9192 return std::make_pair(SDValue(), SDValue()); 9193 } 9194 9195 #ifndef NDEBUG 9196 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 9197 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 9198 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 9199 "LowerCall emitted a value with the wrong type!"); 9200 } 9201 #endif 9202 9203 SmallVector<SDValue, 4> ReturnValues; 9204 if (!CanLowerReturn) { 9205 // The instruction result is the result of loading from the 9206 // hidden sret parameter. 9207 SmallVector<EVT, 1> PVTs; 9208 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 9209 9210 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 9211 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 9212 EVT PtrVT = PVTs[0]; 9213 9214 unsigned NumValues = RetTys.size(); 9215 ReturnValues.resize(NumValues); 9216 SmallVector<SDValue, 4> Chains(NumValues); 9217 9218 // An aggregate return value cannot wrap around the address space, so 9219 // offsets to its parts don't wrap either. 9220 SDNodeFlags Flags; 9221 Flags.setNoUnsignedWrap(true); 9222 9223 for (unsigned i = 0; i < NumValues; ++i) { 9224 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 9225 CLI.DAG.getConstant(Offsets[i], CLI.DL, 9226 PtrVT), Flags); 9227 SDValue L = CLI.DAG.getLoad( 9228 RetTys[i], CLI.DL, CLI.Chain, Add, 9229 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 9230 DemoteStackIdx, Offsets[i]), 9231 /* Alignment = */ 1); 9232 ReturnValues[i] = L; 9233 Chains[i] = L.getValue(1); 9234 } 9235 9236 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 9237 } else { 9238 // Collect the legal value parts into potentially illegal values 9239 // that correspond to the original function's return values. 9240 Optional<ISD::NodeType> AssertOp; 9241 if (CLI.RetSExt) 9242 AssertOp = ISD::AssertSext; 9243 else if (CLI.RetZExt) 9244 AssertOp = ISD::AssertZext; 9245 unsigned CurReg = 0; 9246 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9247 EVT VT = RetTys[I]; 9248 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9249 CLI.CallConv, VT); 9250 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9251 CLI.CallConv, VT); 9252 9253 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 9254 NumRegs, RegisterVT, VT, nullptr, 9255 CLI.CallConv, AssertOp)); 9256 CurReg += NumRegs; 9257 } 9258 9259 // For a function returning void, there is no return value. We can't create 9260 // such a node, so we just return a null return value in that case. In 9261 // that case, nothing will actually look at the value. 9262 if (ReturnValues.empty()) 9263 return std::make_pair(SDValue(), CLI.Chain); 9264 } 9265 9266 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 9267 CLI.DAG.getVTList(RetTys), ReturnValues); 9268 return std::make_pair(Res, CLI.Chain); 9269 } 9270 9271 void TargetLowering::LowerOperationWrapper(SDNode *N, 9272 SmallVectorImpl<SDValue> &Results, 9273 SelectionDAG &DAG) const { 9274 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG)) 9275 Results.push_back(Res); 9276 } 9277 9278 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9279 llvm_unreachable("LowerOperation not implemented for this target!"); 9280 } 9281 9282 void 9283 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 9284 SDValue Op = getNonRegisterValue(V); 9285 assert((Op.getOpcode() != ISD::CopyFromReg || 9286 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 9287 "Copy from a reg to the same reg!"); 9288 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 9289 9290 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9291 // If this is an InlineAsm we have to match the registers required, not the 9292 // notional registers required by the type. 9293 9294 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 9295 None); // This is not an ABI copy. 9296 SDValue Chain = DAG.getEntryNode(); 9297 9298 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 9299 FuncInfo.PreferredExtendType.end()) 9300 ? ISD::ANY_EXTEND 9301 : FuncInfo.PreferredExtendType[V]; 9302 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 9303 PendingExports.push_back(Chain); 9304 } 9305 9306 #include "llvm/CodeGen/SelectionDAGISel.h" 9307 9308 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 9309 /// entry block, return true. This includes arguments used by switches, since 9310 /// the switch may expand into multiple basic blocks. 9311 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 9312 // With FastISel active, we may be splitting blocks, so force creation 9313 // of virtual registers for all non-dead arguments. 9314 if (FastISel) 9315 return A->use_empty(); 9316 9317 const BasicBlock &Entry = A->getParent()->front(); 9318 for (const User *U : A->users()) 9319 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 9320 return false; // Use not in entry block. 9321 9322 return true; 9323 } 9324 9325 using ArgCopyElisionMapTy = 9326 DenseMap<const Argument *, 9327 std::pair<const AllocaInst *, const StoreInst *>>; 9328 9329 /// Scan the entry block of the function in FuncInfo for arguments that look 9330 /// like copies into a local alloca. Record any copied arguments in 9331 /// ArgCopyElisionCandidates. 9332 static void 9333 findArgumentCopyElisionCandidates(const DataLayout &DL, 9334 FunctionLoweringInfo *FuncInfo, 9335 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 9336 // Record the state of every static alloca used in the entry block. Argument 9337 // allocas are all used in the entry block, so we need approximately as many 9338 // entries as we have arguments. 9339 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 9340 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 9341 unsigned NumArgs = FuncInfo->Fn->arg_size(); 9342 StaticAllocas.reserve(NumArgs * 2); 9343 9344 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 9345 if (!V) 9346 return nullptr; 9347 V = V->stripPointerCasts(); 9348 const auto *AI = dyn_cast<AllocaInst>(V); 9349 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 9350 return nullptr; 9351 auto Iter = StaticAllocas.insert({AI, Unknown}); 9352 return &Iter.first->second; 9353 }; 9354 9355 // Look for stores of arguments to static allocas. Look through bitcasts and 9356 // GEPs to handle type coercions, as long as the alloca is fully initialized 9357 // by the store. Any non-store use of an alloca escapes it and any subsequent 9358 // unanalyzed store might write it. 9359 // FIXME: Handle structs initialized with multiple stores. 9360 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 9361 // Look for stores, and handle non-store uses conservatively. 9362 const auto *SI = dyn_cast<StoreInst>(&I); 9363 if (!SI) { 9364 // We will look through cast uses, so ignore them completely. 9365 if (I.isCast()) 9366 continue; 9367 // Ignore debug info intrinsics, they don't escape or store to allocas. 9368 if (isa<DbgInfoIntrinsic>(I)) 9369 continue; 9370 // This is an unknown instruction. Assume it escapes or writes to all 9371 // static alloca operands. 9372 for (const Use &U : I.operands()) { 9373 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 9374 *Info = StaticAllocaInfo::Clobbered; 9375 } 9376 continue; 9377 } 9378 9379 // If the stored value is a static alloca, mark it as escaped. 9380 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 9381 *Info = StaticAllocaInfo::Clobbered; 9382 9383 // Check if the destination is a static alloca. 9384 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 9385 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 9386 if (!Info) 9387 continue; 9388 const AllocaInst *AI = cast<AllocaInst>(Dst); 9389 9390 // Skip allocas that have been initialized or clobbered. 9391 if (*Info != StaticAllocaInfo::Unknown) 9392 continue; 9393 9394 // Check if the stored value is an argument, and that this store fully 9395 // initializes the alloca. Don't elide copies from the same argument twice. 9396 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 9397 const auto *Arg = dyn_cast<Argument>(Val); 9398 if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() || 9399 Arg->getType()->isEmptyTy() || 9400 DL.getTypeStoreSize(Arg->getType()) != 9401 DL.getTypeAllocSize(AI->getAllocatedType()) || 9402 ArgCopyElisionCandidates.count(Arg)) { 9403 *Info = StaticAllocaInfo::Clobbered; 9404 continue; 9405 } 9406 9407 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 9408 << '\n'); 9409 9410 // Mark this alloca and store for argument copy elision. 9411 *Info = StaticAllocaInfo::Elidable; 9412 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 9413 9414 // Stop scanning if we've seen all arguments. This will happen early in -O0 9415 // builds, which is useful, because -O0 builds have large entry blocks and 9416 // many allocas. 9417 if (ArgCopyElisionCandidates.size() == NumArgs) 9418 break; 9419 } 9420 } 9421 9422 /// Try to elide argument copies from memory into a local alloca. Succeeds if 9423 /// ArgVal is a load from a suitable fixed stack object. 9424 static void tryToElideArgumentCopy( 9425 FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains, 9426 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 9427 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 9428 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 9429 SDValue ArgVal, bool &ArgHasUses) { 9430 // Check if this is a load from a fixed stack object. 9431 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 9432 if (!LNode) 9433 return; 9434 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 9435 if (!FINode) 9436 return; 9437 9438 // Check that the fixed stack object is the right size and alignment. 9439 // Look at the alignment that the user wrote on the alloca instead of looking 9440 // at the stack object. 9441 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 9442 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 9443 const AllocaInst *AI = ArgCopyIter->second.first; 9444 int FixedIndex = FINode->getIndex(); 9445 int &AllocaIndex = FuncInfo->StaticAllocaMap[AI]; 9446 int OldIndex = AllocaIndex; 9447 MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo(); 9448 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 9449 LLVM_DEBUG( 9450 dbgs() << " argument copy elision failed due to bad fixed stack " 9451 "object size\n"); 9452 return; 9453 } 9454 unsigned RequiredAlignment = AI->getAlignment(); 9455 if (!RequiredAlignment) { 9456 RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment( 9457 AI->getAllocatedType()); 9458 } 9459 if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) { 9460 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 9461 "greater than stack argument alignment (" 9462 << RequiredAlignment << " vs " 9463 << MFI.getObjectAlignment(FixedIndex) << ")\n"); 9464 return; 9465 } 9466 9467 // Perform the elision. Delete the old stack object and replace its only use 9468 // in the variable info map. Mark the stack object as mutable. 9469 LLVM_DEBUG({ 9470 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 9471 << " Replacing frame index " << OldIndex << " with " << FixedIndex 9472 << '\n'; 9473 }); 9474 MFI.RemoveStackObject(OldIndex); 9475 MFI.setIsImmutableObjectIndex(FixedIndex, false); 9476 AllocaIndex = FixedIndex; 9477 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 9478 Chains.push_back(ArgVal.getValue(1)); 9479 9480 // Avoid emitting code for the store implementing the copy. 9481 const StoreInst *SI = ArgCopyIter->second.second; 9482 ElidedArgCopyInstrs.insert(SI); 9483 9484 // Check for uses of the argument again so that we can avoid exporting ArgVal 9485 // if it is't used by anything other than the store. 9486 for (const Value *U : Arg.users()) { 9487 if (U != SI) { 9488 ArgHasUses = true; 9489 break; 9490 } 9491 } 9492 } 9493 9494 void SelectionDAGISel::LowerArguments(const Function &F) { 9495 SelectionDAG &DAG = SDB->DAG; 9496 SDLoc dl = SDB->getCurSDLoc(); 9497 const DataLayout &DL = DAG.getDataLayout(); 9498 SmallVector<ISD::InputArg, 16> Ins; 9499 9500 if (!FuncInfo->CanLowerReturn) { 9501 // Put in an sret pointer parameter before all the other parameters. 9502 SmallVector<EVT, 1> ValueVTs; 9503 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9504 F.getReturnType()->getPointerTo( 9505 DAG.getDataLayout().getAllocaAddrSpace()), 9506 ValueVTs); 9507 9508 // NOTE: Assuming that a pointer will never break down to more than one VT 9509 // or one register. 9510 ISD::ArgFlagsTy Flags; 9511 Flags.setSRet(); 9512 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 9513 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 9514 ISD::InputArg::NoArgIndex, 0); 9515 Ins.push_back(RetArg); 9516 } 9517 9518 // Look for stores of arguments to static allocas. Mark such arguments with a 9519 // flag to ask the target to give us the memory location of that argument if 9520 // available. 9521 ArgCopyElisionMapTy ArgCopyElisionCandidates; 9522 findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates); 9523 9524 // Set up the incoming argument description vector. 9525 for (const Argument &Arg : F.args()) { 9526 unsigned ArgNo = Arg.getArgNo(); 9527 SmallVector<EVT, 4> ValueVTs; 9528 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9529 bool isArgValueUsed = !Arg.use_empty(); 9530 unsigned PartBase = 0; 9531 Type *FinalType = Arg.getType(); 9532 if (Arg.hasAttribute(Attribute::ByVal)) 9533 FinalType = Arg.getParamByValType(); 9534 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 9535 FinalType, F.getCallingConv(), F.isVarArg()); 9536 for (unsigned Value = 0, NumValues = ValueVTs.size(); 9537 Value != NumValues; ++Value) { 9538 EVT VT = ValueVTs[Value]; 9539 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 9540 ISD::ArgFlagsTy Flags; 9541 9542 // Certain targets (such as MIPS), may have a different ABI alignment 9543 // for a type depending on the context. Give the target a chance to 9544 // specify the alignment it wants. 9545 const Align OriginalAlignment( 9546 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 9547 9548 if (Arg.getType()->isPointerTy()) { 9549 Flags.setPointer(); 9550 Flags.setPointerAddrSpace( 9551 cast<PointerType>(Arg.getType())->getAddressSpace()); 9552 } 9553 if (Arg.hasAttribute(Attribute::ZExt)) 9554 Flags.setZExt(); 9555 if (Arg.hasAttribute(Attribute::SExt)) 9556 Flags.setSExt(); 9557 if (Arg.hasAttribute(Attribute::InReg)) { 9558 // If we are using vectorcall calling convention, a structure that is 9559 // passed InReg - is surely an HVA 9560 if (F.getCallingConv() == CallingConv::X86_VectorCall && 9561 isa<StructType>(Arg.getType())) { 9562 // The first value of a structure is marked 9563 if (0 == Value) 9564 Flags.setHvaStart(); 9565 Flags.setHva(); 9566 } 9567 // Set InReg Flag 9568 Flags.setInReg(); 9569 } 9570 if (Arg.hasAttribute(Attribute::StructRet)) 9571 Flags.setSRet(); 9572 if (Arg.hasAttribute(Attribute::SwiftSelf)) 9573 Flags.setSwiftSelf(); 9574 if (Arg.hasAttribute(Attribute::SwiftError)) 9575 Flags.setSwiftError(); 9576 if (Arg.hasAttribute(Attribute::ByVal)) 9577 Flags.setByVal(); 9578 if (Arg.hasAttribute(Attribute::InAlloca)) { 9579 Flags.setInAlloca(); 9580 // Set the byval flag for CCAssignFn callbacks that don't know about 9581 // inalloca. This way we can know how many bytes we should've allocated 9582 // and how many bytes a callee cleanup function will pop. If we port 9583 // inalloca to more targets, we'll have to add custom inalloca handling 9584 // in the various CC lowering callbacks. 9585 Flags.setByVal(); 9586 } 9587 if (F.getCallingConv() == CallingConv::X86_INTR) { 9588 // IA Interrupt passes frame (1st parameter) by value in the stack. 9589 if (ArgNo == 0) 9590 Flags.setByVal(); 9591 } 9592 if (Flags.isByVal() || Flags.isInAlloca()) { 9593 Type *ElementTy = Arg.getParamByValType(); 9594 9595 // For ByVal, size and alignment should be passed from FE. BE will 9596 // guess if this info is not there but there are cases it cannot get 9597 // right. 9598 unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType()); 9599 Flags.setByValSize(FrameSize); 9600 9601 unsigned FrameAlign; 9602 if (Arg.getParamAlignment()) 9603 FrameAlign = Arg.getParamAlignment(); 9604 else 9605 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL); 9606 Flags.setByValAlign(Align(FrameAlign)); 9607 } 9608 if (Arg.hasAttribute(Attribute::Nest)) 9609 Flags.setNest(); 9610 if (NeedsRegBlock) 9611 Flags.setInConsecutiveRegs(); 9612 Flags.setOrigAlign(OriginalAlignment); 9613 if (ArgCopyElisionCandidates.count(&Arg)) 9614 Flags.setCopyElisionCandidate(); 9615 if (Arg.hasAttribute(Attribute::Returned)) 9616 Flags.setReturned(); 9617 9618 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 9619 *CurDAG->getContext(), F.getCallingConv(), VT); 9620 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 9621 *CurDAG->getContext(), F.getCallingConv(), VT); 9622 for (unsigned i = 0; i != NumRegs; ++i) { 9623 // For scalable vectors, use the minimum size; individual targets 9624 // are responsible for handling scalable vector arguments and 9625 // return values. 9626 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 9627 ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize()); 9628 if (NumRegs > 1 && i == 0) 9629 MyFlags.Flags.setSplit(); 9630 // if it isn't first piece, alignment must be 1 9631 else if (i > 0) { 9632 MyFlags.Flags.setOrigAlign(Align::None()); 9633 if (i == NumRegs - 1) 9634 MyFlags.Flags.setSplitEnd(); 9635 } 9636 Ins.push_back(MyFlags); 9637 } 9638 if (NeedsRegBlock && Value == NumValues - 1) 9639 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 9640 PartBase += VT.getStoreSize().getKnownMinSize(); 9641 } 9642 } 9643 9644 // Call the target to set up the argument values. 9645 SmallVector<SDValue, 8> InVals; 9646 SDValue NewRoot = TLI->LowerFormalArguments( 9647 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 9648 9649 // Verify that the target's LowerFormalArguments behaved as expected. 9650 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 9651 "LowerFormalArguments didn't return a valid chain!"); 9652 assert(InVals.size() == Ins.size() && 9653 "LowerFormalArguments didn't emit the correct number of values!"); 9654 LLVM_DEBUG({ 9655 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 9656 assert(InVals[i].getNode() && 9657 "LowerFormalArguments emitted a null value!"); 9658 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 9659 "LowerFormalArguments emitted a value with the wrong type!"); 9660 } 9661 }); 9662 9663 // Update the DAG with the new chain value resulting from argument lowering. 9664 DAG.setRoot(NewRoot); 9665 9666 // Set up the argument values. 9667 unsigned i = 0; 9668 if (!FuncInfo->CanLowerReturn) { 9669 // Create a virtual register for the sret pointer, and put in a copy 9670 // from the sret argument into it. 9671 SmallVector<EVT, 1> ValueVTs; 9672 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9673 F.getReturnType()->getPointerTo( 9674 DAG.getDataLayout().getAllocaAddrSpace()), 9675 ValueVTs); 9676 MVT VT = ValueVTs[0].getSimpleVT(); 9677 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 9678 Optional<ISD::NodeType> AssertOp = None; 9679 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 9680 nullptr, F.getCallingConv(), AssertOp); 9681 9682 MachineFunction& MF = SDB->DAG.getMachineFunction(); 9683 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 9684 Register SRetReg = 9685 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 9686 FuncInfo->DemoteRegister = SRetReg; 9687 NewRoot = 9688 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 9689 DAG.setRoot(NewRoot); 9690 9691 // i indexes lowered arguments. Bump it past the hidden sret argument. 9692 ++i; 9693 } 9694 9695 SmallVector<SDValue, 4> Chains; 9696 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 9697 for (const Argument &Arg : F.args()) { 9698 SmallVector<SDValue, 4> ArgValues; 9699 SmallVector<EVT, 4> ValueVTs; 9700 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9701 unsigned NumValues = ValueVTs.size(); 9702 if (NumValues == 0) 9703 continue; 9704 9705 bool ArgHasUses = !Arg.use_empty(); 9706 9707 // Elide the copying store if the target loaded this argument from a 9708 // suitable fixed stack object. 9709 if (Ins[i].Flags.isCopyElisionCandidate()) { 9710 tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 9711 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 9712 InVals[i], ArgHasUses); 9713 } 9714 9715 // If this argument is unused then remember its value. It is used to generate 9716 // debugging information. 9717 bool isSwiftErrorArg = 9718 TLI->supportSwiftError() && 9719 Arg.hasAttribute(Attribute::SwiftError); 9720 if (!ArgHasUses && !isSwiftErrorArg) { 9721 SDB->setUnusedArgValue(&Arg, InVals[i]); 9722 9723 // Also remember any frame index for use in FastISel. 9724 if (FrameIndexSDNode *FI = 9725 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 9726 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9727 } 9728 9729 for (unsigned Val = 0; Val != NumValues; ++Val) { 9730 EVT VT = ValueVTs[Val]; 9731 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 9732 F.getCallingConv(), VT); 9733 unsigned NumParts = TLI->getNumRegistersForCallingConv( 9734 *CurDAG->getContext(), F.getCallingConv(), VT); 9735 9736 // Even an apparent 'unused' swifterror argument needs to be returned. So 9737 // we do generate a copy for it that can be used on return from the 9738 // function. 9739 if (ArgHasUses || isSwiftErrorArg) { 9740 Optional<ISD::NodeType> AssertOp; 9741 if (Arg.hasAttribute(Attribute::SExt)) 9742 AssertOp = ISD::AssertSext; 9743 else if (Arg.hasAttribute(Attribute::ZExt)) 9744 AssertOp = ISD::AssertZext; 9745 9746 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 9747 PartVT, VT, nullptr, 9748 F.getCallingConv(), AssertOp)); 9749 } 9750 9751 i += NumParts; 9752 } 9753 9754 // We don't need to do anything else for unused arguments. 9755 if (ArgValues.empty()) 9756 continue; 9757 9758 // Note down frame index. 9759 if (FrameIndexSDNode *FI = 9760 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 9761 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9762 9763 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 9764 SDB->getCurSDLoc()); 9765 9766 SDB->setValue(&Arg, Res); 9767 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 9768 // We want to associate the argument with the frame index, among 9769 // involved operands, that correspond to the lowest address. The 9770 // getCopyFromParts function, called earlier, is swapping the order of 9771 // the operands to BUILD_PAIR depending on endianness. The result of 9772 // that swapping is that the least significant bits of the argument will 9773 // be in the first operand of the BUILD_PAIR node, and the most 9774 // significant bits will be in the second operand. 9775 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 9776 if (LoadSDNode *LNode = 9777 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 9778 if (FrameIndexSDNode *FI = 9779 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 9780 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9781 } 9782 9783 // Analyses past this point are naive and don't expect an assertion. 9784 if (Res.getOpcode() == ISD::AssertZext) 9785 Res = Res.getOperand(0); 9786 9787 // Update the SwiftErrorVRegDefMap. 9788 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 9789 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9790 if (Register::isVirtualRegister(Reg)) 9791 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 9792 Reg); 9793 } 9794 9795 // If this argument is live outside of the entry block, insert a copy from 9796 // wherever we got it to the vreg that other BB's will reference it as. 9797 if (Res.getOpcode() == ISD::CopyFromReg) { 9798 // If we can, though, try to skip creating an unnecessary vreg. 9799 // FIXME: This isn't very clean... it would be nice to make this more 9800 // general. 9801 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9802 if (Register::isVirtualRegister(Reg)) { 9803 FuncInfo->ValueMap[&Arg] = Reg; 9804 continue; 9805 } 9806 } 9807 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 9808 FuncInfo->InitializeRegForValue(&Arg); 9809 SDB->CopyToExportRegsIfNeeded(&Arg); 9810 } 9811 } 9812 9813 if (!Chains.empty()) { 9814 Chains.push_back(NewRoot); 9815 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 9816 } 9817 9818 DAG.setRoot(NewRoot); 9819 9820 assert(i == InVals.size() && "Argument register count mismatch!"); 9821 9822 // If any argument copy elisions occurred and we have debug info, update the 9823 // stale frame indices used in the dbg.declare variable info table. 9824 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 9825 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 9826 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 9827 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 9828 if (I != ArgCopyElisionFrameIndexMap.end()) 9829 VI.Slot = I->second; 9830 } 9831 } 9832 9833 // Finally, if the target has anything special to do, allow it to do so. 9834 EmitFunctionEntryCode(); 9835 } 9836 9837 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 9838 /// ensure constants are generated when needed. Remember the virtual registers 9839 /// that need to be added to the Machine PHI nodes as input. We cannot just 9840 /// directly add them, because expansion might result in multiple MBB's for one 9841 /// BB. As such, the start of the BB might correspond to a different MBB than 9842 /// the end. 9843 void 9844 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 9845 const Instruction *TI = LLVMBB->getTerminator(); 9846 9847 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 9848 9849 // Check PHI nodes in successors that expect a value to be available from this 9850 // block. 9851 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 9852 const BasicBlock *SuccBB = TI->getSuccessor(succ); 9853 if (!isa<PHINode>(SuccBB->begin())) continue; 9854 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 9855 9856 // If this terminator has multiple identical successors (common for 9857 // switches), only handle each succ once. 9858 if (!SuccsHandled.insert(SuccMBB).second) 9859 continue; 9860 9861 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 9862 9863 // At this point we know that there is a 1-1 correspondence between LLVM PHI 9864 // nodes and Machine PHI nodes, but the incoming operands have not been 9865 // emitted yet. 9866 for (const PHINode &PN : SuccBB->phis()) { 9867 // Ignore dead phi's. 9868 if (PN.use_empty()) 9869 continue; 9870 9871 // Skip empty types 9872 if (PN.getType()->isEmptyTy()) 9873 continue; 9874 9875 unsigned Reg; 9876 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 9877 9878 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 9879 unsigned &RegOut = ConstantsOut[C]; 9880 if (RegOut == 0) { 9881 RegOut = FuncInfo.CreateRegs(C); 9882 CopyValueToVirtualRegister(C, RegOut); 9883 } 9884 Reg = RegOut; 9885 } else { 9886 DenseMap<const Value *, unsigned>::iterator I = 9887 FuncInfo.ValueMap.find(PHIOp); 9888 if (I != FuncInfo.ValueMap.end()) 9889 Reg = I->second; 9890 else { 9891 assert(isa<AllocaInst>(PHIOp) && 9892 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 9893 "Didn't codegen value into a register!??"); 9894 Reg = FuncInfo.CreateRegs(PHIOp); 9895 CopyValueToVirtualRegister(PHIOp, Reg); 9896 } 9897 } 9898 9899 // Remember that this register needs to added to the machine PHI node as 9900 // the input for this MBB. 9901 SmallVector<EVT, 4> ValueVTs; 9902 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9903 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 9904 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 9905 EVT VT = ValueVTs[vti]; 9906 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 9907 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 9908 FuncInfo.PHINodesToUpdate.push_back( 9909 std::make_pair(&*MBBI++, Reg + i)); 9910 Reg += NumRegisters; 9911 } 9912 } 9913 } 9914 9915 ConstantsOut.clear(); 9916 } 9917 9918 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 9919 /// is 0. 9920 MachineBasicBlock * 9921 SelectionDAGBuilder::StackProtectorDescriptor:: 9922 AddSuccessorMBB(const BasicBlock *BB, 9923 MachineBasicBlock *ParentMBB, 9924 bool IsLikely, 9925 MachineBasicBlock *SuccMBB) { 9926 // If SuccBB has not been created yet, create it. 9927 if (!SuccMBB) { 9928 MachineFunction *MF = ParentMBB->getParent(); 9929 MachineFunction::iterator BBI(ParentMBB); 9930 SuccMBB = MF->CreateMachineBasicBlock(BB); 9931 MF->insert(++BBI, SuccMBB); 9932 } 9933 // Add it as a successor of ParentMBB. 9934 ParentMBB->addSuccessor( 9935 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 9936 return SuccMBB; 9937 } 9938 9939 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 9940 MachineFunction::iterator I(MBB); 9941 if (++I == FuncInfo.MF->end()) 9942 return nullptr; 9943 return &*I; 9944 } 9945 9946 /// During lowering new call nodes can be created (such as memset, etc.). 9947 /// Those will become new roots of the current DAG, but complications arise 9948 /// when they are tail calls. In such cases, the call lowering will update 9949 /// the root, but the builder still needs to know that a tail call has been 9950 /// lowered in order to avoid generating an additional return. 9951 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 9952 // If the node is null, we do have a tail call. 9953 if (MaybeTC.getNode() != nullptr) 9954 DAG.setRoot(MaybeTC); 9955 else 9956 HasTailCall = true; 9957 } 9958 9959 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 9960 MachineBasicBlock *SwitchMBB, 9961 MachineBasicBlock *DefaultMBB) { 9962 MachineFunction *CurMF = FuncInfo.MF; 9963 MachineBasicBlock *NextMBB = nullptr; 9964 MachineFunction::iterator BBI(W.MBB); 9965 if (++BBI != FuncInfo.MF->end()) 9966 NextMBB = &*BBI; 9967 9968 unsigned Size = W.LastCluster - W.FirstCluster + 1; 9969 9970 BranchProbabilityInfo *BPI = FuncInfo.BPI; 9971 9972 if (Size == 2 && W.MBB == SwitchMBB) { 9973 // If any two of the cases has the same destination, and if one value 9974 // is the same as the other, but has one bit unset that the other has set, 9975 // use bit manipulation to do two compares at once. For example: 9976 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 9977 // TODO: This could be extended to merge any 2 cases in switches with 3 9978 // cases. 9979 // TODO: Handle cases where W.CaseBB != SwitchBB. 9980 CaseCluster &Small = *W.FirstCluster; 9981 CaseCluster &Big = *W.LastCluster; 9982 9983 if (Small.Low == Small.High && Big.Low == Big.High && 9984 Small.MBB == Big.MBB) { 9985 const APInt &SmallValue = Small.Low->getValue(); 9986 const APInt &BigValue = Big.Low->getValue(); 9987 9988 // Check that there is only one bit different. 9989 APInt CommonBit = BigValue ^ SmallValue; 9990 if (CommonBit.isPowerOf2()) { 9991 SDValue CondLHS = getValue(Cond); 9992 EVT VT = CondLHS.getValueType(); 9993 SDLoc DL = getCurSDLoc(); 9994 9995 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 9996 DAG.getConstant(CommonBit, DL, VT)); 9997 SDValue Cond = DAG.getSetCC( 9998 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 9999 ISD::SETEQ); 10000 10001 // Update successor info. 10002 // Both Small and Big will jump to Small.BB, so we sum up the 10003 // probabilities. 10004 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10005 if (BPI) 10006 addSuccessorWithProb( 10007 SwitchMBB, DefaultMBB, 10008 // The default destination is the first successor in IR. 10009 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10010 else 10011 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10012 10013 // Insert the true branch. 10014 SDValue BrCond = 10015 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10016 DAG.getBasicBlock(Small.MBB)); 10017 // Insert the false branch. 10018 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10019 DAG.getBasicBlock(DefaultMBB)); 10020 10021 DAG.setRoot(BrCond); 10022 return; 10023 } 10024 } 10025 } 10026 10027 if (TM.getOptLevel() != CodeGenOpt::None) { 10028 // Here, we order cases by probability so the most likely case will be 10029 // checked first. However, two clusters can have the same probability in 10030 // which case their relative ordering is non-deterministic. So we use Low 10031 // as a tie-breaker as clusters are guaranteed to never overlap. 10032 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10033 [](const CaseCluster &a, const CaseCluster &b) { 10034 return a.Prob != b.Prob ? 10035 a.Prob > b.Prob : 10036 a.Low->getValue().slt(b.Low->getValue()); 10037 }); 10038 10039 // Rearrange the case blocks so that the last one falls through if possible 10040 // without changing the order of probabilities. 10041 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10042 --I; 10043 if (I->Prob > W.LastCluster->Prob) 10044 break; 10045 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10046 std::swap(*I, *W.LastCluster); 10047 break; 10048 } 10049 } 10050 } 10051 10052 // Compute total probability. 10053 BranchProbability DefaultProb = W.DefaultProb; 10054 BranchProbability UnhandledProbs = DefaultProb; 10055 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10056 UnhandledProbs += I->Prob; 10057 10058 MachineBasicBlock *CurMBB = W.MBB; 10059 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10060 bool FallthroughUnreachable = false; 10061 MachineBasicBlock *Fallthrough; 10062 if (I == W.LastCluster) { 10063 // For the last cluster, fall through to the default destination. 10064 Fallthrough = DefaultMBB; 10065 FallthroughUnreachable = isa<UnreachableInst>( 10066 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10067 } else { 10068 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10069 CurMF->insert(BBI, Fallthrough); 10070 // Put Cond in a virtual register to make it available from the new blocks. 10071 ExportFromCurrentBlock(Cond); 10072 } 10073 UnhandledProbs -= I->Prob; 10074 10075 switch (I->Kind) { 10076 case CC_JumpTable: { 10077 // FIXME: Optimize away range check based on pivot comparisons. 10078 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 10079 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 10080 10081 // The jump block hasn't been inserted yet; insert it here. 10082 MachineBasicBlock *JumpMBB = JT->MBB; 10083 CurMF->insert(BBI, JumpMBB); 10084 10085 auto JumpProb = I->Prob; 10086 auto FallthroughProb = UnhandledProbs; 10087 10088 // If the default statement is a target of the jump table, we evenly 10089 // distribute the default probability to successors of CurMBB. Also 10090 // update the probability on the edge from JumpMBB to Fallthrough. 10091 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10092 SE = JumpMBB->succ_end(); 10093 SI != SE; ++SI) { 10094 if (*SI == DefaultMBB) { 10095 JumpProb += DefaultProb / 2; 10096 FallthroughProb -= DefaultProb / 2; 10097 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10098 JumpMBB->normalizeSuccProbs(); 10099 break; 10100 } 10101 } 10102 10103 if (FallthroughUnreachable) { 10104 // Skip the range check if the fallthrough block is unreachable. 10105 JTH->OmitRangeCheck = true; 10106 } 10107 10108 if (!JTH->OmitRangeCheck) 10109 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10110 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10111 CurMBB->normalizeSuccProbs(); 10112 10113 // The jump table header will be inserted in our current block, do the 10114 // range check, and fall through to our fallthrough block. 10115 JTH->HeaderBB = CurMBB; 10116 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10117 10118 // If we're in the right place, emit the jump table header right now. 10119 if (CurMBB == SwitchMBB) { 10120 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10121 JTH->Emitted = true; 10122 } 10123 break; 10124 } 10125 case CC_BitTests: { 10126 // FIXME: Optimize away range check based on pivot comparisons. 10127 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 10128 10129 // The bit test blocks haven't been inserted yet; insert them here. 10130 for (BitTestCase &BTC : BTB->Cases) 10131 CurMF->insert(BBI, BTC.ThisBB); 10132 10133 // Fill in fields of the BitTestBlock. 10134 BTB->Parent = CurMBB; 10135 BTB->Default = Fallthrough; 10136 10137 BTB->DefaultProb = UnhandledProbs; 10138 // If the cases in bit test don't form a contiguous range, we evenly 10139 // distribute the probability on the edge to Fallthrough to two 10140 // successors of CurMBB. 10141 if (!BTB->ContiguousRange) { 10142 BTB->Prob += DefaultProb / 2; 10143 BTB->DefaultProb -= DefaultProb / 2; 10144 } 10145 10146 if (FallthroughUnreachable) { 10147 // Skip the range check if the fallthrough block is unreachable. 10148 BTB->OmitRangeCheck = true; 10149 } 10150 10151 // If we're in the right place, emit the bit test header right now. 10152 if (CurMBB == SwitchMBB) { 10153 visitBitTestHeader(*BTB, SwitchMBB); 10154 BTB->Emitted = true; 10155 } 10156 break; 10157 } 10158 case CC_Range: { 10159 const Value *RHS, *LHS, *MHS; 10160 ISD::CondCode CC; 10161 if (I->Low == I->High) { 10162 // Check Cond == I->Low. 10163 CC = ISD::SETEQ; 10164 LHS = Cond; 10165 RHS=I->Low; 10166 MHS = nullptr; 10167 } else { 10168 // Check I->Low <= Cond <= I->High. 10169 CC = ISD::SETLE; 10170 LHS = I->Low; 10171 MHS = Cond; 10172 RHS = I->High; 10173 } 10174 10175 // If Fallthrough is unreachable, fold away the comparison. 10176 if (FallthroughUnreachable) 10177 CC = ISD::SETTRUE; 10178 10179 // The false probability is the sum of all unhandled cases. 10180 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10181 getCurSDLoc(), I->Prob, UnhandledProbs); 10182 10183 if (CurMBB == SwitchMBB) 10184 visitSwitchCase(CB, SwitchMBB); 10185 else 10186 SL->SwitchCases.push_back(CB); 10187 10188 break; 10189 } 10190 } 10191 CurMBB = Fallthrough; 10192 } 10193 } 10194 10195 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10196 CaseClusterIt First, 10197 CaseClusterIt Last) { 10198 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10199 if (X.Prob != CC.Prob) 10200 return X.Prob > CC.Prob; 10201 10202 // Ties are broken by comparing the case value. 10203 return X.Low->getValue().slt(CC.Low->getValue()); 10204 }); 10205 } 10206 10207 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10208 const SwitchWorkListItem &W, 10209 Value *Cond, 10210 MachineBasicBlock *SwitchMBB) { 10211 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10212 "Clusters not sorted?"); 10213 10214 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10215 10216 // Balance the tree based on branch probabilities to create a near-optimal (in 10217 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10218 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10219 CaseClusterIt LastLeft = W.FirstCluster; 10220 CaseClusterIt FirstRight = W.LastCluster; 10221 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10222 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10223 10224 // Move LastLeft and FirstRight towards each other from opposite directions to 10225 // find a partitioning of the clusters which balances the probability on both 10226 // sides. If LeftProb and RightProb are equal, alternate which side is 10227 // taken to ensure 0-probability nodes are distributed evenly. 10228 unsigned I = 0; 10229 while (LastLeft + 1 < FirstRight) { 10230 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10231 LeftProb += (++LastLeft)->Prob; 10232 else 10233 RightProb += (--FirstRight)->Prob; 10234 I++; 10235 } 10236 10237 while (true) { 10238 // Our binary search tree differs from a typical BST in that ours can have up 10239 // to three values in each leaf. The pivot selection above doesn't take that 10240 // into account, which means the tree might require more nodes and be less 10241 // efficient. We compensate for this here. 10242 10243 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10244 unsigned NumRight = W.LastCluster - FirstRight + 1; 10245 10246 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10247 // If one side has less than 3 clusters, and the other has more than 3, 10248 // consider taking a cluster from the other side. 10249 10250 if (NumLeft < NumRight) { 10251 // Consider moving the first cluster on the right to the left side. 10252 CaseCluster &CC = *FirstRight; 10253 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10254 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10255 if (LeftSideRank <= RightSideRank) { 10256 // Moving the cluster to the left does not demote it. 10257 ++LastLeft; 10258 ++FirstRight; 10259 continue; 10260 } 10261 } else { 10262 assert(NumRight < NumLeft); 10263 // Consider moving the last element on the left to the right side. 10264 CaseCluster &CC = *LastLeft; 10265 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10266 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10267 if (RightSideRank <= LeftSideRank) { 10268 // Moving the cluster to the right does not demot it. 10269 --LastLeft; 10270 --FirstRight; 10271 continue; 10272 } 10273 } 10274 } 10275 break; 10276 } 10277 10278 assert(LastLeft + 1 == FirstRight); 10279 assert(LastLeft >= W.FirstCluster); 10280 assert(FirstRight <= W.LastCluster); 10281 10282 // Use the first element on the right as pivot since we will make less-than 10283 // comparisons against it. 10284 CaseClusterIt PivotCluster = FirstRight; 10285 assert(PivotCluster > W.FirstCluster); 10286 assert(PivotCluster <= W.LastCluster); 10287 10288 CaseClusterIt FirstLeft = W.FirstCluster; 10289 CaseClusterIt LastRight = W.LastCluster; 10290 10291 const ConstantInt *Pivot = PivotCluster->Low; 10292 10293 // New blocks will be inserted immediately after the current one. 10294 MachineFunction::iterator BBI(W.MBB); 10295 ++BBI; 10296 10297 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10298 // we can branch to its destination directly if it's squeezed exactly in 10299 // between the known lower bound and Pivot - 1. 10300 MachineBasicBlock *LeftMBB; 10301 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10302 FirstLeft->Low == W.GE && 10303 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10304 LeftMBB = FirstLeft->MBB; 10305 } else { 10306 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10307 FuncInfo.MF->insert(BBI, LeftMBB); 10308 WorkList.push_back( 10309 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10310 // Put Cond in a virtual register to make it available from the new blocks. 10311 ExportFromCurrentBlock(Cond); 10312 } 10313 10314 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10315 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10316 // directly if RHS.High equals the current upper bound. 10317 MachineBasicBlock *RightMBB; 10318 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10319 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10320 RightMBB = FirstRight->MBB; 10321 } else { 10322 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10323 FuncInfo.MF->insert(BBI, RightMBB); 10324 WorkList.push_back( 10325 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10326 // Put Cond in a virtual register to make it available from the new blocks. 10327 ExportFromCurrentBlock(Cond); 10328 } 10329 10330 // Create the CaseBlock record that will be used to lower the branch. 10331 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10332 getCurSDLoc(), LeftProb, RightProb); 10333 10334 if (W.MBB == SwitchMBB) 10335 visitSwitchCase(CB, SwitchMBB); 10336 else 10337 SL->SwitchCases.push_back(CB); 10338 } 10339 10340 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10341 // from the swith statement. 10342 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10343 BranchProbability PeeledCaseProb) { 10344 if (PeeledCaseProb == BranchProbability::getOne()) 10345 return BranchProbability::getZero(); 10346 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10347 10348 uint32_t Numerator = CaseProb.getNumerator(); 10349 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10350 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10351 } 10352 10353 // Try to peel the top probability case if it exceeds the threshold. 10354 // Return current MachineBasicBlock for the switch statement if the peeling 10355 // does not occur. 10356 // If the peeling is performed, return the newly created MachineBasicBlock 10357 // for the peeled switch statement. Also update Clusters to remove the peeled 10358 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10359 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10360 const SwitchInst &SI, CaseClusterVector &Clusters, 10361 BranchProbability &PeeledCaseProb) { 10362 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10363 // Don't perform if there is only one cluster or optimizing for size. 10364 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10365 TM.getOptLevel() == CodeGenOpt::None || 10366 SwitchMBB->getParent()->getFunction().hasMinSize()) 10367 return SwitchMBB; 10368 10369 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10370 unsigned PeeledCaseIndex = 0; 10371 bool SwitchPeeled = false; 10372 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10373 CaseCluster &CC = Clusters[Index]; 10374 if (CC.Prob < TopCaseProb) 10375 continue; 10376 TopCaseProb = CC.Prob; 10377 PeeledCaseIndex = Index; 10378 SwitchPeeled = true; 10379 } 10380 if (!SwitchPeeled) 10381 return SwitchMBB; 10382 10383 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10384 << TopCaseProb << "\n"); 10385 10386 // Record the MBB for the peeled switch statement. 10387 MachineFunction::iterator BBI(SwitchMBB); 10388 ++BBI; 10389 MachineBasicBlock *PeeledSwitchMBB = 10390 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10391 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10392 10393 ExportFromCurrentBlock(SI.getCondition()); 10394 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10395 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10396 nullptr, nullptr, TopCaseProb.getCompl()}; 10397 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10398 10399 Clusters.erase(PeeledCaseIt); 10400 for (CaseCluster &CC : Clusters) { 10401 LLVM_DEBUG( 10402 dbgs() << "Scale the probablity for one cluster, before scaling: " 10403 << CC.Prob << "\n"); 10404 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10405 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10406 } 10407 PeeledCaseProb = TopCaseProb; 10408 return PeeledSwitchMBB; 10409 } 10410 10411 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10412 // Extract cases from the switch. 10413 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10414 CaseClusterVector Clusters; 10415 Clusters.reserve(SI.getNumCases()); 10416 for (auto I : SI.cases()) { 10417 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10418 const ConstantInt *CaseVal = I.getCaseValue(); 10419 BranchProbability Prob = 10420 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10421 : BranchProbability(1, SI.getNumCases() + 1); 10422 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10423 } 10424 10425 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10426 10427 // Cluster adjacent cases with the same destination. We do this at all 10428 // optimization levels because it's cheap to do and will make codegen faster 10429 // if there are many clusters. 10430 sortAndRangeify(Clusters); 10431 10432 // The branch probablity of the peeled case. 10433 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10434 MachineBasicBlock *PeeledSwitchMBB = 10435 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10436 10437 // If there is only the default destination, jump there directly. 10438 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10439 if (Clusters.empty()) { 10440 assert(PeeledSwitchMBB == SwitchMBB); 10441 SwitchMBB->addSuccessor(DefaultMBB); 10442 if (DefaultMBB != NextBlock(SwitchMBB)) { 10443 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10444 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10445 } 10446 return; 10447 } 10448 10449 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 10450 SL->findBitTestClusters(Clusters, &SI); 10451 10452 LLVM_DEBUG({ 10453 dbgs() << "Case clusters: "; 10454 for (const CaseCluster &C : Clusters) { 10455 if (C.Kind == CC_JumpTable) 10456 dbgs() << "JT:"; 10457 if (C.Kind == CC_BitTests) 10458 dbgs() << "BT:"; 10459 10460 C.Low->getValue().print(dbgs(), true); 10461 if (C.Low != C.High) { 10462 dbgs() << '-'; 10463 C.High->getValue().print(dbgs(), true); 10464 } 10465 dbgs() << ' '; 10466 } 10467 dbgs() << '\n'; 10468 }); 10469 10470 assert(!Clusters.empty()); 10471 SwitchWorkList WorkList; 10472 CaseClusterIt First = Clusters.begin(); 10473 CaseClusterIt Last = Clusters.end() - 1; 10474 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10475 // Scale the branchprobability for DefaultMBB if the peel occurs and 10476 // DefaultMBB is not replaced. 10477 if (PeeledCaseProb != BranchProbability::getZero() && 10478 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10479 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10480 WorkList.push_back( 10481 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10482 10483 while (!WorkList.empty()) { 10484 SwitchWorkListItem W = WorkList.back(); 10485 WorkList.pop_back(); 10486 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10487 10488 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10489 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 10490 // For optimized builds, lower large range as a balanced binary tree. 10491 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10492 continue; 10493 } 10494 10495 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10496 } 10497 } 10498 10499 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 10500 SDValue N = getValue(I.getOperand(0)); 10501 setValue(&I, N); 10502 } 10503