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/ConstantFolding.h" 32 #include "llvm/Analysis/EHPersonalities.h" 33 #include "llvm/Analysis/Loads.h" 34 #include "llvm/Analysis/MemoryLocation.h" 35 #include "llvm/Analysis/TargetLibraryInfo.h" 36 #include "llvm/Analysis/ValueTracking.h" 37 #include "llvm/Analysis/VectorUtils.h" 38 #include "llvm/CodeGen/Analysis.h" 39 #include "llvm/CodeGen/FunctionLoweringInfo.h" 40 #include "llvm/CodeGen/GCMetadata.h" 41 #include "llvm/CodeGen/ISDOpcodes.h" 42 #include "llvm/CodeGen/MachineBasicBlock.h" 43 #include "llvm/CodeGen/MachineFrameInfo.h" 44 #include "llvm/CodeGen/MachineFunction.h" 45 #include "llvm/CodeGen/MachineInstr.h" 46 #include "llvm/CodeGen/MachineInstrBuilder.h" 47 #include "llvm/CodeGen/MachineJumpTableInfo.h" 48 #include "llvm/CodeGen/MachineMemOperand.h" 49 #include "llvm/CodeGen/MachineModuleInfo.h" 50 #include "llvm/CodeGen/MachineOperand.h" 51 #include "llvm/CodeGen/MachineRegisterInfo.h" 52 #include "llvm/CodeGen/RuntimeLibcalls.h" 53 #include "llvm/CodeGen/SelectionDAG.h" 54 #include "llvm/CodeGen/SelectionDAGNodes.h" 55 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 56 #include "llvm/CodeGen/StackMaps.h" 57 #include "llvm/CodeGen/SwiftErrorValueTracking.h" 58 #include "llvm/CodeGen/TargetFrameLowering.h" 59 #include "llvm/CodeGen/TargetInstrInfo.h" 60 #include "llvm/CodeGen/TargetLowering.h" 61 #include "llvm/CodeGen/TargetOpcodes.h" 62 #include "llvm/CodeGen/TargetRegisterInfo.h" 63 #include "llvm/CodeGen/TargetSubtargetInfo.h" 64 #include "llvm/CodeGen/ValueTypes.h" 65 #include "llvm/CodeGen/WinEHFuncInfo.h" 66 #include "llvm/IR/Argument.h" 67 #include "llvm/IR/Attributes.h" 68 #include "llvm/IR/BasicBlock.h" 69 #include "llvm/IR/CFG.h" 70 #include "llvm/IR/CallSite.h" 71 #include "llvm/IR/CallingConv.h" 72 #include "llvm/IR/Constant.h" 73 #include "llvm/IR/ConstantRange.h" 74 #include "llvm/IR/Constants.h" 75 #include "llvm/IR/DataLayout.h" 76 #include "llvm/IR/DebugInfoMetadata.h" 77 #include "llvm/IR/DebugLoc.h" 78 #include "llvm/IR/DerivedTypes.h" 79 #include "llvm/IR/Function.h" 80 #include "llvm/IR/GetElementPtrTypeIterator.h" 81 #include "llvm/IR/InlineAsm.h" 82 #include "llvm/IR/InstrTypes.h" 83 #include "llvm/IR/Instruction.h" 84 #include "llvm/IR/Instructions.h" 85 #include "llvm/IR/IntrinsicInst.h" 86 #include "llvm/IR/Intrinsics.h" 87 #include "llvm/IR/LLVMContext.h" 88 #include "llvm/IR/Metadata.h" 89 #include "llvm/IR/Module.h" 90 #include "llvm/IR/Operator.h" 91 #include "llvm/IR/PatternMatch.h" 92 #include "llvm/IR/Statepoint.h" 93 #include "llvm/IR/Type.h" 94 #include "llvm/IR/User.h" 95 #include "llvm/IR/Value.h" 96 #include "llvm/MC/MCContext.h" 97 #include "llvm/MC/MCSymbol.h" 98 #include "llvm/Support/AtomicOrdering.h" 99 #include "llvm/Support/BranchProbability.h" 100 #include "llvm/Support/Casting.h" 101 #include "llvm/Support/CodeGen.h" 102 #include "llvm/Support/CommandLine.h" 103 #include "llvm/Support/Compiler.h" 104 #include "llvm/Support/Debug.h" 105 #include "llvm/Support/ErrorHandling.h" 106 #include "llvm/Support/MachineValueType.h" 107 #include "llvm/Support/MathExtras.h" 108 #include "llvm/Support/raw_ostream.h" 109 #include "llvm/Target/TargetIntrinsicInfo.h" 110 #include "llvm/Target/TargetMachine.h" 111 #include "llvm/Target/TargetOptions.h" 112 #include "llvm/Transforms/Utils/Local.h" 113 #include <algorithm> 114 #include <cassert> 115 #include <cstddef> 116 #include <cstdint> 117 #include <cstring> 118 #include <iterator> 119 #include <limits> 120 #include <numeric> 121 #include <tuple> 122 #include <utility> 123 #include <vector> 124 125 using namespace llvm; 126 using namespace PatternMatch; 127 using namespace SwitchCG; 128 129 #define DEBUG_TYPE "isel" 130 131 /// LimitFloatPrecision - Generate low-precision inline sequences for 132 /// some float libcalls (6, 8 or 12 bits). 133 static unsigned LimitFloatPrecision; 134 135 static cl::opt<unsigned, true> 136 LimitFPPrecision("limit-float-precision", 137 cl::desc("Generate low-precision inline sequences " 138 "for some float libcalls"), 139 cl::location(LimitFloatPrecision), cl::Hidden, 140 cl::init(0)); 141 142 static cl::opt<unsigned> SwitchPeelThreshold( 143 "switch-peel-threshold", cl::Hidden, cl::init(66), 144 cl::desc("Set the case probability threshold for peeling the case from a " 145 "switch statement. A value greater than 100 will void this " 146 "optimization")); 147 148 // Limit the width of DAG chains. This is important in general to prevent 149 // DAG-based analysis from blowing up. For example, alias analysis and 150 // load clustering may not complete in reasonable time. It is difficult to 151 // recognize and avoid this situation within each individual analysis, and 152 // future analyses are likely to have the same behavior. Limiting DAG width is 153 // the safe approach and will be especially important with global DAGs. 154 // 155 // MaxParallelChains default is arbitrarily high to avoid affecting 156 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 157 // sequence over this should have been converted to llvm.memcpy by the 158 // frontend. It is easy to induce this behavior with .ll code such as: 159 // %buffer = alloca [4096 x i8] 160 // %data = load [4096 x i8]* %argPtr 161 // store [4096 x i8] %data, [4096 x i8]* %buffer 162 static const unsigned MaxParallelChains = 64; 163 164 // Return the calling convention if the Value passed requires ABI mangling as it 165 // is a parameter to a function or a return value from a function which is not 166 // an intrinsic. 167 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) { 168 if (auto *R = dyn_cast<ReturnInst>(V)) 169 return R->getParent()->getParent()->getCallingConv(); 170 171 if (auto *CI = dyn_cast<CallInst>(V)) { 172 const bool IsInlineAsm = CI->isInlineAsm(); 173 const bool IsIndirectFunctionCall = 174 !IsInlineAsm && !CI->getCalledFunction(); 175 176 // It is possible that the call instruction is an inline asm statement or an 177 // indirect function call in which case the return value of 178 // getCalledFunction() would be nullptr. 179 const bool IsInstrinsicCall = 180 !IsInlineAsm && !IsIndirectFunctionCall && 181 CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic; 182 183 if (!IsInlineAsm && !IsInstrinsicCall) 184 return CI->getCallingConv(); 185 } 186 187 return None; 188 } 189 190 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 191 const SDValue *Parts, unsigned NumParts, 192 MVT PartVT, EVT ValueVT, const Value *V, 193 Optional<CallingConv::ID> CC); 194 195 /// getCopyFromParts - Create a value that contains the specified legal parts 196 /// combined into the value they represent. If the parts combine to a type 197 /// larger than ValueVT then AssertOp can be used to specify whether the extra 198 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 199 /// (ISD::AssertSext). 200 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 201 const SDValue *Parts, unsigned NumParts, 202 MVT PartVT, EVT ValueVT, const Value *V, 203 Optional<CallingConv::ID> CC = None, 204 Optional<ISD::NodeType> AssertOp = None) { 205 if (ValueVT.isVector()) 206 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 207 CC); 208 209 assert(NumParts > 0 && "No parts to assemble!"); 210 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 211 SDValue Val = Parts[0]; 212 213 if (NumParts > 1) { 214 // Assemble the value from multiple parts. 215 if (ValueVT.isInteger()) { 216 unsigned PartBits = PartVT.getSizeInBits(); 217 unsigned ValueBits = ValueVT.getSizeInBits(); 218 219 // Assemble the power of 2 part. 220 unsigned RoundParts = 221 (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts; 222 unsigned RoundBits = PartBits * RoundParts; 223 EVT RoundVT = RoundBits == ValueBits ? 224 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 225 SDValue Lo, Hi; 226 227 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 228 229 if (RoundParts > 2) { 230 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 231 PartVT, HalfVT, V); 232 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 233 RoundParts / 2, PartVT, HalfVT, V); 234 } else { 235 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 236 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 237 } 238 239 if (DAG.getDataLayout().isBigEndian()) 240 std::swap(Lo, Hi); 241 242 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 243 244 if (RoundParts < NumParts) { 245 // Assemble the trailing non-power-of-2 part. 246 unsigned OddParts = NumParts - RoundParts; 247 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 248 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 249 OddVT, V, CC); 250 251 // Combine the round and odd parts. 252 Lo = Val; 253 if (DAG.getDataLayout().isBigEndian()) 254 std::swap(Lo, Hi); 255 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 256 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 257 Hi = 258 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 259 DAG.getConstant(Lo.getValueSizeInBits(), DL, 260 TLI.getPointerTy(DAG.getDataLayout()))); 261 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 262 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 263 } 264 } else if (PartVT.isFloatingPoint()) { 265 // FP split into multiple FP parts (for ppcf128) 266 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 267 "Unexpected split"); 268 SDValue Lo, Hi; 269 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 270 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 271 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 272 std::swap(Lo, Hi); 273 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 274 } else { 275 // FP split into integer parts (soft fp) 276 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 277 !PartVT.isVector() && "Unexpected split"); 278 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 279 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 280 } 281 } 282 283 // There is now one part, held in Val. Correct it to match ValueVT. 284 // PartEVT is the type of the register class that holds the value. 285 // ValueVT is the type of the inline asm operation. 286 EVT PartEVT = Val.getValueType(); 287 288 if (PartEVT == ValueVT) 289 return Val; 290 291 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 292 ValueVT.bitsLT(PartEVT)) { 293 // For an FP value in an integer part, we need to truncate to the right 294 // width first. 295 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 296 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 297 } 298 299 // Handle types that have the same size. 300 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 301 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 302 303 // Handle types with different sizes. 304 if (PartEVT.isInteger() && ValueVT.isInteger()) { 305 if (ValueVT.bitsLT(PartEVT)) { 306 // For a truncate, see if we have any information to 307 // indicate whether the truncated bits will always be 308 // zero or sign-extension. 309 if (AssertOp.hasValue()) 310 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 311 DAG.getValueType(ValueVT)); 312 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 313 } 314 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 315 } 316 317 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 318 // FP_ROUND's are always exact here. 319 if (ValueVT.bitsLT(Val.getValueType())) 320 return DAG.getNode( 321 ISD::FP_ROUND, DL, ValueVT, Val, 322 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 323 324 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 325 } 326 327 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 328 // then truncating. 329 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 330 ValueVT.bitsLT(PartEVT)) { 331 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 332 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 333 } 334 335 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 336 } 337 338 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 339 const Twine &ErrMsg) { 340 const Instruction *I = dyn_cast_or_null<Instruction>(V); 341 if (!V) 342 return Ctx.emitError(ErrMsg); 343 344 const char *AsmError = ", possible invalid constraint for vector type"; 345 if (const CallInst *CI = dyn_cast<CallInst>(I)) 346 if (isa<InlineAsm>(CI->getCalledValue())) 347 return Ctx.emitError(I, ErrMsg + AsmError); 348 349 return Ctx.emitError(I, ErrMsg); 350 } 351 352 /// getCopyFromPartsVector - Create a value that contains the specified legal 353 /// parts combined into the value they represent. If the parts combine to a 354 /// type larger than ValueVT then AssertOp can be used to specify whether the 355 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 356 /// ValueVT (ISD::AssertSext). 357 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 358 const SDValue *Parts, unsigned NumParts, 359 MVT PartVT, EVT ValueVT, const Value *V, 360 Optional<CallingConv::ID> CallConv) { 361 assert(ValueVT.isVector() && "Not a vector value"); 362 assert(NumParts > 0 && "No parts to assemble!"); 363 const bool IsABIRegCopy = CallConv.hasValue(); 364 365 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 366 SDValue Val = Parts[0]; 367 368 // Handle a multi-element vector. 369 if (NumParts > 1) { 370 EVT IntermediateVT; 371 MVT RegisterVT; 372 unsigned NumIntermediates; 373 unsigned NumRegs; 374 375 if (IsABIRegCopy) { 376 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 377 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 378 NumIntermediates, RegisterVT); 379 } else { 380 NumRegs = 381 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 382 NumIntermediates, RegisterVT); 383 } 384 385 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 386 NumParts = NumRegs; // Silence a compiler warning. 387 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 388 assert(RegisterVT.getSizeInBits() == 389 Parts[0].getSimpleValueType().getSizeInBits() && 390 "Part type sizes don't match!"); 391 392 // Assemble the parts into intermediate operands. 393 SmallVector<SDValue, 8> Ops(NumIntermediates); 394 if (NumIntermediates == NumParts) { 395 // If the register was not expanded, truncate or copy the value, 396 // as appropriate. 397 for (unsigned i = 0; i != NumParts; ++i) 398 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 399 PartVT, IntermediateVT, V); 400 } else if (NumParts > 0) { 401 // If the intermediate type was expanded, build the intermediate 402 // operands from the parts. 403 assert(NumParts % NumIntermediates == 0 && 404 "Must expand into a divisible number of parts!"); 405 unsigned Factor = NumParts / NumIntermediates; 406 for (unsigned i = 0; i != NumIntermediates; ++i) 407 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 408 PartVT, IntermediateVT, V); 409 } 410 411 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 412 // intermediate operands. 413 EVT BuiltVectorTy = 414 EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(), 415 (IntermediateVT.isVector() 416 ? IntermediateVT.getVectorNumElements() * NumParts 417 : NumIntermediates)); 418 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 419 : ISD::BUILD_VECTOR, 420 DL, BuiltVectorTy, Ops); 421 } 422 423 // There is now one part, held in Val. Correct it to match ValueVT. 424 EVT PartEVT = Val.getValueType(); 425 426 if (PartEVT == ValueVT) 427 return Val; 428 429 if (PartEVT.isVector()) { 430 // If the element type of the source/dest vectors are the same, but the 431 // parts vector has more elements than the value vector, then we have a 432 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 433 // elements we want. 434 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { 435 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() && 436 "Cannot narrow, it would be a lossy transformation"); 437 return DAG.getNode( 438 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 439 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 440 } 441 442 // Vector/Vector bitcast. 443 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 444 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 445 446 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() && 447 "Cannot handle this kind of promotion"); 448 // Promoted vector extract 449 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 450 451 } 452 453 // Trivial bitcast if the types are the same size and the destination 454 // vector type is legal. 455 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 456 TLI.isTypeLegal(ValueVT)) 457 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 458 459 if (ValueVT.getVectorNumElements() != 1) { 460 // Certain ABIs require that vectors are passed as integers. For vectors 461 // are the same size, this is an obvious bitcast. 462 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 463 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 464 } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) { 465 // Bitcast Val back the original type and extract the corresponding 466 // vector we want. 467 unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits(); 468 EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(), 469 ValueVT.getVectorElementType(), Elts); 470 Val = DAG.getBitcast(WiderVecType, Val); 471 return DAG.getNode( 472 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 473 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 474 } 475 476 diagnosePossiblyInvalidConstraint( 477 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 478 return DAG.getUNDEF(ValueVT); 479 } 480 481 // Handle cases such as i8 -> <1 x i1> 482 EVT ValueSVT = ValueVT.getVectorElementType(); 483 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) 484 Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 485 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 486 487 return DAG.getBuildVector(ValueVT, DL, Val); 488 } 489 490 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 491 SDValue Val, SDValue *Parts, unsigned NumParts, 492 MVT PartVT, const Value *V, 493 Optional<CallingConv::ID> CallConv); 494 495 /// getCopyToParts - Create a series of nodes that contain the specified value 496 /// split into legal parts. If the parts contain more bits than Val, then, for 497 /// integers, ExtendKind can be used to specify how to generate the extra bits. 498 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 499 SDValue *Parts, unsigned NumParts, MVT PartVT, 500 const Value *V, 501 Optional<CallingConv::ID> CallConv = None, 502 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 503 EVT ValueVT = Val.getValueType(); 504 505 // Handle the vector case separately. 506 if (ValueVT.isVector()) 507 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 508 CallConv); 509 510 unsigned PartBits = PartVT.getSizeInBits(); 511 unsigned OrigNumParts = NumParts; 512 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 513 "Copying to an illegal type!"); 514 515 if (NumParts == 0) 516 return; 517 518 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 519 EVT PartEVT = PartVT; 520 if (PartEVT == ValueVT) { 521 assert(NumParts == 1 && "No-op copy with multiple parts!"); 522 Parts[0] = Val; 523 return; 524 } 525 526 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 527 // If the parts cover more bits than the value has, promote the value. 528 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 529 assert(NumParts == 1 && "Do not know what to promote to!"); 530 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 531 } else { 532 if (ValueVT.isFloatingPoint()) { 533 // FP values need to be bitcast, then extended if they are being put 534 // into a larger container. 535 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 536 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 537 } 538 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 539 ValueVT.isInteger() && 540 "Unknown mismatch!"); 541 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 542 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 543 if (PartVT == MVT::x86mmx) 544 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 545 } 546 } else if (PartBits == ValueVT.getSizeInBits()) { 547 // Different types of the same size. 548 assert(NumParts == 1 && PartEVT != ValueVT); 549 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 550 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 551 // If the parts cover less bits than value has, truncate the value. 552 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 553 ValueVT.isInteger() && 554 "Unknown mismatch!"); 555 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 556 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 557 if (PartVT == MVT::x86mmx) 558 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 559 } 560 561 // The value may have changed - recompute ValueVT. 562 ValueVT = Val.getValueType(); 563 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 564 "Failed to tile the value with PartVT!"); 565 566 if (NumParts == 1) { 567 if (PartEVT != ValueVT) { 568 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 569 "scalar-to-vector conversion failed"); 570 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 571 } 572 573 Parts[0] = Val; 574 return; 575 } 576 577 // Expand the value into multiple parts. 578 if (NumParts & (NumParts - 1)) { 579 // The number of parts is not a power of 2. Split off and copy the tail. 580 assert(PartVT.isInteger() && ValueVT.isInteger() && 581 "Do not know what to expand to!"); 582 unsigned RoundParts = 1 << Log2_32(NumParts); 583 unsigned RoundBits = RoundParts * PartBits; 584 unsigned OddParts = NumParts - RoundParts; 585 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 586 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false)); 587 588 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 589 CallConv); 590 591 if (DAG.getDataLayout().isBigEndian()) 592 // The odd parts were reversed by getCopyToParts - unreverse them. 593 std::reverse(Parts + RoundParts, Parts + NumParts); 594 595 NumParts = RoundParts; 596 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 597 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 598 } 599 600 // The number of parts is a power of 2. Repeatedly bisect the value using 601 // EXTRACT_ELEMENT. 602 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 603 EVT::getIntegerVT(*DAG.getContext(), 604 ValueVT.getSizeInBits()), 605 Val); 606 607 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 608 for (unsigned i = 0; i < NumParts; i += StepSize) { 609 unsigned ThisBits = StepSize * PartBits / 2; 610 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 611 SDValue &Part0 = Parts[i]; 612 SDValue &Part1 = Parts[i+StepSize/2]; 613 614 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 615 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 616 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 617 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 618 619 if (ThisBits == PartBits && ThisVT != PartVT) { 620 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 621 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 622 } 623 } 624 } 625 626 if (DAG.getDataLayout().isBigEndian()) 627 std::reverse(Parts, Parts + OrigNumParts); 628 } 629 630 static SDValue widenVectorToPartType(SelectionDAG &DAG, 631 SDValue Val, const SDLoc &DL, EVT PartVT) { 632 if (!PartVT.isVector()) 633 return SDValue(); 634 635 EVT ValueVT = Val.getValueType(); 636 unsigned PartNumElts = PartVT.getVectorNumElements(); 637 unsigned ValueNumElts = ValueVT.getVectorNumElements(); 638 if (PartNumElts > ValueNumElts && 639 PartVT.getVectorElementType() == ValueVT.getVectorElementType()) { 640 EVT ElementVT = PartVT.getVectorElementType(); 641 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 642 // undef elements. 643 SmallVector<SDValue, 16> Ops; 644 DAG.ExtractVectorElements(Val, Ops); 645 SDValue EltUndef = DAG.getUNDEF(ElementVT); 646 for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i) 647 Ops.push_back(EltUndef); 648 649 // FIXME: Use CONCAT for 2x -> 4x. 650 return DAG.getBuildVector(PartVT, DL, Ops); 651 } 652 653 return SDValue(); 654 } 655 656 /// getCopyToPartsVector - Create a series of nodes that contain the specified 657 /// value split into legal parts. 658 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 659 SDValue Val, SDValue *Parts, unsigned NumParts, 660 MVT PartVT, const Value *V, 661 Optional<CallingConv::ID> CallConv) { 662 EVT ValueVT = Val.getValueType(); 663 assert(ValueVT.isVector() && "Not a vector"); 664 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 665 const bool IsABIRegCopy = CallConv.hasValue(); 666 667 if (NumParts == 1) { 668 EVT PartEVT = PartVT; 669 if (PartEVT == ValueVT) { 670 // Nothing to do. 671 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 672 // Bitconvert vector->vector case. 673 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 674 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 675 Val = Widened; 676 } else if (PartVT.isVector() && 677 PartEVT.getVectorElementType().bitsGE( 678 ValueVT.getVectorElementType()) && 679 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) { 680 681 // Promoted vector extract 682 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 683 } else { 684 if (ValueVT.getVectorNumElements() == 1) { 685 Val = DAG.getNode( 686 ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 687 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 688 } else { 689 assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() && 690 "lossy conversion of vector to scalar type"); 691 EVT IntermediateType = 692 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 693 Val = DAG.getBitcast(IntermediateType, Val); 694 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 695 } 696 } 697 698 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 699 Parts[0] = Val; 700 return; 701 } 702 703 // Handle a multi-element vector. 704 EVT IntermediateVT; 705 MVT RegisterVT; 706 unsigned NumIntermediates; 707 unsigned NumRegs; 708 if (IsABIRegCopy) { 709 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 710 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 711 NumIntermediates, RegisterVT); 712 } else { 713 NumRegs = 714 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 715 NumIntermediates, RegisterVT); 716 } 717 718 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 719 NumParts = NumRegs; // Silence a compiler warning. 720 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 721 722 unsigned IntermediateNumElts = IntermediateVT.isVector() ? 723 IntermediateVT.getVectorNumElements() : 1; 724 725 // Convert the vector to the appropriate type if necessary. 726 unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts; 727 728 EVT BuiltVectorTy = EVT::getVectorVT( 729 *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts); 730 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 731 if (ValueVT != BuiltVectorTy) { 732 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) 733 Val = Widened; 734 735 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 736 } 737 738 // Split the vector into intermediate operands. 739 SmallVector<SDValue, 8> Ops(NumIntermediates); 740 for (unsigned i = 0; i != NumIntermediates; ++i) { 741 if (IntermediateVT.isVector()) { 742 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 743 DAG.getConstant(i * IntermediateNumElts, DL, IdxVT)); 744 } else { 745 Ops[i] = DAG.getNode( 746 ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 747 DAG.getConstant(i, DL, IdxVT)); 748 } 749 } 750 751 // Split the intermediate operands into legal parts. 752 if (NumParts == NumIntermediates) { 753 // If the register was not expanded, promote or copy the value, 754 // as appropriate. 755 for (unsigned i = 0; i != NumParts; ++i) 756 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 757 } else if (NumParts > 0) { 758 // If the intermediate type was expanded, split each the value into 759 // legal parts. 760 assert(NumIntermediates != 0 && "division by zero"); 761 assert(NumParts % NumIntermediates == 0 && 762 "Must expand into a divisible number of parts!"); 763 unsigned Factor = NumParts / NumIntermediates; 764 for (unsigned i = 0; i != NumIntermediates; ++i) 765 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 766 CallConv); 767 } 768 } 769 770 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 771 EVT valuevt, Optional<CallingConv::ID> CC) 772 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 773 RegCount(1, regs.size()), CallConv(CC) {} 774 775 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 776 const DataLayout &DL, unsigned Reg, Type *Ty, 777 Optional<CallingConv::ID> CC) { 778 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 779 780 CallConv = CC; 781 782 for (EVT ValueVT : ValueVTs) { 783 unsigned NumRegs = 784 isABIMangled() 785 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) 786 : TLI.getNumRegisters(Context, ValueVT); 787 MVT RegisterVT = 788 isABIMangled() 789 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) 790 : TLI.getRegisterType(Context, ValueVT); 791 for (unsigned i = 0; i != NumRegs; ++i) 792 Regs.push_back(Reg + i); 793 RegVTs.push_back(RegisterVT); 794 RegCount.push_back(NumRegs); 795 Reg += NumRegs; 796 } 797 } 798 799 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 800 FunctionLoweringInfo &FuncInfo, 801 const SDLoc &dl, SDValue &Chain, 802 SDValue *Flag, const Value *V) const { 803 // A Value with type {} or [0 x %t] needs no registers. 804 if (ValueVTs.empty()) 805 return SDValue(); 806 807 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 808 809 // Assemble the legal parts into the final values. 810 SmallVector<SDValue, 4> Values(ValueVTs.size()); 811 SmallVector<SDValue, 8> Parts; 812 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 813 // Copy the legal parts from the registers. 814 EVT ValueVT = ValueVTs[Value]; 815 unsigned NumRegs = RegCount[Value]; 816 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 817 *DAG.getContext(), 818 CallConv.getValue(), RegVTs[Value]) 819 : RegVTs[Value]; 820 821 Parts.resize(NumRegs); 822 for (unsigned i = 0; i != NumRegs; ++i) { 823 SDValue P; 824 if (!Flag) { 825 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 826 } else { 827 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 828 *Flag = P.getValue(2); 829 } 830 831 Chain = P.getValue(1); 832 Parts[i] = P; 833 834 // If the source register was virtual and if we know something about it, 835 // add an assert node. 836 if (!Register::isVirtualRegister(Regs[Part + i]) || 837 !RegisterVT.isInteger()) 838 continue; 839 840 const FunctionLoweringInfo::LiveOutInfo *LOI = 841 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 842 if (!LOI) 843 continue; 844 845 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 846 unsigned NumSignBits = LOI->NumSignBits; 847 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 848 849 if (NumZeroBits == RegSize) { 850 // The current value is a zero. 851 // Explicitly express that as it would be easier for 852 // optimizations to kick in. 853 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 854 continue; 855 } 856 857 // FIXME: We capture more information than the dag can represent. For 858 // now, just use the tightest assertzext/assertsext possible. 859 bool isSExt; 860 EVT FromVT(MVT::Other); 861 if (NumZeroBits) { 862 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 863 isSExt = false; 864 } else if (NumSignBits > 1) { 865 FromVT = 866 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 867 isSExt = true; 868 } else { 869 continue; 870 } 871 // Add an assertion node. 872 assert(FromVT != MVT::Other); 873 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 874 RegisterVT, P, DAG.getValueType(FromVT)); 875 } 876 877 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 878 RegisterVT, ValueVT, V, CallConv); 879 Part += NumRegs; 880 Parts.clear(); 881 } 882 883 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 884 } 885 886 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 887 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 888 const Value *V, 889 ISD::NodeType PreferredExtendType) const { 890 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 891 ISD::NodeType ExtendKind = PreferredExtendType; 892 893 // Get the list of the values's legal parts. 894 unsigned NumRegs = Regs.size(); 895 SmallVector<SDValue, 8> Parts(NumRegs); 896 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 897 unsigned NumParts = RegCount[Value]; 898 899 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 900 *DAG.getContext(), 901 CallConv.getValue(), RegVTs[Value]) 902 : RegVTs[Value]; 903 904 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 905 ExtendKind = ISD::ZERO_EXTEND; 906 907 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 908 NumParts, RegisterVT, V, CallConv, ExtendKind); 909 Part += NumParts; 910 } 911 912 // Copy the parts into the registers. 913 SmallVector<SDValue, 8> Chains(NumRegs); 914 for (unsigned i = 0; i != NumRegs; ++i) { 915 SDValue Part; 916 if (!Flag) { 917 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 918 } else { 919 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 920 *Flag = Part.getValue(1); 921 } 922 923 Chains[i] = Part.getValue(0); 924 } 925 926 if (NumRegs == 1 || Flag) 927 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 928 // flagged to it. That is the CopyToReg nodes and the user are considered 929 // a single scheduling unit. If we create a TokenFactor and return it as 930 // chain, then the TokenFactor is both a predecessor (operand) of the 931 // user as well as a successor (the TF operands are flagged to the user). 932 // c1, f1 = CopyToReg 933 // c2, f2 = CopyToReg 934 // c3 = TokenFactor c1, c2 935 // ... 936 // = op c3, ..., f2 937 Chain = Chains[NumRegs-1]; 938 else 939 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 940 } 941 942 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 943 unsigned MatchingIdx, const SDLoc &dl, 944 SelectionDAG &DAG, 945 std::vector<SDValue> &Ops) const { 946 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 947 948 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 949 if (HasMatching) 950 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 951 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 952 // Put the register class of the virtual registers in the flag word. That 953 // way, later passes can recompute register class constraints for inline 954 // assembly as well as normal instructions. 955 // Don't do this for tied operands that can use the regclass information 956 // from the def. 957 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 958 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 959 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 960 } 961 962 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 963 Ops.push_back(Res); 964 965 if (Code == InlineAsm::Kind_Clobber) { 966 // Clobbers should always have a 1:1 mapping with registers, and may 967 // reference registers that have illegal (e.g. vector) types. Hence, we 968 // shouldn't try to apply any sort of splitting logic to them. 969 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 970 "No 1:1 mapping from clobbers to regs?"); 971 unsigned SP = TLI.getStackPointerRegisterToSaveRestore(); 972 (void)SP; 973 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 974 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 975 assert( 976 (Regs[I] != SP || 977 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 978 "If we clobbered the stack pointer, MFI should know about it."); 979 } 980 return; 981 } 982 983 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 984 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 985 MVT RegisterVT = RegVTs[Value]; 986 for (unsigned i = 0; i != NumRegs; ++i) { 987 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 988 unsigned TheReg = Regs[Reg++]; 989 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 990 } 991 } 992 } 993 994 SmallVector<std::pair<unsigned, unsigned>, 4> 995 RegsForValue::getRegsAndSizes() const { 996 SmallVector<std::pair<unsigned, unsigned>, 4> OutVec; 997 unsigned I = 0; 998 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 999 unsigned RegCount = std::get<0>(CountAndVT); 1000 MVT RegisterVT = std::get<1>(CountAndVT); 1001 unsigned RegisterSize = RegisterVT.getSizeInBits(); 1002 for (unsigned E = I + RegCount; I != E; ++I) 1003 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1004 } 1005 return OutVec; 1006 } 1007 1008 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1009 const TargetLibraryInfo *li) { 1010 AA = aa; 1011 GFI = gfi; 1012 LibInfo = li; 1013 DL = &DAG.getDataLayout(); 1014 Context = DAG.getContext(); 1015 LPadToCallSiteMap.clear(); 1016 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1017 } 1018 1019 void SelectionDAGBuilder::clear() { 1020 NodeMap.clear(); 1021 UnusedArgNodeMap.clear(); 1022 PendingLoads.clear(); 1023 PendingExports.clear(); 1024 CurInst = nullptr; 1025 HasTailCall = false; 1026 SDNodeOrder = LowestSDNodeOrder; 1027 StatepointLowering.clear(); 1028 } 1029 1030 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1031 DanglingDebugInfoMap.clear(); 1032 } 1033 1034 SDValue SelectionDAGBuilder::getRoot() { 1035 if (PendingLoads.empty()) 1036 return DAG.getRoot(); 1037 1038 if (PendingLoads.size() == 1) { 1039 SDValue Root = PendingLoads[0]; 1040 DAG.setRoot(Root); 1041 PendingLoads.clear(); 1042 return Root; 1043 } 1044 1045 // Otherwise, we have to make a token factor node. 1046 SDValue Root = DAG.getTokenFactor(getCurSDLoc(), PendingLoads); 1047 PendingLoads.clear(); 1048 DAG.setRoot(Root); 1049 return Root; 1050 } 1051 1052 SDValue SelectionDAGBuilder::getControlRoot() { 1053 SDValue Root = DAG.getRoot(); 1054 1055 if (PendingExports.empty()) 1056 return Root; 1057 1058 // Turn all of the CopyToReg chains into one factored node. 1059 if (Root.getOpcode() != ISD::EntryToken) { 1060 unsigned i = 0, e = PendingExports.size(); 1061 for (; i != e; ++i) { 1062 assert(PendingExports[i].getNode()->getNumOperands() > 1); 1063 if (PendingExports[i].getNode()->getOperand(0) == Root) 1064 break; // Don't add the root if we already indirectly depend on it. 1065 } 1066 1067 if (i == e) 1068 PendingExports.push_back(Root); 1069 } 1070 1071 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, 1072 PendingExports); 1073 PendingExports.clear(); 1074 DAG.setRoot(Root); 1075 return Root; 1076 } 1077 1078 void SelectionDAGBuilder::visit(const Instruction &I) { 1079 // Set up outgoing PHI node register values before emitting the terminator. 1080 if (I.isTerminator()) { 1081 HandlePHINodesInSuccessorBlocks(I.getParent()); 1082 } 1083 1084 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1085 if (!isa<DbgInfoIntrinsic>(I)) 1086 ++SDNodeOrder; 1087 1088 CurInst = &I; 1089 1090 visit(I.getOpcode(), I); 1091 1092 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) { 1093 // Propagate the fast-math-flags of this IR instruction to the DAG node that 1094 // maps to this instruction. 1095 // TODO: We could handle all flags (nsw, etc) here. 1096 // TODO: If an IR instruction maps to >1 node, only the final node will have 1097 // flags set. 1098 if (SDNode *Node = getNodeForIRValue(&I)) { 1099 SDNodeFlags IncomingFlags; 1100 IncomingFlags.copyFMF(*FPMO); 1101 if (!Node->getFlags().isDefined()) 1102 Node->setFlags(IncomingFlags); 1103 else 1104 Node->intersectFlagsWith(IncomingFlags); 1105 } 1106 } 1107 1108 if (!I.isTerminator() && !HasTailCall && 1109 !isStatepoint(&I)) // statepoints handle their exports internally 1110 CopyToExportRegsIfNeeded(&I); 1111 1112 CurInst = nullptr; 1113 } 1114 1115 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1116 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1117 } 1118 1119 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1120 // Note: this doesn't use InstVisitor, because it has to work with 1121 // ConstantExpr's in addition to instructions. 1122 switch (Opcode) { 1123 default: llvm_unreachable("Unknown instruction type encountered!"); 1124 // Build the switch statement using the Instruction.def file. 1125 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1126 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1127 #include "llvm/IR/Instruction.def" 1128 } 1129 } 1130 1131 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1132 const DIExpression *Expr) { 1133 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1134 const DbgValueInst *DI = DDI.getDI(); 1135 DIVariable *DanglingVariable = DI->getVariable(); 1136 DIExpression *DanglingExpr = DI->getExpression(); 1137 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1138 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1139 return true; 1140 } 1141 return false; 1142 }; 1143 1144 for (auto &DDIMI : DanglingDebugInfoMap) { 1145 DanglingDebugInfoVector &DDIV = DDIMI.second; 1146 1147 // If debug info is to be dropped, run it through final checks to see 1148 // whether it can be salvaged. 1149 for (auto &DDI : DDIV) 1150 if (isMatchingDbgValue(DDI)) 1151 salvageUnresolvedDbgValue(DDI); 1152 1153 DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end()); 1154 } 1155 } 1156 1157 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1158 // generate the debug data structures now that we've seen its definition. 1159 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1160 SDValue Val) { 1161 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1162 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1163 return; 1164 1165 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1166 for (auto &DDI : DDIV) { 1167 const DbgValueInst *DI = DDI.getDI(); 1168 assert(DI && "Ill-formed DanglingDebugInfo"); 1169 DebugLoc dl = DDI.getdl(); 1170 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1171 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1172 DILocalVariable *Variable = DI->getVariable(); 1173 DIExpression *Expr = DI->getExpression(); 1174 assert(Variable->isValidLocationForIntrinsic(dl) && 1175 "Expected inlined-at fields to agree"); 1176 SDDbgValue *SDV; 1177 if (Val.getNode()) { 1178 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1179 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1180 // we couldn't resolve it directly when examining the DbgValue intrinsic 1181 // in the first place we should not be more successful here). Unless we 1182 // have some test case that prove this to be correct we should avoid 1183 // calling EmitFuncArgumentDbgValue here. 1184 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1185 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1186 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1187 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1188 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1189 // inserted after the definition of Val when emitting the instructions 1190 // after ISel. An alternative could be to teach 1191 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1192 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1193 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1194 << ValSDNodeOrder << "\n"); 1195 SDV = getDbgValue(Val, Variable, Expr, dl, 1196 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1197 DAG.AddDbgValue(SDV, Val.getNode(), false); 1198 } else 1199 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1200 << "in EmitFuncArgumentDbgValue\n"); 1201 } else { 1202 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1203 auto Undef = 1204 UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1205 auto SDV = 1206 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); 1207 DAG.AddDbgValue(SDV, nullptr, false); 1208 } 1209 } 1210 DDIV.clear(); 1211 } 1212 1213 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1214 Value *V = DDI.getDI()->getValue(); 1215 DILocalVariable *Var = DDI.getDI()->getVariable(); 1216 DIExpression *Expr = DDI.getDI()->getExpression(); 1217 DebugLoc DL = DDI.getdl(); 1218 DebugLoc InstDL = DDI.getDI()->getDebugLoc(); 1219 unsigned SDOrder = DDI.getSDNodeOrder(); 1220 1221 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1222 // that DW_OP_stack_value is desired. 1223 assert(isa<DbgValueInst>(DDI.getDI())); 1224 bool StackValue = true; 1225 1226 // Can this Value can be encoded without any further work? 1227 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) 1228 return; 1229 1230 // Attempt to salvage back through as many instructions as possible. Bail if 1231 // a non-instruction is seen, such as a constant expression or global 1232 // variable. FIXME: Further work could recover those too. 1233 while (isa<Instruction>(V)) { 1234 Instruction &VAsInst = *cast<Instruction>(V); 1235 DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue); 1236 1237 // If we cannot salvage any further, and haven't yet found a suitable debug 1238 // expression, bail out. 1239 if (!NewExpr) 1240 break; 1241 1242 // New value and expr now represent this debuginfo. 1243 V = VAsInst.getOperand(0); 1244 Expr = NewExpr; 1245 1246 // Some kind of simplification occurred: check whether the operand of the 1247 // salvaged debug expression can be encoded in this DAG. 1248 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) { 1249 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n " 1250 << DDI.getDI() << "\nBy stripping back to:\n " << V); 1251 return; 1252 } 1253 } 1254 1255 // This was the final opportunity to salvage this debug information, and it 1256 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1257 // any earlier variable location. 1258 auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1259 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1260 DAG.AddDbgValue(SDV, nullptr, false); 1261 1262 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI() 1263 << "\n"); 1264 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0) 1265 << "\n"); 1266 } 1267 1268 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var, 1269 DIExpression *Expr, DebugLoc dl, 1270 DebugLoc InstDL, unsigned Order) { 1271 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1272 SDDbgValue *SDV; 1273 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1274 isa<ConstantPointerNull>(V)) { 1275 SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder); 1276 DAG.AddDbgValue(SDV, nullptr, false); 1277 return true; 1278 } 1279 1280 // If the Value is a frame index, we can create a FrameIndex debug value 1281 // without relying on the DAG at all. 1282 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1283 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1284 if (SI != FuncInfo.StaticAllocaMap.end()) { 1285 auto SDV = 1286 DAG.getFrameIndexDbgValue(Var, Expr, SI->second, 1287 /*IsIndirect*/ false, dl, SDNodeOrder); 1288 // Do not attach the SDNodeDbgValue to an SDNode: this variable location 1289 // is still available even if the SDNode gets optimized out. 1290 DAG.AddDbgValue(SDV, nullptr, false); 1291 return true; 1292 } 1293 } 1294 1295 // Do not use getValue() in here; we don't want to generate code at 1296 // this point if it hasn't been done yet. 1297 SDValue N = NodeMap[V]; 1298 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1299 N = UnusedArgNodeMap[V]; 1300 if (N.getNode()) { 1301 if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N)) 1302 return true; 1303 SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder); 1304 DAG.AddDbgValue(SDV, N.getNode(), false); 1305 return true; 1306 } 1307 1308 // Special rules apply for the first dbg.values of parameter variables in a 1309 // function. Identify them by the fact they reference Argument Values, that 1310 // they're parameters, and they are parameters of the current function. We 1311 // need to let them dangle until they get an SDNode. 1312 bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() && 1313 !InstDL.getInlinedAt(); 1314 if (!IsParamOfFunc) { 1315 // The value is not used in this block yet (or it would have an SDNode). 1316 // We still want the value to appear for the user if possible -- if it has 1317 // an associated VReg, we can refer to that instead. 1318 auto VMI = FuncInfo.ValueMap.find(V); 1319 if (VMI != FuncInfo.ValueMap.end()) { 1320 unsigned Reg = VMI->second; 1321 // If this is a PHI node, it may be split up into several MI PHI nodes 1322 // (in FunctionLoweringInfo::set). 1323 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1324 V->getType(), None); 1325 if (RFV.occupiesMultipleRegs()) { 1326 unsigned Offset = 0; 1327 unsigned BitsToDescribe = 0; 1328 if (auto VarSize = Var->getSizeInBits()) 1329 BitsToDescribe = *VarSize; 1330 if (auto Fragment = Expr->getFragmentInfo()) 1331 BitsToDescribe = Fragment->SizeInBits; 1332 for (auto RegAndSize : RFV.getRegsAndSizes()) { 1333 unsigned RegisterSize = RegAndSize.second; 1334 // Bail out if all bits are described already. 1335 if (Offset >= BitsToDescribe) 1336 break; 1337 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1338 ? BitsToDescribe - Offset 1339 : RegisterSize; 1340 auto FragmentExpr = DIExpression::createFragmentExpression( 1341 Expr, Offset, FragmentSize); 1342 if (!FragmentExpr) 1343 continue; 1344 SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first, 1345 false, dl, SDNodeOrder); 1346 DAG.AddDbgValue(SDV, nullptr, false); 1347 Offset += RegisterSize; 1348 } 1349 } else { 1350 SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder); 1351 DAG.AddDbgValue(SDV, nullptr, false); 1352 } 1353 return true; 1354 } 1355 } 1356 1357 return false; 1358 } 1359 1360 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1361 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1362 for (auto &Pair : DanglingDebugInfoMap) 1363 for (auto &DDI : Pair.second) 1364 salvageUnresolvedDbgValue(DDI); 1365 clearDanglingDebugInfo(); 1366 } 1367 1368 /// getCopyFromRegs - If there was virtual register allocated for the value V 1369 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1370 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1371 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V); 1372 SDValue Result; 1373 1374 if (It != FuncInfo.ValueMap.end()) { 1375 unsigned InReg = It->second; 1376 1377 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1378 DAG.getDataLayout(), InReg, Ty, 1379 None); // This is not an ABI copy. 1380 SDValue Chain = DAG.getEntryNode(); 1381 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1382 V); 1383 resolveDanglingDebugInfo(V, Result); 1384 } 1385 1386 return Result; 1387 } 1388 1389 /// getValue - Return an SDValue for the given Value. 1390 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1391 // If we already have an SDValue for this value, use it. It's important 1392 // to do this first, so that we don't create a CopyFromReg if we already 1393 // have a regular SDValue. 1394 SDValue &N = NodeMap[V]; 1395 if (N.getNode()) return N; 1396 1397 // If there's a virtual register allocated and initialized for this 1398 // value, use it. 1399 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1400 return copyFromReg; 1401 1402 // Otherwise create a new SDValue and remember it. 1403 SDValue Val = getValueImpl(V); 1404 NodeMap[V] = Val; 1405 resolveDanglingDebugInfo(V, Val); 1406 return Val; 1407 } 1408 1409 // Return true if SDValue exists for the given Value 1410 bool SelectionDAGBuilder::findValue(const Value *V) const { 1411 return (NodeMap.find(V) != NodeMap.end()) || 1412 (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end()); 1413 } 1414 1415 /// getNonRegisterValue - Return an SDValue for the given Value, but 1416 /// don't look in FuncInfo.ValueMap for a virtual register. 1417 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1418 // If we already have an SDValue for this value, use it. 1419 SDValue &N = NodeMap[V]; 1420 if (N.getNode()) { 1421 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1422 // Remove the debug location from the node as the node is about to be used 1423 // in a location which may differ from the original debug location. This 1424 // is relevant to Constant and ConstantFP nodes because they can appear 1425 // as constant expressions inside PHI nodes. 1426 N->setDebugLoc(DebugLoc()); 1427 } 1428 return N; 1429 } 1430 1431 // Otherwise create a new SDValue and remember it. 1432 SDValue Val = getValueImpl(V); 1433 NodeMap[V] = Val; 1434 resolveDanglingDebugInfo(V, Val); 1435 return Val; 1436 } 1437 1438 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1439 /// Create an SDValue for the given value. 1440 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1441 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1442 1443 if (const Constant *C = dyn_cast<Constant>(V)) { 1444 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1445 1446 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1447 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1448 1449 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1450 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1451 1452 if (isa<ConstantPointerNull>(C)) { 1453 unsigned AS = V->getType()->getPointerAddressSpace(); 1454 return DAG.getConstant(0, getCurSDLoc(), 1455 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1456 } 1457 1458 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1459 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1460 1461 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1462 return DAG.getUNDEF(VT); 1463 1464 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1465 visit(CE->getOpcode(), *CE); 1466 SDValue N1 = NodeMap[V]; 1467 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1468 return N1; 1469 } 1470 1471 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1472 SmallVector<SDValue, 4> Constants; 1473 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 1474 OI != OE; ++OI) { 1475 SDNode *Val = getValue(*OI).getNode(); 1476 // If the operand is an empty aggregate, there are no values. 1477 if (!Val) continue; 1478 // Add each leaf value from the operand to the Constants list 1479 // to form a flattened list of all the values. 1480 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1481 Constants.push_back(SDValue(Val, i)); 1482 } 1483 1484 return DAG.getMergeValues(Constants, getCurSDLoc()); 1485 } 1486 1487 if (const ConstantDataSequential *CDS = 1488 dyn_cast<ConstantDataSequential>(C)) { 1489 SmallVector<SDValue, 4> Ops; 1490 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1491 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1492 // Add each leaf value from the operand to the Constants list 1493 // to form a flattened list of all the values. 1494 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1495 Ops.push_back(SDValue(Val, i)); 1496 } 1497 1498 if (isa<ArrayType>(CDS->getType())) 1499 return DAG.getMergeValues(Ops, getCurSDLoc()); 1500 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1501 } 1502 1503 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1504 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1505 "Unknown struct or array constant!"); 1506 1507 SmallVector<EVT, 4> ValueVTs; 1508 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1509 unsigned NumElts = ValueVTs.size(); 1510 if (NumElts == 0) 1511 return SDValue(); // empty struct 1512 SmallVector<SDValue, 4> Constants(NumElts); 1513 for (unsigned i = 0; i != NumElts; ++i) { 1514 EVT EltVT = ValueVTs[i]; 1515 if (isa<UndefValue>(C)) 1516 Constants[i] = DAG.getUNDEF(EltVT); 1517 else if (EltVT.isFloatingPoint()) 1518 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1519 else 1520 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1521 } 1522 1523 return DAG.getMergeValues(Constants, getCurSDLoc()); 1524 } 1525 1526 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1527 return DAG.getBlockAddress(BA, VT); 1528 1529 VectorType *VecTy = cast<VectorType>(V->getType()); 1530 unsigned NumElements = VecTy->getNumElements(); 1531 1532 // Now that we know the number and type of the elements, get that number of 1533 // elements into the Ops array based on what kind of constant it is. 1534 SmallVector<SDValue, 16> Ops; 1535 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1536 for (unsigned i = 0; i != NumElements; ++i) 1537 Ops.push_back(getValue(CV->getOperand(i))); 1538 } else { 1539 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!"); 1540 EVT EltVT = 1541 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1542 1543 SDValue Op; 1544 if (EltVT.isFloatingPoint()) 1545 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1546 else 1547 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1548 Ops.assign(NumElements, Op); 1549 } 1550 1551 // Create a BUILD_VECTOR node. 1552 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1553 } 1554 1555 // If this is a static alloca, generate it as the frameindex instead of 1556 // computation. 1557 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1558 DenseMap<const AllocaInst*, int>::iterator SI = 1559 FuncInfo.StaticAllocaMap.find(AI); 1560 if (SI != FuncInfo.StaticAllocaMap.end()) 1561 return DAG.getFrameIndex(SI->second, 1562 TLI.getFrameIndexTy(DAG.getDataLayout())); 1563 } 1564 1565 // If this is an instruction which fast-isel has deferred, select it now. 1566 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1567 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1568 1569 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1570 Inst->getType(), getABIRegCopyCC(V)); 1571 SDValue Chain = DAG.getEntryNode(); 1572 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1573 } 1574 1575 llvm_unreachable("Can't get register for value!"); 1576 } 1577 1578 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1579 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1580 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1581 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1582 bool IsSEH = isAsynchronousEHPersonality(Pers); 1583 bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX; 1584 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1585 if (!IsSEH) 1586 CatchPadMBB->setIsEHScopeEntry(); 1587 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1588 if (IsMSVCCXX || IsCoreCLR) 1589 CatchPadMBB->setIsEHFuncletEntry(); 1590 // Wasm does not need catchpads anymore 1591 if (!IsWasmCXX) 1592 DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other, 1593 getControlRoot())); 1594 } 1595 1596 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1597 // Update machine-CFG edge. 1598 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1599 FuncInfo.MBB->addSuccessor(TargetMBB); 1600 1601 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1602 bool IsSEH = isAsynchronousEHPersonality(Pers); 1603 if (IsSEH) { 1604 // If this is not a fall-through branch or optimizations are switched off, 1605 // emit the branch. 1606 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1607 TM.getOptLevel() == CodeGenOpt::None) 1608 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1609 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1610 return; 1611 } 1612 1613 // Figure out the funclet membership for the catchret's successor. 1614 // This will be used by the FuncletLayout pass to determine how to order the 1615 // BB's. 1616 // A 'catchret' returns to the outer scope's color. 1617 Value *ParentPad = I.getCatchSwitchParentPad(); 1618 const BasicBlock *SuccessorColor; 1619 if (isa<ConstantTokenNone>(ParentPad)) 1620 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1621 else 1622 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1623 assert(SuccessorColor && "No parent funclet for catchret!"); 1624 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1625 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1626 1627 // Create the terminator node. 1628 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1629 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1630 DAG.getBasicBlock(SuccessorColorMBB)); 1631 DAG.setRoot(Ret); 1632 } 1633 1634 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1635 // Don't emit any special code for the cleanuppad instruction. It just marks 1636 // the start of an EH scope/funclet. 1637 FuncInfo.MBB->setIsEHScopeEntry(); 1638 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1639 if (Pers != EHPersonality::Wasm_CXX) { 1640 FuncInfo.MBB->setIsEHFuncletEntry(); 1641 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1642 } 1643 } 1644 1645 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and 1646 // the control flow always stops at the single catch pad, as it does for a 1647 // cleanup pad. In case the exception caught is not of the types the catch pad 1648 // catches, it will be rethrown by a rethrow. 1649 static void findWasmUnwindDestinations( 1650 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1651 BranchProbability Prob, 1652 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1653 &UnwindDests) { 1654 while (EHPadBB) { 1655 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1656 if (isa<CleanupPadInst>(Pad)) { 1657 // Stop on cleanup pads. 1658 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1659 UnwindDests.back().first->setIsEHScopeEntry(); 1660 break; 1661 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1662 // Add the catchpad handlers to the possible destinations. We don't 1663 // continue to the unwind destination of the catchswitch for wasm. 1664 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1665 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1666 UnwindDests.back().first->setIsEHScopeEntry(); 1667 } 1668 break; 1669 } else { 1670 continue; 1671 } 1672 } 1673 } 1674 1675 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1676 /// many places it could ultimately go. In the IR, we have a single unwind 1677 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1678 /// This function skips over imaginary basic blocks that hold catchswitch 1679 /// instructions, and finds all the "real" machine 1680 /// basic block destinations. As those destinations may not be successors of 1681 /// EHPadBB, here we also calculate the edge probability to those destinations. 1682 /// The passed-in Prob is the edge probability to EHPadBB. 1683 static void findUnwindDestinations( 1684 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1685 BranchProbability Prob, 1686 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1687 &UnwindDests) { 1688 EHPersonality Personality = 1689 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1690 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1691 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1692 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1693 bool IsSEH = isAsynchronousEHPersonality(Personality); 1694 1695 if (IsWasmCXX) { 1696 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1697 assert(UnwindDests.size() <= 1 && 1698 "There should be at most one unwind destination for wasm"); 1699 return; 1700 } 1701 1702 while (EHPadBB) { 1703 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1704 BasicBlock *NewEHPadBB = nullptr; 1705 if (isa<LandingPadInst>(Pad)) { 1706 // Stop on landingpads. They are not funclets. 1707 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1708 break; 1709 } else if (isa<CleanupPadInst>(Pad)) { 1710 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1711 // personalities. 1712 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1713 UnwindDests.back().first->setIsEHScopeEntry(); 1714 UnwindDests.back().first->setIsEHFuncletEntry(); 1715 break; 1716 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1717 // Add the catchpad handlers to the possible destinations. 1718 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1719 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1720 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1721 if (IsMSVCCXX || IsCoreCLR) 1722 UnwindDests.back().first->setIsEHFuncletEntry(); 1723 if (!IsSEH) 1724 UnwindDests.back().first->setIsEHScopeEntry(); 1725 } 1726 NewEHPadBB = CatchSwitch->getUnwindDest(); 1727 } else { 1728 continue; 1729 } 1730 1731 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1732 if (BPI && NewEHPadBB) 1733 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1734 EHPadBB = NewEHPadBB; 1735 } 1736 } 1737 1738 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1739 // Update successor info. 1740 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1741 auto UnwindDest = I.getUnwindDest(); 1742 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1743 BranchProbability UnwindDestProb = 1744 (BPI && UnwindDest) 1745 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1746 : BranchProbability::getZero(); 1747 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1748 for (auto &UnwindDest : UnwindDests) { 1749 UnwindDest.first->setIsEHPad(); 1750 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1751 } 1752 FuncInfo.MBB->normalizeSuccProbs(); 1753 1754 // Create the terminator node. 1755 SDValue Ret = 1756 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1757 DAG.setRoot(Ret); 1758 } 1759 1760 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1761 report_fatal_error("visitCatchSwitch not yet implemented!"); 1762 } 1763 1764 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1765 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1766 auto &DL = DAG.getDataLayout(); 1767 SDValue Chain = getControlRoot(); 1768 SmallVector<ISD::OutputArg, 8> Outs; 1769 SmallVector<SDValue, 8> OutVals; 1770 1771 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1772 // lower 1773 // 1774 // %val = call <ty> @llvm.experimental.deoptimize() 1775 // ret <ty> %val 1776 // 1777 // differently. 1778 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1779 LowerDeoptimizingReturn(); 1780 return; 1781 } 1782 1783 if (!FuncInfo.CanLowerReturn) { 1784 unsigned DemoteReg = FuncInfo.DemoteRegister; 1785 const Function *F = I.getParent()->getParent(); 1786 1787 // Emit a store of the return value through the virtual register. 1788 // Leave Outs empty so that LowerReturn won't try to load return 1789 // registers the usual way. 1790 SmallVector<EVT, 1> PtrValueVTs; 1791 ComputeValueVTs(TLI, DL, 1792 F->getReturnType()->getPointerTo( 1793 DAG.getDataLayout().getAllocaAddrSpace()), 1794 PtrValueVTs); 1795 1796 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1797 DemoteReg, PtrValueVTs[0]); 1798 SDValue RetOp = getValue(I.getOperand(0)); 1799 1800 SmallVector<EVT, 4> ValueVTs, MemVTs; 1801 SmallVector<uint64_t, 4> Offsets; 1802 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1803 &Offsets); 1804 unsigned NumValues = ValueVTs.size(); 1805 1806 SmallVector<SDValue, 4> Chains(NumValues); 1807 for (unsigned i = 0; i != NumValues; ++i) { 1808 // An aggregate return value cannot wrap around the address space, so 1809 // offsets to its parts don't wrap either. 1810 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]); 1811 1812 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 1813 if (MemVTs[i] != ValueVTs[i]) 1814 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 1815 Chains[i] = DAG.getStore(Chain, getCurSDLoc(), Val, 1816 // FIXME: better loc info would be nice. 1817 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction())); 1818 } 1819 1820 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1821 MVT::Other, Chains); 1822 } else if (I.getNumOperands() != 0) { 1823 SmallVector<EVT, 4> ValueVTs; 1824 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1825 unsigned NumValues = ValueVTs.size(); 1826 if (NumValues) { 1827 SDValue RetOp = getValue(I.getOperand(0)); 1828 1829 const Function *F = I.getParent()->getParent(); 1830 1831 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 1832 I.getOperand(0)->getType(), F->getCallingConv(), 1833 /*IsVarArg*/ false); 1834 1835 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1836 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1837 Attribute::SExt)) 1838 ExtendKind = ISD::SIGN_EXTEND; 1839 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1840 Attribute::ZExt)) 1841 ExtendKind = ISD::ZERO_EXTEND; 1842 1843 LLVMContext &Context = F->getContext(); 1844 bool RetInReg = F->getAttributes().hasAttribute( 1845 AttributeList::ReturnIndex, Attribute::InReg); 1846 1847 for (unsigned j = 0; j != NumValues; ++j) { 1848 EVT VT = ValueVTs[j]; 1849 1850 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1851 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1852 1853 CallingConv::ID CC = F->getCallingConv(); 1854 1855 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1856 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1857 SmallVector<SDValue, 4> Parts(NumParts); 1858 getCopyToParts(DAG, getCurSDLoc(), 1859 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1860 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1861 1862 // 'inreg' on function refers to return value 1863 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1864 if (RetInReg) 1865 Flags.setInReg(); 1866 1867 if (I.getOperand(0)->getType()->isPointerTy()) { 1868 Flags.setPointer(); 1869 Flags.setPointerAddrSpace( 1870 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 1871 } 1872 1873 if (NeedsRegBlock) { 1874 Flags.setInConsecutiveRegs(); 1875 if (j == NumValues - 1) 1876 Flags.setInConsecutiveRegsLast(); 1877 } 1878 1879 // Propagate extension type if any 1880 if (ExtendKind == ISD::SIGN_EXTEND) 1881 Flags.setSExt(); 1882 else if (ExtendKind == ISD::ZERO_EXTEND) 1883 Flags.setZExt(); 1884 1885 for (unsigned i = 0; i < NumParts; ++i) { 1886 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1887 VT, /*isfixed=*/true, 0, 0)); 1888 OutVals.push_back(Parts[i]); 1889 } 1890 } 1891 } 1892 } 1893 1894 // Push in swifterror virtual register as the last element of Outs. This makes 1895 // sure swifterror virtual register will be returned in the swifterror 1896 // physical register. 1897 const Function *F = I.getParent()->getParent(); 1898 if (TLI.supportSwiftError() && 1899 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 1900 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 1901 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1902 Flags.setSwiftError(); 1903 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 1904 EVT(TLI.getPointerTy(DL)) /*argvt*/, 1905 true /*isfixed*/, 1 /*origidx*/, 1906 0 /*partOffs*/)); 1907 // Create SDNode for the swifterror virtual register. 1908 OutVals.push_back( 1909 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 1910 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 1911 EVT(TLI.getPointerTy(DL)))); 1912 } 1913 1914 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 1915 CallingConv::ID CallConv = 1916 DAG.getMachineFunction().getFunction().getCallingConv(); 1917 Chain = DAG.getTargetLoweringInfo().LowerReturn( 1918 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 1919 1920 // Verify that the target's LowerReturn behaved as expected. 1921 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 1922 "LowerReturn didn't return a valid chain!"); 1923 1924 // Update the DAG with the new chain value resulting from return lowering. 1925 DAG.setRoot(Chain); 1926 } 1927 1928 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 1929 /// created for it, emit nodes to copy the value into the virtual 1930 /// registers. 1931 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 1932 // Skip empty types 1933 if (V->getType()->isEmptyTy()) 1934 return; 1935 1936 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 1937 if (VMI != FuncInfo.ValueMap.end()) { 1938 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 1939 CopyValueToVirtualRegister(V, VMI->second); 1940 } 1941 } 1942 1943 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 1944 /// the current basic block, add it to ValueMap now so that we'll get a 1945 /// CopyTo/FromReg. 1946 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 1947 // No need to export constants. 1948 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 1949 1950 // Already exported? 1951 if (FuncInfo.isExportedInst(V)) return; 1952 1953 unsigned Reg = FuncInfo.InitializeRegForValue(V); 1954 CopyValueToVirtualRegister(V, Reg); 1955 } 1956 1957 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 1958 const BasicBlock *FromBB) { 1959 // The operands of the setcc have to be in this block. We don't know 1960 // how to export them from some other block. 1961 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 1962 // Can export from current BB. 1963 if (VI->getParent() == FromBB) 1964 return true; 1965 1966 // Is already exported, noop. 1967 return FuncInfo.isExportedInst(V); 1968 } 1969 1970 // If this is an argument, we can export it if the BB is the entry block or 1971 // if it is already exported. 1972 if (isa<Argument>(V)) { 1973 if (FromBB == &FromBB->getParent()->getEntryBlock()) 1974 return true; 1975 1976 // Otherwise, can only export this if it is already exported. 1977 return FuncInfo.isExportedInst(V); 1978 } 1979 1980 // Otherwise, constants can always be exported. 1981 return true; 1982 } 1983 1984 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 1985 BranchProbability 1986 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 1987 const MachineBasicBlock *Dst) const { 1988 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1989 const BasicBlock *SrcBB = Src->getBasicBlock(); 1990 const BasicBlock *DstBB = Dst->getBasicBlock(); 1991 if (!BPI) { 1992 // If BPI is not available, set the default probability as 1 / N, where N is 1993 // the number of successors. 1994 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 1995 return BranchProbability(1, SuccSize); 1996 } 1997 return BPI->getEdgeProbability(SrcBB, DstBB); 1998 } 1999 2000 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2001 MachineBasicBlock *Dst, 2002 BranchProbability Prob) { 2003 if (!FuncInfo.BPI) 2004 Src->addSuccessorWithoutProb(Dst); 2005 else { 2006 if (Prob.isUnknown()) 2007 Prob = getEdgeProbability(Src, Dst); 2008 Src->addSuccessor(Dst, Prob); 2009 } 2010 } 2011 2012 static bool InBlock(const Value *V, const BasicBlock *BB) { 2013 if (const Instruction *I = dyn_cast<Instruction>(V)) 2014 return I->getParent() == BB; 2015 return true; 2016 } 2017 2018 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2019 /// This function emits a branch and is used at the leaves of an OR or an 2020 /// AND operator tree. 2021 void 2022 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2023 MachineBasicBlock *TBB, 2024 MachineBasicBlock *FBB, 2025 MachineBasicBlock *CurBB, 2026 MachineBasicBlock *SwitchBB, 2027 BranchProbability TProb, 2028 BranchProbability FProb, 2029 bool InvertCond) { 2030 const BasicBlock *BB = CurBB->getBasicBlock(); 2031 2032 // If the leaf of the tree is a comparison, merge the condition into 2033 // the caseblock. 2034 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2035 // The operands of the cmp have to be in this block. We don't know 2036 // how to export them from some other block. If this is the first block 2037 // of the sequence, no exporting is needed. 2038 if (CurBB == SwitchBB || 2039 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2040 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2041 ISD::CondCode Condition; 2042 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2043 ICmpInst::Predicate Pred = 2044 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2045 Condition = getICmpCondCode(Pred); 2046 } else { 2047 const FCmpInst *FC = cast<FCmpInst>(Cond); 2048 FCmpInst::Predicate Pred = 2049 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2050 Condition = getFCmpCondCode(Pred); 2051 if (TM.Options.NoNaNsFPMath) 2052 Condition = getFCmpCodeWithoutNaN(Condition); 2053 } 2054 2055 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2056 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2057 SL->SwitchCases.push_back(CB); 2058 return; 2059 } 2060 } 2061 2062 // Create a CaseBlock record representing this branch. 2063 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2064 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2065 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2066 SL->SwitchCases.push_back(CB); 2067 } 2068 2069 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2070 MachineBasicBlock *TBB, 2071 MachineBasicBlock *FBB, 2072 MachineBasicBlock *CurBB, 2073 MachineBasicBlock *SwitchBB, 2074 Instruction::BinaryOps Opc, 2075 BranchProbability TProb, 2076 BranchProbability FProb, 2077 bool InvertCond) { 2078 // Skip over not part of the tree and remember to invert op and operands at 2079 // next level. 2080 Value *NotCond; 2081 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2082 InBlock(NotCond, CurBB->getBasicBlock())) { 2083 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2084 !InvertCond); 2085 return; 2086 } 2087 2088 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2089 // Compute the effective opcode for Cond, taking into account whether it needs 2090 // to be inverted, e.g. 2091 // and (not (or A, B)), C 2092 // gets lowered as 2093 // and (and (not A, not B), C) 2094 unsigned BOpc = 0; 2095 if (BOp) { 2096 BOpc = BOp->getOpcode(); 2097 if (InvertCond) { 2098 if (BOpc == Instruction::And) 2099 BOpc = Instruction::Or; 2100 else if (BOpc == Instruction::Or) 2101 BOpc = Instruction::And; 2102 } 2103 } 2104 2105 // If this node is not part of the or/and tree, emit it as a branch. 2106 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 2107 BOpc != unsigned(Opc) || !BOp->hasOneUse() || 2108 BOp->getParent() != CurBB->getBasicBlock() || 2109 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 2110 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 2111 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2112 TProb, FProb, InvertCond); 2113 return; 2114 } 2115 2116 // Create TmpBB after CurBB. 2117 MachineFunction::iterator BBI(CurBB); 2118 MachineFunction &MF = DAG.getMachineFunction(); 2119 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2120 CurBB->getParent()->insert(++BBI, TmpBB); 2121 2122 if (Opc == Instruction::Or) { 2123 // Codegen X | Y as: 2124 // BB1: 2125 // jmp_if_X TBB 2126 // jmp TmpBB 2127 // TmpBB: 2128 // jmp_if_Y TBB 2129 // jmp FBB 2130 // 2131 2132 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2133 // The requirement is that 2134 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2135 // = TrueProb for original BB. 2136 // Assuming the original probabilities are A and B, one choice is to set 2137 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2138 // A/(1+B) and 2B/(1+B). This choice assumes that 2139 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2140 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2141 // TmpBB, but the math is more complicated. 2142 2143 auto NewTrueProb = TProb / 2; 2144 auto NewFalseProb = TProb / 2 + FProb; 2145 // Emit the LHS condition. 2146 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc, 2147 NewTrueProb, NewFalseProb, InvertCond); 2148 2149 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2150 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2151 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2152 // Emit the RHS condition into TmpBB. 2153 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2154 Probs[0], Probs[1], InvertCond); 2155 } else { 2156 assert(Opc == Instruction::And && "Unknown merge op!"); 2157 // Codegen X & Y as: 2158 // BB1: 2159 // jmp_if_X TmpBB 2160 // jmp FBB 2161 // TmpBB: 2162 // jmp_if_Y TBB 2163 // jmp FBB 2164 // 2165 // This requires creation of TmpBB after CurBB. 2166 2167 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2168 // The requirement is that 2169 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2170 // = FalseProb for original BB. 2171 // Assuming the original probabilities are A and B, one choice is to set 2172 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2173 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2174 // TrueProb for BB1 * FalseProb for TmpBB. 2175 2176 auto NewTrueProb = TProb + FProb / 2; 2177 auto NewFalseProb = FProb / 2; 2178 // Emit the LHS condition. 2179 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc, 2180 NewTrueProb, NewFalseProb, InvertCond); 2181 2182 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2183 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2184 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2185 // Emit the RHS condition into TmpBB. 2186 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2187 Probs[0], Probs[1], InvertCond); 2188 } 2189 } 2190 2191 /// If the set of cases should be emitted as a series of branches, return true. 2192 /// If we should emit this as a bunch of and/or'd together conditions, return 2193 /// false. 2194 bool 2195 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2196 if (Cases.size() != 2) return true; 2197 2198 // If this is two comparisons of the same values or'd or and'd together, they 2199 // will get folded into a single comparison, so don't emit two blocks. 2200 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2201 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2202 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2203 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2204 return false; 2205 } 2206 2207 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2208 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2209 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2210 Cases[0].CC == Cases[1].CC && 2211 isa<Constant>(Cases[0].CmpRHS) && 2212 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2213 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2214 return false; 2215 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2216 return false; 2217 } 2218 2219 return true; 2220 } 2221 2222 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2223 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2224 2225 // Update machine-CFG edges. 2226 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2227 2228 if (I.isUnconditional()) { 2229 // Update machine-CFG edges. 2230 BrMBB->addSuccessor(Succ0MBB); 2231 2232 // If this is not a fall-through branch or optimizations are switched off, 2233 // emit the branch. 2234 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2235 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2236 MVT::Other, getControlRoot(), 2237 DAG.getBasicBlock(Succ0MBB))); 2238 2239 return; 2240 } 2241 2242 // If this condition is one of the special cases we handle, do special stuff 2243 // now. 2244 const Value *CondVal = I.getCondition(); 2245 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2246 2247 // If this is a series of conditions that are or'd or and'd together, emit 2248 // this as a sequence of branches instead of setcc's with and/or operations. 2249 // As long as jumps are not expensive, this should improve performance. 2250 // For example, instead of something like: 2251 // cmp A, B 2252 // C = seteq 2253 // cmp D, E 2254 // F = setle 2255 // or C, F 2256 // jnz foo 2257 // Emit: 2258 // cmp A, B 2259 // je foo 2260 // cmp D, E 2261 // jle foo 2262 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 2263 Instruction::BinaryOps Opcode = BOp->getOpcode(); 2264 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() && 2265 !I.hasMetadata(LLVMContext::MD_unpredictable) && 2266 (Opcode == Instruction::And || Opcode == Instruction::Or)) { 2267 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, 2268 Opcode, 2269 getEdgeProbability(BrMBB, Succ0MBB), 2270 getEdgeProbability(BrMBB, Succ1MBB), 2271 /*InvertCond=*/false); 2272 // If the compares in later blocks need to use values not currently 2273 // exported from this block, export them now. This block should always 2274 // be the first entry. 2275 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2276 2277 // Allow some cases to be rejected. 2278 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2279 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2280 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2281 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2282 } 2283 2284 // Emit the branch for this block. 2285 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2286 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2287 return; 2288 } 2289 2290 // Okay, we decided not to do this, remove any inserted MBB's and clear 2291 // SwitchCases. 2292 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2293 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2294 2295 SL->SwitchCases.clear(); 2296 } 2297 } 2298 2299 // Create a CaseBlock record representing this branch. 2300 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2301 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2302 2303 // Use visitSwitchCase to actually insert the fast branch sequence for this 2304 // cond branch. 2305 visitSwitchCase(CB, BrMBB); 2306 } 2307 2308 /// visitSwitchCase - Emits the necessary code to represent a single node in 2309 /// the binary search tree resulting from lowering a switch instruction. 2310 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2311 MachineBasicBlock *SwitchBB) { 2312 SDValue Cond; 2313 SDValue CondLHS = getValue(CB.CmpLHS); 2314 SDLoc dl = CB.DL; 2315 2316 if (CB.CC == ISD::SETTRUE) { 2317 // Branch or fall through to TrueBB. 2318 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2319 SwitchBB->normalizeSuccProbs(); 2320 if (CB.TrueBB != NextBlock(SwitchBB)) { 2321 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2322 DAG.getBasicBlock(CB.TrueBB))); 2323 } 2324 return; 2325 } 2326 2327 auto &TLI = DAG.getTargetLoweringInfo(); 2328 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2329 2330 // Build the setcc now. 2331 if (!CB.CmpMHS) { 2332 // Fold "(X == true)" to X and "(X == false)" to !X to 2333 // handle common cases produced by branch lowering. 2334 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2335 CB.CC == ISD::SETEQ) 2336 Cond = CondLHS; 2337 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2338 CB.CC == ISD::SETEQ) { 2339 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2340 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2341 } else { 2342 SDValue CondRHS = getValue(CB.CmpRHS); 2343 2344 // If a pointer's DAG type is larger than its memory type then the DAG 2345 // values are zero-extended. This breaks signed comparisons so truncate 2346 // back to the underlying type before doing the compare. 2347 if (CondLHS.getValueType() != MemVT) { 2348 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2349 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2350 } 2351 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2352 } 2353 } else { 2354 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2355 2356 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2357 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2358 2359 SDValue CmpOp = getValue(CB.CmpMHS); 2360 EVT VT = CmpOp.getValueType(); 2361 2362 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2363 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2364 ISD::SETLE); 2365 } else { 2366 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2367 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2368 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2369 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2370 } 2371 } 2372 2373 // Update successor info 2374 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2375 // TrueBB and FalseBB are always different unless the incoming IR is 2376 // degenerate. This only happens when running llc on weird IR. 2377 if (CB.TrueBB != CB.FalseBB) 2378 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2379 SwitchBB->normalizeSuccProbs(); 2380 2381 // If the lhs block is the next block, invert the condition so that we can 2382 // fall through to the lhs instead of the rhs block. 2383 if (CB.TrueBB == NextBlock(SwitchBB)) { 2384 std::swap(CB.TrueBB, CB.FalseBB); 2385 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2386 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2387 } 2388 2389 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2390 MVT::Other, getControlRoot(), Cond, 2391 DAG.getBasicBlock(CB.TrueBB)); 2392 2393 // Insert the false branch. Do this even if it's a fall through branch, 2394 // this makes it easier to do DAG optimizations which require inverting 2395 // the branch condition. 2396 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2397 DAG.getBasicBlock(CB.FalseBB)); 2398 2399 DAG.setRoot(BrCond); 2400 } 2401 2402 /// visitJumpTable - Emit JumpTable node in the current MBB 2403 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2404 // Emit the code for the jump table 2405 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2406 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2407 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2408 JT.Reg, PTy); 2409 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2410 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2411 MVT::Other, Index.getValue(1), 2412 Table, Index); 2413 DAG.setRoot(BrJumpTable); 2414 } 2415 2416 /// visitJumpTableHeader - This function emits necessary code to produce index 2417 /// in the JumpTable from switch case. 2418 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2419 JumpTableHeader &JTH, 2420 MachineBasicBlock *SwitchBB) { 2421 SDLoc dl = getCurSDLoc(); 2422 2423 // Subtract the lowest switch case value from the value being switched on. 2424 SDValue SwitchOp = getValue(JTH.SValue); 2425 EVT VT = SwitchOp.getValueType(); 2426 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2427 DAG.getConstant(JTH.First, dl, VT)); 2428 2429 // The SDNode we just created, which holds the value being switched on minus 2430 // the smallest case value, needs to be copied to a virtual register so it 2431 // can be used as an index into the jump table in a subsequent basic block. 2432 // This value may be smaller or larger than the target's pointer type, and 2433 // therefore require extension or truncating. 2434 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2435 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2436 2437 unsigned JumpTableReg = 2438 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2439 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2440 JumpTableReg, SwitchOp); 2441 JT.Reg = JumpTableReg; 2442 2443 if (!JTH.OmitRangeCheck) { 2444 // Emit the range check for the jump table, and branch to the default block 2445 // for the switch statement if the value being switched on exceeds the 2446 // largest case in the switch. 2447 SDValue CMP = DAG.getSetCC( 2448 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2449 Sub.getValueType()), 2450 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2451 2452 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2453 MVT::Other, CopyTo, CMP, 2454 DAG.getBasicBlock(JT.Default)); 2455 2456 // Avoid emitting unnecessary branches to the next block. 2457 if (JT.MBB != NextBlock(SwitchBB)) 2458 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2459 DAG.getBasicBlock(JT.MBB)); 2460 2461 DAG.setRoot(BrCond); 2462 } else { 2463 // Avoid emitting unnecessary branches to the next block. 2464 if (JT.MBB != NextBlock(SwitchBB)) 2465 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2466 DAG.getBasicBlock(JT.MBB))); 2467 else 2468 DAG.setRoot(CopyTo); 2469 } 2470 } 2471 2472 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2473 /// variable if there exists one. 2474 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2475 SDValue &Chain) { 2476 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2477 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2478 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2479 MachineFunction &MF = DAG.getMachineFunction(); 2480 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2481 MachineSDNode *Node = 2482 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2483 if (Global) { 2484 MachinePointerInfo MPInfo(Global); 2485 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2486 MachineMemOperand::MODereferenceable; 2487 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2488 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy)); 2489 DAG.setNodeMemRefs(Node, {MemRef}); 2490 } 2491 if (PtrTy != PtrMemTy) 2492 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2493 return SDValue(Node, 0); 2494 } 2495 2496 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2497 /// tail spliced into a stack protector check success bb. 2498 /// 2499 /// For a high level explanation of how this fits into the stack protector 2500 /// generation see the comment on the declaration of class 2501 /// StackProtectorDescriptor. 2502 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2503 MachineBasicBlock *ParentBB) { 2504 2505 // First create the loads to the guard/stack slot for the comparison. 2506 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2507 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2508 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2509 2510 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2511 int FI = MFI.getStackProtectorIndex(); 2512 2513 SDValue Guard; 2514 SDLoc dl = getCurSDLoc(); 2515 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2516 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2517 unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext())); 2518 2519 // Generate code to load the content of the guard slot. 2520 SDValue GuardVal = DAG.getLoad( 2521 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2522 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2523 MachineMemOperand::MOVolatile); 2524 2525 if (TLI.useStackGuardXorFP()) 2526 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2527 2528 // Retrieve guard check function, nullptr if instrumentation is inlined. 2529 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2530 // The target provides a guard check function to validate the guard value. 2531 // Generate a call to that function with the content of the guard slot as 2532 // argument. 2533 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2534 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2535 2536 TargetLowering::ArgListTy Args; 2537 TargetLowering::ArgListEntry Entry; 2538 Entry.Node = GuardVal; 2539 Entry.Ty = FnTy->getParamType(0); 2540 if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg)) 2541 Entry.IsInReg = true; 2542 Args.push_back(Entry); 2543 2544 TargetLowering::CallLoweringInfo CLI(DAG); 2545 CLI.setDebugLoc(getCurSDLoc()) 2546 .setChain(DAG.getEntryNode()) 2547 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2548 getValue(GuardCheckFn), std::move(Args)); 2549 2550 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2551 DAG.setRoot(Result.second); 2552 return; 2553 } 2554 2555 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2556 // Otherwise, emit a volatile load to retrieve the stack guard value. 2557 SDValue Chain = DAG.getEntryNode(); 2558 if (TLI.useLoadStackGuardNode()) { 2559 Guard = getLoadStackGuard(DAG, dl, Chain); 2560 } else { 2561 const Value *IRGuard = TLI.getSDagStackGuard(M); 2562 SDValue GuardPtr = getValue(IRGuard); 2563 2564 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2565 MachinePointerInfo(IRGuard, 0), Align, 2566 MachineMemOperand::MOVolatile); 2567 } 2568 2569 // Perform the comparison via a subtract/getsetcc. 2570 EVT VT = Guard.getValueType(); 2571 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal); 2572 2573 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2574 *DAG.getContext(), 2575 Sub.getValueType()), 2576 Sub, DAG.getConstant(0, dl, VT), ISD::SETNE); 2577 2578 // If the sub is not 0, then we know the guard/stackslot do not equal, so 2579 // branch to failure MBB. 2580 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2581 MVT::Other, GuardVal.getOperand(0), 2582 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2583 // Otherwise branch to success MBB. 2584 SDValue Br = DAG.getNode(ISD::BR, dl, 2585 MVT::Other, BrCond, 2586 DAG.getBasicBlock(SPD.getSuccessMBB())); 2587 2588 DAG.setRoot(Br); 2589 } 2590 2591 /// Codegen the failure basic block for a stack protector check. 2592 /// 2593 /// A failure stack protector machine basic block consists simply of a call to 2594 /// __stack_chk_fail(). 2595 /// 2596 /// For a high level explanation of how this fits into the stack protector 2597 /// generation see the comment on the declaration of class 2598 /// StackProtectorDescriptor. 2599 void 2600 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2601 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2602 TargetLowering::MakeLibCallOptions CallOptions; 2603 CallOptions.setDiscardResult(true); 2604 SDValue Chain = 2605 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2606 None, CallOptions, getCurSDLoc()).second; 2607 // On PS4, the "return address" must still be within the calling function, 2608 // even if it's at the very end, so emit an explicit TRAP here. 2609 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2610 if (TM.getTargetTriple().isPS4CPU()) 2611 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2612 2613 DAG.setRoot(Chain); 2614 } 2615 2616 /// visitBitTestHeader - This function emits necessary code to produce value 2617 /// suitable for "bit tests" 2618 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2619 MachineBasicBlock *SwitchBB) { 2620 SDLoc dl = getCurSDLoc(); 2621 2622 // Subtract the minimum value. 2623 SDValue SwitchOp = getValue(B.SValue); 2624 EVT VT = SwitchOp.getValueType(); 2625 SDValue RangeSub = 2626 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2627 2628 // Determine the type of the test operands. 2629 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2630 bool UsePtrType = false; 2631 if (!TLI.isTypeLegal(VT)) { 2632 UsePtrType = true; 2633 } else { 2634 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2635 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2636 // Switch table case range are encoded into series of masks. 2637 // Just use pointer type, it's guaranteed to fit. 2638 UsePtrType = true; 2639 break; 2640 } 2641 } 2642 SDValue Sub = RangeSub; 2643 if (UsePtrType) { 2644 VT = TLI.getPointerTy(DAG.getDataLayout()); 2645 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2646 } 2647 2648 B.RegVT = VT.getSimpleVT(); 2649 B.Reg = FuncInfo.CreateReg(B.RegVT); 2650 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2651 2652 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2653 2654 if (!B.OmitRangeCheck) 2655 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2656 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2657 SwitchBB->normalizeSuccProbs(); 2658 2659 SDValue Root = CopyTo; 2660 if (!B.OmitRangeCheck) { 2661 // Conditional branch to the default block. 2662 SDValue RangeCmp = DAG.getSetCC(dl, 2663 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2664 RangeSub.getValueType()), 2665 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2666 ISD::SETUGT); 2667 2668 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2669 DAG.getBasicBlock(B.Default)); 2670 } 2671 2672 // Avoid emitting unnecessary branches to the next block. 2673 if (MBB != NextBlock(SwitchBB)) 2674 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2675 2676 DAG.setRoot(Root); 2677 } 2678 2679 /// visitBitTestCase - this function produces one "bit test" 2680 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2681 MachineBasicBlock* NextMBB, 2682 BranchProbability BranchProbToNext, 2683 unsigned Reg, 2684 BitTestCase &B, 2685 MachineBasicBlock *SwitchBB) { 2686 SDLoc dl = getCurSDLoc(); 2687 MVT VT = BB.RegVT; 2688 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2689 SDValue Cmp; 2690 unsigned PopCount = countPopulation(B.Mask); 2691 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2692 if (PopCount == 1) { 2693 // Testing for a single bit; just compare the shift count with what it 2694 // would need to be to shift a 1 bit in that position. 2695 Cmp = DAG.getSetCC( 2696 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2697 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2698 ISD::SETEQ); 2699 } else if (PopCount == BB.Range) { 2700 // There is only one zero bit in the range, test for it directly. 2701 Cmp = DAG.getSetCC( 2702 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2703 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2704 ISD::SETNE); 2705 } else { 2706 // Make desired shift 2707 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2708 DAG.getConstant(1, dl, VT), ShiftOp); 2709 2710 // Emit bit tests and jumps 2711 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2712 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2713 Cmp = DAG.getSetCC( 2714 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2715 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2716 } 2717 2718 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2719 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2720 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2721 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2722 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2723 // one as they are relative probabilities (and thus work more like weights), 2724 // and hence we need to normalize them to let the sum of them become one. 2725 SwitchBB->normalizeSuccProbs(); 2726 2727 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2728 MVT::Other, getControlRoot(), 2729 Cmp, DAG.getBasicBlock(B.TargetBB)); 2730 2731 // Avoid emitting unnecessary branches to the next block. 2732 if (NextMBB != NextBlock(SwitchBB)) 2733 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2734 DAG.getBasicBlock(NextMBB)); 2735 2736 DAG.setRoot(BrAnd); 2737 } 2738 2739 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2740 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2741 2742 // Retrieve successors. Look through artificial IR level blocks like 2743 // catchswitch for successors. 2744 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2745 const BasicBlock *EHPadBB = I.getSuccessor(1); 2746 2747 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2748 // have to do anything here to lower funclet bundles. 2749 assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt, 2750 LLVMContext::OB_funclet, 2751 LLVMContext::OB_cfguardtarget}) && 2752 "Cannot lower invokes with arbitrary operand bundles yet!"); 2753 2754 const Value *Callee(I.getCalledValue()); 2755 const Function *Fn = dyn_cast<Function>(Callee); 2756 if (isa<InlineAsm>(Callee)) 2757 visitInlineAsm(&I); 2758 else if (Fn && Fn->isIntrinsic()) { 2759 switch (Fn->getIntrinsicID()) { 2760 default: 2761 llvm_unreachable("Cannot invoke this intrinsic"); 2762 case Intrinsic::donothing: 2763 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2764 break; 2765 case Intrinsic::experimental_patchpoint_void: 2766 case Intrinsic::experimental_patchpoint_i64: 2767 visitPatchpoint(&I, EHPadBB); 2768 break; 2769 case Intrinsic::experimental_gc_statepoint: 2770 LowerStatepoint(ImmutableStatepoint(&I), EHPadBB); 2771 break; 2772 case Intrinsic::wasm_rethrow_in_catch: { 2773 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2774 // special because it can be invoked, so we manually lower it to a DAG 2775 // node here. 2776 SmallVector<SDValue, 8> Ops; 2777 Ops.push_back(getRoot()); // inchain 2778 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2779 Ops.push_back( 2780 DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(), 2781 TLI.getPointerTy(DAG.getDataLayout()))); 2782 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2783 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2784 break; 2785 } 2786 } 2787 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2788 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2789 // Eventually we will support lowering the @llvm.experimental.deoptimize 2790 // intrinsic, and right now there are no plans to support other intrinsics 2791 // with deopt state. 2792 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2793 } else { 2794 LowerCallTo(&I, getValue(Callee), false, EHPadBB); 2795 } 2796 2797 // If the value of the invoke is used outside of its defining block, make it 2798 // available as a virtual register. 2799 // We already took care of the exported value for the statepoint instruction 2800 // during call to the LowerStatepoint. 2801 if (!isStatepoint(I)) { 2802 CopyToExportRegsIfNeeded(&I); 2803 } 2804 2805 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2806 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2807 BranchProbability EHPadBBProb = 2808 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2809 : BranchProbability::getZero(); 2810 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2811 2812 // Update successor info. 2813 addSuccessorWithProb(InvokeMBB, Return); 2814 for (auto &UnwindDest : UnwindDests) { 2815 UnwindDest.first->setIsEHPad(); 2816 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2817 } 2818 InvokeMBB->normalizeSuccProbs(); 2819 2820 // Drop into normal successor. 2821 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 2822 DAG.getBasicBlock(Return))); 2823 } 2824 2825 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 2826 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 2827 2828 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2829 // have to do anything here to lower funclet bundles. 2830 assert(!I.hasOperandBundlesOtherThan( 2831 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2832 "Cannot lower callbrs with arbitrary operand bundles yet!"); 2833 2834 assert(isa<InlineAsm>(I.getCalledValue()) && 2835 "Only know how to handle inlineasm callbr"); 2836 visitInlineAsm(&I); 2837 2838 // Retrieve successors. 2839 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 2840 2841 // Update successor info. 2842 addSuccessorWithProb(CallBrMBB, Return); 2843 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 2844 MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)]; 2845 addSuccessorWithProb(CallBrMBB, Target); 2846 } 2847 CallBrMBB->normalizeSuccProbs(); 2848 2849 // Drop into default successor. 2850 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2851 MVT::Other, getControlRoot(), 2852 DAG.getBasicBlock(Return))); 2853 } 2854 2855 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2856 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2857 } 2858 2859 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2860 assert(FuncInfo.MBB->isEHPad() && 2861 "Call to landingpad not in landing pad!"); 2862 2863 // If there aren't registers to copy the values into (e.g., during SjLj 2864 // exceptions), then don't bother to create these DAG nodes. 2865 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2866 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2867 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2868 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2869 return; 2870 2871 // If landingpad's return type is token type, we don't create DAG nodes 2872 // for its exception pointer and selector value. The extraction of exception 2873 // pointer or selector value from token type landingpads is not currently 2874 // supported. 2875 if (LP.getType()->isTokenTy()) 2876 return; 2877 2878 SmallVector<EVT, 2> ValueVTs; 2879 SDLoc dl = getCurSDLoc(); 2880 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2881 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2882 2883 // Get the two live-in registers as SDValues. The physregs have already been 2884 // copied into virtual registers. 2885 SDValue Ops[2]; 2886 if (FuncInfo.ExceptionPointerVirtReg) { 2887 Ops[0] = DAG.getZExtOrTrunc( 2888 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2889 FuncInfo.ExceptionPointerVirtReg, 2890 TLI.getPointerTy(DAG.getDataLayout())), 2891 dl, ValueVTs[0]); 2892 } else { 2893 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2894 } 2895 Ops[1] = DAG.getZExtOrTrunc( 2896 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2897 FuncInfo.ExceptionSelectorVirtReg, 2898 TLI.getPointerTy(DAG.getDataLayout())), 2899 dl, ValueVTs[1]); 2900 2901 // Merge into one. 2902 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 2903 DAG.getVTList(ValueVTs), Ops); 2904 setValue(&LP, Res); 2905 } 2906 2907 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2908 MachineBasicBlock *Last) { 2909 // Update JTCases. 2910 for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i) 2911 if (SL->JTCases[i].first.HeaderBB == First) 2912 SL->JTCases[i].first.HeaderBB = Last; 2913 2914 // Update BitTestCases. 2915 for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i) 2916 if (SL->BitTestCases[i].Parent == First) 2917 SL->BitTestCases[i].Parent = Last; 2918 } 2919 2920 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2921 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2922 2923 // Update machine-CFG edges with unique successors. 2924 SmallSet<BasicBlock*, 32> Done; 2925 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 2926 BasicBlock *BB = I.getSuccessor(i); 2927 bool Inserted = Done.insert(BB).second; 2928 if (!Inserted) 2929 continue; 2930 2931 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 2932 addSuccessorWithProb(IndirectBrMBB, Succ); 2933 } 2934 IndirectBrMBB->normalizeSuccProbs(); 2935 2936 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 2937 MVT::Other, getControlRoot(), 2938 getValue(I.getAddress()))); 2939 } 2940 2941 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 2942 if (!DAG.getTarget().Options.TrapUnreachable) 2943 return; 2944 2945 // We may be able to ignore unreachable behind a noreturn call. 2946 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 2947 const BasicBlock &BB = *I.getParent(); 2948 if (&I != &BB.front()) { 2949 BasicBlock::const_iterator PredI = 2950 std::prev(BasicBlock::const_iterator(&I)); 2951 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 2952 if (Call->doesNotReturn()) 2953 return; 2954 } 2955 } 2956 } 2957 2958 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 2959 } 2960 2961 void SelectionDAGBuilder::visitFSub(const User &I) { 2962 // -0.0 - X --> fneg 2963 Type *Ty = I.getType(); 2964 if (isa<Constant>(I.getOperand(0)) && 2965 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) { 2966 SDValue Op2 = getValue(I.getOperand(1)); 2967 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(), 2968 Op2.getValueType(), Op2)); 2969 return; 2970 } 2971 2972 visitBinary(I, ISD::FSUB); 2973 } 2974 2975 /// Checks if the given instruction performs a vector reduction, in which case 2976 /// we have the freedom to alter the elements in the result as long as the 2977 /// reduction of them stays unchanged. 2978 static bool isVectorReductionOp(const User *I) { 2979 const Instruction *Inst = dyn_cast<Instruction>(I); 2980 if (!Inst || !Inst->getType()->isVectorTy()) 2981 return false; 2982 2983 auto OpCode = Inst->getOpcode(); 2984 switch (OpCode) { 2985 case Instruction::Add: 2986 case Instruction::Mul: 2987 case Instruction::And: 2988 case Instruction::Or: 2989 case Instruction::Xor: 2990 break; 2991 case Instruction::FAdd: 2992 case Instruction::FMul: 2993 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 2994 if (FPOp->getFastMathFlags().isFast()) 2995 break; 2996 LLVM_FALLTHROUGH; 2997 default: 2998 return false; 2999 } 3000 3001 unsigned ElemNum = Inst->getType()->getVectorNumElements(); 3002 // Ensure the reduction size is a power of 2. 3003 if (!isPowerOf2_32(ElemNum)) 3004 return false; 3005 3006 unsigned ElemNumToReduce = ElemNum; 3007 3008 // Do DFS search on the def-use chain from the given instruction. We only 3009 // allow four kinds of operations during the search until we reach the 3010 // instruction that extracts the first element from the vector: 3011 // 3012 // 1. The reduction operation of the same opcode as the given instruction. 3013 // 3014 // 2. PHI node. 3015 // 3016 // 3. ShuffleVector instruction together with a reduction operation that 3017 // does a partial reduction. 3018 // 3019 // 4. ExtractElement that extracts the first element from the vector, and we 3020 // stop searching the def-use chain here. 3021 // 3022 // 3 & 4 above perform a reduction on all elements of the vector. We push defs 3023 // from 1-3 to the stack to continue the DFS. The given instruction is not 3024 // a reduction operation if we meet any other instructions other than those 3025 // listed above. 3026 3027 SmallVector<const User *, 16> UsersToVisit{Inst}; 3028 SmallPtrSet<const User *, 16> Visited; 3029 bool ReduxExtracted = false; 3030 3031 while (!UsersToVisit.empty()) { 3032 auto User = UsersToVisit.back(); 3033 UsersToVisit.pop_back(); 3034 if (!Visited.insert(User).second) 3035 continue; 3036 3037 for (const auto &U : User->users()) { 3038 auto Inst = dyn_cast<Instruction>(U); 3039 if (!Inst) 3040 return false; 3041 3042 if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) { 3043 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 3044 if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast()) 3045 return false; 3046 UsersToVisit.push_back(U); 3047 } else if (const ShuffleVectorInst *ShufInst = 3048 dyn_cast<ShuffleVectorInst>(U)) { 3049 // Detect the following pattern: A ShuffleVector instruction together 3050 // with a reduction that do partial reduction on the first and second 3051 // ElemNumToReduce / 2 elements, and store the result in 3052 // ElemNumToReduce / 2 elements in another vector. 3053 3054 unsigned ResultElements = ShufInst->getType()->getVectorNumElements(); 3055 if (ResultElements < ElemNum) 3056 return false; 3057 3058 if (ElemNumToReduce == 1) 3059 return false; 3060 if (!isa<UndefValue>(U->getOperand(1))) 3061 return false; 3062 for (unsigned i = 0; i < ElemNumToReduce / 2; ++i) 3063 if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2)) 3064 return false; 3065 for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i) 3066 if (ShufInst->getMaskValue(i) != -1) 3067 return false; 3068 3069 // There is only one user of this ShuffleVector instruction, which 3070 // must be a reduction operation. 3071 if (!U->hasOneUse()) 3072 return false; 3073 3074 auto U2 = dyn_cast<Instruction>(*U->user_begin()); 3075 if (!U2 || U2->getOpcode() != OpCode) 3076 return false; 3077 3078 // Check operands of the reduction operation. 3079 if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) || 3080 (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) { 3081 UsersToVisit.push_back(U2); 3082 ElemNumToReduce /= 2; 3083 } else 3084 return false; 3085 } else if (isa<ExtractElementInst>(U)) { 3086 // At this moment we should have reduced all elements in the vector. 3087 if (ElemNumToReduce != 1) 3088 return false; 3089 3090 const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1)); 3091 if (!Val || !Val->isZero()) 3092 return false; 3093 3094 ReduxExtracted = true; 3095 } else 3096 return false; 3097 } 3098 } 3099 return ReduxExtracted; 3100 } 3101 3102 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3103 SDNodeFlags Flags; 3104 3105 SDValue Op = getValue(I.getOperand(0)); 3106 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3107 Op, Flags); 3108 setValue(&I, UnNodeValue); 3109 } 3110 3111 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3112 SDNodeFlags Flags; 3113 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3114 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3115 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3116 } 3117 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) { 3118 Flags.setExact(ExactOp->isExact()); 3119 } 3120 if (isVectorReductionOp(&I)) { 3121 Flags.setVectorReduction(true); 3122 LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n"); 3123 } 3124 3125 SDValue Op1 = getValue(I.getOperand(0)); 3126 SDValue Op2 = getValue(I.getOperand(1)); 3127 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3128 Op1, Op2, Flags); 3129 setValue(&I, BinNodeValue); 3130 } 3131 3132 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3133 SDValue Op1 = getValue(I.getOperand(0)); 3134 SDValue Op2 = getValue(I.getOperand(1)); 3135 3136 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3137 Op1.getValueType(), DAG.getDataLayout()); 3138 3139 // Coerce the shift amount to the right type if we can. 3140 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3141 unsigned ShiftSize = ShiftTy.getSizeInBits(); 3142 unsigned Op2Size = Op2.getValueSizeInBits(); 3143 SDLoc DL = getCurSDLoc(); 3144 3145 // If the operand is smaller than the shift count type, promote it. 3146 if (ShiftSize > Op2Size) 3147 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 3148 3149 // If the operand is larger than the shift count type but the shift 3150 // count type has enough bits to represent any shift value, truncate 3151 // it now. This is a common case and it exposes the truncate to 3152 // optimization early. 3153 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 3154 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 3155 // Otherwise we'll need to temporarily settle for some other convenient 3156 // type. Type legalization will make adjustments once the shiftee is split. 3157 else 3158 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 3159 } 3160 3161 bool nuw = false; 3162 bool nsw = false; 3163 bool exact = false; 3164 3165 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3166 3167 if (const OverflowingBinaryOperator *OFBinOp = 3168 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3169 nuw = OFBinOp->hasNoUnsignedWrap(); 3170 nsw = OFBinOp->hasNoSignedWrap(); 3171 } 3172 if (const PossiblyExactOperator *ExactOp = 3173 dyn_cast<const PossiblyExactOperator>(&I)) 3174 exact = ExactOp->isExact(); 3175 } 3176 SDNodeFlags Flags; 3177 Flags.setExact(exact); 3178 Flags.setNoSignedWrap(nsw); 3179 Flags.setNoUnsignedWrap(nuw); 3180 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3181 Flags); 3182 setValue(&I, Res); 3183 } 3184 3185 void SelectionDAGBuilder::visitSDiv(const User &I) { 3186 SDValue Op1 = getValue(I.getOperand(0)); 3187 SDValue Op2 = getValue(I.getOperand(1)); 3188 3189 SDNodeFlags Flags; 3190 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3191 cast<PossiblyExactOperator>(&I)->isExact()); 3192 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3193 Op2, Flags)); 3194 } 3195 3196 void SelectionDAGBuilder::visitICmp(const User &I) { 3197 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3198 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3199 predicate = IC->getPredicate(); 3200 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3201 predicate = ICmpInst::Predicate(IC->getPredicate()); 3202 SDValue Op1 = getValue(I.getOperand(0)); 3203 SDValue Op2 = getValue(I.getOperand(1)); 3204 ISD::CondCode Opcode = getICmpCondCode(predicate); 3205 3206 auto &TLI = DAG.getTargetLoweringInfo(); 3207 EVT MemVT = 3208 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3209 3210 // If a pointer's DAG type is larger than its memory type then the DAG values 3211 // are zero-extended. This breaks signed comparisons so truncate back to the 3212 // underlying type before doing the compare. 3213 if (Op1.getValueType() != MemVT) { 3214 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3215 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3216 } 3217 3218 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3219 I.getType()); 3220 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3221 } 3222 3223 void SelectionDAGBuilder::visitFCmp(const User &I) { 3224 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3225 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3226 predicate = FC->getPredicate(); 3227 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3228 predicate = FCmpInst::Predicate(FC->getPredicate()); 3229 SDValue Op1 = getValue(I.getOperand(0)); 3230 SDValue Op2 = getValue(I.getOperand(1)); 3231 3232 ISD::CondCode Condition = getFCmpCondCode(predicate); 3233 auto *FPMO = dyn_cast<FPMathOperator>(&I); 3234 if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath) 3235 Condition = getFCmpCodeWithoutNaN(Condition); 3236 3237 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3238 I.getType()); 3239 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3240 } 3241 3242 // Check if the condition of the select has one use or two users that are both 3243 // selects with the same condition. 3244 static bool hasOnlySelectUsers(const Value *Cond) { 3245 return llvm::all_of(Cond->users(), [](const Value *V) { 3246 return isa<SelectInst>(V); 3247 }); 3248 } 3249 3250 void SelectionDAGBuilder::visitSelect(const User &I) { 3251 SmallVector<EVT, 4> ValueVTs; 3252 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3253 ValueVTs); 3254 unsigned NumValues = ValueVTs.size(); 3255 if (NumValues == 0) return; 3256 3257 SmallVector<SDValue, 4> Values(NumValues); 3258 SDValue Cond = getValue(I.getOperand(0)); 3259 SDValue LHSVal = getValue(I.getOperand(1)); 3260 SDValue RHSVal = getValue(I.getOperand(2)); 3261 auto BaseOps = {Cond}; 3262 ISD::NodeType OpCode = Cond.getValueType().isVector() ? 3263 ISD::VSELECT : ISD::SELECT; 3264 3265 bool IsUnaryAbs = false; 3266 3267 // Min/max matching is only viable if all output VTs are the same. 3268 if (is_splat(ValueVTs)) { 3269 EVT VT = ValueVTs[0]; 3270 LLVMContext &Ctx = *DAG.getContext(); 3271 auto &TLI = DAG.getTargetLoweringInfo(); 3272 3273 // We care about the legality of the operation after it has been type 3274 // legalized. 3275 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3276 VT = TLI.getTypeToTransformTo(Ctx, VT); 3277 3278 // If the vselect is legal, assume we want to leave this as a vector setcc + 3279 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3280 // min/max is legal on the scalar type. 3281 bool UseScalarMinMax = VT.isVector() && 3282 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3283 3284 Value *LHS, *RHS; 3285 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3286 ISD::NodeType Opc = ISD::DELETED_NODE; 3287 switch (SPR.Flavor) { 3288 case SPF_UMAX: Opc = ISD::UMAX; break; 3289 case SPF_UMIN: Opc = ISD::UMIN; break; 3290 case SPF_SMAX: Opc = ISD::SMAX; break; 3291 case SPF_SMIN: Opc = ISD::SMIN; break; 3292 case SPF_FMINNUM: 3293 switch (SPR.NaNBehavior) { 3294 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3295 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3296 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3297 case SPNB_RETURNS_ANY: { 3298 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3299 Opc = ISD::FMINNUM; 3300 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3301 Opc = ISD::FMINIMUM; 3302 else if (UseScalarMinMax) 3303 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3304 ISD::FMINNUM : ISD::FMINIMUM; 3305 break; 3306 } 3307 } 3308 break; 3309 case SPF_FMAXNUM: 3310 switch (SPR.NaNBehavior) { 3311 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3312 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3313 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3314 case SPNB_RETURNS_ANY: 3315 3316 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3317 Opc = ISD::FMAXNUM; 3318 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3319 Opc = ISD::FMAXIMUM; 3320 else if (UseScalarMinMax) 3321 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3322 ISD::FMAXNUM : ISD::FMAXIMUM; 3323 break; 3324 } 3325 break; 3326 case SPF_ABS: 3327 IsUnaryAbs = true; 3328 Opc = ISD::ABS; 3329 break; 3330 case SPF_NABS: 3331 // TODO: we need to produce sub(0, abs(X)). 3332 default: break; 3333 } 3334 3335 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3336 (TLI.isOperationLegalOrCustom(Opc, VT) || 3337 (UseScalarMinMax && 3338 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3339 // If the underlying comparison instruction is used by any other 3340 // instruction, the consumed instructions won't be destroyed, so it is 3341 // not profitable to convert to a min/max. 3342 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3343 OpCode = Opc; 3344 LHSVal = getValue(LHS); 3345 RHSVal = getValue(RHS); 3346 BaseOps = {}; 3347 } 3348 3349 if (IsUnaryAbs) { 3350 OpCode = Opc; 3351 LHSVal = getValue(LHS); 3352 BaseOps = {}; 3353 } 3354 } 3355 3356 if (IsUnaryAbs) { 3357 for (unsigned i = 0; i != NumValues; ++i) { 3358 Values[i] = 3359 DAG.getNode(OpCode, getCurSDLoc(), 3360 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), 3361 SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3362 } 3363 } else { 3364 for (unsigned i = 0; i != NumValues; ++i) { 3365 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3366 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3367 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3368 Values[i] = DAG.getNode( 3369 OpCode, getCurSDLoc(), 3370 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops); 3371 } 3372 } 3373 3374 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3375 DAG.getVTList(ValueVTs), Values)); 3376 } 3377 3378 void SelectionDAGBuilder::visitTrunc(const User &I) { 3379 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3380 SDValue N = getValue(I.getOperand(0)); 3381 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3382 I.getType()); 3383 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3384 } 3385 3386 void SelectionDAGBuilder::visitZExt(const User &I) { 3387 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3388 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3389 SDValue N = getValue(I.getOperand(0)); 3390 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3391 I.getType()); 3392 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3393 } 3394 3395 void SelectionDAGBuilder::visitSExt(const User &I) { 3396 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3397 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3398 SDValue N = getValue(I.getOperand(0)); 3399 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3400 I.getType()); 3401 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3402 } 3403 3404 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3405 // FPTrunc is never a no-op cast, no need to check 3406 SDValue N = getValue(I.getOperand(0)); 3407 SDLoc dl = getCurSDLoc(); 3408 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3409 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3410 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3411 DAG.getTargetConstant( 3412 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3413 } 3414 3415 void SelectionDAGBuilder::visitFPExt(const User &I) { 3416 // FPExt is never a no-op cast, no need to check 3417 SDValue N = getValue(I.getOperand(0)); 3418 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3419 I.getType()); 3420 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3421 } 3422 3423 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3424 // FPToUI is never a no-op cast, no need to check 3425 SDValue N = getValue(I.getOperand(0)); 3426 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3427 I.getType()); 3428 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3429 } 3430 3431 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3432 // FPToSI is never a no-op cast, no need to check 3433 SDValue N = getValue(I.getOperand(0)); 3434 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3435 I.getType()); 3436 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3437 } 3438 3439 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3440 // UIToFP is never a no-op cast, no need to check 3441 SDValue N = getValue(I.getOperand(0)); 3442 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3443 I.getType()); 3444 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3445 } 3446 3447 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3448 // SIToFP is never a no-op cast, no need to check 3449 SDValue N = getValue(I.getOperand(0)); 3450 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3451 I.getType()); 3452 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3453 } 3454 3455 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3456 // What to do depends on the size of the integer and the size of the pointer. 3457 // We can either truncate, zero extend, or no-op, accordingly. 3458 SDValue N = getValue(I.getOperand(0)); 3459 auto &TLI = DAG.getTargetLoweringInfo(); 3460 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3461 I.getType()); 3462 EVT PtrMemVT = 3463 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3464 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3465 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3466 setValue(&I, N); 3467 } 3468 3469 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3470 // What to do depends on the size of the integer and the size of the pointer. 3471 // We can either truncate, zero extend, or no-op, accordingly. 3472 SDValue N = getValue(I.getOperand(0)); 3473 auto &TLI = DAG.getTargetLoweringInfo(); 3474 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3475 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3476 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3477 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3478 setValue(&I, N); 3479 } 3480 3481 void SelectionDAGBuilder::visitBitCast(const User &I) { 3482 SDValue N = getValue(I.getOperand(0)); 3483 SDLoc dl = getCurSDLoc(); 3484 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3485 I.getType()); 3486 3487 // BitCast assures us that source and destination are the same size so this is 3488 // either a BITCAST or a no-op. 3489 if (DestVT != N.getValueType()) 3490 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3491 DestVT, N)); // convert types. 3492 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3493 // might fold any kind of constant expression to an integer constant and that 3494 // is not what we are looking for. Only recognize a bitcast of a genuine 3495 // constant integer as an opaque constant. 3496 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3497 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3498 /*isOpaque*/true)); 3499 else 3500 setValue(&I, N); // noop cast. 3501 } 3502 3503 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3504 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3505 const Value *SV = I.getOperand(0); 3506 SDValue N = getValue(SV); 3507 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3508 3509 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3510 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3511 3512 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) 3513 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3514 3515 setValue(&I, N); 3516 } 3517 3518 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3519 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3520 SDValue InVec = getValue(I.getOperand(0)); 3521 SDValue InVal = getValue(I.getOperand(1)); 3522 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3523 TLI.getVectorIdxTy(DAG.getDataLayout())); 3524 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3525 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3526 InVec, InVal, InIdx)); 3527 } 3528 3529 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3530 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3531 SDValue InVec = getValue(I.getOperand(0)); 3532 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3533 TLI.getVectorIdxTy(DAG.getDataLayout())); 3534 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3535 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3536 InVec, InIdx)); 3537 } 3538 3539 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3540 SDValue Src1 = getValue(I.getOperand(0)); 3541 SDValue Src2 = getValue(I.getOperand(1)); 3542 Constant *MaskV = cast<Constant>(I.getOperand(2)); 3543 SDLoc DL = getCurSDLoc(); 3544 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3545 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3546 EVT SrcVT = Src1.getValueType(); 3547 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3548 3549 if (MaskV->isNullValue() && VT.isScalableVector()) { 3550 // Canonical splat form of first element of first input vector. 3551 SDValue FirstElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 3552 SrcVT.getScalarType(), Src1, 3553 DAG.getConstant(0, DL, 3554 TLI.getVectorIdxTy(DAG.getDataLayout()))); 3555 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3556 return; 3557 } 3558 3559 // For now, we only handle splats for scalable vectors. 3560 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3561 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3562 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3563 3564 SmallVector<int, 8> Mask; 3565 ShuffleVectorInst::getShuffleMask(MaskV, Mask); 3566 unsigned MaskNumElts = Mask.size(); 3567 3568 if (SrcNumElts == MaskNumElts) { 3569 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3570 return; 3571 } 3572 3573 // Normalize the shuffle vector since mask and vector length don't match. 3574 if (SrcNumElts < MaskNumElts) { 3575 // Mask is longer than the source vectors. We can use concatenate vector to 3576 // make the mask and vectors lengths match. 3577 3578 if (MaskNumElts % SrcNumElts == 0) { 3579 // Mask length is a multiple of the source vector length. 3580 // Check if the shuffle is some kind of concatenation of the input 3581 // vectors. 3582 unsigned NumConcat = MaskNumElts / SrcNumElts; 3583 bool IsConcat = true; 3584 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3585 for (unsigned i = 0; i != MaskNumElts; ++i) { 3586 int Idx = Mask[i]; 3587 if (Idx < 0) 3588 continue; 3589 // Ensure the indices in each SrcVT sized piece are sequential and that 3590 // the same source is used for the whole piece. 3591 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3592 (ConcatSrcs[i / SrcNumElts] >= 0 && 3593 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3594 IsConcat = false; 3595 break; 3596 } 3597 // Remember which source this index came from. 3598 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3599 } 3600 3601 // The shuffle is concatenating multiple vectors together. Just emit 3602 // a CONCAT_VECTORS operation. 3603 if (IsConcat) { 3604 SmallVector<SDValue, 8> ConcatOps; 3605 for (auto Src : ConcatSrcs) { 3606 if (Src < 0) 3607 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3608 else if (Src == 0) 3609 ConcatOps.push_back(Src1); 3610 else 3611 ConcatOps.push_back(Src2); 3612 } 3613 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3614 return; 3615 } 3616 } 3617 3618 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3619 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3620 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3621 PaddedMaskNumElts); 3622 3623 // Pad both vectors with undefs to make them the same length as the mask. 3624 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3625 3626 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3627 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3628 MOps1[0] = Src1; 3629 MOps2[0] = Src2; 3630 3631 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3632 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3633 3634 // Readjust mask for new input vector length. 3635 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3636 for (unsigned i = 0; i != MaskNumElts; ++i) { 3637 int Idx = Mask[i]; 3638 if (Idx >= (int)SrcNumElts) 3639 Idx -= SrcNumElts - PaddedMaskNumElts; 3640 MappedOps[i] = Idx; 3641 } 3642 3643 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3644 3645 // If the concatenated vector was padded, extract a subvector with the 3646 // correct number of elements. 3647 if (MaskNumElts != PaddedMaskNumElts) 3648 Result = DAG.getNode( 3649 ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3650 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 3651 3652 setValue(&I, Result); 3653 return; 3654 } 3655 3656 if (SrcNumElts > MaskNumElts) { 3657 // Analyze the access pattern of the vector to see if we can extract 3658 // two subvectors and do the shuffle. 3659 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3660 bool CanExtract = true; 3661 for (int Idx : Mask) { 3662 unsigned Input = 0; 3663 if (Idx < 0) 3664 continue; 3665 3666 if (Idx >= (int)SrcNumElts) { 3667 Input = 1; 3668 Idx -= SrcNumElts; 3669 } 3670 3671 // If all the indices come from the same MaskNumElts sized portion of 3672 // the sources we can use extract. Also make sure the extract wouldn't 3673 // extract past the end of the source. 3674 int NewStartIdx = alignDown(Idx, MaskNumElts); 3675 if (NewStartIdx + MaskNumElts > SrcNumElts || 3676 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3677 CanExtract = false; 3678 // Make sure we always update StartIdx as we use it to track if all 3679 // elements are undef. 3680 StartIdx[Input] = NewStartIdx; 3681 } 3682 3683 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3684 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3685 return; 3686 } 3687 if (CanExtract) { 3688 // Extract appropriate subvector and generate a vector shuffle 3689 for (unsigned Input = 0; Input < 2; ++Input) { 3690 SDValue &Src = Input == 0 ? Src1 : Src2; 3691 if (StartIdx[Input] < 0) 3692 Src = DAG.getUNDEF(VT); 3693 else { 3694 Src = DAG.getNode( 3695 ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3696 DAG.getConstant(StartIdx[Input], DL, 3697 TLI.getVectorIdxTy(DAG.getDataLayout()))); 3698 } 3699 } 3700 3701 // Calculate new mask. 3702 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3703 for (int &Idx : MappedOps) { 3704 if (Idx >= (int)SrcNumElts) 3705 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3706 else if (Idx >= 0) 3707 Idx -= StartIdx[0]; 3708 } 3709 3710 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3711 return; 3712 } 3713 } 3714 3715 // We can't use either concat vectors or extract subvectors so fall back to 3716 // replacing the shuffle with extract and build vector. 3717 // to insert and build vector. 3718 EVT EltVT = VT.getVectorElementType(); 3719 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 3720 SmallVector<SDValue,8> Ops; 3721 for (int Idx : Mask) { 3722 SDValue Res; 3723 3724 if (Idx < 0) { 3725 Res = DAG.getUNDEF(EltVT); 3726 } else { 3727 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3728 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3729 3730 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 3731 EltVT, Src, DAG.getConstant(Idx, DL, IdxVT)); 3732 } 3733 3734 Ops.push_back(Res); 3735 } 3736 3737 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3738 } 3739 3740 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3741 ArrayRef<unsigned> Indices; 3742 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3743 Indices = IV->getIndices(); 3744 else 3745 Indices = cast<ConstantExpr>(&I)->getIndices(); 3746 3747 const Value *Op0 = I.getOperand(0); 3748 const Value *Op1 = I.getOperand(1); 3749 Type *AggTy = I.getType(); 3750 Type *ValTy = Op1->getType(); 3751 bool IntoUndef = isa<UndefValue>(Op0); 3752 bool FromUndef = isa<UndefValue>(Op1); 3753 3754 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3755 3756 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3757 SmallVector<EVT, 4> AggValueVTs; 3758 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3759 SmallVector<EVT, 4> ValValueVTs; 3760 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3761 3762 unsigned NumAggValues = AggValueVTs.size(); 3763 unsigned NumValValues = ValValueVTs.size(); 3764 SmallVector<SDValue, 4> Values(NumAggValues); 3765 3766 // Ignore an insertvalue that produces an empty object 3767 if (!NumAggValues) { 3768 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3769 return; 3770 } 3771 3772 SDValue Agg = getValue(Op0); 3773 unsigned i = 0; 3774 // Copy the beginning value(s) from the original aggregate. 3775 for (; i != LinearIndex; ++i) 3776 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3777 SDValue(Agg.getNode(), Agg.getResNo() + i); 3778 // Copy values from the inserted value(s). 3779 if (NumValValues) { 3780 SDValue Val = getValue(Op1); 3781 for (; i != LinearIndex + NumValValues; ++i) 3782 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3783 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3784 } 3785 // Copy remaining value(s) from the original aggregate. 3786 for (; i != NumAggValues; ++i) 3787 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3788 SDValue(Agg.getNode(), Agg.getResNo() + i); 3789 3790 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3791 DAG.getVTList(AggValueVTs), Values)); 3792 } 3793 3794 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3795 ArrayRef<unsigned> Indices; 3796 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3797 Indices = EV->getIndices(); 3798 else 3799 Indices = cast<ConstantExpr>(&I)->getIndices(); 3800 3801 const Value *Op0 = I.getOperand(0); 3802 Type *AggTy = Op0->getType(); 3803 Type *ValTy = I.getType(); 3804 bool OutOfUndef = isa<UndefValue>(Op0); 3805 3806 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3807 3808 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3809 SmallVector<EVT, 4> ValValueVTs; 3810 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3811 3812 unsigned NumValValues = ValValueVTs.size(); 3813 3814 // Ignore a extractvalue that produces an empty object 3815 if (!NumValValues) { 3816 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3817 return; 3818 } 3819 3820 SmallVector<SDValue, 4> Values(NumValValues); 3821 3822 SDValue Agg = getValue(Op0); 3823 // Copy out the selected value(s). 3824 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3825 Values[i - LinearIndex] = 3826 OutOfUndef ? 3827 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3828 SDValue(Agg.getNode(), Agg.getResNo() + i); 3829 3830 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3831 DAG.getVTList(ValValueVTs), Values)); 3832 } 3833 3834 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3835 Value *Op0 = I.getOperand(0); 3836 // Note that the pointer operand may be a vector of pointers. Take the scalar 3837 // element which holds a pointer. 3838 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3839 SDValue N = getValue(Op0); 3840 SDLoc dl = getCurSDLoc(); 3841 auto &TLI = DAG.getTargetLoweringInfo(); 3842 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 3843 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 3844 3845 // Normalize Vector GEP - all scalar operands should be converted to the 3846 // splat vector. 3847 unsigned VectorWidth = I.getType()->isVectorTy() ? 3848 I.getType()->getVectorNumElements() : 0; 3849 3850 if (VectorWidth && !N.getValueType().isVector()) { 3851 LLVMContext &Context = *DAG.getContext(); 3852 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth); 3853 N = DAG.getSplatBuildVector(VT, dl, N); 3854 } 3855 3856 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3857 GTI != E; ++GTI) { 3858 const Value *Idx = GTI.getOperand(); 3859 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3860 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3861 if (Field) { 3862 // N = N + Offset 3863 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3864 3865 // In an inbounds GEP with an offset that is nonnegative even when 3866 // interpreted as signed, assume there is no unsigned overflow. 3867 SDNodeFlags Flags; 3868 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3869 Flags.setNoUnsignedWrap(true); 3870 3871 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3872 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3873 } 3874 } else { 3875 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3876 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3877 APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType())); 3878 3879 // If this is a scalar constant or a splat vector of constants, 3880 // handle it quickly. 3881 const auto *C = dyn_cast<Constant>(Idx); 3882 if (C && isa<VectorType>(C->getType())) 3883 C = C->getSplatValue(); 3884 3885 if (const auto *CI = dyn_cast_or_null<ConstantInt>(C)) { 3886 if (CI->isZero()) 3887 continue; 3888 APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize); 3889 LLVMContext &Context = *DAG.getContext(); 3890 SDValue OffsVal = VectorWidth ? 3891 DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) : 3892 DAG.getConstant(Offs, dl, IdxTy); 3893 3894 // In an inbounds GEP with an offset that is nonnegative even when 3895 // interpreted as signed, assume there is no unsigned overflow. 3896 SDNodeFlags Flags; 3897 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3898 Flags.setNoUnsignedWrap(true); 3899 3900 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3901 3902 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3903 continue; 3904 } 3905 3906 // N = N + Idx * ElementSize; 3907 SDValue IdxN = getValue(Idx); 3908 3909 if (!IdxN.getValueType().isVector() && VectorWidth) { 3910 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth); 3911 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3912 } 3913 3914 // If the index is smaller or larger than intptr_t, truncate or extend 3915 // it. 3916 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3917 3918 // If this is a multiply by a power of two, turn it into a shl 3919 // immediately. This is a very common case. 3920 if (ElementSize != 1) { 3921 if (ElementSize.isPowerOf2()) { 3922 unsigned Amt = ElementSize.logBase2(); 3923 IdxN = DAG.getNode(ISD::SHL, dl, 3924 N.getValueType(), IdxN, 3925 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3926 } else { 3927 SDValue Scale = DAG.getConstant(ElementSize.getZExtValue(), dl, 3928 IdxN.getValueType()); 3929 IdxN = DAG.getNode(ISD::MUL, dl, 3930 N.getValueType(), IdxN, Scale); 3931 } 3932 } 3933 3934 N = DAG.getNode(ISD::ADD, dl, 3935 N.getValueType(), N, IdxN); 3936 } 3937 } 3938 3939 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 3940 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 3941 3942 setValue(&I, N); 3943 } 3944 3945 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3946 // If this is a fixed sized alloca in the entry block of the function, 3947 // allocate it statically on the stack. 3948 if (FuncInfo.StaticAllocaMap.count(&I)) 3949 return; // getValue will auto-populate this. 3950 3951 SDLoc dl = getCurSDLoc(); 3952 Type *Ty = I.getAllocatedType(); 3953 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3954 auto &DL = DAG.getDataLayout(); 3955 uint64_t TySize = DL.getTypeAllocSize(Ty); 3956 unsigned Align = 3957 std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment()); 3958 3959 SDValue AllocSize = getValue(I.getArraySize()); 3960 3961 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3962 if (AllocSize.getValueType() != IntPtr) 3963 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3964 3965 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3966 AllocSize, 3967 DAG.getConstant(TySize, dl, IntPtr)); 3968 3969 // Handle alignment. If the requested alignment is less than or equal to 3970 // the stack alignment, ignore it. If the size is greater than or equal to 3971 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3972 unsigned StackAlign = 3973 DAG.getSubtarget().getFrameLowering()->getStackAlignment(); 3974 if (Align <= StackAlign) 3975 Align = 0; 3976 3977 // Round the size of the allocation up to the stack alignment size 3978 // by add SA-1 to the size. This doesn't overflow because we're computing 3979 // an address inside an alloca. 3980 SDNodeFlags Flags; 3981 Flags.setNoUnsignedWrap(true); 3982 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 3983 DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags); 3984 3985 // Mask out the low bits for alignment purposes. 3986 AllocSize = 3987 DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 3988 DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr)); 3989 3990 SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)}; 3991 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 3992 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 3993 setValue(&I, DSA); 3994 DAG.setRoot(DSA.getValue(1)); 3995 3996 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 3997 } 3998 3999 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4000 if (I.isAtomic()) 4001 return visitAtomicLoad(I); 4002 4003 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4004 const Value *SV = I.getOperand(0); 4005 if (TLI.supportSwiftError()) { 4006 // Swifterror values can come from either a function parameter with 4007 // swifterror attribute or an alloca with swifterror attribute. 4008 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4009 if (Arg->hasSwiftErrorAttr()) 4010 return visitLoadFromSwiftError(I); 4011 } 4012 4013 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4014 if (Alloca->isSwiftError()) 4015 return visitLoadFromSwiftError(I); 4016 } 4017 } 4018 4019 SDValue Ptr = getValue(SV); 4020 4021 Type *Ty = I.getType(); 4022 4023 bool isVolatile = I.isVolatile(); 4024 bool isNonTemporal = I.hasMetadata(LLVMContext::MD_nontemporal); 4025 bool isInvariant = I.hasMetadata(LLVMContext::MD_invariant_load); 4026 bool isDereferenceable = 4027 isDereferenceablePointer(SV, I.getType(), DAG.getDataLayout()); 4028 unsigned Alignment = I.getAlignment(); 4029 4030 AAMDNodes AAInfo; 4031 I.getAAMetadata(AAInfo); 4032 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4033 4034 SmallVector<EVT, 4> ValueVTs, MemVTs; 4035 SmallVector<uint64_t, 4> Offsets; 4036 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4037 unsigned NumValues = ValueVTs.size(); 4038 if (NumValues == 0) 4039 return; 4040 4041 SDValue Root; 4042 bool ConstantMemory = false; 4043 if (isVolatile || NumValues > MaxParallelChains) 4044 // Serialize volatile loads with other side effects. 4045 Root = getRoot(); 4046 else if (AA && 4047 AA->pointsToConstantMemory(MemoryLocation( 4048 SV, 4049 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4050 AAInfo))) { 4051 // Do not serialize (non-volatile) loads of constant memory with anything. 4052 Root = DAG.getEntryNode(); 4053 ConstantMemory = true; 4054 } else { 4055 // Do not serialize non-volatile loads against each other. 4056 Root = DAG.getRoot(); 4057 } 4058 4059 SDLoc dl = getCurSDLoc(); 4060 4061 if (isVolatile) 4062 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4063 4064 // An aggregate load cannot wrap around the address space, so offsets to its 4065 // parts don't wrap either. 4066 SDNodeFlags Flags; 4067 Flags.setNoUnsignedWrap(true); 4068 4069 SmallVector<SDValue, 4> Values(NumValues); 4070 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4071 EVT PtrVT = Ptr.getValueType(); 4072 unsigned ChainI = 0; 4073 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4074 // Serializing loads here may result in excessive register pressure, and 4075 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4076 // could recover a bit by hoisting nodes upward in the chain by recognizing 4077 // they are side-effect free or do not alias. The optimizer should really 4078 // avoid this case by converting large object/array copies to llvm.memcpy 4079 // (MaxParallelChains should always remain as failsafe). 4080 if (ChainI == MaxParallelChains) { 4081 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4082 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4083 makeArrayRef(Chains.data(), ChainI)); 4084 Root = Chain; 4085 ChainI = 0; 4086 } 4087 SDValue A = DAG.getNode(ISD::ADD, dl, 4088 PtrVT, Ptr, 4089 DAG.getConstant(Offsets[i], dl, PtrVT), 4090 Flags); 4091 auto MMOFlags = MachineMemOperand::MONone; 4092 if (isVolatile) 4093 MMOFlags |= MachineMemOperand::MOVolatile; 4094 if (isNonTemporal) 4095 MMOFlags |= MachineMemOperand::MONonTemporal; 4096 if (isInvariant) 4097 MMOFlags |= MachineMemOperand::MOInvariant; 4098 if (isDereferenceable) 4099 MMOFlags |= MachineMemOperand::MODereferenceable; 4100 MMOFlags |= TLI.getMMOFlags(I); 4101 4102 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4103 MachinePointerInfo(SV, Offsets[i]), Alignment, 4104 MMOFlags, AAInfo, Ranges); 4105 Chains[ChainI] = L.getValue(1); 4106 4107 if (MemVTs[i] != ValueVTs[i]) 4108 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4109 4110 Values[i] = L; 4111 } 4112 4113 if (!ConstantMemory) { 4114 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4115 makeArrayRef(Chains.data(), ChainI)); 4116 if (isVolatile) 4117 DAG.setRoot(Chain); 4118 else 4119 PendingLoads.push_back(Chain); 4120 } 4121 4122 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4123 DAG.getVTList(ValueVTs), Values)); 4124 } 4125 4126 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4127 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4128 "call visitStoreToSwiftError when backend supports swifterror"); 4129 4130 SmallVector<EVT, 4> ValueVTs; 4131 SmallVector<uint64_t, 4> Offsets; 4132 const Value *SrcV = I.getOperand(0); 4133 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4134 SrcV->getType(), ValueVTs, &Offsets); 4135 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4136 "expect a single EVT for swifterror"); 4137 4138 SDValue Src = getValue(SrcV); 4139 // Create a virtual register, then update the virtual register. 4140 Register VReg = 4141 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4142 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4143 // Chain can be getRoot or getControlRoot. 4144 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4145 SDValue(Src.getNode(), Src.getResNo())); 4146 DAG.setRoot(CopyNode); 4147 } 4148 4149 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4150 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4151 "call visitLoadFromSwiftError when backend supports swifterror"); 4152 4153 assert(!I.isVolatile() && 4154 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4155 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4156 "Support volatile, non temporal, invariant for load_from_swift_error"); 4157 4158 const Value *SV = I.getOperand(0); 4159 Type *Ty = I.getType(); 4160 AAMDNodes AAInfo; 4161 I.getAAMetadata(AAInfo); 4162 assert( 4163 (!AA || 4164 !AA->pointsToConstantMemory(MemoryLocation( 4165 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4166 AAInfo))) && 4167 "load_from_swift_error should not be constant memory"); 4168 4169 SmallVector<EVT, 4> ValueVTs; 4170 SmallVector<uint64_t, 4> Offsets; 4171 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4172 ValueVTs, &Offsets); 4173 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4174 "expect a single EVT for swifterror"); 4175 4176 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4177 SDValue L = DAG.getCopyFromReg( 4178 getRoot(), getCurSDLoc(), 4179 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4180 4181 setValue(&I, L); 4182 } 4183 4184 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4185 if (I.isAtomic()) 4186 return visitAtomicStore(I); 4187 4188 const Value *SrcV = I.getOperand(0); 4189 const Value *PtrV = I.getOperand(1); 4190 4191 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4192 if (TLI.supportSwiftError()) { 4193 // Swifterror values can come from either a function parameter with 4194 // swifterror attribute or an alloca with swifterror attribute. 4195 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4196 if (Arg->hasSwiftErrorAttr()) 4197 return visitStoreToSwiftError(I); 4198 } 4199 4200 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4201 if (Alloca->isSwiftError()) 4202 return visitStoreToSwiftError(I); 4203 } 4204 } 4205 4206 SmallVector<EVT, 4> ValueVTs, MemVTs; 4207 SmallVector<uint64_t, 4> Offsets; 4208 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4209 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4210 unsigned NumValues = ValueVTs.size(); 4211 if (NumValues == 0) 4212 return; 4213 4214 // Get the lowered operands. Note that we do this after 4215 // checking if NumResults is zero, because with zero results 4216 // the operands won't have values in the map. 4217 SDValue Src = getValue(SrcV); 4218 SDValue Ptr = getValue(PtrV); 4219 4220 SDValue Root = getRoot(); 4221 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4222 SDLoc dl = getCurSDLoc(); 4223 EVT PtrVT = Ptr.getValueType(); 4224 unsigned Alignment = I.getAlignment(); 4225 AAMDNodes AAInfo; 4226 I.getAAMetadata(AAInfo); 4227 4228 auto MMOFlags = MachineMemOperand::MONone; 4229 if (I.isVolatile()) 4230 MMOFlags |= MachineMemOperand::MOVolatile; 4231 if (I.hasMetadata(LLVMContext::MD_nontemporal)) 4232 MMOFlags |= MachineMemOperand::MONonTemporal; 4233 MMOFlags |= TLI.getMMOFlags(I); 4234 4235 // An aggregate load cannot wrap around the address space, so offsets to its 4236 // parts don't wrap either. 4237 SDNodeFlags Flags; 4238 Flags.setNoUnsignedWrap(true); 4239 4240 unsigned ChainI = 0; 4241 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4242 // See visitLoad comments. 4243 if (ChainI == MaxParallelChains) { 4244 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4245 makeArrayRef(Chains.data(), ChainI)); 4246 Root = Chain; 4247 ChainI = 0; 4248 } 4249 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, 4250 DAG.getConstant(Offsets[i], dl, PtrVT), Flags); 4251 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4252 if (MemVTs[i] != ValueVTs[i]) 4253 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4254 SDValue St = 4255 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4256 Alignment, MMOFlags, AAInfo); 4257 Chains[ChainI] = St; 4258 } 4259 4260 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4261 makeArrayRef(Chains.data(), ChainI)); 4262 DAG.setRoot(StoreNode); 4263 } 4264 4265 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4266 bool IsCompressing) { 4267 SDLoc sdl = getCurSDLoc(); 4268 4269 auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4270 unsigned& Alignment) { 4271 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4272 Src0 = I.getArgOperand(0); 4273 Ptr = I.getArgOperand(1); 4274 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 4275 Mask = I.getArgOperand(3); 4276 }; 4277 auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4278 unsigned& Alignment) { 4279 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4280 Src0 = I.getArgOperand(0); 4281 Ptr = I.getArgOperand(1); 4282 Mask = I.getArgOperand(2); 4283 Alignment = 0; 4284 }; 4285 4286 Value *PtrOperand, *MaskOperand, *Src0Operand; 4287 unsigned Alignment; 4288 if (IsCompressing) 4289 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4290 else 4291 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4292 4293 SDValue Ptr = getValue(PtrOperand); 4294 SDValue Src0 = getValue(Src0Operand); 4295 SDValue Mask = getValue(MaskOperand); 4296 4297 EVT VT = Src0.getValueType(); 4298 if (!Alignment) 4299 Alignment = DAG.getEVTAlignment(VT); 4300 4301 AAMDNodes AAInfo; 4302 I.getAAMetadata(AAInfo); 4303 4304 MachineMemOperand *MMO = 4305 DAG.getMachineFunction(). 4306 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4307 MachineMemOperand::MOStore, 4308 // TODO: Make MachineMemOperands aware of scalable 4309 // vectors. 4310 VT.getStoreSize().getKnownMinSize(), 4311 Alignment, AAInfo); 4312 SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT, 4313 MMO, false /* Truncating */, 4314 IsCompressing); 4315 DAG.setRoot(StoreNode); 4316 setValue(&I, StoreNode); 4317 } 4318 4319 // Get a uniform base for the Gather/Scatter intrinsic. 4320 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4321 // We try to represent it as a base pointer + vector of indices. 4322 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4323 // The first operand of the GEP may be a single pointer or a vector of pointers 4324 // Example: 4325 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4326 // or 4327 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4328 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4329 // 4330 // When the first GEP operand is a single pointer - it is the uniform base we 4331 // are looking for. If first operand of the GEP is a splat vector - we 4332 // extract the splat value and use it as a uniform base. 4333 // In all other cases the function returns 'false'. 4334 static bool getUniformBase(const Value *&Ptr, SDValue &Base, SDValue &Index, 4335 ISD::MemIndexType &IndexType, SDValue &Scale, 4336 SelectionDAGBuilder *SDB) { 4337 SelectionDAG& DAG = SDB->DAG; 4338 LLVMContext &Context = *DAG.getContext(); 4339 4340 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 4341 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4342 if (!GEP) 4343 return false; 4344 4345 const Value *GEPPtr = GEP->getPointerOperand(); 4346 if (!GEPPtr->getType()->isVectorTy()) 4347 Ptr = GEPPtr; 4348 else if (!(Ptr = getSplatValue(GEPPtr))) 4349 return false; 4350 4351 unsigned FinalIndex = GEP->getNumOperands() - 1; 4352 Value *IndexVal = GEP->getOperand(FinalIndex); 4353 4354 // Ensure all the other indices are 0. 4355 for (unsigned i = 1; i < FinalIndex; ++i) { 4356 auto *C = dyn_cast<Constant>(GEP->getOperand(i)); 4357 if (!C) 4358 return false; 4359 if (isa<VectorType>(C->getType())) 4360 C = C->getSplatValue(); 4361 auto *CI = dyn_cast_or_null<ConstantInt>(C); 4362 if (!CI || !CI->isZero()) 4363 return false; 4364 } 4365 4366 // The operands of the GEP may be defined in another basic block. 4367 // In this case we'll not find nodes for the operands. 4368 if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal)) 4369 return false; 4370 4371 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4372 const DataLayout &DL = DAG.getDataLayout(); 4373 Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()), 4374 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4375 Base = SDB->getValue(Ptr); 4376 Index = SDB->getValue(IndexVal); 4377 IndexType = ISD::SIGNED_SCALED; 4378 4379 if (!Index.getValueType().isVector()) { 4380 unsigned GEPWidth = GEP->getType()->getVectorNumElements(); 4381 EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth); 4382 Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index); 4383 } 4384 return true; 4385 } 4386 4387 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4388 SDLoc sdl = getCurSDLoc(); 4389 4390 // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask) 4391 const Value *Ptr = I.getArgOperand(1); 4392 SDValue Src0 = getValue(I.getArgOperand(0)); 4393 SDValue Mask = getValue(I.getArgOperand(3)); 4394 EVT VT = Src0.getValueType(); 4395 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue(); 4396 if (!Alignment) 4397 Alignment = DAG.getEVTAlignment(VT); 4398 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4399 4400 AAMDNodes AAInfo; 4401 I.getAAMetadata(AAInfo); 4402 4403 SDValue Base; 4404 SDValue Index; 4405 ISD::MemIndexType IndexType; 4406 SDValue Scale; 4407 const Value *BasePtr = Ptr; 4408 bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale, 4409 this); 4410 4411 const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr; 4412 MachineMemOperand *MMO = DAG.getMachineFunction(). 4413 getMachineMemOperand(MachinePointerInfo(MemOpBasePtr), 4414 MachineMemOperand::MOStore, 4415 // TODO: Make MachineMemOperands aware of scalable 4416 // vectors. 4417 VT.getStoreSize().getKnownMinSize(), 4418 Alignment, AAInfo); 4419 if (!UniformBase) { 4420 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4421 Index = getValue(Ptr); 4422 IndexType = ISD::SIGNED_SCALED; 4423 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4424 } 4425 SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale }; 4426 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4427 Ops, MMO, IndexType); 4428 DAG.setRoot(Scatter); 4429 setValue(&I, Scatter); 4430 } 4431 4432 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4433 SDLoc sdl = getCurSDLoc(); 4434 4435 auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4436 unsigned& Alignment) { 4437 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4438 Ptr = I.getArgOperand(0); 4439 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 4440 Mask = I.getArgOperand(2); 4441 Src0 = I.getArgOperand(3); 4442 }; 4443 auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4444 unsigned& Alignment) { 4445 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4446 Ptr = I.getArgOperand(0); 4447 Alignment = 0; 4448 Mask = I.getArgOperand(1); 4449 Src0 = I.getArgOperand(2); 4450 }; 4451 4452 Value *PtrOperand, *MaskOperand, *Src0Operand; 4453 unsigned Alignment; 4454 if (IsExpanding) 4455 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4456 else 4457 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4458 4459 SDValue Ptr = getValue(PtrOperand); 4460 SDValue Src0 = getValue(Src0Operand); 4461 SDValue Mask = getValue(MaskOperand); 4462 4463 EVT VT = Src0.getValueType(); 4464 if (!Alignment) 4465 Alignment = DAG.getEVTAlignment(VT); 4466 4467 AAMDNodes AAInfo; 4468 I.getAAMetadata(AAInfo); 4469 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4470 4471 // Do not serialize masked loads of constant memory with anything. 4472 MemoryLocation ML; 4473 if (VT.isScalableVector()) 4474 ML = MemoryLocation(PtrOperand); 4475 else 4476 ML = MemoryLocation(PtrOperand, LocationSize::precise( 4477 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4478 AAInfo); 4479 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4480 4481 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4482 4483 MachineMemOperand *MMO = 4484 DAG.getMachineFunction(). 4485 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4486 MachineMemOperand::MOLoad, 4487 // TODO: Make MachineMemOperands aware of scalable 4488 // vectors. 4489 VT.getStoreSize().getKnownMinSize(), 4490 Alignment, AAInfo, Ranges); 4491 4492 SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO, 4493 ISD::NON_EXTLOAD, IsExpanding); 4494 if (AddToChain) 4495 PendingLoads.push_back(Load.getValue(1)); 4496 setValue(&I, Load); 4497 } 4498 4499 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4500 SDLoc sdl = getCurSDLoc(); 4501 4502 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4503 const Value *Ptr = I.getArgOperand(0); 4504 SDValue Src0 = getValue(I.getArgOperand(3)); 4505 SDValue Mask = getValue(I.getArgOperand(2)); 4506 4507 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4508 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4509 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue(); 4510 if (!Alignment) 4511 Alignment = DAG.getEVTAlignment(VT); 4512 4513 AAMDNodes AAInfo; 4514 I.getAAMetadata(AAInfo); 4515 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4516 4517 SDValue Root = DAG.getRoot(); 4518 SDValue Base; 4519 SDValue Index; 4520 ISD::MemIndexType IndexType; 4521 SDValue Scale; 4522 const Value *BasePtr = Ptr; 4523 bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale, 4524 this); 4525 bool ConstantMemory = false; 4526 if (UniformBase && AA && 4527 AA->pointsToConstantMemory( 4528 MemoryLocation(BasePtr, 4529 LocationSize::precise( 4530 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4531 AAInfo))) { 4532 // Do not serialize (non-volatile) loads of constant memory with anything. 4533 Root = DAG.getEntryNode(); 4534 ConstantMemory = true; 4535 } 4536 4537 MachineMemOperand *MMO = 4538 DAG.getMachineFunction(). 4539 getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr), 4540 MachineMemOperand::MOLoad, 4541 // TODO: Make MachineMemOperands aware of scalable 4542 // vectors. 4543 VT.getStoreSize().getKnownMinSize(), 4544 Alignment, AAInfo, Ranges); 4545 4546 if (!UniformBase) { 4547 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4548 Index = getValue(Ptr); 4549 IndexType = ISD::SIGNED_SCALED; 4550 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4551 } 4552 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4553 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4554 Ops, MMO, IndexType); 4555 4556 SDValue OutChain = Gather.getValue(1); 4557 if (!ConstantMemory) 4558 PendingLoads.push_back(OutChain); 4559 setValue(&I, Gather); 4560 } 4561 4562 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4563 SDLoc dl = getCurSDLoc(); 4564 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4565 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4566 SyncScope::ID SSID = I.getSyncScopeID(); 4567 4568 SDValue InChain = getRoot(); 4569 4570 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4571 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4572 4573 auto Alignment = DAG.getEVTAlignment(MemVT); 4574 4575 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 4576 if (I.isVolatile()) 4577 Flags |= MachineMemOperand::MOVolatile; 4578 Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I); 4579 4580 MachineFunction &MF = DAG.getMachineFunction(); 4581 MachineMemOperand *MMO = 4582 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4583 Flags, MemVT.getStoreSize(), Alignment, 4584 AAMDNodes(), nullptr, SSID, SuccessOrdering, 4585 FailureOrdering); 4586 4587 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4588 dl, MemVT, VTs, InChain, 4589 getValue(I.getPointerOperand()), 4590 getValue(I.getCompareOperand()), 4591 getValue(I.getNewValOperand()), MMO); 4592 4593 SDValue OutChain = L.getValue(2); 4594 4595 setValue(&I, L); 4596 DAG.setRoot(OutChain); 4597 } 4598 4599 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4600 SDLoc dl = getCurSDLoc(); 4601 ISD::NodeType NT; 4602 switch (I.getOperation()) { 4603 default: llvm_unreachable("Unknown atomicrmw operation"); 4604 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4605 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4606 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4607 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4608 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4609 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4610 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4611 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4612 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4613 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4614 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4615 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4616 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4617 } 4618 AtomicOrdering Ordering = I.getOrdering(); 4619 SyncScope::ID SSID = I.getSyncScopeID(); 4620 4621 SDValue InChain = getRoot(); 4622 4623 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4624 auto Alignment = DAG.getEVTAlignment(MemVT); 4625 4626 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 4627 if (I.isVolatile()) 4628 Flags |= MachineMemOperand::MOVolatile; 4629 Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I); 4630 4631 MachineFunction &MF = DAG.getMachineFunction(); 4632 MachineMemOperand *MMO = 4633 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags, 4634 MemVT.getStoreSize(), Alignment, AAMDNodes(), 4635 nullptr, SSID, Ordering); 4636 4637 SDValue L = 4638 DAG.getAtomic(NT, dl, MemVT, InChain, 4639 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4640 MMO); 4641 4642 SDValue OutChain = L.getValue(1); 4643 4644 setValue(&I, L); 4645 DAG.setRoot(OutChain); 4646 } 4647 4648 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4649 SDLoc dl = getCurSDLoc(); 4650 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4651 SDValue Ops[3]; 4652 Ops[0] = getRoot(); 4653 Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl, 4654 TLI.getFenceOperandTy(DAG.getDataLayout())); 4655 Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl, 4656 TLI.getFenceOperandTy(DAG.getDataLayout())); 4657 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4658 } 4659 4660 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4661 SDLoc dl = getCurSDLoc(); 4662 AtomicOrdering Order = I.getOrdering(); 4663 SyncScope::ID SSID = I.getSyncScopeID(); 4664 4665 SDValue InChain = getRoot(); 4666 4667 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4668 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4669 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4670 4671 if (!TLI.supportsUnalignedAtomics() && 4672 I.getAlignment() < MemVT.getSizeInBits() / 8) 4673 report_fatal_error("Cannot generate unaligned atomic load"); 4674 4675 auto Flags = MachineMemOperand::MOLoad; 4676 if (I.isVolatile()) 4677 Flags |= MachineMemOperand::MOVolatile; 4678 if (I.hasMetadata(LLVMContext::MD_invariant_load)) 4679 Flags |= MachineMemOperand::MOInvariant; 4680 if (isDereferenceablePointer(I.getPointerOperand(), I.getType(), 4681 DAG.getDataLayout())) 4682 Flags |= MachineMemOperand::MODereferenceable; 4683 4684 Flags |= TLI.getMMOFlags(I); 4685 4686 MachineMemOperand *MMO = 4687 DAG.getMachineFunction(). 4688 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4689 Flags, MemVT.getStoreSize(), 4690 I.getAlignment() ? I.getAlignment() : 4691 DAG.getEVTAlignment(MemVT), 4692 AAMDNodes(), nullptr, SSID, Order); 4693 4694 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4695 4696 SDValue Ptr = getValue(I.getPointerOperand()); 4697 4698 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4699 // TODO: Once this is better exercised by tests, it should be merged with 4700 // the normal path for loads to prevent future divergence. 4701 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4702 if (MemVT != VT) 4703 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4704 4705 setValue(&I, L); 4706 SDValue OutChain = L.getValue(1); 4707 if (!I.isUnordered()) 4708 DAG.setRoot(OutChain); 4709 else 4710 PendingLoads.push_back(OutChain); 4711 return; 4712 } 4713 4714 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4715 Ptr, MMO); 4716 4717 SDValue OutChain = L.getValue(1); 4718 if (MemVT != VT) 4719 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4720 4721 setValue(&I, L); 4722 DAG.setRoot(OutChain); 4723 } 4724 4725 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4726 SDLoc dl = getCurSDLoc(); 4727 4728 AtomicOrdering Ordering = I.getOrdering(); 4729 SyncScope::ID SSID = I.getSyncScopeID(); 4730 4731 SDValue InChain = getRoot(); 4732 4733 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4734 EVT MemVT = 4735 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4736 4737 if (I.getAlignment() < MemVT.getSizeInBits() / 8) 4738 report_fatal_error("Cannot generate unaligned atomic store"); 4739 4740 auto Flags = MachineMemOperand::MOStore; 4741 if (I.isVolatile()) 4742 Flags |= MachineMemOperand::MOVolatile; 4743 Flags |= TLI.getMMOFlags(I); 4744 4745 MachineFunction &MF = DAG.getMachineFunction(); 4746 MachineMemOperand *MMO = 4747 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags, 4748 MemVT.getStoreSize(), I.getAlignment(), AAMDNodes(), 4749 nullptr, SSID, Ordering); 4750 4751 SDValue Val = getValue(I.getValueOperand()); 4752 if (Val.getValueType() != MemVT) 4753 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4754 SDValue Ptr = getValue(I.getPointerOperand()); 4755 4756 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4757 // TODO: Once this is better exercised by tests, it should be merged with 4758 // the normal path for stores to prevent future divergence. 4759 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4760 DAG.setRoot(S); 4761 return; 4762 } 4763 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4764 Ptr, Val, MMO); 4765 4766 4767 DAG.setRoot(OutChain); 4768 } 4769 4770 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4771 /// node. 4772 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4773 unsigned Intrinsic) { 4774 // Ignore the callsite's attributes. A specific call site may be marked with 4775 // readnone, but the lowering code will expect the chain based on the 4776 // definition. 4777 const Function *F = I.getCalledFunction(); 4778 bool HasChain = !F->doesNotAccessMemory(); 4779 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4780 4781 // Build the operand list. 4782 SmallVector<SDValue, 8> Ops; 4783 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4784 if (OnlyLoad) { 4785 // We don't need to serialize loads against other loads. 4786 Ops.push_back(DAG.getRoot()); 4787 } else { 4788 Ops.push_back(getRoot()); 4789 } 4790 } 4791 4792 // Info is set by getTgtMemInstrinsic 4793 TargetLowering::IntrinsicInfo Info; 4794 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4795 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4796 DAG.getMachineFunction(), 4797 Intrinsic); 4798 4799 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4800 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4801 Info.opc == ISD::INTRINSIC_W_CHAIN) 4802 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4803 TLI.getPointerTy(DAG.getDataLayout()))); 4804 4805 // Add all operands of the call to the operand list. 4806 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4807 const Value *Arg = I.getArgOperand(i); 4808 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4809 Ops.push_back(getValue(Arg)); 4810 continue; 4811 } 4812 4813 // Use TargetConstant instead of a regular constant for immarg. 4814 EVT VT = TLI.getValueType(*DL, Arg->getType(), true); 4815 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4816 assert(CI->getBitWidth() <= 64 && 4817 "large intrinsic immediates not handled"); 4818 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4819 } else { 4820 Ops.push_back( 4821 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4822 } 4823 } 4824 4825 SmallVector<EVT, 4> ValueVTs; 4826 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4827 4828 if (HasChain) 4829 ValueVTs.push_back(MVT::Other); 4830 4831 SDVTList VTs = DAG.getVTList(ValueVTs); 4832 4833 // Create the node. 4834 SDValue Result; 4835 if (IsTgtIntrinsic) { 4836 // This is target intrinsic that touches memory 4837 AAMDNodes AAInfo; 4838 I.getAAMetadata(AAInfo); 4839 Result = DAG.getMemIntrinsicNode( 4840 Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT, 4841 MachinePointerInfo(Info.ptrVal, Info.offset), 4842 Info.align ? Info.align->value() : 0, Info.flags, Info.size, AAInfo); 4843 } else if (!HasChain) { 4844 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4845 } else if (!I.getType()->isVoidTy()) { 4846 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4847 } else { 4848 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4849 } 4850 4851 if (HasChain) { 4852 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4853 if (OnlyLoad) 4854 PendingLoads.push_back(Chain); 4855 else 4856 DAG.setRoot(Chain); 4857 } 4858 4859 if (!I.getType()->isVoidTy()) { 4860 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4861 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4862 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4863 } else 4864 Result = lowerRangeToAssertZExt(DAG, I, Result); 4865 4866 setValue(&I, Result); 4867 } 4868 } 4869 4870 /// GetSignificand - Get the significand and build it into a floating-point 4871 /// number with exponent of 1: 4872 /// 4873 /// Op = (Op & 0x007fffff) | 0x3f800000; 4874 /// 4875 /// where Op is the hexadecimal representation of floating point value. 4876 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4877 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4878 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4879 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4880 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4881 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4882 } 4883 4884 /// GetExponent - Get the exponent: 4885 /// 4886 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4887 /// 4888 /// where Op is the hexadecimal representation of floating point value. 4889 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4890 const TargetLowering &TLI, const SDLoc &dl) { 4891 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4892 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4893 SDValue t1 = DAG.getNode( 4894 ISD::SRL, dl, MVT::i32, t0, 4895 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4896 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4897 DAG.getConstant(127, dl, MVT::i32)); 4898 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4899 } 4900 4901 /// getF32Constant - Get 32-bit floating point constant. 4902 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4903 const SDLoc &dl) { 4904 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4905 MVT::f32); 4906 } 4907 4908 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4909 SelectionDAG &DAG) { 4910 // TODO: What fast-math-flags should be set on the floating-point nodes? 4911 4912 // IntegerPartOfX = ((int32_t)(t0); 4913 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4914 4915 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4916 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4917 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4918 4919 // IntegerPartOfX <<= 23; 4920 IntegerPartOfX = DAG.getNode( 4921 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4922 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4923 DAG.getDataLayout()))); 4924 4925 SDValue TwoToFractionalPartOfX; 4926 if (LimitFloatPrecision <= 6) { 4927 // For floating-point precision of 6: 4928 // 4929 // TwoToFractionalPartOfX = 4930 // 0.997535578f + 4931 // (0.735607626f + 0.252464424f * x) * x; 4932 // 4933 // error 0.0144103317, which is 6 bits 4934 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4935 getF32Constant(DAG, 0x3e814304, dl)); 4936 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4937 getF32Constant(DAG, 0x3f3c50c8, dl)); 4938 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4939 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4940 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4941 } else if (LimitFloatPrecision <= 12) { 4942 // For floating-point precision of 12: 4943 // 4944 // TwoToFractionalPartOfX = 4945 // 0.999892986f + 4946 // (0.696457318f + 4947 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4948 // 4949 // error 0.000107046256, which is 13 to 14 bits 4950 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4951 getF32Constant(DAG, 0x3da235e3, dl)); 4952 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4953 getF32Constant(DAG, 0x3e65b8f3, dl)); 4954 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4955 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4956 getF32Constant(DAG, 0x3f324b07, dl)); 4957 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4958 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4959 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4960 } else { // LimitFloatPrecision <= 18 4961 // For floating-point precision of 18: 4962 // 4963 // TwoToFractionalPartOfX = 4964 // 0.999999982f + 4965 // (0.693148872f + 4966 // (0.240227044f + 4967 // (0.554906021e-1f + 4968 // (0.961591928e-2f + 4969 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4970 // error 2.47208000*10^(-7), which is better than 18 bits 4971 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4972 getF32Constant(DAG, 0x3924b03e, dl)); 4973 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4974 getF32Constant(DAG, 0x3ab24b87, dl)); 4975 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4976 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4977 getF32Constant(DAG, 0x3c1d8c17, dl)); 4978 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4979 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4980 getF32Constant(DAG, 0x3d634a1d, dl)); 4981 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4982 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4983 getF32Constant(DAG, 0x3e75fe14, dl)); 4984 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4985 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4986 getF32Constant(DAG, 0x3f317234, dl)); 4987 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4988 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4989 getF32Constant(DAG, 0x3f800000, dl)); 4990 } 4991 4992 // Add the exponent into the result in integer domain. 4993 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4994 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4995 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4996 } 4997 4998 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4999 /// limited-precision mode. 5000 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5001 const TargetLowering &TLI) { 5002 if (Op.getValueType() == MVT::f32 && 5003 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5004 5005 // Put the exponent in the right bit position for later addition to the 5006 // final result: 5007 // 5008 // t0 = Op * log2(e) 5009 5010 // TODO: What fast-math-flags should be set here? 5011 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5012 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5013 return getLimitedPrecisionExp2(t0, dl, DAG); 5014 } 5015 5016 // No special expansion. 5017 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op); 5018 } 5019 5020 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5021 /// limited-precision mode. 5022 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5023 const TargetLowering &TLI) { 5024 // TODO: What fast-math-flags should be set on the floating-point nodes? 5025 5026 if (Op.getValueType() == MVT::f32 && 5027 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5028 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5029 5030 // Scale the exponent by log(2). 5031 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5032 SDValue LogOfExponent = 5033 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5034 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5035 5036 // Get the significand and build it into a floating-point number with 5037 // exponent of 1. 5038 SDValue X = GetSignificand(DAG, Op1, dl); 5039 5040 SDValue LogOfMantissa; 5041 if (LimitFloatPrecision <= 6) { 5042 // For floating-point precision of 6: 5043 // 5044 // LogofMantissa = 5045 // -1.1609546f + 5046 // (1.4034025f - 0.23903021f * x) * x; 5047 // 5048 // error 0.0034276066, which is better than 8 bits 5049 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5050 getF32Constant(DAG, 0xbe74c456, dl)); 5051 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5052 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5053 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5054 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5055 getF32Constant(DAG, 0x3f949a29, dl)); 5056 } else if (LimitFloatPrecision <= 12) { 5057 // For floating-point precision of 12: 5058 // 5059 // LogOfMantissa = 5060 // -1.7417939f + 5061 // (2.8212026f + 5062 // (-1.4699568f + 5063 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5064 // 5065 // error 0.000061011436, which is 14 bits 5066 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5067 getF32Constant(DAG, 0xbd67b6d6, dl)); 5068 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5069 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5070 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5071 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5072 getF32Constant(DAG, 0x3fbc278b, dl)); 5073 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5074 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5075 getF32Constant(DAG, 0x40348e95, dl)); 5076 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5077 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5078 getF32Constant(DAG, 0x3fdef31a, dl)); 5079 } else { // LimitFloatPrecision <= 18 5080 // For floating-point precision of 18: 5081 // 5082 // LogOfMantissa = 5083 // -2.1072184f + 5084 // (4.2372794f + 5085 // (-3.7029485f + 5086 // (2.2781945f + 5087 // (-0.87823314f + 5088 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5089 // 5090 // error 0.0000023660568, which is better than 18 bits 5091 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5092 getF32Constant(DAG, 0xbc91e5ac, dl)); 5093 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5094 getF32Constant(DAG, 0x3e4350aa, dl)); 5095 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5096 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5097 getF32Constant(DAG, 0x3f60d3e3, dl)); 5098 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5099 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5100 getF32Constant(DAG, 0x4011cdf0, dl)); 5101 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5102 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5103 getF32Constant(DAG, 0x406cfd1c, dl)); 5104 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5105 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5106 getF32Constant(DAG, 0x408797cb, dl)); 5107 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5108 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5109 getF32Constant(DAG, 0x4006dcab, dl)); 5110 } 5111 5112 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5113 } 5114 5115 // No special expansion. 5116 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op); 5117 } 5118 5119 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5120 /// limited-precision mode. 5121 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5122 const TargetLowering &TLI) { 5123 // TODO: What fast-math-flags should be set on the floating-point nodes? 5124 5125 if (Op.getValueType() == MVT::f32 && 5126 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5127 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5128 5129 // Get the exponent. 5130 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5131 5132 // Get the significand and build it into a floating-point number with 5133 // exponent of 1. 5134 SDValue X = GetSignificand(DAG, Op1, dl); 5135 5136 // Different possible minimax approximations of significand in 5137 // floating-point for various degrees of accuracy over [1,2]. 5138 SDValue Log2ofMantissa; 5139 if (LimitFloatPrecision <= 6) { 5140 // For floating-point precision of 6: 5141 // 5142 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5143 // 5144 // error 0.0049451742, which is more than 7 bits 5145 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5146 getF32Constant(DAG, 0xbeb08fe0, dl)); 5147 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5148 getF32Constant(DAG, 0x40019463, dl)); 5149 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5150 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5151 getF32Constant(DAG, 0x3fd6633d, dl)); 5152 } else if (LimitFloatPrecision <= 12) { 5153 // For floating-point precision of 12: 5154 // 5155 // Log2ofMantissa = 5156 // -2.51285454f + 5157 // (4.07009056f + 5158 // (-2.12067489f + 5159 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5160 // 5161 // error 0.0000876136000, which is better than 13 bits 5162 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5163 getF32Constant(DAG, 0xbda7262e, dl)); 5164 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5165 getF32Constant(DAG, 0x3f25280b, dl)); 5166 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5167 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5168 getF32Constant(DAG, 0x4007b923, dl)); 5169 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5170 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5171 getF32Constant(DAG, 0x40823e2f, dl)); 5172 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5173 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5174 getF32Constant(DAG, 0x4020d29c, dl)); 5175 } else { // LimitFloatPrecision <= 18 5176 // For floating-point precision of 18: 5177 // 5178 // Log2ofMantissa = 5179 // -3.0400495f + 5180 // (6.1129976f + 5181 // (-5.3420409f + 5182 // (3.2865683f + 5183 // (-1.2669343f + 5184 // (0.27515199f - 5185 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5186 // 5187 // error 0.0000018516, which is better than 18 bits 5188 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5189 getF32Constant(DAG, 0xbcd2769e, dl)); 5190 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5191 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5192 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5193 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5194 getF32Constant(DAG, 0x3fa22ae7, dl)); 5195 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5196 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5197 getF32Constant(DAG, 0x40525723, dl)); 5198 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5199 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5200 getF32Constant(DAG, 0x40aaf200, dl)); 5201 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5202 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5203 getF32Constant(DAG, 0x40c39dad, dl)); 5204 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5205 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5206 getF32Constant(DAG, 0x4042902c, dl)); 5207 } 5208 5209 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5210 } 5211 5212 // No special expansion. 5213 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op); 5214 } 5215 5216 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5217 /// limited-precision mode. 5218 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5219 const TargetLowering &TLI) { 5220 // TODO: What fast-math-flags should be set on the floating-point nodes? 5221 5222 if (Op.getValueType() == MVT::f32 && 5223 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5224 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5225 5226 // Scale the exponent by log10(2) [0.30102999f]. 5227 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5228 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5229 getF32Constant(DAG, 0x3e9a209a, dl)); 5230 5231 // Get the significand and build it into a floating-point number with 5232 // exponent of 1. 5233 SDValue X = GetSignificand(DAG, Op1, dl); 5234 5235 SDValue Log10ofMantissa; 5236 if (LimitFloatPrecision <= 6) { 5237 // For floating-point precision of 6: 5238 // 5239 // Log10ofMantissa = 5240 // -0.50419619f + 5241 // (0.60948995f - 0.10380950f * x) * x; 5242 // 5243 // error 0.0014886165, which is 6 bits 5244 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5245 getF32Constant(DAG, 0xbdd49a13, dl)); 5246 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5247 getF32Constant(DAG, 0x3f1c0789, dl)); 5248 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5249 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5250 getF32Constant(DAG, 0x3f011300, dl)); 5251 } else if (LimitFloatPrecision <= 12) { 5252 // For floating-point precision of 12: 5253 // 5254 // Log10ofMantissa = 5255 // -0.64831180f + 5256 // (0.91751397f + 5257 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5258 // 5259 // error 0.00019228036, which is better than 12 bits 5260 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5261 getF32Constant(DAG, 0x3d431f31, dl)); 5262 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5263 getF32Constant(DAG, 0x3ea21fb2, dl)); 5264 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5265 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5266 getF32Constant(DAG, 0x3f6ae232, dl)); 5267 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5268 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5269 getF32Constant(DAG, 0x3f25f7c3, dl)); 5270 } else { // LimitFloatPrecision <= 18 5271 // For floating-point precision of 18: 5272 // 5273 // Log10ofMantissa = 5274 // -0.84299375f + 5275 // (1.5327582f + 5276 // (-1.0688956f + 5277 // (0.49102474f + 5278 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5279 // 5280 // error 0.0000037995730, which is better than 18 bits 5281 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5282 getF32Constant(DAG, 0x3c5d51ce, dl)); 5283 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5284 getF32Constant(DAG, 0x3e00685a, dl)); 5285 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5286 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5287 getF32Constant(DAG, 0x3efb6798, dl)); 5288 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5289 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5290 getF32Constant(DAG, 0x3f88d192, dl)); 5291 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5292 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5293 getF32Constant(DAG, 0x3fc4316c, dl)); 5294 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5295 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5296 getF32Constant(DAG, 0x3f57ce70, dl)); 5297 } 5298 5299 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5300 } 5301 5302 // No special expansion. 5303 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op); 5304 } 5305 5306 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5307 /// limited-precision mode. 5308 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5309 const TargetLowering &TLI) { 5310 if (Op.getValueType() == MVT::f32 && 5311 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5312 return getLimitedPrecisionExp2(Op, dl, DAG); 5313 5314 // No special expansion. 5315 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op); 5316 } 5317 5318 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5319 /// limited-precision mode with x == 10.0f. 5320 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5321 SelectionDAG &DAG, const TargetLowering &TLI) { 5322 bool IsExp10 = false; 5323 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5324 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5325 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5326 APFloat Ten(10.0f); 5327 IsExp10 = LHSC->isExactlyValue(Ten); 5328 } 5329 } 5330 5331 // TODO: What fast-math-flags should be set on the FMUL node? 5332 if (IsExp10) { 5333 // Put the exponent in the right bit position for later addition to the 5334 // final result: 5335 // 5336 // #define LOG2OF10 3.3219281f 5337 // t0 = Op * LOG2OF10; 5338 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5339 getF32Constant(DAG, 0x40549a78, dl)); 5340 return getLimitedPrecisionExp2(t0, dl, DAG); 5341 } 5342 5343 // No special expansion. 5344 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS); 5345 } 5346 5347 /// ExpandPowI - Expand a llvm.powi intrinsic. 5348 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5349 SelectionDAG &DAG) { 5350 // If RHS is a constant, we can expand this out to a multiplication tree, 5351 // otherwise we end up lowering to a call to __powidf2 (for example). When 5352 // optimizing for size, we only want to do this if the expansion would produce 5353 // a small number of multiplies, otherwise we do the full expansion. 5354 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5355 // Get the exponent as a positive value. 5356 unsigned Val = RHSC->getSExtValue(); 5357 if ((int)Val < 0) Val = -Val; 5358 5359 // powi(x, 0) -> 1.0 5360 if (Val == 0) 5361 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5362 5363 const Function &F = DAG.getMachineFunction().getFunction(); 5364 if (!F.hasOptSize() || 5365 // If optimizing for size, don't insert too many multiplies. 5366 // This inserts up to 5 multiplies. 5367 countPopulation(Val) + Log2_32(Val) < 7) { 5368 // We use the simple binary decomposition method to generate the multiply 5369 // sequence. There are more optimal ways to do this (for example, 5370 // powi(x,15) generates one more multiply than it should), but this has 5371 // the benefit of being both really simple and much better than a libcall. 5372 SDValue Res; // Logically starts equal to 1.0 5373 SDValue CurSquare = LHS; 5374 // TODO: Intrinsics should have fast-math-flags that propagate to these 5375 // nodes. 5376 while (Val) { 5377 if (Val & 1) { 5378 if (Res.getNode()) 5379 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 5380 else 5381 Res = CurSquare; // 1.0*CurSquare. 5382 } 5383 5384 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5385 CurSquare, CurSquare); 5386 Val >>= 1; 5387 } 5388 5389 // If the original was negative, invert the result, producing 1/(x*x*x). 5390 if (RHSC->getSExtValue() < 0) 5391 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5392 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5393 return Res; 5394 } 5395 } 5396 5397 // Otherwise, expand to a libcall. 5398 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5399 } 5400 5401 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5402 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5403 static void 5404 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs, 5405 const SDValue &N) { 5406 switch (N.getOpcode()) { 5407 case ISD::CopyFromReg: { 5408 SDValue Op = N.getOperand(1); 5409 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5410 Op.getValueType().getSizeInBits()); 5411 return; 5412 } 5413 case ISD::BITCAST: 5414 case ISD::AssertZext: 5415 case ISD::AssertSext: 5416 case ISD::TRUNCATE: 5417 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5418 return; 5419 case ISD::BUILD_PAIR: 5420 case ISD::BUILD_VECTOR: 5421 case ISD::CONCAT_VECTORS: 5422 for (SDValue Op : N->op_values()) 5423 getUnderlyingArgRegs(Regs, Op); 5424 return; 5425 default: 5426 return; 5427 } 5428 } 5429 5430 /// If the DbgValueInst is a dbg_value of a function argument, create the 5431 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5432 /// instruction selection, they will be inserted to the entry BB. 5433 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5434 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5435 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 5436 const Argument *Arg = dyn_cast<Argument>(V); 5437 if (!Arg) 5438 return false; 5439 5440 if (!IsDbgDeclare) { 5441 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5442 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5443 // the entry block. 5444 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5445 if (!IsInEntryBlock) 5446 return false; 5447 5448 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5449 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5450 // variable that also is a param. 5451 // 5452 // Although, if we are at the top of the entry block already, we can still 5453 // emit using ArgDbgValue. This might catch some situations when the 5454 // dbg.value refers to an argument that isn't used in the entry block, so 5455 // any CopyToReg node would be optimized out and the only way to express 5456 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5457 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5458 // we should only emit as ArgDbgValue if the Variable is an argument to the 5459 // current function, and the dbg.value intrinsic is found in the entry 5460 // block. 5461 bool VariableIsFunctionInputArg = Variable->isParameter() && 5462 !DL->getInlinedAt(); 5463 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5464 if (!IsInPrologue && !VariableIsFunctionInputArg) 5465 return false; 5466 5467 // Here we assume that a function argument on IR level only can be used to 5468 // describe one input parameter on source level. If we for example have 5469 // source code like this 5470 // 5471 // struct A { long x, y; }; 5472 // void foo(struct A a, long b) { 5473 // ... 5474 // b = a.x; 5475 // ... 5476 // } 5477 // 5478 // and IR like this 5479 // 5480 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5481 // entry: 5482 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5483 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5484 // call void @llvm.dbg.value(metadata i32 %b, "b", 5485 // ... 5486 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5487 // ... 5488 // 5489 // then the last dbg.value is describing a parameter "b" using a value that 5490 // is an argument. But since we already has used %a1 to describe a parameter 5491 // we should not handle that last dbg.value here (that would result in an 5492 // incorrect hoisting of the DBG_VALUE to the function entry). 5493 // Notice that we allow one dbg.value per IR level argument, to accommodate 5494 // for the situation with fragments above. 5495 if (VariableIsFunctionInputArg) { 5496 unsigned ArgNo = Arg->getArgNo(); 5497 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5498 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5499 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5500 return false; 5501 FuncInfo.DescribedArgs.set(ArgNo); 5502 } 5503 } 5504 5505 MachineFunction &MF = DAG.getMachineFunction(); 5506 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5507 5508 Optional<MachineOperand> Op; 5509 // Some arguments' frame index is recorded during argument lowering. 5510 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5511 if (FI != std::numeric_limits<int>::max()) 5512 Op = MachineOperand::CreateFI(FI); 5513 5514 SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes; 5515 if (!Op && N.getNode()) { 5516 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5517 Register Reg; 5518 if (ArgRegsAndSizes.size() == 1) 5519 Reg = ArgRegsAndSizes.front().first; 5520 5521 if (Reg && Reg.isVirtual()) { 5522 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5523 Register PR = RegInfo.getLiveInPhysReg(Reg); 5524 if (PR) 5525 Reg = PR; 5526 } 5527 if (Reg) { 5528 Op = MachineOperand::CreateReg(Reg, false); 5529 } 5530 } 5531 5532 if (!Op && N.getNode()) { 5533 // Check if frame index is available. 5534 SDValue LCandidate = peekThroughBitcasts(N); 5535 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5536 if (FrameIndexSDNode *FINode = 5537 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5538 Op = MachineOperand::CreateFI(FINode->getIndex()); 5539 } 5540 5541 if (!Op) { 5542 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5543 auto splitMultiRegDbgValue 5544 = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) { 5545 unsigned Offset = 0; 5546 for (auto RegAndSize : SplitRegs) { 5547 auto FragmentExpr = DIExpression::createFragmentExpression( 5548 Expr, Offset, RegAndSize.second); 5549 if (!FragmentExpr) 5550 continue; 5551 assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?"); 5552 FuncInfo.ArgDbgValues.push_back( 5553 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), false, 5554 RegAndSize.first, Variable, *FragmentExpr)); 5555 Offset += RegAndSize.second; 5556 } 5557 }; 5558 5559 // Check if ValueMap has reg number. 5560 DenseMap<const Value *, unsigned>::const_iterator 5561 VMI = FuncInfo.ValueMap.find(V); 5562 if (VMI != FuncInfo.ValueMap.end()) { 5563 const auto &TLI = DAG.getTargetLoweringInfo(); 5564 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5565 V->getType(), getABIRegCopyCC(V)); 5566 if (RFV.occupiesMultipleRegs()) { 5567 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5568 return true; 5569 } 5570 5571 Op = MachineOperand::CreateReg(VMI->second, false); 5572 } else if (ArgRegsAndSizes.size() > 1) { 5573 // This was split due to the calling convention, and no virtual register 5574 // mapping exists for the value. 5575 splitMultiRegDbgValue(ArgRegsAndSizes); 5576 return true; 5577 } 5578 } 5579 5580 if (!Op) 5581 return false; 5582 5583 assert(Variable->isValidLocationForIntrinsic(DL) && 5584 "Expected inlined-at fields to agree"); 5585 5586 // If the argument arrives in a stack slot, then what the IR thought was a 5587 // normal Value is actually in memory, and we must add a deref to load it. 5588 if (Op->isFI()) { 5589 int FI = Op->getIndex(); 5590 unsigned Size = DAG.getMachineFunction().getFrameInfo().getObjectSize(FI); 5591 if (Expr->isImplicit()) { 5592 SmallVector<uint64_t, 2> Ops = {dwarf::DW_OP_deref_size, Size}; 5593 Expr = DIExpression::prependOpcodes(Expr, Ops); 5594 } else { 5595 Expr = DIExpression::prepend(Expr, DIExpression::DerefBefore); 5596 } 5597 } 5598 5599 // If this location was specified with a dbg.declare, then it and its 5600 // expression calculate the address of the variable. Append a deref to 5601 // force it to be a memory location. 5602 if (IsDbgDeclare) 5603 Expr = DIExpression::append(Expr, {dwarf::DW_OP_deref}); 5604 5605 FuncInfo.ArgDbgValues.push_back( 5606 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), false, 5607 *Op, Variable, Expr)); 5608 5609 return true; 5610 } 5611 5612 /// Return the appropriate SDDbgValue based on N. 5613 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5614 DILocalVariable *Variable, 5615 DIExpression *Expr, 5616 const DebugLoc &dl, 5617 unsigned DbgSDNodeOrder) { 5618 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5619 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5620 // stack slot locations. 5621 // 5622 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5623 // debug values here after optimization: 5624 // 5625 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5626 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5627 // 5628 // Both describe the direct values of their associated variables. 5629 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5630 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5631 } 5632 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5633 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5634 } 5635 5636 // VisualStudio defines setjmp as _setjmp 5637 #if defined(_MSC_VER) && defined(setjmp) && \ 5638 !defined(setjmp_undefined_for_msvc) 5639 # pragma push_macro("setjmp") 5640 # undef setjmp 5641 # define setjmp_undefined_for_msvc 5642 #endif 5643 5644 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5645 switch (Intrinsic) { 5646 case Intrinsic::smul_fix: 5647 return ISD::SMULFIX; 5648 case Intrinsic::umul_fix: 5649 return ISD::UMULFIX; 5650 default: 5651 llvm_unreachable("Unhandled fixed point intrinsic"); 5652 } 5653 } 5654 5655 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5656 const char *FunctionName) { 5657 assert(FunctionName && "FunctionName must not be nullptr"); 5658 SDValue Callee = DAG.getExternalSymbol( 5659 FunctionName, 5660 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5661 LowerCallTo(&I, Callee, I.isTailCall()); 5662 } 5663 5664 /// Lower the call to the specified intrinsic function. 5665 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5666 unsigned Intrinsic) { 5667 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5668 SDLoc sdl = getCurSDLoc(); 5669 DebugLoc dl = getCurDebugLoc(); 5670 SDValue Res; 5671 5672 switch (Intrinsic) { 5673 default: 5674 // By default, turn this into a target intrinsic node. 5675 visitTargetIntrinsic(I, Intrinsic); 5676 return; 5677 case Intrinsic::vastart: visitVAStart(I); return; 5678 case Intrinsic::vaend: visitVAEnd(I); return; 5679 case Intrinsic::vacopy: visitVACopy(I); return; 5680 case Intrinsic::returnaddress: 5681 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5682 TLI.getPointerTy(DAG.getDataLayout()), 5683 getValue(I.getArgOperand(0)))); 5684 return; 5685 case Intrinsic::addressofreturnaddress: 5686 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5687 TLI.getPointerTy(DAG.getDataLayout()))); 5688 return; 5689 case Intrinsic::sponentry: 5690 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5691 TLI.getFrameIndexTy(DAG.getDataLayout()))); 5692 return; 5693 case Intrinsic::frameaddress: 5694 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5695 TLI.getFrameIndexTy(DAG.getDataLayout()), 5696 getValue(I.getArgOperand(0)))); 5697 return; 5698 case Intrinsic::read_register: { 5699 Value *Reg = I.getArgOperand(0); 5700 SDValue Chain = getRoot(); 5701 SDValue RegName = 5702 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5703 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5704 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5705 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5706 setValue(&I, Res); 5707 DAG.setRoot(Res.getValue(1)); 5708 return; 5709 } 5710 case Intrinsic::write_register: { 5711 Value *Reg = I.getArgOperand(0); 5712 Value *RegValue = I.getArgOperand(1); 5713 SDValue Chain = getRoot(); 5714 SDValue RegName = 5715 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5716 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5717 RegName, getValue(RegValue))); 5718 return; 5719 } 5720 case Intrinsic::setjmp: 5721 lowerCallToExternalSymbol(I, &"_setjmp"[!TLI.usesUnderscoreSetJmp()]); 5722 return; 5723 case Intrinsic::longjmp: 5724 lowerCallToExternalSymbol(I, &"_longjmp"[!TLI.usesUnderscoreLongJmp()]); 5725 return; 5726 case Intrinsic::memcpy: { 5727 const auto &MCI = cast<MemCpyInst>(I); 5728 SDValue Op1 = getValue(I.getArgOperand(0)); 5729 SDValue Op2 = getValue(I.getArgOperand(1)); 5730 SDValue Op3 = getValue(I.getArgOperand(2)); 5731 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5732 unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1); 5733 unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1); 5734 unsigned Align = MinAlign(DstAlign, SrcAlign); 5735 bool isVol = MCI.isVolatile(); 5736 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5737 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5738 // node. 5739 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5740 false, isTC, 5741 MachinePointerInfo(I.getArgOperand(0)), 5742 MachinePointerInfo(I.getArgOperand(1))); 5743 updateDAGForMaybeTailCall(MC); 5744 return; 5745 } 5746 case Intrinsic::memset: { 5747 const auto &MSI = cast<MemSetInst>(I); 5748 SDValue Op1 = getValue(I.getArgOperand(0)); 5749 SDValue Op2 = getValue(I.getArgOperand(1)); 5750 SDValue Op3 = getValue(I.getArgOperand(2)); 5751 // @llvm.memset defines 0 and 1 to both mean no alignment. 5752 unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1); 5753 bool isVol = MSI.isVolatile(); 5754 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5755 SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5756 isTC, MachinePointerInfo(I.getArgOperand(0))); 5757 updateDAGForMaybeTailCall(MS); 5758 return; 5759 } 5760 case Intrinsic::memmove: { 5761 const auto &MMI = cast<MemMoveInst>(I); 5762 SDValue Op1 = getValue(I.getArgOperand(0)); 5763 SDValue Op2 = getValue(I.getArgOperand(1)); 5764 SDValue Op3 = getValue(I.getArgOperand(2)); 5765 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5766 unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1); 5767 unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1); 5768 unsigned Align = MinAlign(DstAlign, SrcAlign); 5769 bool isVol = MMI.isVolatile(); 5770 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5771 // FIXME: Support passing different dest/src alignments to the memmove DAG 5772 // node. 5773 SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5774 isTC, MachinePointerInfo(I.getArgOperand(0)), 5775 MachinePointerInfo(I.getArgOperand(1))); 5776 updateDAGForMaybeTailCall(MM); 5777 return; 5778 } 5779 case Intrinsic::memcpy_element_unordered_atomic: { 5780 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5781 SDValue Dst = getValue(MI.getRawDest()); 5782 SDValue Src = getValue(MI.getRawSource()); 5783 SDValue Length = getValue(MI.getLength()); 5784 5785 unsigned DstAlign = MI.getDestAlignment(); 5786 unsigned SrcAlign = MI.getSourceAlignment(); 5787 Type *LengthTy = MI.getLength()->getType(); 5788 unsigned ElemSz = MI.getElementSizeInBytes(); 5789 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5790 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5791 SrcAlign, Length, LengthTy, ElemSz, isTC, 5792 MachinePointerInfo(MI.getRawDest()), 5793 MachinePointerInfo(MI.getRawSource())); 5794 updateDAGForMaybeTailCall(MC); 5795 return; 5796 } 5797 case Intrinsic::memmove_element_unordered_atomic: { 5798 auto &MI = cast<AtomicMemMoveInst>(I); 5799 SDValue Dst = getValue(MI.getRawDest()); 5800 SDValue Src = getValue(MI.getRawSource()); 5801 SDValue Length = getValue(MI.getLength()); 5802 5803 unsigned DstAlign = MI.getDestAlignment(); 5804 unsigned SrcAlign = MI.getSourceAlignment(); 5805 Type *LengthTy = MI.getLength()->getType(); 5806 unsigned ElemSz = MI.getElementSizeInBytes(); 5807 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5808 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5809 SrcAlign, Length, LengthTy, ElemSz, isTC, 5810 MachinePointerInfo(MI.getRawDest()), 5811 MachinePointerInfo(MI.getRawSource())); 5812 updateDAGForMaybeTailCall(MC); 5813 return; 5814 } 5815 case Intrinsic::memset_element_unordered_atomic: { 5816 auto &MI = cast<AtomicMemSetInst>(I); 5817 SDValue Dst = getValue(MI.getRawDest()); 5818 SDValue Val = getValue(MI.getValue()); 5819 SDValue Length = getValue(MI.getLength()); 5820 5821 unsigned DstAlign = MI.getDestAlignment(); 5822 Type *LengthTy = MI.getLength()->getType(); 5823 unsigned ElemSz = MI.getElementSizeInBytes(); 5824 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5825 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5826 LengthTy, ElemSz, isTC, 5827 MachinePointerInfo(MI.getRawDest())); 5828 updateDAGForMaybeTailCall(MC); 5829 return; 5830 } 5831 case Intrinsic::dbg_addr: 5832 case Intrinsic::dbg_declare: { 5833 const auto &DI = cast<DbgVariableIntrinsic>(I); 5834 DILocalVariable *Variable = DI.getVariable(); 5835 DIExpression *Expression = DI.getExpression(); 5836 dropDanglingDebugInfo(Variable, Expression); 5837 assert(Variable && "Missing variable"); 5838 5839 // Check if address has undef value. 5840 const Value *Address = DI.getVariableLocation(); 5841 if (!Address || isa<UndefValue>(Address) || 5842 (Address->use_empty() && !isa<Argument>(Address))) { 5843 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5844 return; 5845 } 5846 5847 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5848 5849 // Check if this variable can be described by a frame index, typically 5850 // either as a static alloca or a byval parameter. 5851 int FI = std::numeric_limits<int>::max(); 5852 if (const auto *AI = 5853 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5854 if (AI->isStaticAlloca()) { 5855 auto I = FuncInfo.StaticAllocaMap.find(AI); 5856 if (I != FuncInfo.StaticAllocaMap.end()) 5857 FI = I->second; 5858 } 5859 } else if (const auto *Arg = dyn_cast<Argument>( 5860 Address->stripInBoundsConstantOffsets())) { 5861 FI = FuncInfo.getArgumentFrameIndex(Arg); 5862 } 5863 5864 // llvm.dbg.addr is control dependent and always generates indirect 5865 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5866 // the MachineFunction variable table. 5867 if (FI != std::numeric_limits<int>::max()) { 5868 if (Intrinsic == Intrinsic::dbg_addr) { 5869 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 5870 Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder); 5871 DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter); 5872 } 5873 return; 5874 } 5875 5876 SDValue &N = NodeMap[Address]; 5877 if (!N.getNode() && isa<Argument>(Address)) 5878 // Check unused arguments map. 5879 N = UnusedArgNodeMap[Address]; 5880 SDDbgValue *SDV; 5881 if (N.getNode()) { 5882 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 5883 Address = BCI->getOperand(0); 5884 // Parameters are handled specially. 5885 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 5886 if (isParameter && FINode) { 5887 // Byval parameter. We have a frame index at this point. 5888 SDV = 5889 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 5890 /*IsIndirect*/ true, dl, SDNodeOrder); 5891 } else if (isa<Argument>(Address)) { 5892 // Address is an argument, so try to emit its dbg value using 5893 // virtual register info from the FuncInfo.ValueMap. 5894 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 5895 return; 5896 } else { 5897 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 5898 true, dl, SDNodeOrder); 5899 } 5900 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 5901 } else { 5902 // If Address is an argument then try to emit its dbg value using 5903 // virtual register info from the FuncInfo.ValueMap. 5904 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 5905 N)) { 5906 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5907 } 5908 } 5909 return; 5910 } 5911 case Intrinsic::dbg_label: { 5912 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 5913 DILabel *Label = DI.getLabel(); 5914 assert(Label && "Missing label"); 5915 5916 SDDbgLabel *SDV; 5917 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 5918 DAG.AddDbgLabel(SDV); 5919 return; 5920 } 5921 case Intrinsic::dbg_value: { 5922 const DbgValueInst &DI = cast<DbgValueInst>(I); 5923 assert(DI.getVariable() && "Missing variable"); 5924 5925 DILocalVariable *Variable = DI.getVariable(); 5926 DIExpression *Expression = DI.getExpression(); 5927 dropDanglingDebugInfo(Variable, Expression); 5928 const Value *V = DI.getValue(); 5929 if (!V) 5930 return; 5931 5932 if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(), 5933 SDNodeOrder)) 5934 return; 5935 5936 // TODO: Dangling debug info will eventually either be resolved or produce 5937 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 5938 // between the original dbg.value location and its resolved DBG_VALUE, which 5939 // we should ideally fill with an extra Undef DBG_VALUE. 5940 5941 DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder); 5942 return; 5943 } 5944 5945 case Intrinsic::eh_typeid_for: { 5946 // Find the type id for the given typeinfo. 5947 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 5948 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 5949 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 5950 setValue(&I, Res); 5951 return; 5952 } 5953 5954 case Intrinsic::eh_return_i32: 5955 case Intrinsic::eh_return_i64: 5956 DAG.getMachineFunction().setCallsEHReturn(true); 5957 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 5958 MVT::Other, 5959 getControlRoot(), 5960 getValue(I.getArgOperand(0)), 5961 getValue(I.getArgOperand(1)))); 5962 return; 5963 case Intrinsic::eh_unwind_init: 5964 DAG.getMachineFunction().setCallsUnwindInit(true); 5965 return; 5966 case Intrinsic::eh_dwarf_cfa: 5967 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 5968 TLI.getPointerTy(DAG.getDataLayout()), 5969 getValue(I.getArgOperand(0)))); 5970 return; 5971 case Intrinsic::eh_sjlj_callsite: { 5972 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5973 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 5974 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 5975 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 5976 5977 MMI.setCurrentCallSite(CI->getZExtValue()); 5978 return; 5979 } 5980 case Intrinsic::eh_sjlj_functioncontext: { 5981 // Get and store the index of the function context. 5982 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5983 AllocaInst *FnCtx = 5984 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 5985 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 5986 MFI.setFunctionContextIndex(FI); 5987 return; 5988 } 5989 case Intrinsic::eh_sjlj_setjmp: { 5990 SDValue Ops[2]; 5991 Ops[0] = getRoot(); 5992 Ops[1] = getValue(I.getArgOperand(0)); 5993 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 5994 DAG.getVTList(MVT::i32, MVT::Other), Ops); 5995 setValue(&I, Op.getValue(0)); 5996 DAG.setRoot(Op.getValue(1)); 5997 return; 5998 } 5999 case Intrinsic::eh_sjlj_longjmp: 6000 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6001 getRoot(), getValue(I.getArgOperand(0)))); 6002 return; 6003 case Intrinsic::eh_sjlj_setup_dispatch: 6004 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6005 getRoot())); 6006 return; 6007 case Intrinsic::masked_gather: 6008 visitMaskedGather(I); 6009 return; 6010 case Intrinsic::masked_load: 6011 visitMaskedLoad(I); 6012 return; 6013 case Intrinsic::masked_scatter: 6014 visitMaskedScatter(I); 6015 return; 6016 case Intrinsic::masked_store: 6017 visitMaskedStore(I); 6018 return; 6019 case Intrinsic::masked_expandload: 6020 visitMaskedLoad(I, true /* IsExpanding */); 6021 return; 6022 case Intrinsic::masked_compressstore: 6023 visitMaskedStore(I, true /* IsCompressing */); 6024 return; 6025 case Intrinsic::powi: 6026 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6027 getValue(I.getArgOperand(1)), DAG)); 6028 return; 6029 case Intrinsic::log: 6030 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6031 return; 6032 case Intrinsic::log2: 6033 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6034 return; 6035 case Intrinsic::log10: 6036 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6037 return; 6038 case Intrinsic::exp: 6039 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6040 return; 6041 case Intrinsic::exp2: 6042 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6043 return; 6044 case Intrinsic::pow: 6045 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6046 getValue(I.getArgOperand(1)), DAG, TLI)); 6047 return; 6048 case Intrinsic::sqrt: 6049 case Intrinsic::fabs: 6050 case Intrinsic::sin: 6051 case Intrinsic::cos: 6052 case Intrinsic::floor: 6053 case Intrinsic::ceil: 6054 case Intrinsic::trunc: 6055 case Intrinsic::rint: 6056 case Intrinsic::nearbyint: 6057 case Intrinsic::round: 6058 case Intrinsic::canonicalize: { 6059 unsigned Opcode; 6060 switch (Intrinsic) { 6061 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6062 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6063 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6064 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6065 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6066 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6067 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6068 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6069 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6070 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6071 case Intrinsic::round: Opcode = ISD::FROUND; break; 6072 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6073 } 6074 6075 setValue(&I, DAG.getNode(Opcode, sdl, 6076 getValue(I.getArgOperand(0)).getValueType(), 6077 getValue(I.getArgOperand(0)))); 6078 return; 6079 } 6080 case Intrinsic::lround: 6081 case Intrinsic::llround: 6082 case Intrinsic::lrint: 6083 case Intrinsic::llrint: { 6084 unsigned Opcode; 6085 switch (Intrinsic) { 6086 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6087 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6088 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6089 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6090 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6091 } 6092 6093 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6094 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6095 getValue(I.getArgOperand(0)))); 6096 return; 6097 } 6098 case Intrinsic::minnum: 6099 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6100 getValue(I.getArgOperand(0)).getValueType(), 6101 getValue(I.getArgOperand(0)), 6102 getValue(I.getArgOperand(1)))); 6103 return; 6104 case Intrinsic::maxnum: 6105 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6106 getValue(I.getArgOperand(0)).getValueType(), 6107 getValue(I.getArgOperand(0)), 6108 getValue(I.getArgOperand(1)))); 6109 return; 6110 case Intrinsic::minimum: 6111 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6112 getValue(I.getArgOperand(0)).getValueType(), 6113 getValue(I.getArgOperand(0)), 6114 getValue(I.getArgOperand(1)))); 6115 return; 6116 case Intrinsic::maximum: 6117 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6118 getValue(I.getArgOperand(0)).getValueType(), 6119 getValue(I.getArgOperand(0)), 6120 getValue(I.getArgOperand(1)))); 6121 return; 6122 case Intrinsic::copysign: 6123 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6124 getValue(I.getArgOperand(0)).getValueType(), 6125 getValue(I.getArgOperand(0)), 6126 getValue(I.getArgOperand(1)))); 6127 return; 6128 case Intrinsic::fma: 6129 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6130 getValue(I.getArgOperand(0)).getValueType(), 6131 getValue(I.getArgOperand(0)), 6132 getValue(I.getArgOperand(1)), 6133 getValue(I.getArgOperand(2)))); 6134 return; 6135 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 6136 case Intrinsic::INTRINSIC: 6137 #include "llvm/IR/ConstrainedOps.def" 6138 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6139 return; 6140 case Intrinsic::fmuladd: { 6141 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6142 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6143 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6144 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6145 getValue(I.getArgOperand(0)).getValueType(), 6146 getValue(I.getArgOperand(0)), 6147 getValue(I.getArgOperand(1)), 6148 getValue(I.getArgOperand(2)))); 6149 } else { 6150 // TODO: Intrinsic calls should have fast-math-flags. 6151 SDValue Mul = DAG.getNode(ISD::FMUL, sdl, 6152 getValue(I.getArgOperand(0)).getValueType(), 6153 getValue(I.getArgOperand(0)), 6154 getValue(I.getArgOperand(1))); 6155 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6156 getValue(I.getArgOperand(0)).getValueType(), 6157 Mul, 6158 getValue(I.getArgOperand(2))); 6159 setValue(&I, Add); 6160 } 6161 return; 6162 } 6163 case Intrinsic::convert_to_fp16: 6164 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6165 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6166 getValue(I.getArgOperand(0)), 6167 DAG.getTargetConstant(0, sdl, 6168 MVT::i32)))); 6169 return; 6170 case Intrinsic::convert_from_fp16: 6171 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6172 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6173 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6174 getValue(I.getArgOperand(0))))); 6175 return; 6176 case Intrinsic::pcmarker: { 6177 SDValue Tmp = getValue(I.getArgOperand(0)); 6178 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6179 return; 6180 } 6181 case Intrinsic::readcyclecounter: { 6182 SDValue Op = getRoot(); 6183 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6184 DAG.getVTList(MVT::i64, MVT::Other), Op); 6185 setValue(&I, Res); 6186 DAG.setRoot(Res.getValue(1)); 6187 return; 6188 } 6189 case Intrinsic::bitreverse: 6190 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6191 getValue(I.getArgOperand(0)).getValueType(), 6192 getValue(I.getArgOperand(0)))); 6193 return; 6194 case Intrinsic::bswap: 6195 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6196 getValue(I.getArgOperand(0)).getValueType(), 6197 getValue(I.getArgOperand(0)))); 6198 return; 6199 case Intrinsic::cttz: { 6200 SDValue Arg = getValue(I.getArgOperand(0)); 6201 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6202 EVT Ty = Arg.getValueType(); 6203 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6204 sdl, Ty, Arg)); 6205 return; 6206 } 6207 case Intrinsic::ctlz: { 6208 SDValue Arg = getValue(I.getArgOperand(0)); 6209 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6210 EVT Ty = Arg.getValueType(); 6211 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6212 sdl, Ty, Arg)); 6213 return; 6214 } 6215 case Intrinsic::ctpop: { 6216 SDValue Arg = getValue(I.getArgOperand(0)); 6217 EVT Ty = Arg.getValueType(); 6218 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6219 return; 6220 } 6221 case Intrinsic::fshl: 6222 case Intrinsic::fshr: { 6223 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6224 SDValue X = getValue(I.getArgOperand(0)); 6225 SDValue Y = getValue(I.getArgOperand(1)); 6226 SDValue Z = getValue(I.getArgOperand(2)); 6227 EVT VT = X.getValueType(); 6228 SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT); 6229 SDValue Zero = DAG.getConstant(0, sdl, VT); 6230 SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC); 6231 6232 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6233 if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) { 6234 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6235 return; 6236 } 6237 6238 // When X == Y, this is rotate. If the data type has a power-of-2 size, we 6239 // avoid the select that is necessary in the general case to filter out 6240 // the 0-shift possibility that leads to UB. 6241 if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) { 6242 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6243 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 6244 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6245 return; 6246 } 6247 6248 // Some targets only rotate one way. Try the opposite direction. 6249 RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL; 6250 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 6251 // Negate the shift amount because it is safe to ignore the high bits. 6252 SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 6253 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt)); 6254 return; 6255 } 6256 6257 // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW)) 6258 // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW)) 6259 SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 6260 SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC); 6261 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt); 6262 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt); 6263 setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY)); 6264 return; 6265 } 6266 6267 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 6268 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 6269 SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt); 6270 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt); 6271 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt); 6272 SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY); 6273 6274 // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth, 6275 // and that is undefined. We must compare and select to avoid UB. 6276 EVT CCVT = MVT::i1; 6277 if (VT.isVector()) 6278 CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements()); 6279 6280 // For fshl, 0-shift returns the 1st arg (X). 6281 // For fshr, 0-shift returns the 2nd arg (Y). 6282 SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ); 6283 setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or)); 6284 return; 6285 } 6286 case Intrinsic::sadd_sat: { 6287 SDValue Op1 = getValue(I.getArgOperand(0)); 6288 SDValue Op2 = getValue(I.getArgOperand(1)); 6289 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6290 return; 6291 } 6292 case Intrinsic::uadd_sat: { 6293 SDValue Op1 = getValue(I.getArgOperand(0)); 6294 SDValue Op2 = getValue(I.getArgOperand(1)); 6295 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6296 return; 6297 } 6298 case Intrinsic::ssub_sat: { 6299 SDValue Op1 = getValue(I.getArgOperand(0)); 6300 SDValue Op2 = getValue(I.getArgOperand(1)); 6301 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6302 return; 6303 } 6304 case Intrinsic::usub_sat: { 6305 SDValue Op1 = getValue(I.getArgOperand(0)); 6306 SDValue Op2 = getValue(I.getArgOperand(1)); 6307 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6308 return; 6309 } 6310 case Intrinsic::smul_fix: 6311 case Intrinsic::umul_fix: { 6312 SDValue Op1 = getValue(I.getArgOperand(0)); 6313 SDValue Op2 = getValue(I.getArgOperand(1)); 6314 SDValue Op3 = getValue(I.getArgOperand(2)); 6315 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6316 Op1.getValueType(), Op1, Op2, Op3)); 6317 return; 6318 } 6319 case Intrinsic::smul_fix_sat: { 6320 SDValue Op1 = getValue(I.getArgOperand(0)); 6321 SDValue Op2 = getValue(I.getArgOperand(1)); 6322 SDValue Op3 = getValue(I.getArgOperand(2)); 6323 setValue(&I, DAG.getNode(ISD::SMULFIXSAT, sdl, Op1.getValueType(), Op1, Op2, 6324 Op3)); 6325 return; 6326 } 6327 case Intrinsic::umul_fix_sat: { 6328 SDValue Op1 = getValue(I.getArgOperand(0)); 6329 SDValue Op2 = getValue(I.getArgOperand(1)); 6330 SDValue Op3 = getValue(I.getArgOperand(2)); 6331 setValue(&I, DAG.getNode(ISD::UMULFIXSAT, sdl, Op1.getValueType(), Op1, Op2, 6332 Op3)); 6333 return; 6334 } 6335 case Intrinsic::stacksave: { 6336 SDValue Op = getRoot(); 6337 Res = DAG.getNode( 6338 ISD::STACKSAVE, sdl, 6339 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op); 6340 setValue(&I, Res); 6341 DAG.setRoot(Res.getValue(1)); 6342 return; 6343 } 6344 case Intrinsic::stackrestore: 6345 Res = getValue(I.getArgOperand(0)); 6346 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6347 return; 6348 case Intrinsic::get_dynamic_area_offset: { 6349 SDValue Op = getRoot(); 6350 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6351 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6352 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6353 // target. 6354 if (PtrTy.getSizeInBits() < ResTy.getSizeInBits()) 6355 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6356 " intrinsic!"); 6357 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6358 Op); 6359 DAG.setRoot(Op); 6360 setValue(&I, Res); 6361 return; 6362 } 6363 case Intrinsic::stackguard: { 6364 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6365 MachineFunction &MF = DAG.getMachineFunction(); 6366 const Module &M = *MF.getFunction().getParent(); 6367 SDValue Chain = getRoot(); 6368 if (TLI.useLoadStackGuardNode()) { 6369 Res = getLoadStackGuard(DAG, sdl, Chain); 6370 } else { 6371 const Value *Global = TLI.getSDagStackGuard(M); 6372 unsigned Align = DL->getPrefTypeAlignment(Global->getType()); 6373 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6374 MachinePointerInfo(Global, 0), Align, 6375 MachineMemOperand::MOVolatile); 6376 } 6377 if (TLI.useStackGuardXorFP()) 6378 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6379 DAG.setRoot(Chain); 6380 setValue(&I, Res); 6381 return; 6382 } 6383 case Intrinsic::stackprotector: { 6384 // Emit code into the DAG to store the stack guard onto the stack. 6385 MachineFunction &MF = DAG.getMachineFunction(); 6386 MachineFrameInfo &MFI = MF.getFrameInfo(); 6387 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6388 SDValue Src, Chain = getRoot(); 6389 6390 if (TLI.useLoadStackGuardNode()) 6391 Src = getLoadStackGuard(DAG, sdl, Chain); 6392 else 6393 Src = getValue(I.getArgOperand(0)); // The guard's value. 6394 6395 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6396 6397 int FI = FuncInfo.StaticAllocaMap[Slot]; 6398 MFI.setStackProtectorIndex(FI); 6399 6400 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6401 6402 // Store the stack protector onto the stack. 6403 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack( 6404 DAG.getMachineFunction(), FI), 6405 /* Alignment = */ 0, MachineMemOperand::MOVolatile); 6406 setValue(&I, Res); 6407 DAG.setRoot(Res); 6408 return; 6409 } 6410 case Intrinsic::objectsize: 6411 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6412 6413 case Intrinsic::is_constant: 6414 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6415 6416 case Intrinsic::annotation: 6417 case Intrinsic::ptr_annotation: 6418 case Intrinsic::launder_invariant_group: 6419 case Intrinsic::strip_invariant_group: 6420 // Drop the intrinsic, but forward the value 6421 setValue(&I, getValue(I.getOperand(0))); 6422 return; 6423 case Intrinsic::assume: 6424 case Intrinsic::var_annotation: 6425 case Intrinsic::sideeffect: 6426 // Discard annotate attributes, assumptions, and artificial side-effects. 6427 return; 6428 6429 case Intrinsic::codeview_annotation: { 6430 // Emit a label associated with this metadata. 6431 MachineFunction &MF = DAG.getMachineFunction(); 6432 MCSymbol *Label = 6433 MF.getMMI().getContext().createTempSymbol("annotation", true); 6434 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6435 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6436 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6437 DAG.setRoot(Res); 6438 return; 6439 } 6440 6441 case Intrinsic::init_trampoline: { 6442 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6443 6444 SDValue Ops[6]; 6445 Ops[0] = getRoot(); 6446 Ops[1] = getValue(I.getArgOperand(0)); 6447 Ops[2] = getValue(I.getArgOperand(1)); 6448 Ops[3] = getValue(I.getArgOperand(2)); 6449 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6450 Ops[5] = DAG.getSrcValue(F); 6451 6452 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6453 6454 DAG.setRoot(Res); 6455 return; 6456 } 6457 case Intrinsic::adjust_trampoline: 6458 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6459 TLI.getPointerTy(DAG.getDataLayout()), 6460 getValue(I.getArgOperand(0)))); 6461 return; 6462 case Intrinsic::gcroot: { 6463 assert(DAG.getMachineFunction().getFunction().hasGC() && 6464 "only valid in functions with gc specified, enforced by Verifier"); 6465 assert(GFI && "implied by previous"); 6466 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6467 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6468 6469 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6470 GFI->addStackRoot(FI->getIndex(), TypeMap); 6471 return; 6472 } 6473 case Intrinsic::gcread: 6474 case Intrinsic::gcwrite: 6475 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6476 case Intrinsic::flt_rounds: 6477 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32)); 6478 return; 6479 6480 case Intrinsic::expect: 6481 // Just replace __builtin_expect(exp, c) with EXP. 6482 setValue(&I, getValue(I.getArgOperand(0))); 6483 return; 6484 6485 case Intrinsic::debugtrap: 6486 case Intrinsic::trap: { 6487 StringRef TrapFuncName = 6488 I.getAttributes() 6489 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6490 .getValueAsString(); 6491 if (TrapFuncName.empty()) { 6492 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 6493 ISD::TRAP : ISD::DEBUGTRAP; 6494 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 6495 return; 6496 } 6497 TargetLowering::ArgListTy Args; 6498 6499 TargetLowering::CallLoweringInfo CLI(DAG); 6500 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6501 CallingConv::C, I.getType(), 6502 DAG.getExternalSymbol(TrapFuncName.data(), 6503 TLI.getPointerTy(DAG.getDataLayout())), 6504 std::move(Args)); 6505 6506 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6507 DAG.setRoot(Result.second); 6508 return; 6509 } 6510 6511 case Intrinsic::uadd_with_overflow: 6512 case Intrinsic::sadd_with_overflow: 6513 case Intrinsic::usub_with_overflow: 6514 case Intrinsic::ssub_with_overflow: 6515 case Intrinsic::umul_with_overflow: 6516 case Intrinsic::smul_with_overflow: { 6517 ISD::NodeType Op; 6518 switch (Intrinsic) { 6519 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6520 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6521 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6522 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6523 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6524 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6525 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6526 } 6527 SDValue Op1 = getValue(I.getArgOperand(0)); 6528 SDValue Op2 = getValue(I.getArgOperand(1)); 6529 6530 EVT ResultVT = Op1.getValueType(); 6531 EVT OverflowVT = MVT::i1; 6532 if (ResultVT.isVector()) 6533 OverflowVT = EVT::getVectorVT( 6534 *Context, OverflowVT, ResultVT.getVectorNumElements()); 6535 6536 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6537 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6538 return; 6539 } 6540 case Intrinsic::prefetch: { 6541 SDValue Ops[5]; 6542 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6543 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6544 Ops[0] = DAG.getRoot(); 6545 Ops[1] = getValue(I.getArgOperand(0)); 6546 Ops[2] = getValue(I.getArgOperand(1)); 6547 Ops[3] = getValue(I.getArgOperand(2)); 6548 Ops[4] = getValue(I.getArgOperand(3)); 6549 SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl, 6550 DAG.getVTList(MVT::Other), Ops, 6551 EVT::getIntegerVT(*Context, 8), 6552 MachinePointerInfo(I.getArgOperand(0)), 6553 0, /* align */ 6554 Flags); 6555 6556 // Chain the prefetch in parallell with any pending loads, to stay out of 6557 // the way of later optimizations. 6558 PendingLoads.push_back(Result); 6559 Result = getRoot(); 6560 DAG.setRoot(Result); 6561 return; 6562 } 6563 case Intrinsic::lifetime_start: 6564 case Intrinsic::lifetime_end: { 6565 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6566 // Stack coloring is not enabled in O0, discard region information. 6567 if (TM.getOptLevel() == CodeGenOpt::None) 6568 return; 6569 6570 const int64_t ObjectSize = 6571 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6572 Value *const ObjectPtr = I.getArgOperand(1); 6573 SmallVector<const Value *, 4> Allocas; 6574 GetUnderlyingObjects(ObjectPtr, Allocas, *DL); 6575 6576 for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(), 6577 E = Allocas.end(); Object != E; ++Object) { 6578 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 6579 6580 // Could not find an Alloca. 6581 if (!LifetimeObject) 6582 continue; 6583 6584 // First check that the Alloca is static, otherwise it won't have a 6585 // valid frame index. 6586 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6587 if (SI == FuncInfo.StaticAllocaMap.end()) 6588 return; 6589 6590 const int FrameIndex = SI->second; 6591 int64_t Offset; 6592 if (GetPointerBaseWithConstantOffset( 6593 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6594 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6595 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6596 Offset); 6597 DAG.setRoot(Res); 6598 } 6599 return; 6600 } 6601 case Intrinsic::invariant_start: 6602 // Discard region information. 6603 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6604 return; 6605 case Intrinsic::invariant_end: 6606 // Discard region information. 6607 return; 6608 case Intrinsic::clear_cache: 6609 /// FunctionName may be null. 6610 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6611 lowerCallToExternalSymbol(I, FunctionName); 6612 return; 6613 case Intrinsic::donothing: 6614 // ignore 6615 return; 6616 case Intrinsic::experimental_stackmap: 6617 visitStackmap(I); 6618 return; 6619 case Intrinsic::experimental_patchpoint_void: 6620 case Intrinsic::experimental_patchpoint_i64: 6621 visitPatchpoint(&I); 6622 return; 6623 case Intrinsic::experimental_gc_statepoint: 6624 LowerStatepoint(ImmutableStatepoint(&I)); 6625 return; 6626 case Intrinsic::experimental_gc_result: 6627 visitGCResult(cast<GCResultInst>(I)); 6628 return; 6629 case Intrinsic::experimental_gc_relocate: 6630 visitGCRelocate(cast<GCRelocateInst>(I)); 6631 return; 6632 case Intrinsic::instrprof_increment: 6633 llvm_unreachable("instrprof failed to lower an increment"); 6634 case Intrinsic::instrprof_value_profile: 6635 llvm_unreachable("instrprof failed to lower a value profiling call"); 6636 case Intrinsic::localescape: { 6637 MachineFunction &MF = DAG.getMachineFunction(); 6638 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6639 6640 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6641 // is the same on all targets. 6642 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6643 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6644 if (isa<ConstantPointerNull>(Arg)) 6645 continue; // Skip null pointers. They represent a hole in index space. 6646 AllocaInst *Slot = cast<AllocaInst>(Arg); 6647 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6648 "can only escape static allocas"); 6649 int FI = FuncInfo.StaticAllocaMap[Slot]; 6650 MCSymbol *FrameAllocSym = 6651 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6652 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6653 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6654 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6655 .addSym(FrameAllocSym) 6656 .addFrameIndex(FI); 6657 } 6658 6659 return; 6660 } 6661 6662 case Intrinsic::localrecover: { 6663 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6664 MachineFunction &MF = DAG.getMachineFunction(); 6665 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0); 6666 6667 // Get the symbol that defines the frame offset. 6668 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6669 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6670 unsigned IdxVal = 6671 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6672 MCSymbol *FrameAllocSym = 6673 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6674 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6675 6676 // Create a MCSymbol for the label to avoid any target lowering 6677 // that would make this PC relative. 6678 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6679 SDValue OffsetVal = 6680 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6681 6682 // Add the offset to the FP. 6683 Value *FP = I.getArgOperand(1); 6684 SDValue FPVal = getValue(FP); 6685 SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal); 6686 setValue(&I, Add); 6687 6688 return; 6689 } 6690 6691 case Intrinsic::eh_exceptionpointer: 6692 case Intrinsic::eh_exceptioncode: { 6693 // Get the exception pointer vreg, copy from it, and resize it to fit. 6694 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6695 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6696 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6697 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6698 SDValue N = 6699 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6700 if (Intrinsic == Intrinsic::eh_exceptioncode) 6701 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6702 setValue(&I, N); 6703 return; 6704 } 6705 case Intrinsic::xray_customevent: { 6706 // Here we want to make sure that the intrinsic behaves as if it has a 6707 // specific calling convention, and only for x86_64. 6708 // FIXME: Support other platforms later. 6709 const auto &Triple = DAG.getTarget().getTargetTriple(); 6710 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6711 return; 6712 6713 SDLoc DL = getCurSDLoc(); 6714 SmallVector<SDValue, 8> Ops; 6715 6716 // We want to say that we always want the arguments in registers. 6717 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6718 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6719 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6720 SDValue Chain = getRoot(); 6721 Ops.push_back(LogEntryVal); 6722 Ops.push_back(StrSizeVal); 6723 Ops.push_back(Chain); 6724 6725 // We need to enforce the calling convention for the callsite, so that 6726 // argument ordering is enforced correctly, and that register allocation can 6727 // see that some registers may be assumed clobbered and have to preserve 6728 // them across calls to the intrinsic. 6729 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6730 DL, NodeTys, Ops); 6731 SDValue patchableNode = SDValue(MN, 0); 6732 DAG.setRoot(patchableNode); 6733 setValue(&I, patchableNode); 6734 return; 6735 } 6736 case Intrinsic::xray_typedevent: { 6737 // Here we want to make sure that the intrinsic behaves as if it has a 6738 // specific calling convention, and only for x86_64. 6739 // FIXME: Support other platforms later. 6740 const auto &Triple = DAG.getTarget().getTargetTriple(); 6741 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6742 return; 6743 6744 SDLoc DL = getCurSDLoc(); 6745 SmallVector<SDValue, 8> Ops; 6746 6747 // We want to say that we always want the arguments in registers. 6748 // It's unclear to me how manipulating the selection DAG here forces callers 6749 // to provide arguments in registers instead of on the stack. 6750 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6751 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6752 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6753 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6754 SDValue Chain = getRoot(); 6755 Ops.push_back(LogTypeId); 6756 Ops.push_back(LogEntryVal); 6757 Ops.push_back(StrSizeVal); 6758 Ops.push_back(Chain); 6759 6760 // We need to enforce the calling convention for the callsite, so that 6761 // argument ordering is enforced correctly, and that register allocation can 6762 // see that some registers may be assumed clobbered and have to preserve 6763 // them across calls to the intrinsic. 6764 MachineSDNode *MN = DAG.getMachineNode( 6765 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6766 SDValue patchableNode = SDValue(MN, 0); 6767 DAG.setRoot(patchableNode); 6768 setValue(&I, patchableNode); 6769 return; 6770 } 6771 case Intrinsic::experimental_deoptimize: 6772 LowerDeoptimizeCall(&I); 6773 return; 6774 6775 case Intrinsic::experimental_vector_reduce_v2_fadd: 6776 case Intrinsic::experimental_vector_reduce_v2_fmul: 6777 case Intrinsic::experimental_vector_reduce_add: 6778 case Intrinsic::experimental_vector_reduce_mul: 6779 case Intrinsic::experimental_vector_reduce_and: 6780 case Intrinsic::experimental_vector_reduce_or: 6781 case Intrinsic::experimental_vector_reduce_xor: 6782 case Intrinsic::experimental_vector_reduce_smax: 6783 case Intrinsic::experimental_vector_reduce_smin: 6784 case Intrinsic::experimental_vector_reduce_umax: 6785 case Intrinsic::experimental_vector_reduce_umin: 6786 case Intrinsic::experimental_vector_reduce_fmax: 6787 case Intrinsic::experimental_vector_reduce_fmin: 6788 visitVectorReduce(I, Intrinsic); 6789 return; 6790 6791 case Intrinsic::icall_branch_funnel: { 6792 SmallVector<SDValue, 16> Ops; 6793 Ops.push_back(getValue(I.getArgOperand(0))); 6794 6795 int64_t Offset; 6796 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6797 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6798 if (!Base) 6799 report_fatal_error( 6800 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6801 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6802 6803 struct BranchFunnelTarget { 6804 int64_t Offset; 6805 SDValue Target; 6806 }; 6807 SmallVector<BranchFunnelTarget, 8> Targets; 6808 6809 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6810 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6811 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6812 if (ElemBase != Base) 6813 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6814 "to the same GlobalValue"); 6815 6816 SDValue Val = getValue(I.getArgOperand(Op + 1)); 6817 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 6818 if (!GA) 6819 report_fatal_error( 6820 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6821 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 6822 GA->getGlobal(), getCurSDLoc(), 6823 Val.getValueType(), GA->getOffset())}); 6824 } 6825 llvm::sort(Targets, 6826 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 6827 return T1.Offset < T2.Offset; 6828 }); 6829 6830 for (auto &T : Targets) { 6831 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 6832 Ops.push_back(T.Target); 6833 } 6834 6835 Ops.push_back(DAG.getRoot()); // Chain 6836 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 6837 getCurSDLoc(), MVT::Other, Ops), 6838 0); 6839 DAG.setRoot(N); 6840 setValue(&I, N); 6841 HasTailCall = true; 6842 return; 6843 } 6844 6845 case Intrinsic::wasm_landingpad_index: 6846 // Information this intrinsic contained has been transferred to 6847 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 6848 // delete it now. 6849 return; 6850 6851 case Intrinsic::aarch64_settag: 6852 case Intrinsic::aarch64_settag_zero: { 6853 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6854 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 6855 SDValue Val = TSI.EmitTargetCodeForSetTag( 6856 DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)), 6857 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 6858 ZeroMemory); 6859 DAG.setRoot(Val); 6860 setValue(&I, Val); 6861 return; 6862 } 6863 case Intrinsic::ptrmask: { 6864 SDValue Ptr = getValue(I.getOperand(0)); 6865 SDValue Const = getValue(I.getOperand(1)); 6866 6867 EVT DestVT = 6868 EVT(DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 6869 6870 setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), DestVT, Ptr, 6871 DAG.getZExtOrTrunc(Const, getCurSDLoc(), DestVT))); 6872 return; 6873 } 6874 } 6875 } 6876 6877 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 6878 const ConstrainedFPIntrinsic &FPI) { 6879 SDLoc sdl = getCurSDLoc(); 6880 6881 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6882 SmallVector<EVT, 4> ValueVTs; 6883 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 6884 ValueVTs.push_back(MVT::Other); // Out chain 6885 6886 SDValue Chain = getRoot(); 6887 SmallVector<SDValue, 4> Opers; 6888 Opers.push_back(Chain); 6889 if (FPI.isUnaryOp()) { 6890 Opers.push_back(getValue(FPI.getArgOperand(0))); 6891 } else if (FPI.isTernaryOp()) { 6892 Opers.push_back(getValue(FPI.getArgOperand(0))); 6893 Opers.push_back(getValue(FPI.getArgOperand(1))); 6894 Opers.push_back(getValue(FPI.getArgOperand(2))); 6895 } else { 6896 Opers.push_back(getValue(FPI.getArgOperand(0))); 6897 Opers.push_back(getValue(FPI.getArgOperand(1))); 6898 } 6899 6900 unsigned Opcode; 6901 switch (FPI.getIntrinsicID()) { 6902 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6903 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 6904 case Intrinsic::INTRINSIC: \ 6905 Opcode = ISD::STRICT_##DAGN; \ 6906 break; 6907 #include "llvm/IR/ConstrainedOps.def" 6908 } 6909 6910 if (Opcode == ISD::STRICT_FP_ROUND) 6911 Opers.push_back( 6912 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 6913 6914 SDVTList VTs = DAG.getVTList(ValueVTs); 6915 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers); 6916 6917 if (FPI.getExceptionBehavior() != fp::ExceptionBehavior::ebIgnore) { 6918 SDNodeFlags Flags; 6919 Flags.setFPExcept(true); 6920 Result->setFlags(Flags); 6921 } 6922 6923 assert(Result.getNode()->getNumValues() == 2); 6924 SDValue OutChain = Result.getValue(1); 6925 DAG.setRoot(OutChain); 6926 SDValue FPResult = Result.getValue(0); 6927 setValue(&FPI, FPResult); 6928 } 6929 6930 std::pair<SDValue, SDValue> 6931 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 6932 const BasicBlock *EHPadBB) { 6933 MachineFunction &MF = DAG.getMachineFunction(); 6934 MachineModuleInfo &MMI = MF.getMMI(); 6935 MCSymbol *BeginLabel = nullptr; 6936 6937 if (EHPadBB) { 6938 // Insert a label before the invoke call to mark the try range. This can be 6939 // used to detect deletion of the invoke via the MachineModuleInfo. 6940 BeginLabel = MMI.getContext().createTempSymbol(); 6941 6942 // For SjLj, keep track of which landing pads go with which invokes 6943 // so as to maintain the ordering of pads in the LSDA. 6944 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 6945 if (CallSiteIndex) { 6946 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 6947 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 6948 6949 // Now that the call site is handled, stop tracking it. 6950 MMI.setCurrentCallSite(0); 6951 } 6952 6953 // Both PendingLoads and PendingExports must be flushed here; 6954 // this call might not return. 6955 (void)getRoot(); 6956 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 6957 6958 CLI.setChain(getRoot()); 6959 } 6960 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6961 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6962 6963 assert((CLI.IsTailCall || Result.second.getNode()) && 6964 "Non-null chain expected with non-tail call!"); 6965 assert((Result.second.getNode() || !Result.first.getNode()) && 6966 "Null value expected with tail call!"); 6967 6968 if (!Result.second.getNode()) { 6969 // As a special case, a null chain means that a tail call has been emitted 6970 // and the DAG root is already updated. 6971 HasTailCall = true; 6972 6973 // Since there's no actual continuation from this block, nothing can be 6974 // relying on us setting vregs for them. 6975 PendingExports.clear(); 6976 } else { 6977 DAG.setRoot(Result.second); 6978 } 6979 6980 if (EHPadBB) { 6981 // Insert a label at the end of the invoke call to mark the try range. This 6982 // can be used to detect deletion of the invoke via the MachineModuleInfo. 6983 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 6984 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 6985 6986 // Inform MachineModuleInfo of range. 6987 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 6988 // There is a platform (e.g. wasm) that uses funclet style IR but does not 6989 // actually use outlined funclets and their LSDA info style. 6990 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 6991 assert(CLI.CS); 6992 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 6993 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()), 6994 BeginLabel, EndLabel); 6995 } else if (!isScopedEHPersonality(Pers)) { 6996 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 6997 } 6998 } 6999 7000 return Result; 7001 } 7002 7003 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee, 7004 bool isTailCall, 7005 const BasicBlock *EHPadBB) { 7006 auto &DL = DAG.getDataLayout(); 7007 FunctionType *FTy = CS.getFunctionType(); 7008 Type *RetTy = CS.getType(); 7009 7010 TargetLowering::ArgListTy Args; 7011 Args.reserve(CS.arg_size()); 7012 7013 const Value *SwiftErrorVal = nullptr; 7014 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7015 7016 // We can't tail call inside a function with a swifterror argument. Lowering 7017 // does not support this yet. It would have to move into the swifterror 7018 // register before the call. 7019 auto *Caller = CS.getInstruction()->getParent()->getParent(); 7020 if (TLI.supportSwiftError() && 7021 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7022 isTailCall = false; 7023 7024 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 7025 i != e; ++i) { 7026 TargetLowering::ArgListEntry Entry; 7027 const Value *V = *i; 7028 7029 // Skip empty types 7030 if (V->getType()->isEmptyTy()) 7031 continue; 7032 7033 SDValue ArgNode = getValue(V); 7034 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7035 7036 Entry.setAttributes(&CS, i - CS.arg_begin()); 7037 7038 // Use swifterror virtual register as input to the call. 7039 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7040 SwiftErrorVal = V; 7041 // We find the virtual register for the actual swifterror argument. 7042 // Instead of using the Value, we use the virtual register instead. 7043 Entry.Node = DAG.getRegister( 7044 SwiftError.getOrCreateVRegUseAt(CS.getInstruction(), FuncInfo.MBB, V), 7045 EVT(TLI.getPointerTy(DL))); 7046 } 7047 7048 Args.push_back(Entry); 7049 7050 // If we have an explicit sret argument that is an Instruction, (i.e., it 7051 // might point to function-local memory), we can't meaningfully tail-call. 7052 if (Entry.IsSRet && isa<Instruction>(V)) 7053 isTailCall = false; 7054 } 7055 7056 // If call site has a cfguardtarget operand bundle, create and add an 7057 // additional ArgListEntry. 7058 if (auto Bundle = CS.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7059 TargetLowering::ArgListEntry Entry; 7060 Value *V = Bundle->Inputs[0]; 7061 SDValue ArgNode = getValue(V); 7062 Entry.Node = ArgNode; 7063 Entry.Ty = V->getType(); 7064 Entry.IsCFGuardTarget = true; 7065 Args.push_back(Entry); 7066 } 7067 7068 // Check if target-independent constraints permit a tail call here. 7069 // Target-dependent constraints are checked within TLI->LowerCallTo. 7070 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget())) 7071 isTailCall = false; 7072 7073 // Disable tail calls if there is an swifterror argument. Targets have not 7074 // been updated to support tail calls. 7075 if (TLI.supportSwiftError() && SwiftErrorVal) 7076 isTailCall = false; 7077 7078 TargetLowering::CallLoweringInfo CLI(DAG); 7079 CLI.setDebugLoc(getCurSDLoc()) 7080 .setChain(getRoot()) 7081 .setCallee(RetTy, FTy, Callee, std::move(Args), CS) 7082 .setTailCall(isTailCall) 7083 .setConvergent(CS.isConvergent()); 7084 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7085 7086 if (Result.first.getNode()) { 7087 const Instruction *Inst = CS.getInstruction(); 7088 Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first); 7089 setValue(Inst, Result.first); 7090 } 7091 7092 // The last element of CLI.InVals has the SDValue for swifterror return. 7093 // Here we copy it to a virtual register and update SwiftErrorMap for 7094 // book-keeping. 7095 if (SwiftErrorVal && TLI.supportSwiftError()) { 7096 // Get the last element of InVals. 7097 SDValue Src = CLI.InVals.back(); 7098 Register VReg = SwiftError.getOrCreateVRegDefAt( 7099 CS.getInstruction(), FuncInfo.MBB, SwiftErrorVal); 7100 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7101 DAG.setRoot(CopyNode); 7102 } 7103 } 7104 7105 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7106 SelectionDAGBuilder &Builder) { 7107 // Check to see if this load can be trivially constant folded, e.g. if the 7108 // input is from a string literal. 7109 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7110 // Cast pointer to the type we really want to load. 7111 Type *LoadTy = 7112 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7113 if (LoadVT.isVector()) 7114 LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7115 7116 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7117 PointerType::getUnqual(LoadTy)); 7118 7119 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 7120 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 7121 return Builder.getValue(LoadCst); 7122 } 7123 7124 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7125 // still constant memory, the input chain can be the entry node. 7126 SDValue Root; 7127 bool ConstantMemory = false; 7128 7129 // Do not serialize (non-volatile) loads of constant memory with anything. 7130 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7131 Root = Builder.DAG.getEntryNode(); 7132 ConstantMemory = true; 7133 } else { 7134 // Do not serialize non-volatile loads against each other. 7135 Root = Builder.DAG.getRoot(); 7136 } 7137 7138 SDValue Ptr = Builder.getValue(PtrVal); 7139 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, 7140 Ptr, MachinePointerInfo(PtrVal), 7141 /* Alignment = */ 1); 7142 7143 if (!ConstantMemory) 7144 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7145 return LoadVal; 7146 } 7147 7148 /// Record the value for an instruction that produces an integer result, 7149 /// converting the type where necessary. 7150 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7151 SDValue Value, 7152 bool IsSigned) { 7153 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7154 I.getType(), true); 7155 if (IsSigned) 7156 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7157 else 7158 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7159 setValue(&I, Value); 7160 } 7161 7162 /// See if we can lower a memcmp call into an optimized form. If so, return 7163 /// true and lower it. Otherwise return false, and it will be lowered like a 7164 /// normal call. 7165 /// The caller already checked that \p I calls the appropriate LibFunc with a 7166 /// correct prototype. 7167 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 7168 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 7169 const Value *Size = I.getArgOperand(2); 7170 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 7171 if (CSize && CSize->getZExtValue() == 0) { 7172 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7173 I.getType(), true); 7174 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 7175 return true; 7176 } 7177 7178 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7179 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 7180 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 7181 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 7182 if (Res.first.getNode()) { 7183 processIntegerCallValue(I, Res.first, true); 7184 PendingLoads.push_back(Res.second); 7185 return true; 7186 } 7187 7188 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 7189 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 7190 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 7191 return false; 7192 7193 // If the target has a fast compare for the given size, it will return a 7194 // preferred load type for that size. Require that the load VT is legal and 7195 // that the target supports unaligned loads of that type. Otherwise, return 7196 // INVALID. 7197 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 7198 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7199 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 7200 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 7201 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 7202 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 7203 // TODO: Check alignment of src and dest ptrs. 7204 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 7205 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 7206 if (!TLI.isTypeLegal(LVT) || 7207 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 7208 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 7209 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 7210 } 7211 7212 return LVT; 7213 }; 7214 7215 // This turns into unaligned loads. We only do this if the target natively 7216 // supports the MVT we'll be loading or if it is small enough (<= 4) that 7217 // we'll only produce a small number of byte loads. 7218 MVT LoadVT; 7219 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 7220 switch (NumBitsToCompare) { 7221 default: 7222 return false; 7223 case 16: 7224 LoadVT = MVT::i16; 7225 break; 7226 case 32: 7227 LoadVT = MVT::i32; 7228 break; 7229 case 64: 7230 case 128: 7231 case 256: 7232 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 7233 break; 7234 } 7235 7236 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 7237 return false; 7238 7239 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 7240 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 7241 7242 // Bitcast to a wide integer type if the loads are vectors. 7243 if (LoadVT.isVector()) { 7244 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 7245 LoadL = DAG.getBitcast(CmpVT, LoadL); 7246 LoadR = DAG.getBitcast(CmpVT, LoadR); 7247 } 7248 7249 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 7250 processIntegerCallValue(I, Cmp, false); 7251 return true; 7252 } 7253 7254 /// See if we can lower a memchr call into an optimized form. If so, return 7255 /// true and lower it. Otherwise return false, and it will be lowered like a 7256 /// normal call. 7257 /// The caller already checked that \p I calls the appropriate LibFunc with a 7258 /// correct prototype. 7259 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 7260 const Value *Src = I.getArgOperand(0); 7261 const Value *Char = I.getArgOperand(1); 7262 const Value *Length = I.getArgOperand(2); 7263 7264 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7265 std::pair<SDValue, SDValue> Res = 7266 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 7267 getValue(Src), getValue(Char), getValue(Length), 7268 MachinePointerInfo(Src)); 7269 if (Res.first.getNode()) { 7270 setValue(&I, Res.first); 7271 PendingLoads.push_back(Res.second); 7272 return true; 7273 } 7274 7275 return false; 7276 } 7277 7278 /// See if we can lower a mempcpy call into an optimized form. If so, return 7279 /// true and lower it. Otherwise return false, and it will be lowered like a 7280 /// normal call. 7281 /// The caller already checked that \p I calls the appropriate LibFunc with a 7282 /// correct prototype. 7283 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 7284 SDValue Dst = getValue(I.getArgOperand(0)); 7285 SDValue Src = getValue(I.getArgOperand(1)); 7286 SDValue Size = getValue(I.getArgOperand(2)); 7287 7288 unsigned DstAlign = DAG.InferPtrAlignment(Dst); 7289 unsigned SrcAlign = DAG.InferPtrAlignment(Src); 7290 unsigned Align = std::min(DstAlign, SrcAlign); 7291 if (Align == 0) // Alignment of one or both could not be inferred. 7292 Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved. 7293 7294 bool isVol = false; 7295 SDLoc sdl = getCurSDLoc(); 7296 7297 // In the mempcpy context we need to pass in a false value for isTailCall 7298 // because the return pointer needs to be adjusted by the size of 7299 // the copied memory. 7300 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol, 7301 false, /*isTailCall=*/false, 7302 MachinePointerInfo(I.getArgOperand(0)), 7303 MachinePointerInfo(I.getArgOperand(1))); 7304 assert(MC.getNode() != nullptr && 7305 "** memcpy should not be lowered as TailCall in mempcpy context **"); 7306 DAG.setRoot(MC); 7307 7308 // Check if Size needs to be truncated or extended. 7309 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 7310 7311 // Adjust return pointer to point just past the last dst byte. 7312 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 7313 Dst, Size); 7314 setValue(&I, DstPlusSize); 7315 return true; 7316 } 7317 7318 /// See if we can lower a strcpy call into an optimized form. If so, return 7319 /// true and lower it, otherwise return false and it will be lowered like a 7320 /// normal call. 7321 /// The caller already checked that \p I calls the appropriate LibFunc with a 7322 /// correct prototype. 7323 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 7324 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7325 7326 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7327 std::pair<SDValue, SDValue> Res = 7328 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 7329 getValue(Arg0), getValue(Arg1), 7330 MachinePointerInfo(Arg0), 7331 MachinePointerInfo(Arg1), isStpcpy); 7332 if (Res.first.getNode()) { 7333 setValue(&I, Res.first); 7334 DAG.setRoot(Res.second); 7335 return true; 7336 } 7337 7338 return false; 7339 } 7340 7341 /// See if we can lower a strcmp call into an optimized form. If so, return 7342 /// true and lower it, otherwise return false and it will be lowered like a 7343 /// normal call. 7344 /// The caller already checked that \p I calls the appropriate LibFunc with a 7345 /// correct prototype. 7346 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 7347 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7348 7349 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7350 std::pair<SDValue, SDValue> Res = 7351 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 7352 getValue(Arg0), getValue(Arg1), 7353 MachinePointerInfo(Arg0), 7354 MachinePointerInfo(Arg1)); 7355 if (Res.first.getNode()) { 7356 processIntegerCallValue(I, Res.first, true); 7357 PendingLoads.push_back(Res.second); 7358 return true; 7359 } 7360 7361 return false; 7362 } 7363 7364 /// See if we can lower a strlen call into an optimized form. If so, return 7365 /// true and lower it, otherwise return false and it will be lowered like a 7366 /// normal call. 7367 /// The caller already checked that \p I calls the appropriate LibFunc with a 7368 /// correct prototype. 7369 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 7370 const Value *Arg0 = I.getArgOperand(0); 7371 7372 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7373 std::pair<SDValue, SDValue> Res = 7374 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 7375 getValue(Arg0), MachinePointerInfo(Arg0)); 7376 if (Res.first.getNode()) { 7377 processIntegerCallValue(I, Res.first, false); 7378 PendingLoads.push_back(Res.second); 7379 return true; 7380 } 7381 7382 return false; 7383 } 7384 7385 /// See if we can lower a strnlen call into an optimized form. If so, return 7386 /// true and lower it, otherwise return false and it will be lowered like a 7387 /// normal call. 7388 /// The caller already checked that \p I calls the appropriate LibFunc with a 7389 /// correct prototype. 7390 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 7391 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7392 7393 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7394 std::pair<SDValue, SDValue> Res = 7395 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 7396 getValue(Arg0), getValue(Arg1), 7397 MachinePointerInfo(Arg0)); 7398 if (Res.first.getNode()) { 7399 processIntegerCallValue(I, Res.first, false); 7400 PendingLoads.push_back(Res.second); 7401 return true; 7402 } 7403 7404 return false; 7405 } 7406 7407 /// See if we can lower a unary floating-point operation into an SDNode with 7408 /// the specified Opcode. If so, return true and lower it, otherwise return 7409 /// false and it will be lowered like a normal call. 7410 /// The caller already checked that \p I calls the appropriate LibFunc with a 7411 /// correct prototype. 7412 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 7413 unsigned Opcode) { 7414 // We already checked this call's prototype; verify it doesn't modify errno. 7415 if (!I.onlyReadsMemory()) 7416 return false; 7417 7418 SDValue Tmp = getValue(I.getArgOperand(0)); 7419 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); 7420 return true; 7421 } 7422 7423 /// See if we can lower a binary floating-point operation into an SDNode with 7424 /// the specified Opcode. If so, return true and lower it. Otherwise return 7425 /// false, and it will be lowered like a normal call. 7426 /// The caller already checked that \p I calls the appropriate LibFunc with a 7427 /// correct prototype. 7428 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 7429 unsigned Opcode) { 7430 // We already checked this call's prototype; verify it doesn't modify errno. 7431 if (!I.onlyReadsMemory()) 7432 return false; 7433 7434 SDValue Tmp0 = getValue(I.getArgOperand(0)); 7435 SDValue Tmp1 = getValue(I.getArgOperand(1)); 7436 EVT VT = Tmp0.getValueType(); 7437 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1)); 7438 return true; 7439 } 7440 7441 void SelectionDAGBuilder::visitCall(const CallInst &I) { 7442 // Handle inline assembly differently. 7443 if (isa<InlineAsm>(I.getCalledValue())) { 7444 visitInlineAsm(&I); 7445 return; 7446 } 7447 7448 if (Function *F = I.getCalledFunction()) { 7449 if (F->isDeclaration()) { 7450 // Is this an LLVM intrinsic or a target-specific intrinsic? 7451 unsigned IID = F->getIntrinsicID(); 7452 if (!IID) 7453 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7454 IID = II->getIntrinsicID(F); 7455 7456 if (IID) { 7457 visitIntrinsicCall(I, IID); 7458 return; 7459 } 7460 } 7461 7462 // Check for well-known libc/libm calls. If the function is internal, it 7463 // can't be a library call. Don't do the check if marked as nobuiltin for 7464 // some reason or the call site requires strict floating point semantics. 7465 LibFunc Func; 7466 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7467 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7468 LibInfo->hasOptimizedCodeGen(Func)) { 7469 switch (Func) { 7470 default: break; 7471 case LibFunc_copysign: 7472 case LibFunc_copysignf: 7473 case LibFunc_copysignl: 7474 // We already checked this call's prototype; verify it doesn't modify 7475 // errno. 7476 if (I.onlyReadsMemory()) { 7477 SDValue LHS = getValue(I.getArgOperand(0)); 7478 SDValue RHS = getValue(I.getArgOperand(1)); 7479 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7480 LHS.getValueType(), LHS, RHS)); 7481 return; 7482 } 7483 break; 7484 case LibFunc_fabs: 7485 case LibFunc_fabsf: 7486 case LibFunc_fabsl: 7487 if (visitUnaryFloatCall(I, ISD::FABS)) 7488 return; 7489 break; 7490 case LibFunc_fmin: 7491 case LibFunc_fminf: 7492 case LibFunc_fminl: 7493 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7494 return; 7495 break; 7496 case LibFunc_fmax: 7497 case LibFunc_fmaxf: 7498 case LibFunc_fmaxl: 7499 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7500 return; 7501 break; 7502 case LibFunc_sin: 7503 case LibFunc_sinf: 7504 case LibFunc_sinl: 7505 if (visitUnaryFloatCall(I, ISD::FSIN)) 7506 return; 7507 break; 7508 case LibFunc_cos: 7509 case LibFunc_cosf: 7510 case LibFunc_cosl: 7511 if (visitUnaryFloatCall(I, ISD::FCOS)) 7512 return; 7513 break; 7514 case LibFunc_sqrt: 7515 case LibFunc_sqrtf: 7516 case LibFunc_sqrtl: 7517 case LibFunc_sqrt_finite: 7518 case LibFunc_sqrtf_finite: 7519 case LibFunc_sqrtl_finite: 7520 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7521 return; 7522 break; 7523 case LibFunc_floor: 7524 case LibFunc_floorf: 7525 case LibFunc_floorl: 7526 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7527 return; 7528 break; 7529 case LibFunc_nearbyint: 7530 case LibFunc_nearbyintf: 7531 case LibFunc_nearbyintl: 7532 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7533 return; 7534 break; 7535 case LibFunc_ceil: 7536 case LibFunc_ceilf: 7537 case LibFunc_ceill: 7538 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7539 return; 7540 break; 7541 case LibFunc_rint: 7542 case LibFunc_rintf: 7543 case LibFunc_rintl: 7544 if (visitUnaryFloatCall(I, ISD::FRINT)) 7545 return; 7546 break; 7547 case LibFunc_round: 7548 case LibFunc_roundf: 7549 case LibFunc_roundl: 7550 if (visitUnaryFloatCall(I, ISD::FROUND)) 7551 return; 7552 break; 7553 case LibFunc_trunc: 7554 case LibFunc_truncf: 7555 case LibFunc_truncl: 7556 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7557 return; 7558 break; 7559 case LibFunc_log2: 7560 case LibFunc_log2f: 7561 case LibFunc_log2l: 7562 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7563 return; 7564 break; 7565 case LibFunc_exp2: 7566 case LibFunc_exp2f: 7567 case LibFunc_exp2l: 7568 if (visitUnaryFloatCall(I, ISD::FEXP2)) 7569 return; 7570 break; 7571 case LibFunc_memcmp: 7572 if (visitMemCmpCall(I)) 7573 return; 7574 break; 7575 case LibFunc_mempcpy: 7576 if (visitMemPCpyCall(I)) 7577 return; 7578 break; 7579 case LibFunc_memchr: 7580 if (visitMemChrCall(I)) 7581 return; 7582 break; 7583 case LibFunc_strcpy: 7584 if (visitStrCpyCall(I, false)) 7585 return; 7586 break; 7587 case LibFunc_stpcpy: 7588 if (visitStrCpyCall(I, true)) 7589 return; 7590 break; 7591 case LibFunc_strcmp: 7592 if (visitStrCmpCall(I)) 7593 return; 7594 break; 7595 case LibFunc_strlen: 7596 if (visitStrLenCall(I)) 7597 return; 7598 break; 7599 case LibFunc_strnlen: 7600 if (visitStrNLenCall(I)) 7601 return; 7602 break; 7603 } 7604 } 7605 } 7606 7607 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 7608 // have to do anything here to lower funclet bundles. 7609 // CFGuardTarget bundles are lowered in LowerCallTo. 7610 assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt, 7611 LLVMContext::OB_funclet, 7612 LLVMContext::OB_cfguardtarget}) && 7613 "Cannot lower calls with arbitrary operand bundles!"); 7614 7615 SDValue Callee = getValue(I.getCalledValue()); 7616 7617 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 7618 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 7619 else 7620 // Check if we can potentially perform a tail call. More detailed checking 7621 // is be done within LowerCallTo, after more information about the call is 7622 // known. 7623 LowerCallTo(&I, Callee, I.isTailCall()); 7624 } 7625 7626 namespace { 7627 7628 /// AsmOperandInfo - This contains information for each constraint that we are 7629 /// lowering. 7630 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 7631 public: 7632 /// CallOperand - If this is the result output operand or a clobber 7633 /// this is null, otherwise it is the incoming operand to the CallInst. 7634 /// This gets modified as the asm is processed. 7635 SDValue CallOperand; 7636 7637 /// AssignedRegs - If this is a register or register class operand, this 7638 /// contains the set of register corresponding to the operand. 7639 RegsForValue AssignedRegs; 7640 7641 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 7642 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 7643 } 7644 7645 /// Whether or not this operand accesses memory 7646 bool hasMemory(const TargetLowering &TLI) const { 7647 // Indirect operand accesses access memory. 7648 if (isIndirect) 7649 return true; 7650 7651 for (const auto &Code : Codes) 7652 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 7653 return true; 7654 7655 return false; 7656 } 7657 7658 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 7659 /// corresponds to. If there is no Value* for this operand, it returns 7660 /// MVT::Other. 7661 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 7662 const DataLayout &DL) const { 7663 if (!CallOperandVal) return MVT::Other; 7664 7665 if (isa<BasicBlock>(CallOperandVal)) 7666 return TLI.getPointerTy(DL); 7667 7668 llvm::Type *OpTy = CallOperandVal->getType(); 7669 7670 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 7671 // If this is an indirect operand, the operand is a pointer to the 7672 // accessed type. 7673 if (isIndirect) { 7674 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 7675 if (!PtrTy) 7676 report_fatal_error("Indirect operand for inline asm not a pointer!"); 7677 OpTy = PtrTy->getElementType(); 7678 } 7679 7680 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 7681 if (StructType *STy = dyn_cast<StructType>(OpTy)) 7682 if (STy->getNumElements() == 1) 7683 OpTy = STy->getElementType(0); 7684 7685 // If OpTy is not a single value, it may be a struct/union that we 7686 // can tile with integers. 7687 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 7688 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 7689 switch (BitSize) { 7690 default: break; 7691 case 1: 7692 case 8: 7693 case 16: 7694 case 32: 7695 case 64: 7696 case 128: 7697 OpTy = IntegerType::get(Context, BitSize); 7698 break; 7699 } 7700 } 7701 7702 return TLI.getValueType(DL, OpTy, true); 7703 } 7704 }; 7705 7706 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>; 7707 7708 } // end anonymous namespace 7709 7710 /// Make sure that the output operand \p OpInfo and its corresponding input 7711 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 7712 /// out). 7713 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 7714 SDISelAsmOperandInfo &MatchingOpInfo, 7715 SelectionDAG &DAG) { 7716 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 7717 return; 7718 7719 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 7720 const auto &TLI = DAG.getTargetLoweringInfo(); 7721 7722 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 7723 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 7724 OpInfo.ConstraintVT); 7725 std::pair<unsigned, const TargetRegisterClass *> InputRC = 7726 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 7727 MatchingOpInfo.ConstraintVT); 7728 if ((OpInfo.ConstraintVT.isInteger() != 7729 MatchingOpInfo.ConstraintVT.isInteger()) || 7730 (MatchRC.second != InputRC.second)) { 7731 // FIXME: error out in a more elegant fashion 7732 report_fatal_error("Unsupported asm: input constraint" 7733 " with a matching output constraint of" 7734 " incompatible type!"); 7735 } 7736 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 7737 } 7738 7739 /// Get a direct memory input to behave well as an indirect operand. 7740 /// This may introduce stores, hence the need for a \p Chain. 7741 /// \return The (possibly updated) chain. 7742 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 7743 SDISelAsmOperandInfo &OpInfo, 7744 SelectionDAG &DAG) { 7745 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7746 7747 // If we don't have an indirect input, put it in the constpool if we can, 7748 // otherwise spill it to a stack slot. 7749 // TODO: This isn't quite right. We need to handle these according to 7750 // the addressing mode that the constraint wants. Also, this may take 7751 // an additional register for the computation and we don't want that 7752 // either. 7753 7754 // If the operand is a float, integer, or vector constant, spill to a 7755 // constant pool entry to get its address. 7756 const Value *OpVal = OpInfo.CallOperandVal; 7757 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 7758 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 7759 OpInfo.CallOperand = DAG.getConstantPool( 7760 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 7761 return Chain; 7762 } 7763 7764 // Otherwise, create a stack slot and emit a store to it before the asm. 7765 Type *Ty = OpVal->getType(); 7766 auto &DL = DAG.getDataLayout(); 7767 uint64_t TySize = DL.getTypeAllocSize(Ty); 7768 unsigned Align = DL.getPrefTypeAlignment(Ty); 7769 MachineFunction &MF = DAG.getMachineFunction(); 7770 int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 7771 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 7772 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 7773 MachinePointerInfo::getFixedStack(MF, SSFI), 7774 TLI.getMemValueType(DL, Ty)); 7775 OpInfo.CallOperand = StackSlot; 7776 7777 return Chain; 7778 } 7779 7780 /// GetRegistersForValue - Assign registers (virtual or physical) for the 7781 /// specified operand. We prefer to assign virtual registers, to allow the 7782 /// register allocator to handle the assignment process. However, if the asm 7783 /// uses features that we can't model on machineinstrs, we have SDISel do the 7784 /// allocation. This produces generally horrible, but correct, code. 7785 /// 7786 /// OpInfo describes the operand 7787 /// RefOpInfo describes the matching operand if any, the operand otherwise 7788 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 7789 SDISelAsmOperandInfo &OpInfo, 7790 SDISelAsmOperandInfo &RefOpInfo) { 7791 LLVMContext &Context = *DAG.getContext(); 7792 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7793 7794 MachineFunction &MF = DAG.getMachineFunction(); 7795 SmallVector<unsigned, 4> Regs; 7796 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 7797 7798 // No work to do for memory operations. 7799 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 7800 return; 7801 7802 // If this is a constraint for a single physreg, or a constraint for a 7803 // register class, find it. 7804 unsigned AssignedReg; 7805 const TargetRegisterClass *RC; 7806 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 7807 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 7808 // RC is unset only on failure. Return immediately. 7809 if (!RC) 7810 return; 7811 7812 // Get the actual register value type. This is important, because the user 7813 // may have asked for (e.g.) the AX register in i32 type. We need to 7814 // remember that AX is actually i16 to get the right extension. 7815 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 7816 7817 if (OpInfo.ConstraintVT != MVT::Other) { 7818 // If this is an FP operand in an integer register (or visa versa), or more 7819 // generally if the operand value disagrees with the register class we plan 7820 // to stick it in, fix the operand type. 7821 // 7822 // If this is an input value, the bitcast to the new type is done now. 7823 // Bitcast for output value is done at the end of visitInlineAsm(). 7824 if ((OpInfo.Type == InlineAsm::isOutput || 7825 OpInfo.Type == InlineAsm::isInput) && 7826 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 7827 // Try to convert to the first EVT that the reg class contains. If the 7828 // types are identical size, use a bitcast to convert (e.g. two differing 7829 // vector types). Note: output bitcast is done at the end of 7830 // visitInlineAsm(). 7831 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 7832 // Exclude indirect inputs while they are unsupported because the code 7833 // to perform the load is missing and thus OpInfo.CallOperand still 7834 // refers to the input address rather than the pointed-to value. 7835 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 7836 OpInfo.CallOperand = 7837 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 7838 OpInfo.ConstraintVT = RegVT; 7839 // If the operand is an FP value and we want it in integer registers, 7840 // use the corresponding integer type. This turns an f64 value into 7841 // i64, which can be passed with two i32 values on a 32-bit machine. 7842 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 7843 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 7844 if (OpInfo.Type == InlineAsm::isInput) 7845 OpInfo.CallOperand = 7846 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 7847 OpInfo.ConstraintVT = VT; 7848 } 7849 } 7850 } 7851 7852 // No need to allocate a matching input constraint since the constraint it's 7853 // matching to has already been allocated. 7854 if (OpInfo.isMatchingInputConstraint()) 7855 return; 7856 7857 EVT ValueVT = OpInfo.ConstraintVT; 7858 if (OpInfo.ConstraintVT == MVT::Other) 7859 ValueVT = RegVT; 7860 7861 // Initialize NumRegs. 7862 unsigned NumRegs = 1; 7863 if (OpInfo.ConstraintVT != MVT::Other) 7864 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 7865 7866 // If this is a constraint for a specific physical register, like {r17}, 7867 // assign it now. 7868 7869 // If this associated to a specific register, initialize iterator to correct 7870 // place. If virtual, make sure we have enough registers 7871 7872 // Initialize iterator if necessary 7873 TargetRegisterClass::iterator I = RC->begin(); 7874 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7875 7876 // Do not check for single registers. 7877 if (AssignedReg) { 7878 for (; *I != AssignedReg; ++I) 7879 assert(I != RC->end() && "AssignedReg should be member of RC"); 7880 } 7881 7882 for (; NumRegs; --NumRegs, ++I) { 7883 assert(I != RC->end() && "Ran out of registers to allocate!"); 7884 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 7885 Regs.push_back(R); 7886 } 7887 7888 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 7889 } 7890 7891 static unsigned 7892 findMatchingInlineAsmOperand(unsigned OperandNo, 7893 const std::vector<SDValue> &AsmNodeOperands) { 7894 // Scan until we find the definition we already emitted of this operand. 7895 unsigned CurOp = InlineAsm::Op_FirstOperand; 7896 for (; OperandNo; --OperandNo) { 7897 // Advance to the next operand. 7898 unsigned OpFlag = 7899 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7900 assert((InlineAsm::isRegDefKind(OpFlag) || 7901 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 7902 InlineAsm::isMemKind(OpFlag)) && 7903 "Skipped past definitions?"); 7904 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 7905 } 7906 return CurOp; 7907 } 7908 7909 namespace { 7910 7911 class ExtraFlags { 7912 unsigned Flags = 0; 7913 7914 public: 7915 explicit ExtraFlags(ImmutableCallSite CS) { 7916 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7917 if (IA->hasSideEffects()) 7918 Flags |= InlineAsm::Extra_HasSideEffects; 7919 if (IA->isAlignStack()) 7920 Flags |= InlineAsm::Extra_IsAlignStack; 7921 if (CS.isConvergent()) 7922 Flags |= InlineAsm::Extra_IsConvergent; 7923 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 7924 } 7925 7926 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 7927 // Ideally, we would only check against memory constraints. However, the 7928 // meaning of an Other constraint can be target-specific and we can't easily 7929 // reason about it. Therefore, be conservative and set MayLoad/MayStore 7930 // for Other constraints as well. 7931 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 7932 OpInfo.ConstraintType == TargetLowering::C_Other) { 7933 if (OpInfo.Type == InlineAsm::isInput) 7934 Flags |= InlineAsm::Extra_MayLoad; 7935 else if (OpInfo.Type == InlineAsm::isOutput) 7936 Flags |= InlineAsm::Extra_MayStore; 7937 else if (OpInfo.Type == InlineAsm::isClobber) 7938 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 7939 } 7940 } 7941 7942 unsigned get() const { return Flags; } 7943 }; 7944 7945 } // end anonymous namespace 7946 7947 /// visitInlineAsm - Handle a call to an InlineAsm object. 7948 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) { 7949 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7950 7951 /// ConstraintOperands - Information about all of the constraints. 7952 SDISelAsmOperandInfoVector ConstraintOperands; 7953 7954 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7955 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 7956 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS); 7957 7958 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 7959 // AsmDialect, MayLoad, MayStore). 7960 bool HasSideEffect = IA->hasSideEffects(); 7961 ExtraFlags ExtraInfo(CS); 7962 7963 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 7964 unsigned ResNo = 0; // ResNo - The result number of the next output. 7965 for (auto &T : TargetConstraints) { 7966 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 7967 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 7968 7969 // Compute the value type for each operand. 7970 if (OpInfo.Type == InlineAsm::isInput || 7971 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 7972 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 7973 7974 // Process the call argument. BasicBlocks are labels, currently appearing 7975 // only in asm's. 7976 const Instruction *I = CS.getInstruction(); 7977 if (isa<CallBrInst>(I) && 7978 (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() - 7979 cast<CallBrInst>(I)->getNumIndirectDests())) { 7980 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal); 7981 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true); 7982 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT); 7983 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 7984 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 7985 } else { 7986 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 7987 } 7988 7989 OpInfo.ConstraintVT = 7990 OpInfo 7991 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout()) 7992 .getSimpleVT(); 7993 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 7994 // The return value of the call is this value. As such, there is no 7995 // corresponding argument. 7996 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 7997 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 7998 OpInfo.ConstraintVT = TLI.getSimpleValueType( 7999 DAG.getDataLayout(), STy->getElementType(ResNo)); 8000 } else { 8001 assert(ResNo == 0 && "Asm only has one result!"); 8002 OpInfo.ConstraintVT = 8003 TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType()); 8004 } 8005 ++ResNo; 8006 } else { 8007 OpInfo.ConstraintVT = MVT::Other; 8008 } 8009 8010 if (!HasSideEffect) 8011 HasSideEffect = OpInfo.hasMemory(TLI); 8012 8013 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8014 // FIXME: Could we compute this on OpInfo rather than T? 8015 8016 // Compute the constraint code and ConstraintType to use. 8017 TLI.ComputeConstraintToUse(T, SDValue()); 8018 8019 if (T.ConstraintType == TargetLowering::C_Immediate && 8020 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8021 // We've delayed emitting a diagnostic like the "n" constraint because 8022 // inlining could cause an integer showing up. 8023 return emitInlineAsmError( 8024 CS, "constraint '" + Twine(T.ConstraintCode) + "' expects an " 8025 "integer constant expression"); 8026 8027 ExtraInfo.update(T); 8028 } 8029 8030 8031 // We won't need to flush pending loads if this asm doesn't touch 8032 // memory and is nonvolatile. 8033 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8034 8035 bool IsCallBr = isa<CallBrInst>(CS.getInstruction()); 8036 if (IsCallBr) { 8037 // If this is a callbr we need to flush pending exports since inlineasm_br 8038 // is a terminator. We need to do this before nodes are glued to 8039 // the inlineasm_br node. 8040 Chain = getControlRoot(); 8041 } 8042 8043 // Second pass over the constraints: compute which constraint option to use. 8044 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8045 // If this is an output operand with a matching input operand, look up the 8046 // matching input. If their types mismatch, e.g. one is an integer, the 8047 // other is floating point, or their sizes are different, flag it as an 8048 // error. 8049 if (OpInfo.hasMatchingInput()) { 8050 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8051 patchMatchingInput(OpInfo, Input, DAG); 8052 } 8053 8054 // Compute the constraint code and ConstraintType to use. 8055 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8056 8057 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8058 OpInfo.Type == InlineAsm::isClobber) 8059 continue; 8060 8061 // If this is a memory input, and if the operand is not indirect, do what we 8062 // need to provide an address for the memory input. 8063 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8064 !OpInfo.isIndirect) { 8065 assert((OpInfo.isMultipleAlternative || 8066 (OpInfo.Type == InlineAsm::isInput)) && 8067 "Can only indirectify direct input operands!"); 8068 8069 // Memory operands really want the address of the value. 8070 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8071 8072 // There is no longer a Value* corresponding to this operand. 8073 OpInfo.CallOperandVal = nullptr; 8074 8075 // It is now an indirect operand. 8076 OpInfo.isIndirect = true; 8077 } 8078 8079 } 8080 8081 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8082 std::vector<SDValue> AsmNodeOperands; 8083 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8084 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8085 IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout()))); 8086 8087 // If we have a !srcloc metadata node associated with it, we want to attach 8088 // this to the ultimately generated inline asm machineinstr. To do this, we 8089 // pass in the third operand as this (potentially null) inline asm MDNode. 8090 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc"); 8091 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8092 8093 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8094 // bits as operand 3. 8095 AsmNodeOperands.push_back(DAG.getTargetConstant( 8096 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8097 8098 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8099 // this, assign virtual and physical registers for inputs and otput. 8100 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8101 // Assign Registers. 8102 SDISelAsmOperandInfo &RefOpInfo = 8103 OpInfo.isMatchingInputConstraint() 8104 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8105 : OpInfo; 8106 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8107 8108 switch (OpInfo.Type) { 8109 case InlineAsm::isOutput: 8110 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8111 ((OpInfo.ConstraintType == TargetLowering::C_Immediate || 8112 OpInfo.ConstraintType == TargetLowering::C_Other) && 8113 OpInfo.isIndirect)) { 8114 unsigned ConstraintID = 8115 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8116 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8117 "Failed to convert memory constraint code to constraint id."); 8118 8119 // Add information to the INLINEASM node to know about this output. 8120 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8121 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8122 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8123 MVT::i32)); 8124 AsmNodeOperands.push_back(OpInfo.CallOperand); 8125 break; 8126 } else if (((OpInfo.ConstraintType == TargetLowering::C_Immediate || 8127 OpInfo.ConstraintType == TargetLowering::C_Other) && 8128 !OpInfo.isIndirect) || 8129 OpInfo.ConstraintType == TargetLowering::C_Register || 8130 OpInfo.ConstraintType == TargetLowering::C_RegisterClass) { 8131 // Otherwise, this outputs to a register (directly for C_Register / 8132 // C_RegisterClass, and a target-defined fashion for 8133 // C_Immediate/C_Other). Find a register that we can use. 8134 if (OpInfo.AssignedRegs.Regs.empty()) { 8135 emitInlineAsmError( 8136 CS, "couldn't allocate output register for constraint '" + 8137 Twine(OpInfo.ConstraintCode) + "'"); 8138 return; 8139 } 8140 8141 // Add information to the INLINEASM node to know that this register is 8142 // set. 8143 OpInfo.AssignedRegs.AddInlineAsmOperands( 8144 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8145 : InlineAsm::Kind_RegDef, 8146 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8147 } 8148 break; 8149 8150 case InlineAsm::isInput: { 8151 SDValue InOperandVal = OpInfo.CallOperand; 8152 8153 if (OpInfo.isMatchingInputConstraint()) { 8154 // If this is required to match an output register we have already set, 8155 // just use its register. 8156 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8157 AsmNodeOperands); 8158 unsigned OpFlag = 8159 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8160 if (InlineAsm::isRegDefKind(OpFlag) || 8161 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8162 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8163 if (OpInfo.isIndirect) { 8164 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8165 emitInlineAsmError(CS, "inline asm not supported yet:" 8166 " don't know how to handle tied " 8167 "indirect register inputs"); 8168 return; 8169 } 8170 8171 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 8172 SmallVector<unsigned, 4> Regs; 8173 8174 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { 8175 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8176 MachineRegisterInfo &RegInfo = 8177 DAG.getMachineFunction().getRegInfo(); 8178 for (unsigned i = 0; i != NumRegs; ++i) 8179 Regs.push_back(RegInfo.createVirtualRegister(RC)); 8180 } else { 8181 emitInlineAsmError(CS, "inline asm error: This value type register " 8182 "class is not natively supported!"); 8183 return; 8184 } 8185 8186 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8187 8188 SDLoc dl = getCurSDLoc(); 8189 // Use the produced MatchedRegs object to 8190 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 8191 CS.getInstruction()); 8192 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8193 true, OpInfo.getMatchedOperand(), dl, 8194 DAG, AsmNodeOperands); 8195 break; 8196 } 8197 8198 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8199 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8200 "Unexpected number of operands"); 8201 // Add information to the INLINEASM node to know about this input. 8202 // See InlineAsm.h isUseOperandTiedToDef. 8203 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8204 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8205 OpInfo.getMatchedOperand()); 8206 AsmNodeOperands.push_back(DAG.getTargetConstant( 8207 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8208 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8209 break; 8210 } 8211 8212 // Treat indirect 'X' constraint as memory. 8213 if ((OpInfo.ConstraintType == TargetLowering::C_Immediate || 8214 OpInfo.ConstraintType == TargetLowering::C_Other) && 8215 OpInfo.isIndirect) 8216 OpInfo.ConstraintType = TargetLowering::C_Memory; 8217 8218 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 8219 OpInfo.ConstraintType == TargetLowering::C_Other) { 8220 std::vector<SDValue> Ops; 8221 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 8222 Ops, DAG); 8223 if (Ops.empty()) { 8224 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 8225 if (isa<ConstantSDNode>(InOperandVal)) { 8226 emitInlineAsmError(CS, "value out of range for constraint '" + 8227 Twine(OpInfo.ConstraintCode) + "'"); 8228 return; 8229 } 8230 8231 emitInlineAsmError(CS, "invalid operand for inline asm constraint '" + 8232 Twine(OpInfo.ConstraintCode) + "'"); 8233 return; 8234 } 8235 8236 // Add information to the INLINEASM node to know about this input. 8237 unsigned ResOpType = 8238 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 8239 AsmNodeOperands.push_back(DAG.getTargetConstant( 8240 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8241 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 8242 break; 8243 } 8244 8245 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8246 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 8247 assert(InOperandVal.getValueType() == 8248 TLI.getPointerTy(DAG.getDataLayout()) && 8249 "Memory operands expect pointer values"); 8250 8251 unsigned ConstraintID = 8252 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8253 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8254 "Failed to convert memory constraint code to constraint id."); 8255 8256 // Add information to the INLINEASM node to know about this input. 8257 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8258 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 8259 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 8260 getCurSDLoc(), 8261 MVT::i32)); 8262 AsmNodeOperands.push_back(InOperandVal); 8263 break; 8264 } 8265 8266 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 8267 OpInfo.ConstraintType == TargetLowering::C_Register || 8268 OpInfo.ConstraintType == TargetLowering::C_Immediate) && 8269 "Unknown constraint type!"); 8270 8271 // TODO: Support this. 8272 if (OpInfo.isIndirect) { 8273 emitInlineAsmError( 8274 CS, "Don't know how to handle indirect register inputs yet " 8275 "for constraint '" + 8276 Twine(OpInfo.ConstraintCode) + "'"); 8277 return; 8278 } 8279 8280 // Copy the input into the appropriate registers. 8281 if (OpInfo.AssignedRegs.Regs.empty()) { 8282 emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" + 8283 Twine(OpInfo.ConstraintCode) + "'"); 8284 return; 8285 } 8286 8287 SDLoc dl = getCurSDLoc(); 8288 8289 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, 8290 Chain, &Flag, CS.getInstruction()); 8291 8292 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 8293 dl, DAG, AsmNodeOperands); 8294 break; 8295 } 8296 case InlineAsm::isClobber: 8297 // Add the clobbered value to the operand list, so that the register 8298 // allocator is aware that the physreg got clobbered. 8299 if (!OpInfo.AssignedRegs.Regs.empty()) 8300 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 8301 false, 0, getCurSDLoc(), DAG, 8302 AsmNodeOperands); 8303 break; 8304 } 8305 } 8306 8307 // Finish up input operands. Set the input chain and add the flag last. 8308 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 8309 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 8310 8311 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 8312 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 8313 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 8314 Flag = Chain.getValue(1); 8315 8316 // Do additional work to generate outputs. 8317 8318 SmallVector<EVT, 1> ResultVTs; 8319 SmallVector<SDValue, 1> ResultValues; 8320 SmallVector<SDValue, 8> OutChains; 8321 8322 llvm::Type *CSResultType = CS.getType(); 8323 ArrayRef<Type *> ResultTypes; 8324 if (StructType *StructResult = dyn_cast<StructType>(CSResultType)) 8325 ResultTypes = StructResult->elements(); 8326 else if (!CSResultType->isVoidTy()) 8327 ResultTypes = makeArrayRef(CSResultType); 8328 8329 auto CurResultType = ResultTypes.begin(); 8330 auto handleRegAssign = [&](SDValue V) { 8331 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 8332 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 8333 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 8334 ++CurResultType; 8335 // If the type of the inline asm call site return value is different but has 8336 // same size as the type of the asm output bitcast it. One example of this 8337 // is for vectors with different width / number of elements. This can 8338 // happen for register classes that can contain multiple different value 8339 // types. The preg or vreg allocated may not have the same VT as was 8340 // expected. 8341 // 8342 // This can also happen for a return value that disagrees with the register 8343 // class it is put in, eg. a double in a general-purpose register on a 8344 // 32-bit machine. 8345 if (ResultVT != V.getValueType() && 8346 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 8347 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 8348 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 8349 V.getValueType().isInteger()) { 8350 // If a result value was tied to an input value, the computed result 8351 // may have a wider width than the expected result. Extract the 8352 // relevant portion. 8353 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 8354 } 8355 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 8356 ResultVTs.push_back(ResultVT); 8357 ResultValues.push_back(V); 8358 }; 8359 8360 // Deal with output operands. 8361 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8362 if (OpInfo.Type == InlineAsm::isOutput) { 8363 SDValue Val; 8364 // Skip trivial output operands. 8365 if (OpInfo.AssignedRegs.Regs.empty()) 8366 continue; 8367 8368 switch (OpInfo.ConstraintType) { 8369 case TargetLowering::C_Register: 8370 case TargetLowering::C_RegisterClass: 8371 Val = OpInfo.AssignedRegs.getCopyFromRegs( 8372 DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction()); 8373 break; 8374 case TargetLowering::C_Immediate: 8375 case TargetLowering::C_Other: 8376 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 8377 OpInfo, DAG); 8378 break; 8379 case TargetLowering::C_Memory: 8380 break; // Already handled. 8381 case TargetLowering::C_Unknown: 8382 assert(false && "Unexpected unknown constraint"); 8383 } 8384 8385 // Indirect output manifest as stores. Record output chains. 8386 if (OpInfo.isIndirect) { 8387 const Value *Ptr = OpInfo.CallOperandVal; 8388 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 8389 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 8390 MachinePointerInfo(Ptr)); 8391 OutChains.push_back(Store); 8392 } else { 8393 // generate CopyFromRegs to associated registers. 8394 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 8395 if (Val.getOpcode() == ISD::MERGE_VALUES) { 8396 for (const SDValue &V : Val->op_values()) 8397 handleRegAssign(V); 8398 } else 8399 handleRegAssign(Val); 8400 } 8401 } 8402 } 8403 8404 // Set results. 8405 if (!ResultValues.empty()) { 8406 assert(CurResultType == ResultTypes.end() && 8407 "Mismatch in number of ResultTypes"); 8408 assert(ResultValues.size() == ResultTypes.size() && 8409 "Mismatch in number of output operands in asm result"); 8410 8411 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 8412 DAG.getVTList(ResultVTs), ResultValues); 8413 setValue(CS.getInstruction(), V); 8414 } 8415 8416 // Collect store chains. 8417 if (!OutChains.empty()) 8418 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 8419 8420 // Only Update Root if inline assembly has a memory effect. 8421 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr) 8422 DAG.setRoot(Chain); 8423 } 8424 8425 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS, 8426 const Twine &Message) { 8427 LLVMContext &Ctx = *DAG.getContext(); 8428 Ctx.emitError(CS.getInstruction(), Message); 8429 8430 // Make sure we leave the DAG in a valid state 8431 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8432 SmallVector<EVT, 1> ValueVTs; 8433 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8434 8435 if (ValueVTs.empty()) 8436 return; 8437 8438 SmallVector<SDValue, 1> Ops; 8439 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 8440 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 8441 8442 setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc())); 8443 } 8444 8445 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 8446 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 8447 MVT::Other, getRoot(), 8448 getValue(I.getArgOperand(0)), 8449 DAG.getSrcValue(I.getArgOperand(0)))); 8450 } 8451 8452 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 8453 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8454 const DataLayout &DL = DAG.getDataLayout(); 8455 SDValue V = DAG.getVAArg( 8456 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 8457 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 8458 DL.getABITypeAlignment(I.getType())); 8459 DAG.setRoot(V.getValue(1)); 8460 8461 if (I.getType()->isPointerTy()) 8462 V = DAG.getPtrExtOrTrunc( 8463 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 8464 setValue(&I, V); 8465 } 8466 8467 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 8468 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 8469 MVT::Other, getRoot(), 8470 getValue(I.getArgOperand(0)), 8471 DAG.getSrcValue(I.getArgOperand(0)))); 8472 } 8473 8474 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 8475 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 8476 MVT::Other, getRoot(), 8477 getValue(I.getArgOperand(0)), 8478 getValue(I.getArgOperand(1)), 8479 DAG.getSrcValue(I.getArgOperand(0)), 8480 DAG.getSrcValue(I.getArgOperand(1)))); 8481 } 8482 8483 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 8484 const Instruction &I, 8485 SDValue Op) { 8486 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 8487 if (!Range) 8488 return Op; 8489 8490 ConstantRange CR = getConstantRangeFromMetadata(*Range); 8491 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 8492 return Op; 8493 8494 APInt Lo = CR.getUnsignedMin(); 8495 if (!Lo.isMinValue()) 8496 return Op; 8497 8498 APInt Hi = CR.getUnsignedMax(); 8499 unsigned Bits = std::max(Hi.getActiveBits(), 8500 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 8501 8502 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8503 8504 SDLoc SL = getCurSDLoc(); 8505 8506 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8507 DAG.getValueType(SmallVT)); 8508 unsigned NumVals = Op.getNode()->getNumValues(); 8509 if (NumVals == 1) 8510 return ZExt; 8511 8512 SmallVector<SDValue, 4> Ops; 8513 8514 Ops.push_back(ZExt); 8515 for (unsigned I = 1; I != NumVals; ++I) 8516 Ops.push_back(Op.getValue(I)); 8517 8518 return DAG.getMergeValues(Ops, SL); 8519 } 8520 8521 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8522 /// the call being lowered. 8523 /// 8524 /// This is a helper for lowering intrinsics that follow a target calling 8525 /// convention or require stack pointer adjustment. Only a subset of the 8526 /// intrinsic's operands need to participate in the calling convention. 8527 void SelectionDAGBuilder::populateCallLoweringInfo( 8528 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 8529 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8530 bool IsPatchPoint) { 8531 TargetLowering::ArgListTy Args; 8532 Args.reserve(NumArgs); 8533 8534 // Populate the argument list. 8535 // Attributes for args start at offset 1, after the return attribute. 8536 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8537 ArgI != ArgE; ++ArgI) { 8538 const Value *V = Call->getOperand(ArgI); 8539 8540 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 8541 8542 TargetLowering::ArgListEntry Entry; 8543 Entry.Node = getValue(V); 8544 Entry.Ty = V->getType(); 8545 Entry.setAttributes(Call, ArgI); 8546 Args.push_back(Entry); 8547 } 8548 8549 CLI.setDebugLoc(getCurSDLoc()) 8550 .setChain(getRoot()) 8551 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 8552 .setDiscardResult(Call->use_empty()) 8553 .setIsPatchPoint(IsPatchPoint); 8554 } 8555 8556 /// Add a stack map intrinsic call's live variable operands to a stackmap 8557 /// or patchpoint target node's operand list. 8558 /// 8559 /// Constants are converted to TargetConstants purely as an optimization to 8560 /// avoid constant materialization and register allocation. 8561 /// 8562 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 8563 /// generate addess computation nodes, and so FinalizeISel can convert the 8564 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 8565 /// address materialization and register allocation, but may also be required 8566 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 8567 /// alloca in the entry block, then the runtime may assume that the alloca's 8568 /// StackMap location can be read immediately after compilation and that the 8569 /// location is valid at any point during execution (this is similar to the 8570 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 8571 /// only available in a register, then the runtime would need to trap when 8572 /// execution reaches the StackMap in order to read the alloca's location. 8573 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx, 8574 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 8575 SelectionDAGBuilder &Builder) { 8576 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) { 8577 SDValue OpVal = Builder.getValue(CS.getArgument(i)); 8578 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 8579 Ops.push_back( 8580 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 8581 Ops.push_back( 8582 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 8583 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 8584 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 8585 Ops.push_back(Builder.DAG.getTargetFrameIndex( 8586 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 8587 } else 8588 Ops.push_back(OpVal); 8589 } 8590 } 8591 8592 /// Lower llvm.experimental.stackmap directly to its target opcode. 8593 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 8594 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 8595 // [live variables...]) 8596 8597 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 8598 8599 SDValue Chain, InFlag, Callee, NullPtr; 8600 SmallVector<SDValue, 32> Ops; 8601 8602 SDLoc DL = getCurSDLoc(); 8603 Callee = getValue(CI.getCalledValue()); 8604 NullPtr = DAG.getIntPtrConstant(0, DL, true); 8605 8606 // The stackmap intrinsic only records the live variables (the arguments 8607 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 8608 // intrinsic, this won't be lowered to a function call. This means we don't 8609 // have to worry about calling conventions and target specific lowering code. 8610 // Instead we perform the call lowering right here. 8611 // 8612 // chain, flag = CALLSEQ_START(chain, 0, 0) 8613 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 8614 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 8615 // 8616 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 8617 InFlag = Chain.getValue(1); 8618 8619 // Add the <id> and <numBytes> constants. 8620 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 8621 Ops.push_back(DAG.getTargetConstant( 8622 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 8623 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 8624 Ops.push_back(DAG.getTargetConstant( 8625 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 8626 MVT::i32)); 8627 8628 // Push live variables for the stack map. 8629 addStackMapLiveVars(&CI, 2, DL, Ops, *this); 8630 8631 // We are not pushing any register mask info here on the operands list, 8632 // because the stackmap doesn't clobber anything. 8633 8634 // Push the chain and the glue flag. 8635 Ops.push_back(Chain); 8636 Ops.push_back(InFlag); 8637 8638 // Create the STACKMAP node. 8639 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8640 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 8641 Chain = SDValue(SM, 0); 8642 InFlag = Chain.getValue(1); 8643 8644 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 8645 8646 // Stackmaps don't generate values, so nothing goes into the NodeMap. 8647 8648 // Set the root to the target-lowered call chain. 8649 DAG.setRoot(Chain); 8650 8651 // Inform the Frame Information that we have a stackmap in this function. 8652 FuncInfo.MF->getFrameInfo().setHasStackMap(); 8653 } 8654 8655 /// Lower llvm.experimental.patchpoint directly to its target opcode. 8656 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS, 8657 const BasicBlock *EHPadBB) { 8658 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 8659 // i32 <numBytes>, 8660 // i8* <target>, 8661 // i32 <numArgs>, 8662 // [Args...], 8663 // [live variables...]) 8664 8665 CallingConv::ID CC = CS.getCallingConv(); 8666 bool IsAnyRegCC = CC == CallingConv::AnyReg; 8667 bool HasDef = !CS->getType()->isVoidTy(); 8668 SDLoc dl = getCurSDLoc(); 8669 SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos)); 8670 8671 // Handle immediate and symbolic callees. 8672 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 8673 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 8674 /*isTarget=*/true); 8675 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 8676 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 8677 SDLoc(SymbolicCallee), 8678 SymbolicCallee->getValueType(0)); 8679 8680 // Get the real number of arguments participating in the call <numArgs> 8681 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos)); 8682 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 8683 8684 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 8685 // Intrinsics include all meta-operands up to but not including CC. 8686 unsigned NumMetaOpers = PatchPointOpers::CCPos; 8687 assert(CS.arg_size() >= NumMetaOpers + NumArgs && 8688 "Not enough arguments provided to the patchpoint intrinsic"); 8689 8690 // For AnyRegCC the arguments are lowered later on manually. 8691 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 8692 Type *ReturnTy = 8693 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType(); 8694 8695 TargetLowering::CallLoweringInfo CLI(DAG); 8696 populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()), 8697 NumMetaOpers, NumCallArgs, Callee, ReturnTy, true); 8698 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8699 8700 SDNode *CallEnd = Result.second.getNode(); 8701 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 8702 CallEnd = CallEnd->getOperand(0).getNode(); 8703 8704 /// Get a call instruction from the call sequence chain. 8705 /// Tail calls are not allowed. 8706 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 8707 "Expected a callseq node."); 8708 SDNode *Call = CallEnd->getOperand(0).getNode(); 8709 bool HasGlue = Call->getGluedNode(); 8710 8711 // Replace the target specific call node with the patchable intrinsic. 8712 SmallVector<SDValue, 8> Ops; 8713 8714 // Add the <id> and <numBytes> constants. 8715 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos)); 8716 Ops.push_back(DAG.getTargetConstant( 8717 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 8718 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos)); 8719 Ops.push_back(DAG.getTargetConstant( 8720 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 8721 MVT::i32)); 8722 8723 // Add the callee. 8724 Ops.push_back(Callee); 8725 8726 // Adjust <numArgs> to account for any arguments that have been passed on the 8727 // stack instead. 8728 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 8729 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 8730 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 8731 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 8732 8733 // Add the calling convention 8734 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 8735 8736 // Add the arguments we omitted previously. The register allocator should 8737 // place these in any free register. 8738 if (IsAnyRegCC) 8739 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 8740 Ops.push_back(getValue(CS.getArgument(i))); 8741 8742 // Push the arguments from the call instruction up to the register mask. 8743 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 8744 Ops.append(Call->op_begin() + 2, e); 8745 8746 // Push live variables for the stack map. 8747 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this); 8748 8749 // Push the register mask info. 8750 if (HasGlue) 8751 Ops.push_back(*(Call->op_end()-2)); 8752 else 8753 Ops.push_back(*(Call->op_end()-1)); 8754 8755 // Push the chain (this is originally the first operand of the call, but 8756 // becomes now the last or second to last operand). 8757 Ops.push_back(*(Call->op_begin())); 8758 8759 // Push the glue flag (last operand). 8760 if (HasGlue) 8761 Ops.push_back(*(Call->op_end()-1)); 8762 8763 SDVTList NodeTys; 8764 if (IsAnyRegCC && HasDef) { 8765 // Create the return types based on the intrinsic definition 8766 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8767 SmallVector<EVT, 3> ValueVTs; 8768 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8769 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 8770 8771 // There is always a chain and a glue type at the end 8772 ValueVTs.push_back(MVT::Other); 8773 ValueVTs.push_back(MVT::Glue); 8774 NodeTys = DAG.getVTList(ValueVTs); 8775 } else 8776 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8777 8778 // Replace the target specific call node with a PATCHPOINT node. 8779 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 8780 dl, NodeTys, Ops); 8781 8782 // Update the NodeMap. 8783 if (HasDef) { 8784 if (IsAnyRegCC) 8785 setValue(CS.getInstruction(), SDValue(MN, 0)); 8786 else 8787 setValue(CS.getInstruction(), Result.first); 8788 } 8789 8790 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 8791 // call sequence. Furthermore the location of the chain and glue can change 8792 // when the AnyReg calling convention is used and the intrinsic returns a 8793 // value. 8794 if (IsAnyRegCC && HasDef) { 8795 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 8796 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 8797 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 8798 } else 8799 DAG.ReplaceAllUsesWith(Call, MN); 8800 DAG.DeleteNode(Call); 8801 8802 // Inform the Frame Information that we have a patchpoint in this function. 8803 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 8804 } 8805 8806 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 8807 unsigned Intrinsic) { 8808 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8809 SDValue Op1 = getValue(I.getArgOperand(0)); 8810 SDValue Op2; 8811 if (I.getNumArgOperands() > 1) 8812 Op2 = getValue(I.getArgOperand(1)); 8813 SDLoc dl = getCurSDLoc(); 8814 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8815 SDValue Res; 8816 FastMathFlags FMF; 8817 if (isa<FPMathOperator>(I)) 8818 FMF = I.getFastMathFlags(); 8819 8820 switch (Intrinsic) { 8821 case Intrinsic::experimental_vector_reduce_v2_fadd: 8822 if (FMF.allowReassoc()) 8823 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 8824 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2)); 8825 else 8826 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2); 8827 break; 8828 case Intrinsic::experimental_vector_reduce_v2_fmul: 8829 if (FMF.allowReassoc()) 8830 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 8831 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2)); 8832 else 8833 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2); 8834 break; 8835 case Intrinsic::experimental_vector_reduce_add: 8836 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 8837 break; 8838 case Intrinsic::experimental_vector_reduce_mul: 8839 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 8840 break; 8841 case Intrinsic::experimental_vector_reduce_and: 8842 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 8843 break; 8844 case Intrinsic::experimental_vector_reduce_or: 8845 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 8846 break; 8847 case Intrinsic::experimental_vector_reduce_xor: 8848 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 8849 break; 8850 case Intrinsic::experimental_vector_reduce_smax: 8851 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 8852 break; 8853 case Intrinsic::experimental_vector_reduce_smin: 8854 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 8855 break; 8856 case Intrinsic::experimental_vector_reduce_umax: 8857 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 8858 break; 8859 case Intrinsic::experimental_vector_reduce_umin: 8860 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 8861 break; 8862 case Intrinsic::experimental_vector_reduce_fmax: 8863 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1); 8864 break; 8865 case Intrinsic::experimental_vector_reduce_fmin: 8866 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1); 8867 break; 8868 default: 8869 llvm_unreachable("Unhandled vector reduce intrinsic"); 8870 } 8871 setValue(&I, Res); 8872 } 8873 8874 /// Returns an AttributeList representing the attributes applied to the return 8875 /// value of the given call. 8876 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 8877 SmallVector<Attribute::AttrKind, 2> Attrs; 8878 if (CLI.RetSExt) 8879 Attrs.push_back(Attribute::SExt); 8880 if (CLI.RetZExt) 8881 Attrs.push_back(Attribute::ZExt); 8882 if (CLI.IsInReg) 8883 Attrs.push_back(Attribute::InReg); 8884 8885 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 8886 Attrs); 8887 } 8888 8889 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 8890 /// implementation, which just calls LowerCall. 8891 /// FIXME: When all targets are 8892 /// migrated to using LowerCall, this hook should be integrated into SDISel. 8893 std::pair<SDValue, SDValue> 8894 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 8895 // Handle the incoming return values from the call. 8896 CLI.Ins.clear(); 8897 Type *OrigRetTy = CLI.RetTy; 8898 SmallVector<EVT, 4> RetTys; 8899 SmallVector<uint64_t, 4> Offsets; 8900 auto &DL = CLI.DAG.getDataLayout(); 8901 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 8902 8903 if (CLI.IsPostTypeLegalization) { 8904 // If we are lowering a libcall after legalization, split the return type. 8905 SmallVector<EVT, 4> OldRetTys; 8906 SmallVector<uint64_t, 4> OldOffsets; 8907 RetTys.swap(OldRetTys); 8908 Offsets.swap(OldOffsets); 8909 8910 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 8911 EVT RetVT = OldRetTys[i]; 8912 uint64_t Offset = OldOffsets[i]; 8913 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 8914 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 8915 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 8916 RetTys.append(NumRegs, RegisterVT); 8917 for (unsigned j = 0; j != NumRegs; ++j) 8918 Offsets.push_back(Offset + j * RegisterVTByteSZ); 8919 } 8920 } 8921 8922 SmallVector<ISD::OutputArg, 4> Outs; 8923 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 8924 8925 bool CanLowerReturn = 8926 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 8927 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 8928 8929 SDValue DemoteStackSlot; 8930 int DemoteStackIdx = -100; 8931 if (!CanLowerReturn) { 8932 // FIXME: equivalent assert? 8933 // assert(!CS.hasInAllocaArgument() && 8934 // "sret demotion is incompatible with inalloca"); 8935 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 8936 unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy); 8937 MachineFunction &MF = CLI.DAG.getMachineFunction(); 8938 DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 8939 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 8940 DL.getAllocaAddrSpace()); 8941 8942 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 8943 ArgListEntry Entry; 8944 Entry.Node = DemoteStackSlot; 8945 Entry.Ty = StackSlotPtrType; 8946 Entry.IsSExt = false; 8947 Entry.IsZExt = false; 8948 Entry.IsInReg = false; 8949 Entry.IsSRet = true; 8950 Entry.IsNest = false; 8951 Entry.IsByVal = false; 8952 Entry.IsReturned = false; 8953 Entry.IsSwiftSelf = false; 8954 Entry.IsSwiftError = false; 8955 Entry.IsCFGuardTarget = false; 8956 Entry.Alignment = Align; 8957 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 8958 CLI.NumFixedArgs += 1; 8959 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 8960 8961 // sret demotion isn't compatible with tail-calls, since the sret argument 8962 // points into the callers stack frame. 8963 CLI.IsTailCall = false; 8964 } else { 8965 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 8966 CLI.RetTy, CLI.CallConv, CLI.IsVarArg); 8967 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 8968 ISD::ArgFlagsTy Flags; 8969 if (NeedsRegBlock) { 8970 Flags.setInConsecutiveRegs(); 8971 if (I == RetTys.size() - 1) 8972 Flags.setInConsecutiveRegsLast(); 8973 } 8974 EVT VT = RetTys[I]; 8975 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 8976 CLI.CallConv, VT); 8977 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 8978 CLI.CallConv, VT); 8979 for (unsigned i = 0; i != NumRegs; ++i) { 8980 ISD::InputArg MyFlags; 8981 MyFlags.Flags = Flags; 8982 MyFlags.VT = RegisterVT; 8983 MyFlags.ArgVT = VT; 8984 MyFlags.Used = CLI.IsReturnValueUsed; 8985 if (CLI.RetTy->isPointerTy()) { 8986 MyFlags.Flags.setPointer(); 8987 MyFlags.Flags.setPointerAddrSpace( 8988 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 8989 } 8990 if (CLI.RetSExt) 8991 MyFlags.Flags.setSExt(); 8992 if (CLI.RetZExt) 8993 MyFlags.Flags.setZExt(); 8994 if (CLI.IsInReg) 8995 MyFlags.Flags.setInReg(); 8996 CLI.Ins.push_back(MyFlags); 8997 } 8998 } 8999 } 9000 9001 // We push in swifterror return as the last element of CLI.Ins. 9002 ArgListTy &Args = CLI.getArgs(); 9003 if (supportSwiftError()) { 9004 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9005 if (Args[i].IsSwiftError) { 9006 ISD::InputArg MyFlags; 9007 MyFlags.VT = getPointerTy(DL); 9008 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9009 MyFlags.Flags.setSwiftError(); 9010 CLI.Ins.push_back(MyFlags); 9011 } 9012 } 9013 } 9014 9015 // Handle all of the outgoing arguments. 9016 CLI.Outs.clear(); 9017 CLI.OutVals.clear(); 9018 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9019 SmallVector<EVT, 4> ValueVTs; 9020 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9021 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9022 Type *FinalType = Args[i].Ty; 9023 if (Args[i].IsByVal) 9024 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 9025 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9026 FinalType, CLI.CallConv, CLI.IsVarArg); 9027 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9028 ++Value) { 9029 EVT VT = ValueVTs[Value]; 9030 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9031 SDValue Op = SDValue(Args[i].Node.getNode(), 9032 Args[i].Node.getResNo() + Value); 9033 ISD::ArgFlagsTy Flags; 9034 9035 // Certain targets (such as MIPS), may have a different ABI alignment 9036 // for a type depending on the context. Give the target a chance to 9037 // specify the alignment it wants. 9038 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 9039 9040 if (Args[i].Ty->isPointerTy()) { 9041 Flags.setPointer(); 9042 Flags.setPointerAddrSpace( 9043 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9044 } 9045 if (Args[i].IsZExt) 9046 Flags.setZExt(); 9047 if (Args[i].IsSExt) 9048 Flags.setSExt(); 9049 if (Args[i].IsInReg) { 9050 // If we are using vectorcall calling convention, a structure that is 9051 // passed InReg - is surely an HVA 9052 if (CLI.CallConv == CallingConv::X86_VectorCall && 9053 isa<StructType>(FinalType)) { 9054 // The first value of a structure is marked 9055 if (0 == Value) 9056 Flags.setHvaStart(); 9057 Flags.setHva(); 9058 } 9059 // Set InReg Flag 9060 Flags.setInReg(); 9061 } 9062 if (Args[i].IsSRet) 9063 Flags.setSRet(); 9064 if (Args[i].IsSwiftSelf) 9065 Flags.setSwiftSelf(); 9066 if (Args[i].IsSwiftError) 9067 Flags.setSwiftError(); 9068 if (Args[i].IsCFGuardTarget) 9069 Flags.setCFGuardTarget(); 9070 if (Args[i].IsByVal) 9071 Flags.setByVal(); 9072 if (Args[i].IsInAlloca) { 9073 Flags.setInAlloca(); 9074 // Set the byval flag for CCAssignFn callbacks that don't know about 9075 // inalloca. This way we can know how many bytes we should've allocated 9076 // and how many bytes a callee cleanup function will pop. If we port 9077 // inalloca to more targets, we'll have to add custom inalloca handling 9078 // in the various CC lowering callbacks. 9079 Flags.setByVal(); 9080 } 9081 if (Args[i].IsByVal || Args[i].IsInAlloca) { 9082 PointerType *Ty = cast<PointerType>(Args[i].Ty); 9083 Type *ElementTy = Ty->getElementType(); 9084 9085 unsigned FrameSize = DL.getTypeAllocSize( 9086 Args[i].ByValType ? Args[i].ByValType : ElementTy); 9087 Flags.setByValSize(FrameSize); 9088 9089 // info is not there but there are cases it cannot get right. 9090 unsigned FrameAlign; 9091 if (Args[i].Alignment) 9092 FrameAlign = Args[i].Alignment; 9093 else 9094 FrameAlign = getByValTypeAlignment(ElementTy, DL); 9095 Flags.setByValAlign(Align(FrameAlign)); 9096 } 9097 if (Args[i].IsNest) 9098 Flags.setNest(); 9099 if (NeedsRegBlock) 9100 Flags.setInConsecutiveRegs(); 9101 Flags.setOrigAlign(OriginalAlignment); 9102 9103 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9104 CLI.CallConv, VT); 9105 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9106 CLI.CallConv, VT); 9107 SmallVector<SDValue, 4> Parts(NumParts); 9108 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9109 9110 if (Args[i].IsSExt) 9111 ExtendKind = ISD::SIGN_EXTEND; 9112 else if (Args[i].IsZExt) 9113 ExtendKind = ISD::ZERO_EXTEND; 9114 9115 // Conservatively only handle 'returned' on non-vectors that can be lowered, 9116 // for now. 9117 if (Args[i].IsReturned && !Op.getValueType().isVector() && 9118 CanLowerReturn) { 9119 assert((CLI.RetTy == Args[i].Ty || 9120 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 9121 CLI.RetTy->getPointerAddressSpace() == 9122 Args[i].Ty->getPointerAddressSpace())) && 9123 RetTys.size() == NumValues && "unexpected use of 'returned'"); 9124 // Before passing 'returned' to the target lowering code, ensure that 9125 // either the register MVT and the actual EVT are the same size or that 9126 // the return value and argument are extended in the same way; in these 9127 // cases it's safe to pass the argument register value unchanged as the 9128 // return register value (although it's at the target's option whether 9129 // to do so) 9130 // TODO: allow code generation to take advantage of partially preserved 9131 // registers rather than clobbering the entire register when the 9132 // parameter extension method is not compatible with the return 9133 // extension method 9134 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9135 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9136 CLI.RetZExt == Args[i].IsZExt)) 9137 Flags.setReturned(); 9138 } 9139 9140 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, 9141 CLI.CS.getInstruction(), CLI.CallConv, ExtendKind); 9142 9143 for (unsigned j = 0; j != NumParts; ++j) { 9144 // if it isn't first piece, alignment must be 1 9145 // For scalable vectors the scalable part is currently handled 9146 // by individual targets, so we just use the known minimum size here. 9147 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 9148 i < CLI.NumFixedArgs, i, 9149 j*Parts[j].getValueType().getStoreSize().getKnownMinSize()); 9150 if (NumParts > 1 && j == 0) 9151 MyFlags.Flags.setSplit(); 9152 else if (j != 0) { 9153 MyFlags.Flags.setOrigAlign(Align::None()); 9154 if (j == NumParts - 1) 9155 MyFlags.Flags.setSplitEnd(); 9156 } 9157 9158 CLI.Outs.push_back(MyFlags); 9159 CLI.OutVals.push_back(Parts[j]); 9160 } 9161 9162 if (NeedsRegBlock && Value == NumValues - 1) 9163 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 9164 } 9165 } 9166 9167 SmallVector<SDValue, 4> InVals; 9168 CLI.Chain = LowerCall(CLI, InVals); 9169 9170 // Update CLI.InVals to use outside of this function. 9171 CLI.InVals = InVals; 9172 9173 // Verify that the target's LowerCall behaved as expected. 9174 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 9175 "LowerCall didn't return a valid chain!"); 9176 assert((!CLI.IsTailCall || InVals.empty()) && 9177 "LowerCall emitted a return value for a tail call!"); 9178 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9179 "LowerCall didn't emit the correct number of values!"); 9180 9181 // For a tail call, the return value is merely live-out and there aren't 9182 // any nodes in the DAG representing it. Return a special value to 9183 // indicate that a tail call has been emitted and no more Instructions 9184 // should be processed in the current block. 9185 if (CLI.IsTailCall) { 9186 CLI.DAG.setRoot(CLI.Chain); 9187 return std::make_pair(SDValue(), SDValue()); 9188 } 9189 9190 #ifndef NDEBUG 9191 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 9192 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 9193 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 9194 "LowerCall emitted a value with the wrong type!"); 9195 } 9196 #endif 9197 9198 SmallVector<SDValue, 4> ReturnValues; 9199 if (!CanLowerReturn) { 9200 // The instruction result is the result of loading from the 9201 // hidden sret parameter. 9202 SmallVector<EVT, 1> PVTs; 9203 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 9204 9205 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 9206 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 9207 EVT PtrVT = PVTs[0]; 9208 9209 unsigned NumValues = RetTys.size(); 9210 ReturnValues.resize(NumValues); 9211 SmallVector<SDValue, 4> Chains(NumValues); 9212 9213 // An aggregate return value cannot wrap around the address space, so 9214 // offsets to its parts don't wrap either. 9215 SDNodeFlags Flags; 9216 Flags.setNoUnsignedWrap(true); 9217 9218 for (unsigned i = 0; i < NumValues; ++i) { 9219 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 9220 CLI.DAG.getConstant(Offsets[i], CLI.DL, 9221 PtrVT), Flags); 9222 SDValue L = CLI.DAG.getLoad( 9223 RetTys[i], CLI.DL, CLI.Chain, Add, 9224 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 9225 DemoteStackIdx, Offsets[i]), 9226 /* Alignment = */ 1); 9227 ReturnValues[i] = L; 9228 Chains[i] = L.getValue(1); 9229 } 9230 9231 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 9232 } else { 9233 // Collect the legal value parts into potentially illegal values 9234 // that correspond to the original function's return values. 9235 Optional<ISD::NodeType> AssertOp; 9236 if (CLI.RetSExt) 9237 AssertOp = ISD::AssertSext; 9238 else if (CLI.RetZExt) 9239 AssertOp = ISD::AssertZext; 9240 unsigned CurReg = 0; 9241 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9242 EVT VT = RetTys[I]; 9243 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9244 CLI.CallConv, VT); 9245 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9246 CLI.CallConv, VT); 9247 9248 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 9249 NumRegs, RegisterVT, VT, nullptr, 9250 CLI.CallConv, AssertOp)); 9251 CurReg += NumRegs; 9252 } 9253 9254 // For a function returning void, there is no return value. We can't create 9255 // such a node, so we just return a null return value in that case. In 9256 // that case, nothing will actually look at the value. 9257 if (ReturnValues.empty()) 9258 return std::make_pair(SDValue(), CLI.Chain); 9259 } 9260 9261 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 9262 CLI.DAG.getVTList(RetTys), ReturnValues); 9263 return std::make_pair(Res, CLI.Chain); 9264 } 9265 9266 void TargetLowering::LowerOperationWrapper(SDNode *N, 9267 SmallVectorImpl<SDValue> &Results, 9268 SelectionDAG &DAG) const { 9269 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG)) 9270 Results.push_back(Res); 9271 } 9272 9273 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9274 llvm_unreachable("LowerOperation not implemented for this target!"); 9275 } 9276 9277 void 9278 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 9279 SDValue Op = getNonRegisterValue(V); 9280 assert((Op.getOpcode() != ISD::CopyFromReg || 9281 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 9282 "Copy from a reg to the same reg!"); 9283 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 9284 9285 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9286 // If this is an InlineAsm we have to match the registers required, not the 9287 // notional registers required by the type. 9288 9289 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 9290 None); // This is not an ABI copy. 9291 SDValue Chain = DAG.getEntryNode(); 9292 9293 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 9294 FuncInfo.PreferredExtendType.end()) 9295 ? ISD::ANY_EXTEND 9296 : FuncInfo.PreferredExtendType[V]; 9297 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 9298 PendingExports.push_back(Chain); 9299 } 9300 9301 #include "llvm/CodeGen/SelectionDAGISel.h" 9302 9303 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 9304 /// entry block, return true. This includes arguments used by switches, since 9305 /// the switch may expand into multiple basic blocks. 9306 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 9307 // With FastISel active, we may be splitting blocks, so force creation 9308 // of virtual registers for all non-dead arguments. 9309 if (FastISel) 9310 return A->use_empty(); 9311 9312 const BasicBlock &Entry = A->getParent()->front(); 9313 for (const User *U : A->users()) 9314 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 9315 return false; // Use not in entry block. 9316 9317 return true; 9318 } 9319 9320 using ArgCopyElisionMapTy = 9321 DenseMap<const Argument *, 9322 std::pair<const AllocaInst *, const StoreInst *>>; 9323 9324 /// Scan the entry block of the function in FuncInfo for arguments that look 9325 /// like copies into a local alloca. Record any copied arguments in 9326 /// ArgCopyElisionCandidates. 9327 static void 9328 findArgumentCopyElisionCandidates(const DataLayout &DL, 9329 FunctionLoweringInfo *FuncInfo, 9330 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 9331 // Record the state of every static alloca used in the entry block. Argument 9332 // allocas are all used in the entry block, so we need approximately as many 9333 // entries as we have arguments. 9334 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 9335 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 9336 unsigned NumArgs = FuncInfo->Fn->arg_size(); 9337 StaticAllocas.reserve(NumArgs * 2); 9338 9339 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 9340 if (!V) 9341 return nullptr; 9342 V = V->stripPointerCasts(); 9343 const auto *AI = dyn_cast<AllocaInst>(V); 9344 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 9345 return nullptr; 9346 auto Iter = StaticAllocas.insert({AI, Unknown}); 9347 return &Iter.first->second; 9348 }; 9349 9350 // Look for stores of arguments to static allocas. Look through bitcasts and 9351 // GEPs to handle type coercions, as long as the alloca is fully initialized 9352 // by the store. Any non-store use of an alloca escapes it and any subsequent 9353 // unanalyzed store might write it. 9354 // FIXME: Handle structs initialized with multiple stores. 9355 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 9356 // Look for stores, and handle non-store uses conservatively. 9357 const auto *SI = dyn_cast<StoreInst>(&I); 9358 if (!SI) { 9359 // We will look through cast uses, so ignore them completely. 9360 if (I.isCast()) 9361 continue; 9362 // Ignore debug info intrinsics, they don't escape or store to allocas. 9363 if (isa<DbgInfoIntrinsic>(I)) 9364 continue; 9365 // This is an unknown instruction. Assume it escapes or writes to all 9366 // static alloca operands. 9367 for (const Use &U : I.operands()) { 9368 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 9369 *Info = StaticAllocaInfo::Clobbered; 9370 } 9371 continue; 9372 } 9373 9374 // If the stored value is a static alloca, mark it as escaped. 9375 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 9376 *Info = StaticAllocaInfo::Clobbered; 9377 9378 // Check if the destination is a static alloca. 9379 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 9380 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 9381 if (!Info) 9382 continue; 9383 const AllocaInst *AI = cast<AllocaInst>(Dst); 9384 9385 // Skip allocas that have been initialized or clobbered. 9386 if (*Info != StaticAllocaInfo::Unknown) 9387 continue; 9388 9389 // Check if the stored value is an argument, and that this store fully 9390 // initializes the alloca. Don't elide copies from the same argument twice. 9391 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 9392 const auto *Arg = dyn_cast<Argument>(Val); 9393 if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() || 9394 Arg->getType()->isEmptyTy() || 9395 DL.getTypeStoreSize(Arg->getType()) != 9396 DL.getTypeAllocSize(AI->getAllocatedType()) || 9397 ArgCopyElisionCandidates.count(Arg)) { 9398 *Info = StaticAllocaInfo::Clobbered; 9399 continue; 9400 } 9401 9402 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 9403 << '\n'); 9404 9405 // Mark this alloca and store for argument copy elision. 9406 *Info = StaticAllocaInfo::Elidable; 9407 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 9408 9409 // Stop scanning if we've seen all arguments. This will happen early in -O0 9410 // builds, which is useful, because -O0 builds have large entry blocks and 9411 // many allocas. 9412 if (ArgCopyElisionCandidates.size() == NumArgs) 9413 break; 9414 } 9415 } 9416 9417 /// Try to elide argument copies from memory into a local alloca. Succeeds if 9418 /// ArgVal is a load from a suitable fixed stack object. 9419 static void tryToElideArgumentCopy( 9420 FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains, 9421 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 9422 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 9423 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 9424 SDValue ArgVal, bool &ArgHasUses) { 9425 // Check if this is a load from a fixed stack object. 9426 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 9427 if (!LNode) 9428 return; 9429 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 9430 if (!FINode) 9431 return; 9432 9433 // Check that the fixed stack object is the right size and alignment. 9434 // Look at the alignment that the user wrote on the alloca instead of looking 9435 // at the stack object. 9436 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 9437 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 9438 const AllocaInst *AI = ArgCopyIter->second.first; 9439 int FixedIndex = FINode->getIndex(); 9440 int &AllocaIndex = FuncInfo->StaticAllocaMap[AI]; 9441 int OldIndex = AllocaIndex; 9442 MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo(); 9443 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 9444 LLVM_DEBUG( 9445 dbgs() << " argument copy elision failed due to bad fixed stack " 9446 "object size\n"); 9447 return; 9448 } 9449 unsigned RequiredAlignment = AI->getAlignment(); 9450 if (!RequiredAlignment) { 9451 RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment( 9452 AI->getAllocatedType()); 9453 } 9454 if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) { 9455 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 9456 "greater than stack argument alignment (" 9457 << RequiredAlignment << " vs " 9458 << MFI.getObjectAlignment(FixedIndex) << ")\n"); 9459 return; 9460 } 9461 9462 // Perform the elision. Delete the old stack object and replace its only use 9463 // in the variable info map. Mark the stack object as mutable. 9464 LLVM_DEBUG({ 9465 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 9466 << " Replacing frame index " << OldIndex << " with " << FixedIndex 9467 << '\n'; 9468 }); 9469 MFI.RemoveStackObject(OldIndex); 9470 MFI.setIsImmutableObjectIndex(FixedIndex, false); 9471 AllocaIndex = FixedIndex; 9472 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 9473 Chains.push_back(ArgVal.getValue(1)); 9474 9475 // Avoid emitting code for the store implementing the copy. 9476 const StoreInst *SI = ArgCopyIter->second.second; 9477 ElidedArgCopyInstrs.insert(SI); 9478 9479 // Check for uses of the argument again so that we can avoid exporting ArgVal 9480 // if it is't used by anything other than the store. 9481 for (const Value *U : Arg.users()) { 9482 if (U != SI) { 9483 ArgHasUses = true; 9484 break; 9485 } 9486 } 9487 } 9488 9489 void SelectionDAGISel::LowerArguments(const Function &F) { 9490 SelectionDAG &DAG = SDB->DAG; 9491 SDLoc dl = SDB->getCurSDLoc(); 9492 const DataLayout &DL = DAG.getDataLayout(); 9493 SmallVector<ISD::InputArg, 16> Ins; 9494 9495 if (!FuncInfo->CanLowerReturn) { 9496 // Put in an sret pointer parameter before all the other parameters. 9497 SmallVector<EVT, 1> ValueVTs; 9498 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9499 F.getReturnType()->getPointerTo( 9500 DAG.getDataLayout().getAllocaAddrSpace()), 9501 ValueVTs); 9502 9503 // NOTE: Assuming that a pointer will never break down to more than one VT 9504 // or one register. 9505 ISD::ArgFlagsTy Flags; 9506 Flags.setSRet(); 9507 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 9508 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 9509 ISD::InputArg::NoArgIndex, 0); 9510 Ins.push_back(RetArg); 9511 } 9512 9513 // Look for stores of arguments to static allocas. Mark such arguments with a 9514 // flag to ask the target to give us the memory location of that argument if 9515 // available. 9516 ArgCopyElisionMapTy ArgCopyElisionCandidates; 9517 findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates); 9518 9519 // Set up the incoming argument description vector. 9520 for (const Argument &Arg : F.args()) { 9521 unsigned ArgNo = Arg.getArgNo(); 9522 SmallVector<EVT, 4> ValueVTs; 9523 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9524 bool isArgValueUsed = !Arg.use_empty(); 9525 unsigned PartBase = 0; 9526 Type *FinalType = Arg.getType(); 9527 if (Arg.hasAttribute(Attribute::ByVal)) 9528 FinalType = Arg.getParamByValType(); 9529 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 9530 FinalType, F.getCallingConv(), F.isVarArg()); 9531 for (unsigned Value = 0, NumValues = ValueVTs.size(); 9532 Value != NumValues; ++Value) { 9533 EVT VT = ValueVTs[Value]; 9534 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 9535 ISD::ArgFlagsTy Flags; 9536 9537 // Certain targets (such as MIPS), may have a different ABI alignment 9538 // for a type depending on the context. Give the target a chance to 9539 // specify the alignment it wants. 9540 const Align OriginalAlignment( 9541 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 9542 9543 if (Arg.getType()->isPointerTy()) { 9544 Flags.setPointer(); 9545 Flags.setPointerAddrSpace( 9546 cast<PointerType>(Arg.getType())->getAddressSpace()); 9547 } 9548 if (Arg.hasAttribute(Attribute::ZExt)) 9549 Flags.setZExt(); 9550 if (Arg.hasAttribute(Attribute::SExt)) 9551 Flags.setSExt(); 9552 if (Arg.hasAttribute(Attribute::InReg)) { 9553 // If we are using vectorcall calling convention, a structure that is 9554 // passed InReg - is surely an HVA 9555 if (F.getCallingConv() == CallingConv::X86_VectorCall && 9556 isa<StructType>(Arg.getType())) { 9557 // The first value of a structure is marked 9558 if (0 == Value) 9559 Flags.setHvaStart(); 9560 Flags.setHva(); 9561 } 9562 // Set InReg Flag 9563 Flags.setInReg(); 9564 } 9565 if (Arg.hasAttribute(Attribute::StructRet)) 9566 Flags.setSRet(); 9567 if (Arg.hasAttribute(Attribute::SwiftSelf)) 9568 Flags.setSwiftSelf(); 9569 if (Arg.hasAttribute(Attribute::SwiftError)) 9570 Flags.setSwiftError(); 9571 if (Arg.hasAttribute(Attribute::ByVal)) 9572 Flags.setByVal(); 9573 if (Arg.hasAttribute(Attribute::InAlloca)) { 9574 Flags.setInAlloca(); 9575 // Set the byval flag for CCAssignFn callbacks that don't know about 9576 // inalloca. This way we can know how many bytes we should've allocated 9577 // and how many bytes a callee cleanup function will pop. If we port 9578 // inalloca to more targets, we'll have to add custom inalloca handling 9579 // in the various CC lowering callbacks. 9580 Flags.setByVal(); 9581 } 9582 if (F.getCallingConv() == CallingConv::X86_INTR) { 9583 // IA Interrupt passes frame (1st parameter) by value in the stack. 9584 if (ArgNo == 0) 9585 Flags.setByVal(); 9586 } 9587 if (Flags.isByVal() || Flags.isInAlloca()) { 9588 Type *ElementTy = Arg.getParamByValType(); 9589 9590 // For ByVal, size and alignment should be passed from FE. BE will 9591 // guess if this info is not there but there are cases it cannot get 9592 // right. 9593 unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType()); 9594 Flags.setByValSize(FrameSize); 9595 9596 unsigned FrameAlign; 9597 if (Arg.getParamAlignment()) 9598 FrameAlign = Arg.getParamAlignment(); 9599 else 9600 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL); 9601 Flags.setByValAlign(Align(FrameAlign)); 9602 } 9603 if (Arg.hasAttribute(Attribute::Nest)) 9604 Flags.setNest(); 9605 if (NeedsRegBlock) 9606 Flags.setInConsecutiveRegs(); 9607 Flags.setOrigAlign(OriginalAlignment); 9608 if (ArgCopyElisionCandidates.count(&Arg)) 9609 Flags.setCopyElisionCandidate(); 9610 if (Arg.hasAttribute(Attribute::Returned)) 9611 Flags.setReturned(); 9612 9613 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 9614 *CurDAG->getContext(), F.getCallingConv(), VT); 9615 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 9616 *CurDAG->getContext(), F.getCallingConv(), VT); 9617 for (unsigned i = 0; i != NumRegs; ++i) { 9618 // For scalable vectors, use the minimum size; individual targets 9619 // are responsible for handling scalable vector arguments and 9620 // return values. 9621 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 9622 ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize()); 9623 if (NumRegs > 1 && i == 0) 9624 MyFlags.Flags.setSplit(); 9625 // if it isn't first piece, alignment must be 1 9626 else if (i > 0) { 9627 MyFlags.Flags.setOrigAlign(Align::None()); 9628 if (i == NumRegs - 1) 9629 MyFlags.Flags.setSplitEnd(); 9630 } 9631 Ins.push_back(MyFlags); 9632 } 9633 if (NeedsRegBlock && Value == NumValues - 1) 9634 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 9635 PartBase += VT.getStoreSize().getKnownMinSize(); 9636 } 9637 } 9638 9639 // Call the target to set up the argument values. 9640 SmallVector<SDValue, 8> InVals; 9641 SDValue NewRoot = TLI->LowerFormalArguments( 9642 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 9643 9644 // Verify that the target's LowerFormalArguments behaved as expected. 9645 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 9646 "LowerFormalArguments didn't return a valid chain!"); 9647 assert(InVals.size() == Ins.size() && 9648 "LowerFormalArguments didn't emit the correct number of values!"); 9649 LLVM_DEBUG({ 9650 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 9651 assert(InVals[i].getNode() && 9652 "LowerFormalArguments emitted a null value!"); 9653 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 9654 "LowerFormalArguments emitted a value with the wrong type!"); 9655 } 9656 }); 9657 9658 // Update the DAG with the new chain value resulting from argument lowering. 9659 DAG.setRoot(NewRoot); 9660 9661 // Set up the argument values. 9662 unsigned i = 0; 9663 if (!FuncInfo->CanLowerReturn) { 9664 // Create a virtual register for the sret pointer, and put in a copy 9665 // from the sret argument into it. 9666 SmallVector<EVT, 1> ValueVTs; 9667 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9668 F.getReturnType()->getPointerTo( 9669 DAG.getDataLayout().getAllocaAddrSpace()), 9670 ValueVTs); 9671 MVT VT = ValueVTs[0].getSimpleVT(); 9672 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 9673 Optional<ISD::NodeType> AssertOp = None; 9674 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 9675 nullptr, F.getCallingConv(), AssertOp); 9676 9677 MachineFunction& MF = SDB->DAG.getMachineFunction(); 9678 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 9679 Register SRetReg = 9680 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 9681 FuncInfo->DemoteRegister = SRetReg; 9682 NewRoot = 9683 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 9684 DAG.setRoot(NewRoot); 9685 9686 // i indexes lowered arguments. Bump it past the hidden sret argument. 9687 ++i; 9688 } 9689 9690 SmallVector<SDValue, 4> Chains; 9691 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 9692 for (const Argument &Arg : F.args()) { 9693 SmallVector<SDValue, 4> ArgValues; 9694 SmallVector<EVT, 4> ValueVTs; 9695 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9696 unsigned NumValues = ValueVTs.size(); 9697 if (NumValues == 0) 9698 continue; 9699 9700 bool ArgHasUses = !Arg.use_empty(); 9701 9702 // Elide the copying store if the target loaded this argument from a 9703 // suitable fixed stack object. 9704 if (Ins[i].Flags.isCopyElisionCandidate()) { 9705 tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 9706 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 9707 InVals[i], ArgHasUses); 9708 } 9709 9710 // If this argument is unused then remember its value. It is used to generate 9711 // debugging information. 9712 bool isSwiftErrorArg = 9713 TLI->supportSwiftError() && 9714 Arg.hasAttribute(Attribute::SwiftError); 9715 if (!ArgHasUses && !isSwiftErrorArg) { 9716 SDB->setUnusedArgValue(&Arg, InVals[i]); 9717 9718 // Also remember any frame index for use in FastISel. 9719 if (FrameIndexSDNode *FI = 9720 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 9721 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9722 } 9723 9724 for (unsigned Val = 0; Val != NumValues; ++Val) { 9725 EVT VT = ValueVTs[Val]; 9726 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 9727 F.getCallingConv(), VT); 9728 unsigned NumParts = TLI->getNumRegistersForCallingConv( 9729 *CurDAG->getContext(), F.getCallingConv(), VT); 9730 9731 // Even an apparent 'unused' swifterror argument needs to be returned. So 9732 // we do generate a copy for it that can be used on return from the 9733 // function. 9734 if (ArgHasUses || isSwiftErrorArg) { 9735 Optional<ISD::NodeType> AssertOp; 9736 if (Arg.hasAttribute(Attribute::SExt)) 9737 AssertOp = ISD::AssertSext; 9738 else if (Arg.hasAttribute(Attribute::ZExt)) 9739 AssertOp = ISD::AssertZext; 9740 9741 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 9742 PartVT, VT, nullptr, 9743 F.getCallingConv(), AssertOp)); 9744 } 9745 9746 i += NumParts; 9747 } 9748 9749 // We don't need to do anything else for unused arguments. 9750 if (ArgValues.empty()) 9751 continue; 9752 9753 // Note down frame index. 9754 if (FrameIndexSDNode *FI = 9755 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 9756 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9757 9758 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 9759 SDB->getCurSDLoc()); 9760 9761 SDB->setValue(&Arg, Res); 9762 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 9763 // We want to associate the argument with the frame index, among 9764 // involved operands, that correspond to the lowest address. The 9765 // getCopyFromParts function, called earlier, is swapping the order of 9766 // the operands to BUILD_PAIR depending on endianness. The result of 9767 // that swapping is that the least significant bits of the argument will 9768 // be in the first operand of the BUILD_PAIR node, and the most 9769 // significant bits will be in the second operand. 9770 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 9771 if (LoadSDNode *LNode = 9772 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 9773 if (FrameIndexSDNode *FI = 9774 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 9775 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9776 } 9777 9778 // Analyses past this point are naive and don't expect an assertion. 9779 if (Res.getOpcode() == ISD::AssertZext) 9780 Res = Res.getOperand(0); 9781 9782 // Update the SwiftErrorVRegDefMap. 9783 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 9784 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9785 if (Register::isVirtualRegister(Reg)) 9786 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 9787 Reg); 9788 } 9789 9790 // If this argument is live outside of the entry block, insert a copy from 9791 // wherever we got it to the vreg that other BB's will reference it as. 9792 if (Res.getOpcode() == ISD::CopyFromReg) { 9793 // If we can, though, try to skip creating an unnecessary vreg. 9794 // FIXME: This isn't very clean... it would be nice to make this more 9795 // general. 9796 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9797 if (Register::isVirtualRegister(Reg)) { 9798 FuncInfo->ValueMap[&Arg] = Reg; 9799 continue; 9800 } 9801 } 9802 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 9803 FuncInfo->InitializeRegForValue(&Arg); 9804 SDB->CopyToExportRegsIfNeeded(&Arg); 9805 } 9806 } 9807 9808 if (!Chains.empty()) { 9809 Chains.push_back(NewRoot); 9810 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 9811 } 9812 9813 DAG.setRoot(NewRoot); 9814 9815 assert(i == InVals.size() && "Argument register count mismatch!"); 9816 9817 // If any argument copy elisions occurred and we have debug info, update the 9818 // stale frame indices used in the dbg.declare variable info table. 9819 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 9820 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 9821 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 9822 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 9823 if (I != ArgCopyElisionFrameIndexMap.end()) 9824 VI.Slot = I->second; 9825 } 9826 } 9827 9828 // Finally, if the target has anything special to do, allow it to do so. 9829 EmitFunctionEntryCode(); 9830 } 9831 9832 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 9833 /// ensure constants are generated when needed. Remember the virtual registers 9834 /// that need to be added to the Machine PHI nodes as input. We cannot just 9835 /// directly add them, because expansion might result in multiple MBB's for one 9836 /// BB. As such, the start of the BB might correspond to a different MBB than 9837 /// the end. 9838 void 9839 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 9840 const Instruction *TI = LLVMBB->getTerminator(); 9841 9842 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 9843 9844 // Check PHI nodes in successors that expect a value to be available from this 9845 // block. 9846 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 9847 const BasicBlock *SuccBB = TI->getSuccessor(succ); 9848 if (!isa<PHINode>(SuccBB->begin())) continue; 9849 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 9850 9851 // If this terminator has multiple identical successors (common for 9852 // switches), only handle each succ once. 9853 if (!SuccsHandled.insert(SuccMBB).second) 9854 continue; 9855 9856 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 9857 9858 // At this point we know that there is a 1-1 correspondence between LLVM PHI 9859 // nodes and Machine PHI nodes, but the incoming operands have not been 9860 // emitted yet. 9861 for (const PHINode &PN : SuccBB->phis()) { 9862 // Ignore dead phi's. 9863 if (PN.use_empty()) 9864 continue; 9865 9866 // Skip empty types 9867 if (PN.getType()->isEmptyTy()) 9868 continue; 9869 9870 unsigned Reg; 9871 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 9872 9873 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 9874 unsigned &RegOut = ConstantsOut[C]; 9875 if (RegOut == 0) { 9876 RegOut = FuncInfo.CreateRegs(C); 9877 CopyValueToVirtualRegister(C, RegOut); 9878 } 9879 Reg = RegOut; 9880 } else { 9881 DenseMap<const Value *, unsigned>::iterator I = 9882 FuncInfo.ValueMap.find(PHIOp); 9883 if (I != FuncInfo.ValueMap.end()) 9884 Reg = I->second; 9885 else { 9886 assert(isa<AllocaInst>(PHIOp) && 9887 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 9888 "Didn't codegen value into a register!??"); 9889 Reg = FuncInfo.CreateRegs(PHIOp); 9890 CopyValueToVirtualRegister(PHIOp, Reg); 9891 } 9892 } 9893 9894 // Remember that this register needs to added to the machine PHI node as 9895 // the input for this MBB. 9896 SmallVector<EVT, 4> ValueVTs; 9897 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9898 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 9899 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 9900 EVT VT = ValueVTs[vti]; 9901 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 9902 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 9903 FuncInfo.PHINodesToUpdate.push_back( 9904 std::make_pair(&*MBBI++, Reg + i)); 9905 Reg += NumRegisters; 9906 } 9907 } 9908 } 9909 9910 ConstantsOut.clear(); 9911 } 9912 9913 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 9914 /// is 0. 9915 MachineBasicBlock * 9916 SelectionDAGBuilder::StackProtectorDescriptor:: 9917 AddSuccessorMBB(const BasicBlock *BB, 9918 MachineBasicBlock *ParentMBB, 9919 bool IsLikely, 9920 MachineBasicBlock *SuccMBB) { 9921 // If SuccBB has not been created yet, create it. 9922 if (!SuccMBB) { 9923 MachineFunction *MF = ParentMBB->getParent(); 9924 MachineFunction::iterator BBI(ParentMBB); 9925 SuccMBB = MF->CreateMachineBasicBlock(BB); 9926 MF->insert(++BBI, SuccMBB); 9927 } 9928 // Add it as a successor of ParentMBB. 9929 ParentMBB->addSuccessor( 9930 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 9931 return SuccMBB; 9932 } 9933 9934 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 9935 MachineFunction::iterator I(MBB); 9936 if (++I == FuncInfo.MF->end()) 9937 return nullptr; 9938 return &*I; 9939 } 9940 9941 /// During lowering new call nodes can be created (such as memset, etc.). 9942 /// Those will become new roots of the current DAG, but complications arise 9943 /// when they are tail calls. In such cases, the call lowering will update 9944 /// the root, but the builder still needs to know that a tail call has been 9945 /// lowered in order to avoid generating an additional return. 9946 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 9947 // If the node is null, we do have a tail call. 9948 if (MaybeTC.getNode() != nullptr) 9949 DAG.setRoot(MaybeTC); 9950 else 9951 HasTailCall = true; 9952 } 9953 9954 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 9955 MachineBasicBlock *SwitchMBB, 9956 MachineBasicBlock *DefaultMBB) { 9957 MachineFunction *CurMF = FuncInfo.MF; 9958 MachineBasicBlock *NextMBB = nullptr; 9959 MachineFunction::iterator BBI(W.MBB); 9960 if (++BBI != FuncInfo.MF->end()) 9961 NextMBB = &*BBI; 9962 9963 unsigned Size = W.LastCluster - W.FirstCluster + 1; 9964 9965 BranchProbabilityInfo *BPI = FuncInfo.BPI; 9966 9967 if (Size == 2 && W.MBB == SwitchMBB) { 9968 // If any two of the cases has the same destination, and if one value 9969 // is the same as the other, but has one bit unset that the other has set, 9970 // use bit manipulation to do two compares at once. For example: 9971 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 9972 // TODO: This could be extended to merge any 2 cases in switches with 3 9973 // cases. 9974 // TODO: Handle cases where W.CaseBB != SwitchBB. 9975 CaseCluster &Small = *W.FirstCluster; 9976 CaseCluster &Big = *W.LastCluster; 9977 9978 if (Small.Low == Small.High && Big.Low == Big.High && 9979 Small.MBB == Big.MBB) { 9980 const APInt &SmallValue = Small.Low->getValue(); 9981 const APInt &BigValue = Big.Low->getValue(); 9982 9983 // Check that there is only one bit different. 9984 APInt CommonBit = BigValue ^ SmallValue; 9985 if (CommonBit.isPowerOf2()) { 9986 SDValue CondLHS = getValue(Cond); 9987 EVT VT = CondLHS.getValueType(); 9988 SDLoc DL = getCurSDLoc(); 9989 9990 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 9991 DAG.getConstant(CommonBit, DL, VT)); 9992 SDValue Cond = DAG.getSetCC( 9993 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 9994 ISD::SETEQ); 9995 9996 // Update successor info. 9997 // Both Small and Big will jump to Small.BB, so we sum up the 9998 // probabilities. 9999 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10000 if (BPI) 10001 addSuccessorWithProb( 10002 SwitchMBB, DefaultMBB, 10003 // The default destination is the first successor in IR. 10004 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10005 else 10006 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10007 10008 // Insert the true branch. 10009 SDValue BrCond = 10010 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10011 DAG.getBasicBlock(Small.MBB)); 10012 // Insert the false branch. 10013 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10014 DAG.getBasicBlock(DefaultMBB)); 10015 10016 DAG.setRoot(BrCond); 10017 return; 10018 } 10019 } 10020 } 10021 10022 if (TM.getOptLevel() != CodeGenOpt::None) { 10023 // Here, we order cases by probability so the most likely case will be 10024 // checked first. However, two clusters can have the same probability in 10025 // which case their relative ordering is non-deterministic. So we use Low 10026 // as a tie-breaker as clusters are guaranteed to never overlap. 10027 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10028 [](const CaseCluster &a, const CaseCluster &b) { 10029 return a.Prob != b.Prob ? 10030 a.Prob > b.Prob : 10031 a.Low->getValue().slt(b.Low->getValue()); 10032 }); 10033 10034 // Rearrange the case blocks so that the last one falls through if possible 10035 // without changing the order of probabilities. 10036 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10037 --I; 10038 if (I->Prob > W.LastCluster->Prob) 10039 break; 10040 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10041 std::swap(*I, *W.LastCluster); 10042 break; 10043 } 10044 } 10045 } 10046 10047 // Compute total probability. 10048 BranchProbability DefaultProb = W.DefaultProb; 10049 BranchProbability UnhandledProbs = DefaultProb; 10050 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10051 UnhandledProbs += I->Prob; 10052 10053 MachineBasicBlock *CurMBB = W.MBB; 10054 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10055 bool FallthroughUnreachable = false; 10056 MachineBasicBlock *Fallthrough; 10057 if (I == W.LastCluster) { 10058 // For the last cluster, fall through to the default destination. 10059 Fallthrough = DefaultMBB; 10060 FallthroughUnreachable = isa<UnreachableInst>( 10061 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10062 } else { 10063 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10064 CurMF->insert(BBI, Fallthrough); 10065 // Put Cond in a virtual register to make it available from the new blocks. 10066 ExportFromCurrentBlock(Cond); 10067 } 10068 UnhandledProbs -= I->Prob; 10069 10070 switch (I->Kind) { 10071 case CC_JumpTable: { 10072 // FIXME: Optimize away range check based on pivot comparisons. 10073 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 10074 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 10075 10076 // The jump block hasn't been inserted yet; insert it here. 10077 MachineBasicBlock *JumpMBB = JT->MBB; 10078 CurMF->insert(BBI, JumpMBB); 10079 10080 auto JumpProb = I->Prob; 10081 auto FallthroughProb = UnhandledProbs; 10082 10083 // If the default statement is a target of the jump table, we evenly 10084 // distribute the default probability to successors of CurMBB. Also 10085 // update the probability on the edge from JumpMBB to Fallthrough. 10086 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10087 SE = JumpMBB->succ_end(); 10088 SI != SE; ++SI) { 10089 if (*SI == DefaultMBB) { 10090 JumpProb += DefaultProb / 2; 10091 FallthroughProb -= DefaultProb / 2; 10092 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10093 JumpMBB->normalizeSuccProbs(); 10094 break; 10095 } 10096 } 10097 10098 if (FallthroughUnreachable) { 10099 // Skip the range check if the fallthrough block is unreachable. 10100 JTH->OmitRangeCheck = true; 10101 } 10102 10103 if (!JTH->OmitRangeCheck) 10104 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10105 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10106 CurMBB->normalizeSuccProbs(); 10107 10108 // The jump table header will be inserted in our current block, do the 10109 // range check, and fall through to our fallthrough block. 10110 JTH->HeaderBB = CurMBB; 10111 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10112 10113 // If we're in the right place, emit the jump table header right now. 10114 if (CurMBB == SwitchMBB) { 10115 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10116 JTH->Emitted = true; 10117 } 10118 break; 10119 } 10120 case CC_BitTests: { 10121 // FIXME: Optimize away range check based on pivot comparisons. 10122 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 10123 10124 // The bit test blocks haven't been inserted yet; insert them here. 10125 for (BitTestCase &BTC : BTB->Cases) 10126 CurMF->insert(BBI, BTC.ThisBB); 10127 10128 // Fill in fields of the BitTestBlock. 10129 BTB->Parent = CurMBB; 10130 BTB->Default = Fallthrough; 10131 10132 BTB->DefaultProb = UnhandledProbs; 10133 // If the cases in bit test don't form a contiguous range, we evenly 10134 // distribute the probability on the edge to Fallthrough to two 10135 // successors of CurMBB. 10136 if (!BTB->ContiguousRange) { 10137 BTB->Prob += DefaultProb / 2; 10138 BTB->DefaultProb -= DefaultProb / 2; 10139 } 10140 10141 if (FallthroughUnreachable) { 10142 // Skip the range check if the fallthrough block is unreachable. 10143 BTB->OmitRangeCheck = true; 10144 } 10145 10146 // If we're in the right place, emit the bit test header right now. 10147 if (CurMBB == SwitchMBB) { 10148 visitBitTestHeader(*BTB, SwitchMBB); 10149 BTB->Emitted = true; 10150 } 10151 break; 10152 } 10153 case CC_Range: { 10154 const Value *RHS, *LHS, *MHS; 10155 ISD::CondCode CC; 10156 if (I->Low == I->High) { 10157 // Check Cond == I->Low. 10158 CC = ISD::SETEQ; 10159 LHS = Cond; 10160 RHS=I->Low; 10161 MHS = nullptr; 10162 } else { 10163 // Check I->Low <= Cond <= I->High. 10164 CC = ISD::SETLE; 10165 LHS = I->Low; 10166 MHS = Cond; 10167 RHS = I->High; 10168 } 10169 10170 // If Fallthrough is unreachable, fold away the comparison. 10171 if (FallthroughUnreachable) 10172 CC = ISD::SETTRUE; 10173 10174 // The false probability is the sum of all unhandled cases. 10175 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10176 getCurSDLoc(), I->Prob, UnhandledProbs); 10177 10178 if (CurMBB == SwitchMBB) 10179 visitSwitchCase(CB, SwitchMBB); 10180 else 10181 SL->SwitchCases.push_back(CB); 10182 10183 break; 10184 } 10185 } 10186 CurMBB = Fallthrough; 10187 } 10188 } 10189 10190 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10191 CaseClusterIt First, 10192 CaseClusterIt Last) { 10193 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10194 if (X.Prob != CC.Prob) 10195 return X.Prob > CC.Prob; 10196 10197 // Ties are broken by comparing the case value. 10198 return X.Low->getValue().slt(CC.Low->getValue()); 10199 }); 10200 } 10201 10202 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10203 const SwitchWorkListItem &W, 10204 Value *Cond, 10205 MachineBasicBlock *SwitchMBB) { 10206 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10207 "Clusters not sorted?"); 10208 10209 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10210 10211 // Balance the tree based on branch probabilities to create a near-optimal (in 10212 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10213 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10214 CaseClusterIt LastLeft = W.FirstCluster; 10215 CaseClusterIt FirstRight = W.LastCluster; 10216 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10217 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10218 10219 // Move LastLeft and FirstRight towards each other from opposite directions to 10220 // find a partitioning of the clusters which balances the probability on both 10221 // sides. If LeftProb and RightProb are equal, alternate which side is 10222 // taken to ensure 0-probability nodes are distributed evenly. 10223 unsigned I = 0; 10224 while (LastLeft + 1 < FirstRight) { 10225 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10226 LeftProb += (++LastLeft)->Prob; 10227 else 10228 RightProb += (--FirstRight)->Prob; 10229 I++; 10230 } 10231 10232 while (true) { 10233 // Our binary search tree differs from a typical BST in that ours can have up 10234 // to three values in each leaf. The pivot selection above doesn't take that 10235 // into account, which means the tree might require more nodes and be less 10236 // efficient. We compensate for this here. 10237 10238 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10239 unsigned NumRight = W.LastCluster - FirstRight + 1; 10240 10241 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10242 // If one side has less than 3 clusters, and the other has more than 3, 10243 // consider taking a cluster from the other side. 10244 10245 if (NumLeft < NumRight) { 10246 // Consider moving the first cluster on the right to the left side. 10247 CaseCluster &CC = *FirstRight; 10248 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10249 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10250 if (LeftSideRank <= RightSideRank) { 10251 // Moving the cluster to the left does not demote it. 10252 ++LastLeft; 10253 ++FirstRight; 10254 continue; 10255 } 10256 } else { 10257 assert(NumRight < NumLeft); 10258 // Consider moving the last element on the left to the right side. 10259 CaseCluster &CC = *LastLeft; 10260 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10261 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10262 if (RightSideRank <= LeftSideRank) { 10263 // Moving the cluster to the right does not demot it. 10264 --LastLeft; 10265 --FirstRight; 10266 continue; 10267 } 10268 } 10269 } 10270 break; 10271 } 10272 10273 assert(LastLeft + 1 == FirstRight); 10274 assert(LastLeft >= W.FirstCluster); 10275 assert(FirstRight <= W.LastCluster); 10276 10277 // Use the first element on the right as pivot since we will make less-than 10278 // comparisons against it. 10279 CaseClusterIt PivotCluster = FirstRight; 10280 assert(PivotCluster > W.FirstCluster); 10281 assert(PivotCluster <= W.LastCluster); 10282 10283 CaseClusterIt FirstLeft = W.FirstCluster; 10284 CaseClusterIt LastRight = W.LastCluster; 10285 10286 const ConstantInt *Pivot = PivotCluster->Low; 10287 10288 // New blocks will be inserted immediately after the current one. 10289 MachineFunction::iterator BBI(W.MBB); 10290 ++BBI; 10291 10292 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10293 // we can branch to its destination directly if it's squeezed exactly in 10294 // between the known lower bound and Pivot - 1. 10295 MachineBasicBlock *LeftMBB; 10296 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10297 FirstLeft->Low == W.GE && 10298 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10299 LeftMBB = FirstLeft->MBB; 10300 } else { 10301 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10302 FuncInfo.MF->insert(BBI, LeftMBB); 10303 WorkList.push_back( 10304 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10305 // Put Cond in a virtual register to make it available from the new blocks. 10306 ExportFromCurrentBlock(Cond); 10307 } 10308 10309 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10310 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10311 // directly if RHS.High equals the current upper bound. 10312 MachineBasicBlock *RightMBB; 10313 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10314 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10315 RightMBB = FirstRight->MBB; 10316 } else { 10317 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10318 FuncInfo.MF->insert(BBI, RightMBB); 10319 WorkList.push_back( 10320 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10321 // Put Cond in a virtual register to make it available from the new blocks. 10322 ExportFromCurrentBlock(Cond); 10323 } 10324 10325 // Create the CaseBlock record that will be used to lower the branch. 10326 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10327 getCurSDLoc(), LeftProb, RightProb); 10328 10329 if (W.MBB == SwitchMBB) 10330 visitSwitchCase(CB, SwitchMBB); 10331 else 10332 SL->SwitchCases.push_back(CB); 10333 } 10334 10335 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10336 // from the swith statement. 10337 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10338 BranchProbability PeeledCaseProb) { 10339 if (PeeledCaseProb == BranchProbability::getOne()) 10340 return BranchProbability::getZero(); 10341 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10342 10343 uint32_t Numerator = CaseProb.getNumerator(); 10344 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10345 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10346 } 10347 10348 // Try to peel the top probability case if it exceeds the threshold. 10349 // Return current MachineBasicBlock for the switch statement if the peeling 10350 // does not occur. 10351 // If the peeling is performed, return the newly created MachineBasicBlock 10352 // for the peeled switch statement. Also update Clusters to remove the peeled 10353 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10354 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10355 const SwitchInst &SI, CaseClusterVector &Clusters, 10356 BranchProbability &PeeledCaseProb) { 10357 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10358 // Don't perform if there is only one cluster or optimizing for size. 10359 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10360 TM.getOptLevel() == CodeGenOpt::None || 10361 SwitchMBB->getParent()->getFunction().hasMinSize()) 10362 return SwitchMBB; 10363 10364 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10365 unsigned PeeledCaseIndex = 0; 10366 bool SwitchPeeled = false; 10367 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10368 CaseCluster &CC = Clusters[Index]; 10369 if (CC.Prob < TopCaseProb) 10370 continue; 10371 TopCaseProb = CC.Prob; 10372 PeeledCaseIndex = Index; 10373 SwitchPeeled = true; 10374 } 10375 if (!SwitchPeeled) 10376 return SwitchMBB; 10377 10378 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10379 << TopCaseProb << "\n"); 10380 10381 // Record the MBB for the peeled switch statement. 10382 MachineFunction::iterator BBI(SwitchMBB); 10383 ++BBI; 10384 MachineBasicBlock *PeeledSwitchMBB = 10385 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10386 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10387 10388 ExportFromCurrentBlock(SI.getCondition()); 10389 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10390 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10391 nullptr, nullptr, TopCaseProb.getCompl()}; 10392 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10393 10394 Clusters.erase(PeeledCaseIt); 10395 for (CaseCluster &CC : Clusters) { 10396 LLVM_DEBUG( 10397 dbgs() << "Scale the probablity for one cluster, before scaling: " 10398 << CC.Prob << "\n"); 10399 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10400 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10401 } 10402 PeeledCaseProb = TopCaseProb; 10403 return PeeledSwitchMBB; 10404 } 10405 10406 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10407 // Extract cases from the switch. 10408 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10409 CaseClusterVector Clusters; 10410 Clusters.reserve(SI.getNumCases()); 10411 for (auto I : SI.cases()) { 10412 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10413 const ConstantInt *CaseVal = I.getCaseValue(); 10414 BranchProbability Prob = 10415 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10416 : BranchProbability(1, SI.getNumCases() + 1); 10417 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10418 } 10419 10420 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10421 10422 // Cluster adjacent cases with the same destination. We do this at all 10423 // optimization levels because it's cheap to do and will make codegen faster 10424 // if there are many clusters. 10425 sortAndRangeify(Clusters); 10426 10427 // The branch probablity of the peeled case. 10428 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10429 MachineBasicBlock *PeeledSwitchMBB = 10430 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10431 10432 // If there is only the default destination, jump there directly. 10433 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10434 if (Clusters.empty()) { 10435 assert(PeeledSwitchMBB == SwitchMBB); 10436 SwitchMBB->addSuccessor(DefaultMBB); 10437 if (DefaultMBB != NextBlock(SwitchMBB)) { 10438 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10439 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10440 } 10441 return; 10442 } 10443 10444 SL->findJumpTables(Clusters, &SI, DefaultMBB, nullptr, nullptr); 10445 SL->findBitTestClusters(Clusters, &SI); 10446 10447 LLVM_DEBUG({ 10448 dbgs() << "Case clusters: "; 10449 for (const CaseCluster &C : Clusters) { 10450 if (C.Kind == CC_JumpTable) 10451 dbgs() << "JT:"; 10452 if (C.Kind == CC_BitTests) 10453 dbgs() << "BT:"; 10454 10455 C.Low->getValue().print(dbgs(), true); 10456 if (C.Low != C.High) { 10457 dbgs() << '-'; 10458 C.High->getValue().print(dbgs(), true); 10459 } 10460 dbgs() << ' '; 10461 } 10462 dbgs() << '\n'; 10463 }); 10464 10465 assert(!Clusters.empty()); 10466 SwitchWorkList WorkList; 10467 CaseClusterIt First = Clusters.begin(); 10468 CaseClusterIt Last = Clusters.end() - 1; 10469 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10470 // Scale the branchprobability for DefaultMBB if the peel occurs and 10471 // DefaultMBB is not replaced. 10472 if (PeeledCaseProb != BranchProbability::getZero() && 10473 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10474 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10475 WorkList.push_back( 10476 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10477 10478 while (!WorkList.empty()) { 10479 SwitchWorkListItem W = WorkList.back(); 10480 WorkList.pop_back(); 10481 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10482 10483 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10484 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 10485 // For optimized builds, lower large range as a balanced binary tree. 10486 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10487 continue; 10488 } 10489 10490 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10491 } 10492 } 10493 10494 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 10495 SDValue N = getValue(I.getOperand(0)); 10496 setValue(&I, N); 10497 } 10498