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