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/TargetFrameLowering.h" 58 #include "llvm/CodeGen/TargetInstrInfo.h" 59 #include "llvm/CodeGen/TargetLowering.h" 60 #include "llvm/CodeGen/TargetOpcodes.h" 61 #include "llvm/CodeGen/TargetRegisterInfo.h" 62 #include "llvm/CodeGen/TargetSubtargetInfo.h" 63 #include "llvm/CodeGen/ValueTypes.h" 64 #include "llvm/CodeGen/WinEHFuncInfo.h" 65 #include "llvm/IR/Argument.h" 66 #include "llvm/IR/Attributes.h" 67 #include "llvm/IR/BasicBlock.h" 68 #include "llvm/IR/CFG.h" 69 #include "llvm/IR/CallSite.h" 70 #include "llvm/IR/CallingConv.h" 71 #include "llvm/IR/Constant.h" 72 #include "llvm/IR/ConstantRange.h" 73 #include "llvm/IR/Constants.h" 74 #include "llvm/IR/DataLayout.h" 75 #include "llvm/IR/DebugInfoMetadata.h" 76 #include "llvm/IR/DebugLoc.h" 77 #include "llvm/IR/DerivedTypes.h" 78 #include "llvm/IR/Function.h" 79 #include "llvm/IR/GetElementPtrTypeIterator.h" 80 #include "llvm/IR/InlineAsm.h" 81 #include "llvm/IR/InstrTypes.h" 82 #include "llvm/IR/Instruction.h" 83 #include "llvm/IR/Instructions.h" 84 #include "llvm/IR/IntrinsicInst.h" 85 #include "llvm/IR/Intrinsics.h" 86 #include "llvm/IR/LLVMContext.h" 87 #include "llvm/IR/Metadata.h" 88 #include "llvm/IR/Module.h" 89 #include "llvm/IR/Operator.h" 90 #include "llvm/IR/PatternMatch.h" 91 #include "llvm/IR/Statepoint.h" 92 #include "llvm/IR/Type.h" 93 #include "llvm/IR/User.h" 94 #include "llvm/IR/Value.h" 95 #include "llvm/MC/MCContext.h" 96 #include "llvm/MC/MCSymbol.h" 97 #include "llvm/Support/AtomicOrdering.h" 98 #include "llvm/Support/BranchProbability.h" 99 #include "llvm/Support/Casting.h" 100 #include "llvm/Support/CodeGen.h" 101 #include "llvm/Support/CommandLine.h" 102 #include "llvm/Support/Compiler.h" 103 #include "llvm/Support/Debug.h" 104 #include "llvm/Support/ErrorHandling.h" 105 #include "llvm/Support/MachineValueType.h" 106 #include "llvm/Support/MathExtras.h" 107 #include "llvm/Support/raw_ostream.h" 108 #include "llvm/Target/TargetIntrinsicInfo.h" 109 #include "llvm/Target/TargetMachine.h" 110 #include "llvm/Target/TargetOptions.h" 111 #include "llvm/Transforms/Utils/Local.h" 112 #include <algorithm> 113 #include <cassert> 114 #include <cstddef> 115 #include <cstdint> 116 #include <cstring> 117 #include <iterator> 118 #include <limits> 119 #include <numeric> 120 #include <tuple> 121 #include <utility> 122 #include <vector> 123 124 using namespace llvm; 125 using namespace PatternMatch; 126 127 #define DEBUG_TYPE "isel" 128 129 /// LimitFloatPrecision - Generate low-precision inline sequences for 130 /// some float libcalls (6, 8 or 12 bits). 131 static unsigned LimitFloatPrecision; 132 133 static cl::opt<unsigned, true> 134 LimitFPPrecision("limit-float-precision", 135 cl::desc("Generate low-precision inline sequences " 136 "for some float libcalls"), 137 cl::location(LimitFloatPrecision), cl::Hidden, 138 cl::init(0)); 139 140 static cl::opt<unsigned> SwitchPeelThreshold( 141 "switch-peel-threshold", cl::Hidden, cl::init(66), 142 cl::desc("Set the case probability threshold for peeling the case from a " 143 "switch statement. A value greater than 100 will void this " 144 "optimization")); 145 146 // Limit the width of DAG chains. This is important in general to prevent 147 // DAG-based analysis from blowing up. For example, alias analysis and 148 // load clustering may not complete in reasonable time. It is difficult to 149 // recognize and avoid this situation within each individual analysis, and 150 // future analyses are likely to have the same behavior. Limiting DAG width is 151 // the safe approach and will be especially important with global DAGs. 152 // 153 // MaxParallelChains default is arbitrarily high to avoid affecting 154 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 155 // sequence over this should have been converted to llvm.memcpy by the 156 // frontend. It is easy to induce this behavior with .ll code such as: 157 // %buffer = alloca [4096 x i8] 158 // %data = load [4096 x i8]* %argPtr 159 // store [4096 x i8] %data, [4096 x i8]* %buffer 160 static const unsigned MaxParallelChains = 64; 161 162 // Return the calling convention if the Value passed requires ABI mangling as it 163 // is a parameter to a function or a return value from a function which is not 164 // an intrinsic. 165 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) { 166 if (auto *R = dyn_cast<ReturnInst>(V)) 167 return R->getParent()->getParent()->getCallingConv(); 168 169 if (auto *CI = dyn_cast<CallInst>(V)) { 170 const bool IsInlineAsm = CI->isInlineAsm(); 171 const bool IsIndirectFunctionCall = 172 !IsInlineAsm && !CI->getCalledFunction(); 173 174 // It is possible that the call instruction is an inline asm statement or an 175 // indirect function call in which case the return value of 176 // getCalledFunction() would be nullptr. 177 const bool IsInstrinsicCall = 178 !IsInlineAsm && !IsIndirectFunctionCall && 179 CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic; 180 181 if (!IsInlineAsm && !IsInstrinsicCall) 182 return CI->getCallingConv(); 183 } 184 185 return None; 186 } 187 188 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 189 const SDValue *Parts, unsigned NumParts, 190 MVT PartVT, EVT ValueVT, const Value *V, 191 Optional<CallingConv::ID> CC); 192 193 /// getCopyFromParts - Create a value that contains the specified legal parts 194 /// combined into the value they represent. If the parts combine to a type 195 /// larger than ValueVT then AssertOp can be used to specify whether the extra 196 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 197 /// (ISD::AssertSext). 198 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 199 const SDValue *Parts, unsigned NumParts, 200 MVT PartVT, EVT ValueVT, const Value *V, 201 Optional<CallingConv::ID> CC = None, 202 Optional<ISD::NodeType> AssertOp = None) { 203 if (ValueVT.isVector()) 204 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 205 CC); 206 207 assert(NumParts > 0 && "No parts to assemble!"); 208 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 209 SDValue Val = Parts[0]; 210 211 if (NumParts > 1) { 212 // Assemble the value from multiple parts. 213 if (ValueVT.isInteger()) { 214 unsigned PartBits = PartVT.getSizeInBits(); 215 unsigned ValueBits = ValueVT.getSizeInBits(); 216 217 // Assemble the power of 2 part. 218 unsigned RoundParts = NumParts & (NumParts - 1) ? 219 1 << Log2_32(NumParts) : NumParts; 220 unsigned RoundBits = PartBits * RoundParts; 221 EVT RoundVT = RoundBits == ValueBits ? 222 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 223 SDValue Lo, Hi; 224 225 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 226 227 if (RoundParts > 2) { 228 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 229 PartVT, HalfVT, V); 230 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 231 RoundParts / 2, PartVT, HalfVT, V); 232 } else { 233 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 234 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 235 } 236 237 if (DAG.getDataLayout().isBigEndian()) 238 std::swap(Lo, Hi); 239 240 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 241 242 if (RoundParts < NumParts) { 243 // Assemble the trailing non-power-of-2 part. 244 unsigned OddParts = NumParts - RoundParts; 245 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 246 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 247 OddVT, V, CC); 248 249 // Combine the round and odd parts. 250 Lo = Val; 251 if (DAG.getDataLayout().isBigEndian()) 252 std::swap(Lo, Hi); 253 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 254 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 255 Hi = 256 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 257 DAG.getConstant(Lo.getValueSizeInBits(), DL, 258 TLI.getPointerTy(DAG.getDataLayout()))); 259 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 260 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 261 } 262 } else if (PartVT.isFloatingPoint()) { 263 // FP split into multiple FP parts (for ppcf128) 264 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 265 "Unexpected split"); 266 SDValue Lo, Hi; 267 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 268 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 269 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 270 std::swap(Lo, Hi); 271 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 272 } else { 273 // FP split into integer parts (soft fp) 274 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 275 !PartVT.isVector() && "Unexpected split"); 276 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 277 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 278 } 279 } 280 281 // There is now one part, held in Val. Correct it to match ValueVT. 282 // PartEVT is the type of the register class that holds the value. 283 // ValueVT is the type of the inline asm operation. 284 EVT PartEVT = Val.getValueType(); 285 286 if (PartEVT == ValueVT) 287 return Val; 288 289 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 290 ValueVT.bitsLT(PartEVT)) { 291 // For an FP value in an integer part, we need to truncate to the right 292 // width first. 293 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 294 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 295 } 296 297 // Handle types that have the same size. 298 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 299 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 300 301 // Handle types with different sizes. 302 if (PartEVT.isInteger() && ValueVT.isInteger()) { 303 if (ValueVT.bitsLT(PartEVT)) { 304 // For a truncate, see if we have any information to 305 // indicate whether the truncated bits will always be 306 // zero or sign-extension. 307 if (AssertOp.hasValue()) 308 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 309 DAG.getValueType(ValueVT)); 310 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 311 } 312 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 313 } 314 315 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 316 // FP_ROUND's are always exact here. 317 if (ValueVT.bitsLT(Val.getValueType())) 318 return DAG.getNode( 319 ISD::FP_ROUND, DL, ValueVT, Val, 320 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 321 322 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 323 } 324 325 llvm_unreachable("Unknown mismatch!"); 326 } 327 328 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 329 const Twine &ErrMsg) { 330 const Instruction *I = dyn_cast_or_null<Instruction>(V); 331 if (!V) 332 return Ctx.emitError(ErrMsg); 333 334 const char *AsmError = ", possible invalid constraint for vector type"; 335 if (const CallInst *CI = dyn_cast<CallInst>(I)) 336 if (isa<InlineAsm>(CI->getCalledValue())) 337 return Ctx.emitError(I, ErrMsg + AsmError); 338 339 return Ctx.emitError(I, ErrMsg); 340 } 341 342 /// getCopyFromPartsVector - Create a value that contains the specified legal 343 /// parts combined into the value they represent. If the parts combine to a 344 /// type larger than ValueVT then AssertOp can be used to specify whether the 345 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 346 /// ValueVT (ISD::AssertSext). 347 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 348 const SDValue *Parts, unsigned NumParts, 349 MVT PartVT, EVT ValueVT, const Value *V, 350 Optional<CallingConv::ID> CallConv) { 351 assert(ValueVT.isVector() && "Not a vector value"); 352 assert(NumParts > 0 && "No parts to assemble!"); 353 const bool IsABIRegCopy = CallConv.hasValue(); 354 355 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 356 SDValue Val = Parts[0]; 357 358 // Handle a multi-element vector. 359 if (NumParts > 1) { 360 EVT IntermediateVT; 361 MVT RegisterVT; 362 unsigned NumIntermediates; 363 unsigned NumRegs; 364 365 if (IsABIRegCopy) { 366 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 367 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 368 NumIntermediates, RegisterVT); 369 } else { 370 NumRegs = 371 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 372 NumIntermediates, RegisterVT); 373 } 374 375 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 376 NumParts = NumRegs; // Silence a compiler warning. 377 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 378 assert(RegisterVT.getSizeInBits() == 379 Parts[0].getSimpleValueType().getSizeInBits() && 380 "Part type sizes don't match!"); 381 382 // Assemble the parts into intermediate operands. 383 SmallVector<SDValue, 8> Ops(NumIntermediates); 384 if (NumIntermediates == NumParts) { 385 // If the register was not expanded, truncate or copy the value, 386 // as appropriate. 387 for (unsigned i = 0; i != NumParts; ++i) 388 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 389 PartVT, IntermediateVT, V); 390 } else if (NumParts > 0) { 391 // If the intermediate type was expanded, build the intermediate 392 // operands from the parts. 393 assert(NumParts % NumIntermediates == 0 && 394 "Must expand into a divisible number of parts!"); 395 unsigned Factor = NumParts / NumIntermediates; 396 for (unsigned i = 0; i != NumIntermediates; ++i) 397 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 398 PartVT, IntermediateVT, V); 399 } 400 401 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 402 // intermediate operands. 403 EVT BuiltVectorTy = 404 EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(), 405 (IntermediateVT.isVector() 406 ? IntermediateVT.getVectorNumElements() * NumParts 407 : NumIntermediates)); 408 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 409 : ISD::BUILD_VECTOR, 410 DL, BuiltVectorTy, Ops); 411 } 412 413 // There is now one part, held in Val. Correct it to match ValueVT. 414 EVT PartEVT = Val.getValueType(); 415 416 if (PartEVT == ValueVT) 417 return Val; 418 419 if (PartEVT.isVector()) { 420 // If the element type of the source/dest vectors are the same, but the 421 // parts vector has more elements than the value vector, then we have a 422 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 423 // elements we want. 424 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { 425 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() && 426 "Cannot narrow, it would be a lossy transformation"); 427 return DAG.getNode( 428 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 429 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 430 } 431 432 // Vector/Vector bitcast. 433 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 434 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 435 436 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() && 437 "Cannot handle this kind of promotion"); 438 // Promoted vector extract 439 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 440 441 } 442 443 // Trivial bitcast if the types are the same size and the destination 444 // vector type is legal. 445 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 446 TLI.isTypeLegal(ValueVT)) 447 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 448 449 if (ValueVT.getVectorNumElements() != 1) { 450 // Certain ABIs require that vectors are passed as integers. For vectors 451 // are the same size, this is an obvious bitcast. 452 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 453 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 454 } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) { 455 // Bitcast Val back the original type and extract the corresponding 456 // vector we want. 457 unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits(); 458 EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(), 459 ValueVT.getVectorElementType(), Elts); 460 Val = DAG.getBitcast(WiderVecType, Val); 461 return DAG.getNode( 462 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 463 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 464 } 465 466 diagnosePossiblyInvalidConstraint( 467 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 468 return DAG.getUNDEF(ValueVT); 469 } 470 471 // Handle cases such as i8 -> <1 x i1> 472 EVT ValueSVT = ValueVT.getVectorElementType(); 473 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) 474 Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 475 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 476 477 return DAG.getBuildVector(ValueVT, DL, Val); 478 } 479 480 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 481 SDValue Val, SDValue *Parts, unsigned NumParts, 482 MVT PartVT, const Value *V, 483 Optional<CallingConv::ID> CallConv); 484 485 /// getCopyToParts - Create a series of nodes that contain the specified value 486 /// split into legal parts. If the parts contain more bits than Val, then, for 487 /// integers, ExtendKind can be used to specify how to generate the extra bits. 488 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 489 SDValue *Parts, unsigned NumParts, MVT PartVT, 490 const Value *V, 491 Optional<CallingConv::ID> CallConv = None, 492 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 493 EVT ValueVT = Val.getValueType(); 494 495 // Handle the vector case separately. 496 if (ValueVT.isVector()) 497 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 498 CallConv); 499 500 unsigned PartBits = PartVT.getSizeInBits(); 501 unsigned OrigNumParts = NumParts; 502 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 503 "Copying to an illegal type!"); 504 505 if (NumParts == 0) 506 return; 507 508 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 509 EVT PartEVT = PartVT; 510 if (PartEVT == ValueVT) { 511 assert(NumParts == 1 && "No-op copy with multiple parts!"); 512 Parts[0] = Val; 513 return; 514 } 515 516 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 517 // If the parts cover more bits than the value has, promote the value. 518 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 519 assert(NumParts == 1 && "Do not know what to promote to!"); 520 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 521 } else { 522 if (ValueVT.isFloatingPoint()) { 523 // FP values need to be bitcast, then extended if they are being put 524 // into a larger container. 525 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 526 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 527 } 528 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 529 ValueVT.isInteger() && 530 "Unknown mismatch!"); 531 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 532 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 533 if (PartVT == MVT::x86mmx) 534 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 535 } 536 } else if (PartBits == ValueVT.getSizeInBits()) { 537 // Different types of the same size. 538 assert(NumParts == 1 && PartEVT != ValueVT); 539 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 540 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 541 // If the parts cover less bits than value has, truncate the value. 542 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 543 ValueVT.isInteger() && 544 "Unknown mismatch!"); 545 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 546 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 547 if (PartVT == MVT::x86mmx) 548 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 549 } 550 551 // The value may have changed - recompute ValueVT. 552 ValueVT = Val.getValueType(); 553 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 554 "Failed to tile the value with PartVT!"); 555 556 if (NumParts == 1) { 557 if (PartEVT != ValueVT) { 558 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 559 "scalar-to-vector conversion failed"); 560 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 561 } 562 563 Parts[0] = Val; 564 return; 565 } 566 567 // Expand the value into multiple parts. 568 if (NumParts & (NumParts - 1)) { 569 // The number of parts is not a power of 2. Split off and copy the tail. 570 assert(PartVT.isInteger() && ValueVT.isInteger() && 571 "Do not know what to expand to!"); 572 unsigned RoundParts = 1 << Log2_32(NumParts); 573 unsigned RoundBits = RoundParts * PartBits; 574 unsigned OddParts = NumParts - RoundParts; 575 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 576 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false)); 577 578 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 579 CallConv); 580 581 if (DAG.getDataLayout().isBigEndian()) 582 // The odd parts were reversed by getCopyToParts - unreverse them. 583 std::reverse(Parts + RoundParts, Parts + NumParts); 584 585 NumParts = RoundParts; 586 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 587 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 588 } 589 590 // The number of parts is a power of 2. Repeatedly bisect the value using 591 // EXTRACT_ELEMENT. 592 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 593 EVT::getIntegerVT(*DAG.getContext(), 594 ValueVT.getSizeInBits()), 595 Val); 596 597 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 598 for (unsigned i = 0; i < NumParts; i += StepSize) { 599 unsigned ThisBits = StepSize * PartBits / 2; 600 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 601 SDValue &Part0 = Parts[i]; 602 SDValue &Part1 = Parts[i+StepSize/2]; 603 604 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 605 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 606 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 607 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 608 609 if (ThisBits == PartBits && ThisVT != PartVT) { 610 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 611 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 612 } 613 } 614 } 615 616 if (DAG.getDataLayout().isBigEndian()) 617 std::reverse(Parts, Parts + OrigNumParts); 618 } 619 620 static SDValue widenVectorToPartType(SelectionDAG &DAG, 621 SDValue Val, const SDLoc &DL, EVT PartVT) { 622 if (!PartVT.isVector()) 623 return SDValue(); 624 625 EVT ValueVT = Val.getValueType(); 626 unsigned PartNumElts = PartVT.getVectorNumElements(); 627 unsigned ValueNumElts = ValueVT.getVectorNumElements(); 628 if (PartNumElts > ValueNumElts && 629 PartVT.getVectorElementType() == ValueVT.getVectorElementType()) { 630 EVT ElementVT = PartVT.getVectorElementType(); 631 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 632 // undef elements. 633 SmallVector<SDValue, 16> Ops; 634 DAG.ExtractVectorElements(Val, Ops); 635 SDValue EltUndef = DAG.getUNDEF(ElementVT); 636 for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i) 637 Ops.push_back(EltUndef); 638 639 // FIXME: Use CONCAT for 2x -> 4x. 640 return DAG.getBuildVector(PartVT, DL, Ops); 641 } 642 643 return SDValue(); 644 } 645 646 /// getCopyToPartsVector - Create a series of nodes that contain the specified 647 /// value split into legal parts. 648 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 649 SDValue Val, SDValue *Parts, unsigned NumParts, 650 MVT PartVT, const Value *V, 651 Optional<CallingConv::ID> CallConv) { 652 EVT ValueVT = Val.getValueType(); 653 assert(ValueVT.isVector() && "Not a vector"); 654 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 655 const bool IsABIRegCopy = CallConv.hasValue(); 656 657 if (NumParts == 1) { 658 EVT PartEVT = PartVT; 659 if (PartEVT == ValueVT) { 660 // Nothing to do. 661 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 662 // Bitconvert vector->vector case. 663 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 664 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 665 Val = Widened; 666 } else if (PartVT.isVector() && 667 PartEVT.getVectorElementType().bitsGE( 668 ValueVT.getVectorElementType()) && 669 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) { 670 671 // Promoted vector extract 672 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 673 } else { 674 if (ValueVT.getVectorNumElements() == 1) { 675 Val = DAG.getNode( 676 ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 677 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 678 } else { 679 assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() && 680 "lossy conversion of vector to scalar type"); 681 EVT IntermediateType = 682 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 683 Val = DAG.getBitcast(IntermediateType, Val); 684 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 685 } 686 } 687 688 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 689 Parts[0] = Val; 690 return; 691 } 692 693 // Handle a multi-element vector. 694 EVT IntermediateVT; 695 MVT RegisterVT; 696 unsigned NumIntermediates; 697 unsigned NumRegs; 698 if (IsABIRegCopy) { 699 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 700 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 701 NumIntermediates, RegisterVT); 702 } else { 703 NumRegs = 704 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 705 NumIntermediates, RegisterVT); 706 } 707 708 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 709 NumParts = NumRegs; // Silence a compiler warning. 710 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 711 712 unsigned IntermediateNumElts = IntermediateVT.isVector() ? 713 IntermediateVT.getVectorNumElements() : 1; 714 715 // Convert the vector to the appropiate type if necessary. 716 unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts; 717 718 EVT BuiltVectorTy = EVT::getVectorVT( 719 *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts); 720 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 721 if (ValueVT != BuiltVectorTy) { 722 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) 723 Val = Widened; 724 725 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 726 } 727 728 // Split the vector into intermediate operands. 729 SmallVector<SDValue, 8> Ops(NumIntermediates); 730 for (unsigned i = 0; i != NumIntermediates; ++i) { 731 if (IntermediateVT.isVector()) { 732 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 733 DAG.getConstant(i * IntermediateNumElts, DL, IdxVT)); 734 } else { 735 Ops[i] = DAG.getNode( 736 ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 737 DAG.getConstant(i, DL, IdxVT)); 738 } 739 } 740 741 // Split the intermediate operands into legal parts. 742 if (NumParts == NumIntermediates) { 743 // If the register was not expanded, promote or copy the value, 744 // as appropriate. 745 for (unsigned i = 0; i != NumParts; ++i) 746 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 747 } else if (NumParts > 0) { 748 // If the intermediate type was expanded, split each the value into 749 // legal parts. 750 assert(NumIntermediates != 0 && "division by zero"); 751 assert(NumParts % NumIntermediates == 0 && 752 "Must expand into a divisible number of parts!"); 753 unsigned Factor = NumParts / NumIntermediates; 754 for (unsigned i = 0; i != NumIntermediates; ++i) 755 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 756 CallConv); 757 } 758 } 759 760 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 761 EVT valuevt, Optional<CallingConv::ID> CC) 762 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 763 RegCount(1, regs.size()), CallConv(CC) {} 764 765 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 766 const DataLayout &DL, unsigned Reg, Type *Ty, 767 Optional<CallingConv::ID> CC) { 768 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 769 770 CallConv = CC; 771 772 for (EVT ValueVT : ValueVTs) { 773 unsigned NumRegs = 774 isABIMangled() 775 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) 776 : TLI.getNumRegisters(Context, ValueVT); 777 MVT RegisterVT = 778 isABIMangled() 779 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) 780 : TLI.getRegisterType(Context, ValueVT); 781 for (unsigned i = 0; i != NumRegs; ++i) 782 Regs.push_back(Reg + i); 783 RegVTs.push_back(RegisterVT); 784 RegCount.push_back(NumRegs); 785 Reg += NumRegs; 786 } 787 } 788 789 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 790 FunctionLoweringInfo &FuncInfo, 791 const SDLoc &dl, SDValue &Chain, 792 SDValue *Flag, const Value *V) const { 793 // A Value with type {} or [0 x %t] needs no registers. 794 if (ValueVTs.empty()) 795 return SDValue(); 796 797 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 798 799 // Assemble the legal parts into the final values. 800 SmallVector<SDValue, 4> Values(ValueVTs.size()); 801 SmallVector<SDValue, 8> Parts; 802 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 803 // Copy the legal parts from the registers. 804 EVT ValueVT = ValueVTs[Value]; 805 unsigned NumRegs = RegCount[Value]; 806 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 807 *DAG.getContext(), 808 CallConv.getValue(), RegVTs[Value]) 809 : RegVTs[Value]; 810 811 Parts.resize(NumRegs); 812 for (unsigned i = 0; i != NumRegs; ++i) { 813 SDValue P; 814 if (!Flag) { 815 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 816 } else { 817 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 818 *Flag = P.getValue(2); 819 } 820 821 Chain = P.getValue(1); 822 Parts[i] = P; 823 824 // If the source register was virtual and if we know something about it, 825 // add an assert node. 826 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) || 827 !RegisterVT.isInteger()) 828 continue; 829 830 const FunctionLoweringInfo::LiveOutInfo *LOI = 831 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 832 if (!LOI) 833 continue; 834 835 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 836 unsigned NumSignBits = LOI->NumSignBits; 837 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 838 839 if (NumZeroBits == RegSize) { 840 // The current value is a zero. 841 // Explicitly express that as it would be easier for 842 // optimizations to kick in. 843 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 844 continue; 845 } 846 847 // FIXME: We capture more information than the dag can represent. For 848 // now, just use the tightest assertzext/assertsext possible. 849 bool isSExt; 850 EVT FromVT(MVT::Other); 851 if (NumZeroBits) { 852 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 853 isSExt = false; 854 } else if (NumSignBits > 1) { 855 FromVT = 856 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 857 isSExt = true; 858 } else { 859 continue; 860 } 861 // Add an assertion node. 862 assert(FromVT != MVT::Other); 863 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 864 RegisterVT, P, DAG.getValueType(FromVT)); 865 } 866 867 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 868 RegisterVT, ValueVT, V, CallConv); 869 Part += NumRegs; 870 Parts.clear(); 871 } 872 873 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 874 } 875 876 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 877 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 878 const Value *V, 879 ISD::NodeType PreferredExtendType) const { 880 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 881 ISD::NodeType ExtendKind = PreferredExtendType; 882 883 // Get the list of the values's legal parts. 884 unsigned NumRegs = Regs.size(); 885 SmallVector<SDValue, 8> Parts(NumRegs); 886 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 887 unsigned NumParts = RegCount[Value]; 888 889 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 890 *DAG.getContext(), 891 CallConv.getValue(), RegVTs[Value]) 892 : RegVTs[Value]; 893 894 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 895 ExtendKind = ISD::ZERO_EXTEND; 896 897 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 898 NumParts, RegisterVT, V, CallConv, ExtendKind); 899 Part += NumParts; 900 } 901 902 // Copy the parts into the registers. 903 SmallVector<SDValue, 8> Chains(NumRegs); 904 for (unsigned i = 0; i != NumRegs; ++i) { 905 SDValue Part; 906 if (!Flag) { 907 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 908 } else { 909 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 910 *Flag = Part.getValue(1); 911 } 912 913 Chains[i] = Part.getValue(0); 914 } 915 916 if (NumRegs == 1 || Flag) 917 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 918 // flagged to it. That is the CopyToReg nodes and the user are considered 919 // a single scheduling unit. If we create a TokenFactor and return it as 920 // chain, then the TokenFactor is both a predecessor (operand) of the 921 // user as well as a successor (the TF operands are flagged to the user). 922 // c1, f1 = CopyToReg 923 // c2, f2 = CopyToReg 924 // c3 = TokenFactor c1, c2 925 // ... 926 // = op c3, ..., f2 927 Chain = Chains[NumRegs-1]; 928 else 929 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 930 } 931 932 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 933 unsigned MatchingIdx, const SDLoc &dl, 934 SelectionDAG &DAG, 935 std::vector<SDValue> &Ops) const { 936 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 937 938 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 939 if (HasMatching) 940 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 941 else if (!Regs.empty() && 942 TargetRegisterInfo::isVirtualRegister(Regs.front())) { 943 // Put the register class of the virtual registers in the flag word. That 944 // way, later passes can recompute register class constraints for inline 945 // assembly as well as normal instructions. 946 // Don't do this for tied operands that can use the regclass information 947 // from the def. 948 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 949 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 950 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 951 } 952 953 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 954 Ops.push_back(Res); 955 956 if (Code == InlineAsm::Kind_Clobber) { 957 // Clobbers should always have a 1:1 mapping with registers, and may 958 // reference registers that have illegal (e.g. vector) types. Hence, we 959 // shouldn't try to apply any sort of splitting logic to them. 960 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 961 "No 1:1 mapping from clobbers to regs?"); 962 unsigned SP = TLI.getStackPointerRegisterToSaveRestore(); 963 (void)SP; 964 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 965 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 966 assert( 967 (Regs[I] != SP || 968 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 969 "If we clobbered the stack pointer, MFI should know about it."); 970 } 971 return; 972 } 973 974 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 975 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 976 MVT RegisterVT = RegVTs[Value]; 977 for (unsigned i = 0; i != NumRegs; ++i) { 978 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 979 unsigned TheReg = Regs[Reg++]; 980 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 981 } 982 } 983 } 984 985 SmallVector<std::pair<unsigned, unsigned>, 4> 986 RegsForValue::getRegsAndSizes() const { 987 SmallVector<std::pair<unsigned, unsigned>, 4> OutVec; 988 unsigned I = 0; 989 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 990 unsigned RegCount = std::get<0>(CountAndVT); 991 MVT RegisterVT = std::get<1>(CountAndVT); 992 unsigned RegisterSize = RegisterVT.getSizeInBits(); 993 for (unsigned E = I + RegCount; I != E; ++I) 994 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 995 } 996 return OutVec; 997 } 998 999 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1000 const TargetLibraryInfo *li) { 1001 AA = aa; 1002 GFI = gfi; 1003 LibInfo = li; 1004 DL = &DAG.getDataLayout(); 1005 Context = DAG.getContext(); 1006 LPadToCallSiteMap.clear(); 1007 } 1008 1009 void SelectionDAGBuilder::clear() { 1010 NodeMap.clear(); 1011 UnusedArgNodeMap.clear(); 1012 PendingLoads.clear(); 1013 PendingExports.clear(); 1014 CurInst = nullptr; 1015 HasTailCall = false; 1016 SDNodeOrder = LowestSDNodeOrder; 1017 StatepointLowering.clear(); 1018 } 1019 1020 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1021 DanglingDebugInfoMap.clear(); 1022 } 1023 1024 SDValue SelectionDAGBuilder::getRoot() { 1025 if (PendingLoads.empty()) 1026 return DAG.getRoot(); 1027 1028 if (PendingLoads.size() == 1) { 1029 SDValue Root = PendingLoads[0]; 1030 DAG.setRoot(Root); 1031 PendingLoads.clear(); 1032 return Root; 1033 } 1034 1035 // Otherwise, we have to make a token factor node. 1036 SDValue Root = DAG.getTokenFactor(getCurSDLoc(), PendingLoads); 1037 PendingLoads.clear(); 1038 DAG.setRoot(Root); 1039 return Root; 1040 } 1041 1042 SDValue SelectionDAGBuilder::getControlRoot() { 1043 SDValue Root = DAG.getRoot(); 1044 1045 if (PendingExports.empty()) 1046 return Root; 1047 1048 // Turn all of the CopyToReg chains into one factored node. 1049 if (Root.getOpcode() != ISD::EntryToken) { 1050 unsigned i = 0, e = PendingExports.size(); 1051 for (; i != e; ++i) { 1052 assert(PendingExports[i].getNode()->getNumOperands() > 1); 1053 if (PendingExports[i].getNode()->getOperand(0) == Root) 1054 break; // Don't add the root if we already indirectly depend on it. 1055 } 1056 1057 if (i == e) 1058 PendingExports.push_back(Root); 1059 } 1060 1061 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, 1062 PendingExports); 1063 PendingExports.clear(); 1064 DAG.setRoot(Root); 1065 return Root; 1066 } 1067 1068 void SelectionDAGBuilder::visit(const Instruction &I) { 1069 // Set up outgoing PHI node register values before emitting the terminator. 1070 if (I.isTerminator()) { 1071 HandlePHINodesInSuccessorBlocks(I.getParent()); 1072 } 1073 1074 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1075 if (!isa<DbgInfoIntrinsic>(I)) 1076 ++SDNodeOrder; 1077 1078 CurInst = &I; 1079 1080 visit(I.getOpcode(), I); 1081 1082 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) { 1083 // Propagate the fast-math-flags of this IR instruction to the DAG node that 1084 // maps to this instruction. 1085 // TODO: We could handle all flags (nsw, etc) here. 1086 // TODO: If an IR instruction maps to >1 node, only the final node will have 1087 // flags set. 1088 if (SDNode *Node = getNodeForIRValue(&I)) { 1089 SDNodeFlags IncomingFlags; 1090 IncomingFlags.copyFMF(*FPMO); 1091 if (!Node->getFlags().isDefined()) 1092 Node->setFlags(IncomingFlags); 1093 else 1094 Node->intersectFlagsWith(IncomingFlags); 1095 } 1096 } 1097 1098 if (!I.isTerminator() && !HasTailCall && 1099 !isStatepoint(&I)) // statepoints handle their exports internally 1100 CopyToExportRegsIfNeeded(&I); 1101 1102 CurInst = nullptr; 1103 } 1104 1105 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1106 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1107 } 1108 1109 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1110 // Note: this doesn't use InstVisitor, because it has to work with 1111 // ConstantExpr's in addition to instructions. 1112 switch (Opcode) { 1113 default: llvm_unreachable("Unknown instruction type encountered!"); 1114 // Build the switch statement using the Instruction.def file. 1115 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1116 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1117 #include "llvm/IR/Instruction.def" 1118 } 1119 } 1120 1121 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1122 const DIExpression *Expr) { 1123 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1124 const DbgValueInst *DI = DDI.getDI(); 1125 DIVariable *DanglingVariable = DI->getVariable(); 1126 DIExpression *DanglingExpr = DI->getExpression(); 1127 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1128 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1129 return true; 1130 } 1131 return false; 1132 }; 1133 1134 for (auto &DDIMI : DanglingDebugInfoMap) { 1135 DanglingDebugInfoVector &DDIV = DDIMI.second; 1136 1137 // If debug info is to be dropped, run it through final checks to see 1138 // whether it can be salvaged. 1139 for (auto &DDI : DDIV) 1140 if (isMatchingDbgValue(DDI)) 1141 salvageUnresolvedDbgValue(DDI); 1142 1143 DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end()); 1144 } 1145 } 1146 1147 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1148 // generate the debug data structures now that we've seen its definition. 1149 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1150 SDValue Val) { 1151 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1152 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1153 return; 1154 1155 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1156 for (auto &DDI : DDIV) { 1157 const DbgValueInst *DI = DDI.getDI(); 1158 assert(DI && "Ill-formed DanglingDebugInfo"); 1159 DebugLoc dl = DDI.getdl(); 1160 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1161 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1162 DILocalVariable *Variable = DI->getVariable(); 1163 DIExpression *Expr = DI->getExpression(); 1164 assert(Variable->isValidLocationForIntrinsic(dl) && 1165 "Expected inlined-at fields to agree"); 1166 SDDbgValue *SDV; 1167 if (Val.getNode()) { 1168 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1169 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1170 // we couldn't resolve it directly when examining the DbgValue intrinsic 1171 // in the first place we should not be more successful here). Unless we 1172 // have some test case that prove this to be correct we should avoid 1173 // calling EmitFuncArgumentDbgValue here. 1174 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1175 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1176 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1177 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1178 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1179 // inserted after the definition of Val when emitting the instructions 1180 // after ISel. An alternative could be to teach 1181 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1182 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1183 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1184 << ValSDNodeOrder << "\n"); 1185 SDV = getDbgValue(Val, Variable, Expr, dl, 1186 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1187 DAG.AddDbgValue(SDV, Val.getNode(), false); 1188 } else 1189 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1190 << "in EmitFuncArgumentDbgValue\n"); 1191 } else { 1192 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1193 auto Undef = 1194 UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1195 auto SDV = 1196 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); 1197 DAG.AddDbgValue(SDV, nullptr, false); 1198 } 1199 } 1200 DDIV.clear(); 1201 } 1202 1203 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1204 Value *V = DDI.getDI()->getValue(); 1205 DILocalVariable *Var = DDI.getDI()->getVariable(); 1206 DIExpression *Expr = DDI.getDI()->getExpression(); 1207 DebugLoc DL = DDI.getdl(); 1208 DebugLoc InstDL = DDI.getDI()->getDebugLoc(); 1209 unsigned SDOrder = DDI.getSDNodeOrder(); 1210 1211 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1212 // that DW_OP_stack_value is desired. 1213 assert(isa<DbgValueInst>(DDI.getDI())); 1214 bool StackValue = true; 1215 1216 // Can this Value can be encoded without any further work? 1217 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) 1218 return; 1219 1220 // Attempt to salvage back through as many instructions as possible. Bail if 1221 // a non-instruction is seen, such as a constant expression or global 1222 // variable. FIXME: Further work could recover those too. 1223 while (isa<Instruction>(V)) { 1224 Instruction &VAsInst = *cast<Instruction>(V); 1225 DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue); 1226 1227 // If we cannot salvage any further, and haven't yet found a suitable debug 1228 // expression, bail out. 1229 if (!NewExpr) 1230 break; 1231 1232 // New value and expr now represent this debuginfo. 1233 V = VAsInst.getOperand(0); 1234 Expr = NewExpr; 1235 1236 // Some kind of simplification occurred: check whether the operand of the 1237 // salvaged debug expression can be encoded in this DAG. 1238 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) { 1239 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n " 1240 << DDI.getDI() << "\nBy stripping back to:\n " << V); 1241 return; 1242 } 1243 } 1244 1245 // This was the final opportunity to salvage this debug information, and it 1246 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1247 // any earlier variable location. 1248 auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1249 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1250 DAG.AddDbgValue(SDV, nullptr, false); 1251 1252 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI() 1253 << "\n"); 1254 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0) 1255 << "\n"); 1256 } 1257 1258 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var, 1259 DIExpression *Expr, DebugLoc dl, 1260 DebugLoc InstDL, unsigned Order) { 1261 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1262 SDDbgValue *SDV; 1263 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1264 isa<ConstantPointerNull>(V)) { 1265 SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder); 1266 DAG.AddDbgValue(SDV, nullptr, false); 1267 return true; 1268 } 1269 1270 // If the Value is a frame index, we can create a FrameIndex debug value 1271 // without relying on the DAG at all. 1272 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1273 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1274 if (SI != FuncInfo.StaticAllocaMap.end()) { 1275 auto SDV = 1276 DAG.getFrameIndexDbgValue(Var, Expr, SI->second, 1277 /*IsIndirect*/ false, dl, SDNodeOrder); 1278 // Do not attach the SDNodeDbgValue to an SDNode: this variable location 1279 // is still available even if the SDNode gets optimized out. 1280 DAG.AddDbgValue(SDV, nullptr, false); 1281 return true; 1282 } 1283 } 1284 1285 // Do not use getValue() in here; we don't want to generate code at 1286 // this point if it hasn't been done yet. 1287 SDValue N = NodeMap[V]; 1288 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1289 N = UnusedArgNodeMap[V]; 1290 if (N.getNode()) { 1291 if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N)) 1292 return true; 1293 SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder); 1294 DAG.AddDbgValue(SDV, N.getNode(), false); 1295 return true; 1296 } 1297 1298 // Special rules apply for the first dbg.values of parameter variables in a 1299 // function. Identify them by the fact they reference Argument Values, that 1300 // they're parameters, and they are parameters of the current function. We 1301 // need to let them dangle until they get an SDNode. 1302 bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() && 1303 !InstDL.getInlinedAt(); 1304 if (!IsParamOfFunc) { 1305 // The value is not used in this block yet (or it would have an SDNode). 1306 // We still want the value to appear for the user if possible -- if it has 1307 // an associated VReg, we can refer to that instead. 1308 auto VMI = FuncInfo.ValueMap.find(V); 1309 if (VMI != FuncInfo.ValueMap.end()) { 1310 unsigned Reg = VMI->second; 1311 // If this is a PHI node, it may be split up into several MI PHI nodes 1312 // (in FunctionLoweringInfo::set). 1313 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1314 V->getType(), None); 1315 if (RFV.occupiesMultipleRegs()) { 1316 unsigned Offset = 0; 1317 unsigned BitsToDescribe = 0; 1318 if (auto VarSize = Var->getSizeInBits()) 1319 BitsToDescribe = *VarSize; 1320 if (auto Fragment = Expr->getFragmentInfo()) 1321 BitsToDescribe = Fragment->SizeInBits; 1322 for (auto RegAndSize : RFV.getRegsAndSizes()) { 1323 unsigned RegisterSize = RegAndSize.second; 1324 // Bail out if all bits are described already. 1325 if (Offset >= BitsToDescribe) 1326 break; 1327 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1328 ? BitsToDescribe - Offset 1329 : RegisterSize; 1330 auto FragmentExpr = DIExpression::createFragmentExpression( 1331 Expr, Offset, FragmentSize); 1332 if (!FragmentExpr) 1333 continue; 1334 SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first, 1335 false, dl, SDNodeOrder); 1336 DAG.AddDbgValue(SDV, nullptr, false); 1337 Offset += RegisterSize; 1338 } 1339 } else { 1340 SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder); 1341 DAG.AddDbgValue(SDV, nullptr, false); 1342 } 1343 return true; 1344 } 1345 } 1346 1347 return false; 1348 } 1349 1350 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1351 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1352 for (auto &Pair : DanglingDebugInfoMap) 1353 for (auto &DDI : Pair.second) 1354 salvageUnresolvedDbgValue(DDI); 1355 clearDanglingDebugInfo(); 1356 } 1357 1358 /// getCopyFromRegs - If there was virtual register allocated for the value V 1359 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1360 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1361 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V); 1362 SDValue Result; 1363 1364 if (It != FuncInfo.ValueMap.end()) { 1365 unsigned InReg = It->second; 1366 1367 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1368 DAG.getDataLayout(), InReg, Ty, 1369 None); // This is not an ABI copy. 1370 SDValue Chain = DAG.getEntryNode(); 1371 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1372 V); 1373 resolveDanglingDebugInfo(V, Result); 1374 } 1375 1376 return Result; 1377 } 1378 1379 /// getValue - Return an SDValue for the given Value. 1380 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1381 // If we already have an SDValue for this value, use it. It's important 1382 // to do this first, so that we don't create a CopyFromReg if we already 1383 // have a regular SDValue. 1384 SDValue &N = NodeMap[V]; 1385 if (N.getNode()) return N; 1386 1387 // If there's a virtual register allocated and initialized for this 1388 // value, use it. 1389 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1390 return copyFromReg; 1391 1392 // Otherwise create a new SDValue and remember it. 1393 SDValue Val = getValueImpl(V); 1394 NodeMap[V] = Val; 1395 resolveDanglingDebugInfo(V, Val); 1396 return Val; 1397 } 1398 1399 // Return true if SDValue exists for the given Value 1400 bool SelectionDAGBuilder::findValue(const Value *V) const { 1401 return (NodeMap.find(V) != NodeMap.end()) || 1402 (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end()); 1403 } 1404 1405 /// getNonRegisterValue - Return an SDValue for the given Value, but 1406 /// don't look in FuncInfo.ValueMap for a virtual register. 1407 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1408 // If we already have an SDValue for this value, use it. 1409 SDValue &N = NodeMap[V]; 1410 if (N.getNode()) { 1411 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1412 // Remove the debug location from the node as the node is about to be used 1413 // in a location which may differ from the original debug location. This 1414 // is relevant to Constant and ConstantFP nodes because they can appear 1415 // as constant expressions inside PHI nodes. 1416 N->setDebugLoc(DebugLoc()); 1417 } 1418 return N; 1419 } 1420 1421 // Otherwise create a new SDValue and remember it. 1422 SDValue Val = getValueImpl(V); 1423 NodeMap[V] = Val; 1424 resolveDanglingDebugInfo(V, Val); 1425 return Val; 1426 } 1427 1428 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1429 /// Create an SDValue for the given value. 1430 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1431 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1432 1433 if (const Constant *C = dyn_cast<Constant>(V)) { 1434 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1435 1436 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1437 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1438 1439 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1440 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1441 1442 if (isa<ConstantPointerNull>(C)) { 1443 unsigned AS = V->getType()->getPointerAddressSpace(); 1444 return DAG.getConstant(0, getCurSDLoc(), 1445 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1446 } 1447 1448 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1449 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1450 1451 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1452 return DAG.getUNDEF(VT); 1453 1454 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1455 visit(CE->getOpcode(), *CE); 1456 SDValue N1 = NodeMap[V]; 1457 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1458 return N1; 1459 } 1460 1461 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1462 SmallVector<SDValue, 4> Constants; 1463 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 1464 OI != OE; ++OI) { 1465 SDNode *Val = getValue(*OI).getNode(); 1466 // If the operand is an empty aggregate, there are no values. 1467 if (!Val) continue; 1468 // Add each leaf value from the operand to the Constants list 1469 // to form a flattened list of all the values. 1470 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1471 Constants.push_back(SDValue(Val, i)); 1472 } 1473 1474 return DAG.getMergeValues(Constants, getCurSDLoc()); 1475 } 1476 1477 if (const ConstantDataSequential *CDS = 1478 dyn_cast<ConstantDataSequential>(C)) { 1479 SmallVector<SDValue, 4> Ops; 1480 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1481 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1482 // Add each leaf value from the operand to the Constants list 1483 // to form a flattened list of all the values. 1484 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1485 Ops.push_back(SDValue(Val, i)); 1486 } 1487 1488 if (isa<ArrayType>(CDS->getType())) 1489 return DAG.getMergeValues(Ops, getCurSDLoc()); 1490 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1491 } 1492 1493 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1494 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1495 "Unknown struct or array constant!"); 1496 1497 SmallVector<EVT, 4> ValueVTs; 1498 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1499 unsigned NumElts = ValueVTs.size(); 1500 if (NumElts == 0) 1501 return SDValue(); // empty struct 1502 SmallVector<SDValue, 4> Constants(NumElts); 1503 for (unsigned i = 0; i != NumElts; ++i) { 1504 EVT EltVT = ValueVTs[i]; 1505 if (isa<UndefValue>(C)) 1506 Constants[i] = DAG.getUNDEF(EltVT); 1507 else if (EltVT.isFloatingPoint()) 1508 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1509 else 1510 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1511 } 1512 1513 return DAG.getMergeValues(Constants, getCurSDLoc()); 1514 } 1515 1516 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1517 return DAG.getBlockAddress(BA, VT); 1518 1519 VectorType *VecTy = cast<VectorType>(V->getType()); 1520 unsigned NumElements = VecTy->getNumElements(); 1521 1522 // Now that we know the number and type of the elements, get that number of 1523 // elements into the Ops array based on what kind of constant it is. 1524 SmallVector<SDValue, 16> Ops; 1525 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1526 for (unsigned i = 0; i != NumElements; ++i) 1527 Ops.push_back(getValue(CV->getOperand(i))); 1528 } else { 1529 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!"); 1530 EVT EltVT = 1531 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1532 1533 SDValue Op; 1534 if (EltVT.isFloatingPoint()) 1535 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1536 else 1537 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1538 Ops.assign(NumElements, Op); 1539 } 1540 1541 // Create a BUILD_VECTOR node. 1542 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1543 } 1544 1545 // If this is a static alloca, generate it as the frameindex instead of 1546 // computation. 1547 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1548 DenseMap<const AllocaInst*, int>::iterator SI = 1549 FuncInfo.StaticAllocaMap.find(AI); 1550 if (SI != FuncInfo.StaticAllocaMap.end()) 1551 return DAG.getFrameIndex(SI->second, 1552 TLI.getFrameIndexTy(DAG.getDataLayout())); 1553 } 1554 1555 // If this is an instruction which fast-isel has deferred, select it now. 1556 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1557 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1558 1559 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1560 Inst->getType(), getABIRegCopyCC(V)); 1561 SDValue Chain = DAG.getEntryNode(); 1562 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1563 } 1564 1565 llvm_unreachable("Can't get register for value!"); 1566 } 1567 1568 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1569 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1570 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1571 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1572 bool IsSEH = isAsynchronousEHPersonality(Pers); 1573 bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX; 1574 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1575 if (!IsSEH) 1576 CatchPadMBB->setIsEHScopeEntry(); 1577 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1578 if (IsMSVCCXX || IsCoreCLR) 1579 CatchPadMBB->setIsEHFuncletEntry(); 1580 // Wasm does not need catchpads anymore 1581 if (!IsWasmCXX) 1582 DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other, 1583 getControlRoot())); 1584 } 1585 1586 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1587 // Update machine-CFG edge. 1588 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1589 FuncInfo.MBB->addSuccessor(TargetMBB); 1590 1591 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1592 bool IsSEH = isAsynchronousEHPersonality(Pers); 1593 if (IsSEH) { 1594 // If this is not a fall-through branch or optimizations are switched off, 1595 // emit the branch. 1596 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1597 TM.getOptLevel() == CodeGenOpt::None) 1598 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1599 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1600 return; 1601 } 1602 1603 // Figure out the funclet membership for the catchret's successor. 1604 // This will be used by the FuncletLayout pass to determine how to order the 1605 // BB's. 1606 // A 'catchret' returns to the outer scope's color. 1607 Value *ParentPad = I.getCatchSwitchParentPad(); 1608 const BasicBlock *SuccessorColor; 1609 if (isa<ConstantTokenNone>(ParentPad)) 1610 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1611 else 1612 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1613 assert(SuccessorColor && "No parent funclet for catchret!"); 1614 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1615 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1616 1617 // Create the terminator node. 1618 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1619 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1620 DAG.getBasicBlock(SuccessorColorMBB)); 1621 DAG.setRoot(Ret); 1622 } 1623 1624 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1625 // Don't emit any special code for the cleanuppad instruction. It just marks 1626 // the start of an EH scope/funclet. 1627 FuncInfo.MBB->setIsEHScopeEntry(); 1628 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1629 if (Pers != EHPersonality::Wasm_CXX) { 1630 FuncInfo.MBB->setIsEHFuncletEntry(); 1631 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1632 } 1633 } 1634 1635 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and 1636 // the control flow always stops at the single catch pad, as it does for a 1637 // cleanup pad. In case the exception caught is not of the types the catch pad 1638 // catches, it will be rethrown by a rethrow. 1639 static void findWasmUnwindDestinations( 1640 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1641 BranchProbability Prob, 1642 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1643 &UnwindDests) { 1644 while (EHPadBB) { 1645 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1646 if (isa<CleanupPadInst>(Pad)) { 1647 // Stop on cleanup pads. 1648 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1649 UnwindDests.back().first->setIsEHScopeEntry(); 1650 break; 1651 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1652 // Add the catchpad handlers to the possible destinations. We don't 1653 // continue to the unwind destination of the catchswitch for wasm. 1654 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1655 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1656 UnwindDests.back().first->setIsEHScopeEntry(); 1657 } 1658 break; 1659 } else { 1660 continue; 1661 } 1662 } 1663 } 1664 1665 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1666 /// many places it could ultimately go. In the IR, we have a single unwind 1667 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1668 /// This function skips over imaginary basic blocks that hold catchswitch 1669 /// instructions, and finds all the "real" machine 1670 /// basic block destinations. As those destinations may not be successors of 1671 /// EHPadBB, here we also calculate the edge probability to those destinations. 1672 /// The passed-in Prob is the edge probability to EHPadBB. 1673 static void findUnwindDestinations( 1674 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1675 BranchProbability Prob, 1676 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1677 &UnwindDests) { 1678 EHPersonality Personality = 1679 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1680 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1681 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1682 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1683 bool IsSEH = isAsynchronousEHPersonality(Personality); 1684 1685 if (IsWasmCXX) { 1686 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1687 assert(UnwindDests.size() <= 1 && 1688 "There should be at most one unwind destination for wasm"); 1689 return; 1690 } 1691 1692 while (EHPadBB) { 1693 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1694 BasicBlock *NewEHPadBB = nullptr; 1695 if (isa<LandingPadInst>(Pad)) { 1696 // Stop on landingpads. They are not funclets. 1697 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1698 break; 1699 } else if (isa<CleanupPadInst>(Pad)) { 1700 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1701 // personalities. 1702 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1703 UnwindDests.back().first->setIsEHScopeEntry(); 1704 UnwindDests.back().first->setIsEHFuncletEntry(); 1705 break; 1706 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1707 // Add the catchpad handlers to the possible destinations. 1708 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1709 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1710 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1711 if (IsMSVCCXX || IsCoreCLR) 1712 UnwindDests.back().first->setIsEHFuncletEntry(); 1713 if (!IsSEH) 1714 UnwindDests.back().first->setIsEHScopeEntry(); 1715 } 1716 NewEHPadBB = CatchSwitch->getUnwindDest(); 1717 } else { 1718 continue; 1719 } 1720 1721 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1722 if (BPI && NewEHPadBB) 1723 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1724 EHPadBB = NewEHPadBB; 1725 } 1726 } 1727 1728 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1729 // Update successor info. 1730 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1731 auto UnwindDest = I.getUnwindDest(); 1732 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1733 BranchProbability UnwindDestProb = 1734 (BPI && UnwindDest) 1735 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1736 : BranchProbability::getZero(); 1737 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1738 for (auto &UnwindDest : UnwindDests) { 1739 UnwindDest.first->setIsEHPad(); 1740 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1741 } 1742 FuncInfo.MBB->normalizeSuccProbs(); 1743 1744 // Create the terminator node. 1745 SDValue Ret = 1746 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1747 DAG.setRoot(Ret); 1748 } 1749 1750 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1751 report_fatal_error("visitCatchSwitch not yet implemented!"); 1752 } 1753 1754 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1755 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1756 auto &DL = DAG.getDataLayout(); 1757 SDValue Chain = getControlRoot(); 1758 SmallVector<ISD::OutputArg, 8> Outs; 1759 SmallVector<SDValue, 8> OutVals; 1760 1761 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1762 // lower 1763 // 1764 // %val = call <ty> @llvm.experimental.deoptimize() 1765 // ret <ty> %val 1766 // 1767 // differently. 1768 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1769 LowerDeoptimizingReturn(); 1770 return; 1771 } 1772 1773 if (!FuncInfo.CanLowerReturn) { 1774 unsigned DemoteReg = FuncInfo.DemoteRegister; 1775 const Function *F = I.getParent()->getParent(); 1776 1777 // Emit a store of the return value through the virtual register. 1778 // Leave Outs empty so that LowerReturn won't try to load return 1779 // registers the usual way. 1780 SmallVector<EVT, 1> PtrValueVTs; 1781 ComputeValueVTs(TLI, DL, 1782 F->getReturnType()->getPointerTo( 1783 DAG.getDataLayout().getAllocaAddrSpace()), 1784 PtrValueVTs); 1785 1786 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1787 DemoteReg, PtrValueVTs[0]); 1788 SDValue RetOp = getValue(I.getOperand(0)); 1789 1790 SmallVector<EVT, 4> ValueVTs; 1791 SmallVector<uint64_t, 4> Offsets; 1792 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets); 1793 unsigned NumValues = ValueVTs.size(); 1794 1795 SmallVector<SDValue, 4> Chains(NumValues); 1796 for (unsigned i = 0; i != NumValues; ++i) { 1797 // An aggregate return value cannot wrap around the address space, so 1798 // offsets to its parts don't wrap either. 1799 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]); 1800 Chains[i] = DAG.getStore( 1801 Chain, getCurSDLoc(), SDValue(RetOp.getNode(), RetOp.getResNo() + i), 1802 // FIXME: better loc info would be nice. 1803 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction())); 1804 } 1805 1806 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1807 MVT::Other, Chains); 1808 } else if (I.getNumOperands() != 0) { 1809 SmallVector<EVT, 4> ValueVTs; 1810 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1811 unsigned NumValues = ValueVTs.size(); 1812 if (NumValues) { 1813 SDValue RetOp = getValue(I.getOperand(0)); 1814 1815 const Function *F = I.getParent()->getParent(); 1816 1817 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 1818 I.getOperand(0)->getType(), F->getCallingConv(), 1819 /*IsVarArg*/ false); 1820 1821 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1822 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1823 Attribute::SExt)) 1824 ExtendKind = ISD::SIGN_EXTEND; 1825 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1826 Attribute::ZExt)) 1827 ExtendKind = ISD::ZERO_EXTEND; 1828 1829 LLVMContext &Context = F->getContext(); 1830 bool RetInReg = F->getAttributes().hasAttribute( 1831 AttributeList::ReturnIndex, Attribute::InReg); 1832 1833 for (unsigned j = 0; j != NumValues; ++j) { 1834 EVT VT = ValueVTs[j]; 1835 1836 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1837 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1838 1839 CallingConv::ID CC = F->getCallingConv(); 1840 1841 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1842 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1843 SmallVector<SDValue, 4> Parts(NumParts); 1844 getCopyToParts(DAG, getCurSDLoc(), 1845 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1846 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1847 1848 // 'inreg' on function refers to return value 1849 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1850 if (RetInReg) 1851 Flags.setInReg(); 1852 1853 if (I.getOperand(0)->getType()->isPointerTy()) { 1854 Flags.setPointer(); 1855 Flags.setPointerAddrSpace( 1856 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 1857 } 1858 1859 if (NeedsRegBlock) { 1860 Flags.setInConsecutiveRegs(); 1861 if (j == NumValues - 1) 1862 Flags.setInConsecutiveRegsLast(); 1863 } 1864 1865 // Propagate extension type if any 1866 if (ExtendKind == ISD::SIGN_EXTEND) 1867 Flags.setSExt(); 1868 else if (ExtendKind == ISD::ZERO_EXTEND) 1869 Flags.setZExt(); 1870 1871 for (unsigned i = 0; i < NumParts; ++i) { 1872 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1873 VT, /*isfixed=*/true, 0, 0)); 1874 OutVals.push_back(Parts[i]); 1875 } 1876 } 1877 } 1878 } 1879 1880 // Push in swifterror virtual register as the last element of Outs. This makes 1881 // sure swifterror virtual register will be returned in the swifterror 1882 // physical register. 1883 const Function *F = I.getParent()->getParent(); 1884 if (TLI.supportSwiftError() && 1885 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 1886 assert(FuncInfo.SwiftErrorArg && "Need a swift error argument"); 1887 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1888 Flags.setSwiftError(); 1889 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 1890 EVT(TLI.getPointerTy(DL)) /*argvt*/, 1891 true /*isfixed*/, 1 /*origidx*/, 1892 0 /*partOffs*/)); 1893 // Create SDNode for the swifterror virtual register. 1894 OutVals.push_back( 1895 DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVRegUseAt( 1896 &I, FuncInfo.MBB, FuncInfo.SwiftErrorArg).first, 1897 EVT(TLI.getPointerTy(DL)))); 1898 } 1899 1900 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 1901 CallingConv::ID CallConv = 1902 DAG.getMachineFunction().getFunction().getCallingConv(); 1903 Chain = DAG.getTargetLoweringInfo().LowerReturn( 1904 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 1905 1906 // Verify that the target's LowerReturn behaved as expected. 1907 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 1908 "LowerReturn didn't return a valid chain!"); 1909 1910 // Update the DAG with the new chain value resulting from return lowering. 1911 DAG.setRoot(Chain); 1912 } 1913 1914 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 1915 /// created for it, emit nodes to copy the value into the virtual 1916 /// registers. 1917 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 1918 // Skip empty types 1919 if (V->getType()->isEmptyTy()) 1920 return; 1921 1922 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 1923 if (VMI != FuncInfo.ValueMap.end()) { 1924 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 1925 CopyValueToVirtualRegister(V, VMI->second); 1926 } 1927 } 1928 1929 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 1930 /// the current basic block, add it to ValueMap now so that we'll get a 1931 /// CopyTo/FromReg. 1932 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 1933 // No need to export constants. 1934 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 1935 1936 // Already exported? 1937 if (FuncInfo.isExportedInst(V)) return; 1938 1939 unsigned Reg = FuncInfo.InitializeRegForValue(V); 1940 CopyValueToVirtualRegister(V, Reg); 1941 } 1942 1943 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 1944 const BasicBlock *FromBB) { 1945 // The operands of the setcc have to be in this block. We don't know 1946 // how to export them from some other block. 1947 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 1948 // Can export from current BB. 1949 if (VI->getParent() == FromBB) 1950 return true; 1951 1952 // Is already exported, noop. 1953 return FuncInfo.isExportedInst(V); 1954 } 1955 1956 // If this is an argument, we can export it if the BB is the entry block or 1957 // if it is already exported. 1958 if (isa<Argument>(V)) { 1959 if (FromBB == &FromBB->getParent()->getEntryBlock()) 1960 return true; 1961 1962 // Otherwise, can only export this if it is already exported. 1963 return FuncInfo.isExportedInst(V); 1964 } 1965 1966 // Otherwise, constants can always be exported. 1967 return true; 1968 } 1969 1970 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 1971 BranchProbability 1972 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 1973 const MachineBasicBlock *Dst) const { 1974 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1975 const BasicBlock *SrcBB = Src->getBasicBlock(); 1976 const BasicBlock *DstBB = Dst->getBasicBlock(); 1977 if (!BPI) { 1978 // If BPI is not available, set the default probability as 1 / N, where N is 1979 // the number of successors. 1980 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 1981 return BranchProbability(1, SuccSize); 1982 } 1983 return BPI->getEdgeProbability(SrcBB, DstBB); 1984 } 1985 1986 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 1987 MachineBasicBlock *Dst, 1988 BranchProbability Prob) { 1989 if (!FuncInfo.BPI) 1990 Src->addSuccessorWithoutProb(Dst); 1991 else { 1992 if (Prob.isUnknown()) 1993 Prob = getEdgeProbability(Src, Dst); 1994 Src->addSuccessor(Dst, Prob); 1995 } 1996 } 1997 1998 static bool InBlock(const Value *V, const BasicBlock *BB) { 1999 if (const Instruction *I = dyn_cast<Instruction>(V)) 2000 return I->getParent() == BB; 2001 return true; 2002 } 2003 2004 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2005 /// This function emits a branch and is used at the leaves of an OR or an 2006 /// AND operator tree. 2007 void 2008 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2009 MachineBasicBlock *TBB, 2010 MachineBasicBlock *FBB, 2011 MachineBasicBlock *CurBB, 2012 MachineBasicBlock *SwitchBB, 2013 BranchProbability TProb, 2014 BranchProbability FProb, 2015 bool InvertCond) { 2016 const BasicBlock *BB = CurBB->getBasicBlock(); 2017 2018 // If the leaf of the tree is a comparison, merge the condition into 2019 // the caseblock. 2020 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2021 // The operands of the cmp have to be in this block. We don't know 2022 // how to export them from some other block. If this is the first block 2023 // of the sequence, no exporting is needed. 2024 if (CurBB == SwitchBB || 2025 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2026 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2027 ISD::CondCode Condition; 2028 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2029 ICmpInst::Predicate Pred = 2030 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2031 Condition = getICmpCondCode(Pred); 2032 } else { 2033 const FCmpInst *FC = cast<FCmpInst>(Cond); 2034 FCmpInst::Predicate Pred = 2035 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2036 Condition = getFCmpCondCode(Pred); 2037 if (TM.Options.NoNaNsFPMath) 2038 Condition = getFCmpCodeWithoutNaN(Condition); 2039 } 2040 2041 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2042 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2043 SwitchCases.push_back(CB); 2044 return; 2045 } 2046 } 2047 2048 // Create a CaseBlock record representing this branch. 2049 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2050 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2051 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2052 SwitchCases.push_back(CB); 2053 } 2054 2055 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2056 MachineBasicBlock *TBB, 2057 MachineBasicBlock *FBB, 2058 MachineBasicBlock *CurBB, 2059 MachineBasicBlock *SwitchBB, 2060 Instruction::BinaryOps Opc, 2061 BranchProbability TProb, 2062 BranchProbability FProb, 2063 bool InvertCond) { 2064 // Skip over not part of the tree and remember to invert op and operands at 2065 // next level. 2066 Value *NotCond; 2067 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2068 InBlock(NotCond, CurBB->getBasicBlock())) { 2069 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2070 !InvertCond); 2071 return; 2072 } 2073 2074 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2075 // Compute the effective opcode for Cond, taking into account whether it needs 2076 // to be inverted, e.g. 2077 // and (not (or A, B)), C 2078 // gets lowered as 2079 // and (and (not A, not B), C) 2080 unsigned BOpc = 0; 2081 if (BOp) { 2082 BOpc = BOp->getOpcode(); 2083 if (InvertCond) { 2084 if (BOpc == Instruction::And) 2085 BOpc = Instruction::Or; 2086 else if (BOpc == Instruction::Or) 2087 BOpc = Instruction::And; 2088 } 2089 } 2090 2091 // If this node is not part of the or/and tree, emit it as a branch. 2092 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 2093 BOpc != unsigned(Opc) || !BOp->hasOneUse() || 2094 BOp->getParent() != CurBB->getBasicBlock() || 2095 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 2096 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 2097 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2098 TProb, FProb, InvertCond); 2099 return; 2100 } 2101 2102 // Create TmpBB after CurBB. 2103 MachineFunction::iterator BBI(CurBB); 2104 MachineFunction &MF = DAG.getMachineFunction(); 2105 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2106 CurBB->getParent()->insert(++BBI, TmpBB); 2107 2108 if (Opc == Instruction::Or) { 2109 // Codegen X | Y as: 2110 // BB1: 2111 // jmp_if_X TBB 2112 // jmp TmpBB 2113 // TmpBB: 2114 // jmp_if_Y TBB 2115 // jmp FBB 2116 // 2117 2118 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2119 // The requirement is that 2120 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2121 // = TrueProb for original BB. 2122 // Assuming the original probabilities are A and B, one choice is to set 2123 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2124 // A/(1+B) and 2B/(1+B). This choice assumes that 2125 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2126 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2127 // TmpBB, but the math is more complicated. 2128 2129 auto NewTrueProb = TProb / 2; 2130 auto NewFalseProb = TProb / 2 + FProb; 2131 // Emit the LHS condition. 2132 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc, 2133 NewTrueProb, NewFalseProb, InvertCond); 2134 2135 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2136 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2137 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2138 // Emit the RHS condition into TmpBB. 2139 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2140 Probs[0], Probs[1], InvertCond); 2141 } else { 2142 assert(Opc == Instruction::And && "Unknown merge op!"); 2143 // Codegen X & Y as: 2144 // BB1: 2145 // jmp_if_X TmpBB 2146 // jmp FBB 2147 // TmpBB: 2148 // jmp_if_Y TBB 2149 // jmp FBB 2150 // 2151 // This requires creation of TmpBB after CurBB. 2152 2153 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2154 // The requirement is that 2155 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2156 // = FalseProb for original BB. 2157 // Assuming the original probabilities are A and B, one choice is to set 2158 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2159 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2160 // TrueProb for BB1 * FalseProb for TmpBB. 2161 2162 auto NewTrueProb = TProb + FProb / 2; 2163 auto NewFalseProb = FProb / 2; 2164 // Emit the LHS condition. 2165 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc, 2166 NewTrueProb, NewFalseProb, InvertCond); 2167 2168 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2169 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2170 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2171 // Emit the RHS condition into TmpBB. 2172 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2173 Probs[0], Probs[1], InvertCond); 2174 } 2175 } 2176 2177 /// If the set of cases should be emitted as a series of branches, return true. 2178 /// If we should emit this as a bunch of and/or'd together conditions, return 2179 /// false. 2180 bool 2181 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2182 if (Cases.size() != 2) return true; 2183 2184 // If this is two comparisons of the same values or'd or and'd together, they 2185 // will get folded into a single comparison, so don't emit two blocks. 2186 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2187 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2188 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2189 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2190 return false; 2191 } 2192 2193 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2194 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2195 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2196 Cases[0].CC == Cases[1].CC && 2197 isa<Constant>(Cases[0].CmpRHS) && 2198 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2199 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2200 return false; 2201 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2202 return false; 2203 } 2204 2205 return true; 2206 } 2207 2208 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2209 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2210 2211 // Update machine-CFG edges. 2212 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2213 2214 if (I.isUnconditional()) { 2215 // Update machine-CFG edges. 2216 BrMBB->addSuccessor(Succ0MBB); 2217 2218 // If this is not a fall-through branch or optimizations are switched off, 2219 // emit the branch. 2220 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2221 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2222 MVT::Other, getControlRoot(), 2223 DAG.getBasicBlock(Succ0MBB))); 2224 2225 return; 2226 } 2227 2228 // If this condition is one of the special cases we handle, do special stuff 2229 // now. 2230 const Value *CondVal = I.getCondition(); 2231 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2232 2233 // If this is a series of conditions that are or'd or and'd together, emit 2234 // this as a sequence of branches instead of setcc's with and/or operations. 2235 // As long as jumps are not expensive, this should improve performance. 2236 // For example, instead of something like: 2237 // cmp A, B 2238 // C = seteq 2239 // cmp D, E 2240 // F = setle 2241 // or C, F 2242 // jnz foo 2243 // Emit: 2244 // cmp A, B 2245 // je foo 2246 // cmp D, E 2247 // jle foo 2248 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 2249 Instruction::BinaryOps Opcode = BOp->getOpcode(); 2250 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() && 2251 !I.getMetadata(LLVMContext::MD_unpredictable) && 2252 (Opcode == Instruction::And || Opcode == Instruction::Or)) { 2253 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, 2254 Opcode, 2255 getEdgeProbability(BrMBB, Succ0MBB), 2256 getEdgeProbability(BrMBB, Succ1MBB), 2257 /*InvertCond=*/false); 2258 // If the compares in later blocks need to use values not currently 2259 // exported from this block, export them now. This block should always 2260 // be the first entry. 2261 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2262 2263 // Allow some cases to be rejected. 2264 if (ShouldEmitAsBranches(SwitchCases)) { 2265 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) { 2266 ExportFromCurrentBlock(SwitchCases[i].CmpLHS); 2267 ExportFromCurrentBlock(SwitchCases[i].CmpRHS); 2268 } 2269 2270 // Emit the branch for this block. 2271 visitSwitchCase(SwitchCases[0], BrMBB); 2272 SwitchCases.erase(SwitchCases.begin()); 2273 return; 2274 } 2275 2276 // Okay, we decided not to do this, remove any inserted MBB's and clear 2277 // SwitchCases. 2278 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) 2279 FuncInfo.MF->erase(SwitchCases[i].ThisBB); 2280 2281 SwitchCases.clear(); 2282 } 2283 } 2284 2285 // Create a CaseBlock record representing this branch. 2286 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2287 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2288 2289 // Use visitSwitchCase to actually insert the fast branch sequence for this 2290 // cond branch. 2291 visitSwitchCase(CB, BrMBB); 2292 } 2293 2294 /// visitSwitchCase - Emits the necessary code to represent a single node in 2295 /// the binary search tree resulting from lowering a switch instruction. 2296 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2297 MachineBasicBlock *SwitchBB) { 2298 SDValue Cond; 2299 SDValue CondLHS = getValue(CB.CmpLHS); 2300 SDLoc dl = CB.DL; 2301 2302 if (CB.CC == ISD::SETTRUE) { 2303 // Branch or fall through to TrueBB. 2304 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2305 SwitchBB->normalizeSuccProbs(); 2306 if (CB.TrueBB != NextBlock(SwitchBB)) { 2307 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2308 DAG.getBasicBlock(CB.TrueBB))); 2309 } 2310 return; 2311 } 2312 2313 // Build the setcc now. 2314 if (!CB.CmpMHS) { 2315 // Fold "(X == true)" to X and "(X == false)" to !X to 2316 // handle common cases produced by branch lowering. 2317 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2318 CB.CC == ISD::SETEQ) 2319 Cond = CondLHS; 2320 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2321 CB.CC == ISD::SETEQ) { 2322 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2323 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2324 } else 2325 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC); 2326 } else { 2327 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2328 2329 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2330 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2331 2332 SDValue CmpOp = getValue(CB.CmpMHS); 2333 EVT VT = CmpOp.getValueType(); 2334 2335 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2336 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2337 ISD::SETLE); 2338 } else { 2339 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2340 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2341 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2342 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2343 } 2344 } 2345 2346 // Update successor info 2347 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2348 // TrueBB and FalseBB are always different unless the incoming IR is 2349 // degenerate. This only happens when running llc on weird IR. 2350 if (CB.TrueBB != CB.FalseBB) 2351 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2352 SwitchBB->normalizeSuccProbs(); 2353 2354 // If the lhs block is the next block, invert the condition so that we can 2355 // fall through to the lhs instead of the rhs block. 2356 if (CB.TrueBB == NextBlock(SwitchBB)) { 2357 std::swap(CB.TrueBB, CB.FalseBB); 2358 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2359 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2360 } 2361 2362 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2363 MVT::Other, getControlRoot(), Cond, 2364 DAG.getBasicBlock(CB.TrueBB)); 2365 2366 // Insert the false branch. Do this even if it's a fall through branch, 2367 // this makes it easier to do DAG optimizations which require inverting 2368 // the branch condition. 2369 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2370 DAG.getBasicBlock(CB.FalseBB)); 2371 2372 DAG.setRoot(BrCond); 2373 } 2374 2375 /// visitJumpTable - Emit JumpTable node in the current MBB 2376 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) { 2377 // Emit the code for the jump table 2378 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2379 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2380 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2381 JT.Reg, PTy); 2382 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2383 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2384 MVT::Other, Index.getValue(1), 2385 Table, Index); 2386 DAG.setRoot(BrJumpTable); 2387 } 2388 2389 /// visitJumpTableHeader - This function emits necessary code to produce index 2390 /// in the JumpTable from switch case. 2391 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT, 2392 JumpTableHeader &JTH, 2393 MachineBasicBlock *SwitchBB) { 2394 SDLoc dl = getCurSDLoc(); 2395 2396 // Subtract the lowest switch case value from the value being switched on. 2397 SDValue SwitchOp = getValue(JTH.SValue); 2398 EVT VT = SwitchOp.getValueType(); 2399 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2400 DAG.getConstant(JTH.First, dl, VT)); 2401 2402 // The SDNode we just created, which holds the value being switched on minus 2403 // the smallest case value, needs to be copied to a virtual register so it 2404 // can be used as an index into the jump table in a subsequent basic block. 2405 // This value may be smaller or larger than the target's pointer type, and 2406 // therefore require extension or truncating. 2407 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2408 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2409 2410 unsigned JumpTableReg = 2411 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2412 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2413 JumpTableReg, SwitchOp); 2414 JT.Reg = JumpTableReg; 2415 2416 if (!JTH.OmitRangeCheck) { 2417 // Emit the range check for the jump table, and branch to the default block 2418 // for the switch statement if the value being switched on exceeds the 2419 // largest case in the switch. 2420 SDValue CMP = DAG.getSetCC( 2421 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2422 Sub.getValueType()), 2423 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2424 2425 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2426 MVT::Other, CopyTo, CMP, 2427 DAG.getBasicBlock(JT.Default)); 2428 2429 // Avoid emitting unnecessary branches to the next block. 2430 if (JT.MBB != NextBlock(SwitchBB)) 2431 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2432 DAG.getBasicBlock(JT.MBB)); 2433 2434 DAG.setRoot(BrCond); 2435 } else { 2436 // Avoid emitting unnecessary branches to the next block. 2437 if (JT.MBB != NextBlock(SwitchBB)) 2438 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2439 DAG.getBasicBlock(JT.MBB))); 2440 else 2441 DAG.setRoot(CopyTo); 2442 } 2443 } 2444 2445 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2446 /// variable if there exists one. 2447 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2448 SDValue &Chain) { 2449 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2450 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2451 MachineFunction &MF = DAG.getMachineFunction(); 2452 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2453 MachineSDNode *Node = 2454 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2455 if (Global) { 2456 MachinePointerInfo MPInfo(Global); 2457 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2458 MachineMemOperand::MODereferenceable; 2459 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2460 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy)); 2461 DAG.setNodeMemRefs(Node, {MemRef}); 2462 } 2463 return SDValue(Node, 0); 2464 } 2465 2466 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2467 /// tail spliced into a stack protector check success bb. 2468 /// 2469 /// For a high level explanation of how this fits into the stack protector 2470 /// generation see the comment on the declaration of class 2471 /// StackProtectorDescriptor. 2472 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2473 MachineBasicBlock *ParentBB) { 2474 2475 // First create the loads to the guard/stack slot for the comparison. 2476 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2477 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2478 2479 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2480 int FI = MFI.getStackProtectorIndex(); 2481 2482 SDValue Guard; 2483 SDLoc dl = getCurSDLoc(); 2484 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2485 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2486 unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext())); 2487 2488 // Generate code to load the content of the guard slot. 2489 SDValue GuardVal = DAG.getLoad( 2490 PtrTy, dl, DAG.getEntryNode(), StackSlotPtr, 2491 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2492 MachineMemOperand::MOVolatile); 2493 2494 if (TLI.useStackGuardXorFP()) 2495 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2496 2497 // Retrieve guard check function, nullptr if instrumentation is inlined. 2498 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2499 // The target provides a guard check function to validate the guard value. 2500 // Generate a call to that function with the content of the guard slot as 2501 // argument. 2502 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2503 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2504 2505 TargetLowering::ArgListTy Args; 2506 TargetLowering::ArgListEntry Entry; 2507 Entry.Node = GuardVal; 2508 Entry.Ty = FnTy->getParamType(0); 2509 if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg)) 2510 Entry.IsInReg = true; 2511 Args.push_back(Entry); 2512 2513 TargetLowering::CallLoweringInfo CLI(DAG); 2514 CLI.setDebugLoc(getCurSDLoc()) 2515 .setChain(DAG.getEntryNode()) 2516 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2517 getValue(GuardCheckFn), std::move(Args)); 2518 2519 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2520 DAG.setRoot(Result.second); 2521 return; 2522 } 2523 2524 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2525 // Otherwise, emit a volatile load to retrieve the stack guard value. 2526 SDValue Chain = DAG.getEntryNode(); 2527 if (TLI.useLoadStackGuardNode()) { 2528 Guard = getLoadStackGuard(DAG, dl, Chain); 2529 } else { 2530 const Value *IRGuard = TLI.getSDagStackGuard(M); 2531 SDValue GuardPtr = getValue(IRGuard); 2532 2533 Guard = 2534 DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0), 2535 Align, MachineMemOperand::MOVolatile); 2536 } 2537 2538 // Perform the comparison via a subtract/getsetcc. 2539 EVT VT = Guard.getValueType(); 2540 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal); 2541 2542 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2543 *DAG.getContext(), 2544 Sub.getValueType()), 2545 Sub, DAG.getConstant(0, dl, VT), ISD::SETNE); 2546 2547 // If the sub is not 0, then we know the guard/stackslot do not equal, so 2548 // branch to failure MBB. 2549 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2550 MVT::Other, GuardVal.getOperand(0), 2551 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2552 // Otherwise branch to success MBB. 2553 SDValue Br = DAG.getNode(ISD::BR, dl, 2554 MVT::Other, BrCond, 2555 DAG.getBasicBlock(SPD.getSuccessMBB())); 2556 2557 DAG.setRoot(Br); 2558 } 2559 2560 /// Codegen the failure basic block for a stack protector check. 2561 /// 2562 /// A failure stack protector machine basic block consists simply of a call to 2563 /// __stack_chk_fail(). 2564 /// 2565 /// For a high level explanation of how this fits into the stack protector 2566 /// generation see the comment on the declaration of class 2567 /// StackProtectorDescriptor. 2568 void 2569 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2570 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2571 SDValue Chain = 2572 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2573 None, false, getCurSDLoc(), false, false).second; 2574 // On PS4, the "return address" must still be within the calling function, 2575 // even if it's at the very end, so emit an explicit TRAP here. 2576 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2577 if (TM.getTargetTriple().isPS4CPU()) 2578 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2579 2580 DAG.setRoot(Chain); 2581 } 2582 2583 /// visitBitTestHeader - This function emits necessary code to produce value 2584 /// suitable for "bit tests" 2585 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2586 MachineBasicBlock *SwitchBB) { 2587 SDLoc dl = getCurSDLoc(); 2588 2589 // Subtract the minimum value 2590 SDValue SwitchOp = getValue(B.SValue); 2591 EVT VT = SwitchOp.getValueType(); 2592 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2593 DAG.getConstant(B.First, dl, VT)); 2594 2595 // Check range 2596 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2597 SDValue RangeCmp = DAG.getSetCC( 2598 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2599 Sub.getValueType()), 2600 Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT); 2601 2602 // Determine the type of the test operands. 2603 bool UsePtrType = false; 2604 if (!TLI.isTypeLegal(VT)) 2605 UsePtrType = true; 2606 else { 2607 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2608 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2609 // Switch table case range are encoded into series of masks. 2610 // Just use pointer type, it's guaranteed to fit. 2611 UsePtrType = true; 2612 break; 2613 } 2614 } 2615 if (UsePtrType) { 2616 VT = TLI.getPointerTy(DAG.getDataLayout()); 2617 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2618 } 2619 2620 B.RegVT = VT.getSimpleVT(); 2621 B.Reg = FuncInfo.CreateReg(B.RegVT); 2622 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2623 2624 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2625 2626 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2627 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2628 SwitchBB->normalizeSuccProbs(); 2629 2630 SDValue BrRange = DAG.getNode(ISD::BRCOND, dl, 2631 MVT::Other, CopyTo, RangeCmp, 2632 DAG.getBasicBlock(B.Default)); 2633 2634 // Avoid emitting unnecessary branches to the next block. 2635 if (MBB != NextBlock(SwitchBB)) 2636 BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange, 2637 DAG.getBasicBlock(MBB)); 2638 2639 DAG.setRoot(BrRange); 2640 } 2641 2642 /// visitBitTestCase - this function produces one "bit test" 2643 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2644 MachineBasicBlock* NextMBB, 2645 BranchProbability BranchProbToNext, 2646 unsigned Reg, 2647 BitTestCase &B, 2648 MachineBasicBlock *SwitchBB) { 2649 SDLoc dl = getCurSDLoc(); 2650 MVT VT = BB.RegVT; 2651 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2652 SDValue Cmp; 2653 unsigned PopCount = countPopulation(B.Mask); 2654 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2655 if (PopCount == 1) { 2656 // Testing for a single bit; just compare the shift count with what it 2657 // would need to be to shift a 1 bit in that position. 2658 Cmp = DAG.getSetCC( 2659 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2660 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2661 ISD::SETEQ); 2662 } else if (PopCount == BB.Range) { 2663 // There is only one zero bit in the range, test for it directly. 2664 Cmp = DAG.getSetCC( 2665 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2666 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2667 ISD::SETNE); 2668 } else { 2669 // Make desired shift 2670 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2671 DAG.getConstant(1, dl, VT), ShiftOp); 2672 2673 // Emit bit tests and jumps 2674 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2675 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2676 Cmp = DAG.getSetCC( 2677 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2678 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2679 } 2680 2681 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2682 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2683 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2684 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2685 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2686 // one as they are relative probabilities (and thus work more like weights), 2687 // and hence we need to normalize them to let the sum of them become one. 2688 SwitchBB->normalizeSuccProbs(); 2689 2690 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2691 MVT::Other, getControlRoot(), 2692 Cmp, DAG.getBasicBlock(B.TargetBB)); 2693 2694 // Avoid emitting unnecessary branches to the next block. 2695 if (NextMBB != NextBlock(SwitchBB)) 2696 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2697 DAG.getBasicBlock(NextMBB)); 2698 2699 DAG.setRoot(BrAnd); 2700 } 2701 2702 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2703 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2704 2705 // Retrieve successors. Look through artificial IR level blocks like 2706 // catchswitch for successors. 2707 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2708 const BasicBlock *EHPadBB = I.getSuccessor(1); 2709 2710 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2711 // have to do anything here to lower funclet bundles. 2712 assert(!I.hasOperandBundlesOtherThan( 2713 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2714 "Cannot lower invokes with arbitrary operand bundles yet!"); 2715 2716 const Value *Callee(I.getCalledValue()); 2717 const Function *Fn = dyn_cast<Function>(Callee); 2718 if (isa<InlineAsm>(Callee)) 2719 visitInlineAsm(&I); 2720 else if (Fn && Fn->isIntrinsic()) { 2721 switch (Fn->getIntrinsicID()) { 2722 default: 2723 llvm_unreachable("Cannot invoke this intrinsic"); 2724 case Intrinsic::donothing: 2725 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2726 break; 2727 case Intrinsic::experimental_patchpoint_void: 2728 case Intrinsic::experimental_patchpoint_i64: 2729 visitPatchpoint(&I, EHPadBB); 2730 break; 2731 case Intrinsic::experimental_gc_statepoint: 2732 LowerStatepoint(ImmutableStatepoint(&I), EHPadBB); 2733 break; 2734 case Intrinsic::wasm_rethrow_in_catch: { 2735 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2736 // special because it can be invoked, so we manually lower it to a DAG 2737 // node here. 2738 SmallVector<SDValue, 8> Ops; 2739 Ops.push_back(getRoot()); // inchain 2740 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2741 Ops.push_back( 2742 DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(), 2743 TLI.getPointerTy(DAG.getDataLayout()))); 2744 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2745 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2746 break; 2747 } 2748 } 2749 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2750 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2751 // Eventually we will support lowering the @llvm.experimental.deoptimize 2752 // intrinsic, and right now there are no plans to support other intrinsics 2753 // with deopt state. 2754 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2755 } else { 2756 LowerCallTo(&I, getValue(Callee), false, EHPadBB); 2757 } 2758 2759 // If the value of the invoke is used outside of its defining block, make it 2760 // available as a virtual register. 2761 // We already took care of the exported value for the statepoint instruction 2762 // during call to the LowerStatepoint. 2763 if (!isStatepoint(I)) { 2764 CopyToExportRegsIfNeeded(&I); 2765 } 2766 2767 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2768 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2769 BranchProbability EHPadBBProb = 2770 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2771 : BranchProbability::getZero(); 2772 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2773 2774 // Update successor info. 2775 addSuccessorWithProb(InvokeMBB, Return); 2776 for (auto &UnwindDest : UnwindDests) { 2777 UnwindDest.first->setIsEHPad(); 2778 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2779 } 2780 InvokeMBB->normalizeSuccProbs(); 2781 2782 // Drop into normal successor. 2783 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 2784 DAG.getBasicBlock(Return))); 2785 } 2786 2787 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 2788 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 2789 2790 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2791 // have to do anything here to lower funclet bundles. 2792 assert(!I.hasOperandBundlesOtherThan( 2793 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2794 "Cannot lower callbrs with arbitrary operand bundles yet!"); 2795 2796 assert(isa<InlineAsm>(I.getCalledValue()) && 2797 "Only know how to handle inlineasm callbr"); 2798 visitInlineAsm(&I); 2799 2800 // Retrieve successors. 2801 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 2802 2803 // Update successor info. 2804 addSuccessorWithProb(CallBrMBB, Return); 2805 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 2806 MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)]; 2807 addSuccessorWithProb(CallBrMBB, Target); 2808 } 2809 CallBrMBB->normalizeSuccProbs(); 2810 2811 // Drop into default successor. 2812 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2813 MVT::Other, getControlRoot(), 2814 DAG.getBasicBlock(Return))); 2815 } 2816 2817 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2818 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2819 } 2820 2821 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2822 assert(FuncInfo.MBB->isEHPad() && 2823 "Call to landingpad not in landing pad!"); 2824 2825 // If there aren't registers to copy the values into (e.g., during SjLj 2826 // exceptions), then don't bother to create these DAG nodes. 2827 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2828 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2829 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2830 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2831 return; 2832 2833 // If landingpad's return type is token type, we don't create DAG nodes 2834 // for its exception pointer and selector value. The extraction of exception 2835 // pointer or selector value from token type landingpads is not currently 2836 // supported. 2837 if (LP.getType()->isTokenTy()) 2838 return; 2839 2840 SmallVector<EVT, 2> ValueVTs; 2841 SDLoc dl = getCurSDLoc(); 2842 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2843 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2844 2845 // Get the two live-in registers as SDValues. The physregs have already been 2846 // copied into virtual registers. 2847 SDValue Ops[2]; 2848 if (FuncInfo.ExceptionPointerVirtReg) { 2849 Ops[0] = DAG.getZExtOrTrunc( 2850 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2851 FuncInfo.ExceptionPointerVirtReg, 2852 TLI.getPointerTy(DAG.getDataLayout())), 2853 dl, ValueVTs[0]); 2854 } else { 2855 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2856 } 2857 Ops[1] = DAG.getZExtOrTrunc( 2858 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2859 FuncInfo.ExceptionSelectorVirtReg, 2860 TLI.getPointerTy(DAG.getDataLayout())), 2861 dl, ValueVTs[1]); 2862 2863 // Merge into one. 2864 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 2865 DAG.getVTList(ValueVTs), Ops); 2866 setValue(&LP, Res); 2867 } 2868 2869 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) { 2870 #ifndef NDEBUG 2871 for (const CaseCluster &CC : Clusters) 2872 assert(CC.Low == CC.High && "Input clusters must be single-case"); 2873 #endif 2874 2875 llvm::sort(Clusters, [](const CaseCluster &a, const CaseCluster &b) { 2876 return a.Low->getValue().slt(b.Low->getValue()); 2877 }); 2878 2879 // Merge adjacent clusters with the same destination. 2880 const unsigned N = Clusters.size(); 2881 unsigned DstIndex = 0; 2882 for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) { 2883 CaseCluster &CC = Clusters[SrcIndex]; 2884 const ConstantInt *CaseVal = CC.Low; 2885 MachineBasicBlock *Succ = CC.MBB; 2886 2887 if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ && 2888 (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) { 2889 // If this case has the same successor and is a neighbour, merge it into 2890 // the previous cluster. 2891 Clusters[DstIndex - 1].High = CaseVal; 2892 Clusters[DstIndex - 1].Prob += CC.Prob; 2893 } else { 2894 std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex], 2895 sizeof(Clusters[SrcIndex])); 2896 } 2897 } 2898 Clusters.resize(DstIndex); 2899 } 2900 2901 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2902 MachineBasicBlock *Last) { 2903 // Update JTCases. 2904 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) 2905 if (JTCases[i].first.HeaderBB == First) 2906 JTCases[i].first.HeaderBB = Last; 2907 2908 // Update BitTestCases. 2909 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) 2910 if (BitTestCases[i].Parent == First) 2911 BitTestCases[i].Parent = Last; 2912 } 2913 2914 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2915 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2916 2917 // Update machine-CFG edges with unique successors. 2918 SmallSet<BasicBlock*, 32> Done; 2919 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 2920 BasicBlock *BB = I.getSuccessor(i); 2921 bool Inserted = Done.insert(BB).second; 2922 if (!Inserted) 2923 continue; 2924 2925 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 2926 addSuccessorWithProb(IndirectBrMBB, Succ); 2927 } 2928 IndirectBrMBB->normalizeSuccProbs(); 2929 2930 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 2931 MVT::Other, getControlRoot(), 2932 getValue(I.getAddress()))); 2933 } 2934 2935 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 2936 if (!DAG.getTarget().Options.TrapUnreachable) 2937 return; 2938 2939 // We may be able to ignore unreachable behind a noreturn call. 2940 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 2941 const BasicBlock &BB = *I.getParent(); 2942 if (&I != &BB.front()) { 2943 BasicBlock::const_iterator PredI = 2944 std::prev(BasicBlock::const_iterator(&I)); 2945 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 2946 if (Call->doesNotReturn()) 2947 return; 2948 } 2949 } 2950 } 2951 2952 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 2953 } 2954 2955 void SelectionDAGBuilder::visitFSub(const User &I) { 2956 // -0.0 - X --> fneg 2957 Type *Ty = I.getType(); 2958 if (isa<Constant>(I.getOperand(0)) && 2959 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) { 2960 SDValue Op2 = getValue(I.getOperand(1)); 2961 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(), 2962 Op2.getValueType(), Op2)); 2963 return; 2964 } 2965 2966 visitBinary(I, ISD::FSUB); 2967 } 2968 2969 /// Checks if the given instruction performs a vector reduction, in which case 2970 /// we have the freedom to alter the elements in the result as long as the 2971 /// reduction of them stays unchanged. 2972 static bool isVectorReductionOp(const User *I) { 2973 const Instruction *Inst = dyn_cast<Instruction>(I); 2974 if (!Inst || !Inst->getType()->isVectorTy()) 2975 return false; 2976 2977 auto OpCode = Inst->getOpcode(); 2978 switch (OpCode) { 2979 case Instruction::Add: 2980 case Instruction::Mul: 2981 case Instruction::And: 2982 case Instruction::Or: 2983 case Instruction::Xor: 2984 break; 2985 case Instruction::FAdd: 2986 case Instruction::FMul: 2987 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 2988 if (FPOp->getFastMathFlags().isFast()) 2989 break; 2990 LLVM_FALLTHROUGH; 2991 default: 2992 return false; 2993 } 2994 2995 unsigned ElemNum = Inst->getType()->getVectorNumElements(); 2996 // Ensure the reduction size is a power of 2. 2997 if (!isPowerOf2_32(ElemNum)) 2998 return false; 2999 3000 unsigned ElemNumToReduce = ElemNum; 3001 3002 // Do DFS search on the def-use chain from the given instruction. We only 3003 // allow four kinds of operations during the search until we reach the 3004 // instruction that extracts the first element from the vector: 3005 // 3006 // 1. The reduction operation of the same opcode as the given instruction. 3007 // 3008 // 2. PHI node. 3009 // 3010 // 3. ShuffleVector instruction together with a reduction operation that 3011 // does a partial reduction. 3012 // 3013 // 4. ExtractElement that extracts the first element from the vector, and we 3014 // stop searching the def-use chain here. 3015 // 3016 // 3 & 4 above perform a reduction on all elements of the vector. We push defs 3017 // from 1-3 to the stack to continue the DFS. The given instruction is not 3018 // a reduction operation if we meet any other instructions other than those 3019 // listed above. 3020 3021 SmallVector<const User *, 16> UsersToVisit{Inst}; 3022 SmallPtrSet<const User *, 16> Visited; 3023 bool ReduxExtracted = false; 3024 3025 while (!UsersToVisit.empty()) { 3026 auto User = UsersToVisit.back(); 3027 UsersToVisit.pop_back(); 3028 if (!Visited.insert(User).second) 3029 continue; 3030 3031 for (const auto &U : User->users()) { 3032 auto Inst = dyn_cast<Instruction>(U); 3033 if (!Inst) 3034 return false; 3035 3036 if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) { 3037 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 3038 if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast()) 3039 return false; 3040 UsersToVisit.push_back(U); 3041 } else if (const ShuffleVectorInst *ShufInst = 3042 dyn_cast<ShuffleVectorInst>(U)) { 3043 // Detect the following pattern: A ShuffleVector instruction together 3044 // with a reduction that do partial reduction on the first and second 3045 // ElemNumToReduce / 2 elements, and store the result in 3046 // ElemNumToReduce / 2 elements in another vector. 3047 3048 unsigned ResultElements = ShufInst->getType()->getVectorNumElements(); 3049 if (ResultElements < ElemNum) 3050 return false; 3051 3052 if (ElemNumToReduce == 1) 3053 return false; 3054 if (!isa<UndefValue>(U->getOperand(1))) 3055 return false; 3056 for (unsigned i = 0; i < ElemNumToReduce / 2; ++i) 3057 if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2)) 3058 return false; 3059 for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i) 3060 if (ShufInst->getMaskValue(i) != -1) 3061 return false; 3062 3063 // There is only one user of this ShuffleVector instruction, which 3064 // must be a reduction operation. 3065 if (!U->hasOneUse()) 3066 return false; 3067 3068 auto U2 = dyn_cast<Instruction>(*U->user_begin()); 3069 if (!U2 || U2->getOpcode() != OpCode) 3070 return false; 3071 3072 // Check operands of the reduction operation. 3073 if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) || 3074 (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) { 3075 UsersToVisit.push_back(U2); 3076 ElemNumToReduce /= 2; 3077 } else 3078 return false; 3079 } else if (isa<ExtractElementInst>(U)) { 3080 // At this moment we should have reduced all elements in the vector. 3081 if (ElemNumToReduce != 1) 3082 return false; 3083 3084 const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1)); 3085 if (!Val || !Val->isZero()) 3086 return false; 3087 3088 ReduxExtracted = true; 3089 } else 3090 return false; 3091 } 3092 } 3093 return ReduxExtracted; 3094 } 3095 3096 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3097 SDNodeFlags Flags; 3098 3099 SDValue Op = getValue(I.getOperand(0)); 3100 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3101 Op, Flags); 3102 setValue(&I, UnNodeValue); 3103 } 3104 3105 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3106 SDNodeFlags Flags; 3107 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3108 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3109 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3110 } 3111 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) { 3112 Flags.setExact(ExactOp->isExact()); 3113 } 3114 if (isVectorReductionOp(&I)) { 3115 Flags.setVectorReduction(true); 3116 LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n"); 3117 } 3118 3119 SDValue Op1 = getValue(I.getOperand(0)); 3120 SDValue Op2 = getValue(I.getOperand(1)); 3121 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3122 Op1, Op2, Flags); 3123 setValue(&I, BinNodeValue); 3124 } 3125 3126 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3127 SDValue Op1 = getValue(I.getOperand(0)); 3128 SDValue Op2 = getValue(I.getOperand(1)); 3129 3130 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3131 Op1.getValueType(), DAG.getDataLayout()); 3132 3133 // Coerce the shift amount to the right type if we can. 3134 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3135 unsigned ShiftSize = ShiftTy.getSizeInBits(); 3136 unsigned Op2Size = Op2.getValueSizeInBits(); 3137 SDLoc DL = getCurSDLoc(); 3138 3139 // If the operand is smaller than the shift count type, promote it. 3140 if (ShiftSize > Op2Size) 3141 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 3142 3143 // If the operand is larger than the shift count type but the shift 3144 // count type has enough bits to represent any shift value, truncate 3145 // it now. This is a common case and it exposes the truncate to 3146 // optimization early. 3147 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 3148 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 3149 // Otherwise we'll need to temporarily settle for some other convenient 3150 // type. Type legalization will make adjustments once the shiftee is split. 3151 else 3152 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 3153 } 3154 3155 bool nuw = false; 3156 bool nsw = false; 3157 bool exact = false; 3158 3159 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3160 3161 if (const OverflowingBinaryOperator *OFBinOp = 3162 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3163 nuw = OFBinOp->hasNoUnsignedWrap(); 3164 nsw = OFBinOp->hasNoSignedWrap(); 3165 } 3166 if (const PossiblyExactOperator *ExactOp = 3167 dyn_cast<const PossiblyExactOperator>(&I)) 3168 exact = ExactOp->isExact(); 3169 } 3170 SDNodeFlags Flags; 3171 Flags.setExact(exact); 3172 Flags.setNoSignedWrap(nsw); 3173 Flags.setNoUnsignedWrap(nuw); 3174 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3175 Flags); 3176 setValue(&I, Res); 3177 } 3178 3179 void SelectionDAGBuilder::visitSDiv(const User &I) { 3180 SDValue Op1 = getValue(I.getOperand(0)); 3181 SDValue Op2 = getValue(I.getOperand(1)); 3182 3183 SDNodeFlags Flags; 3184 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3185 cast<PossiblyExactOperator>(&I)->isExact()); 3186 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3187 Op2, Flags)); 3188 } 3189 3190 void SelectionDAGBuilder::visitICmp(const User &I) { 3191 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3192 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3193 predicate = IC->getPredicate(); 3194 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3195 predicate = ICmpInst::Predicate(IC->getPredicate()); 3196 SDValue Op1 = getValue(I.getOperand(0)); 3197 SDValue Op2 = getValue(I.getOperand(1)); 3198 ISD::CondCode Opcode = getICmpCondCode(predicate); 3199 3200 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3201 I.getType()); 3202 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3203 } 3204 3205 void SelectionDAGBuilder::visitFCmp(const User &I) { 3206 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3207 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3208 predicate = FC->getPredicate(); 3209 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3210 predicate = FCmpInst::Predicate(FC->getPredicate()); 3211 SDValue Op1 = getValue(I.getOperand(0)); 3212 SDValue Op2 = getValue(I.getOperand(1)); 3213 3214 ISD::CondCode Condition = getFCmpCondCode(predicate); 3215 auto *FPMO = dyn_cast<FPMathOperator>(&I); 3216 if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath) 3217 Condition = getFCmpCodeWithoutNaN(Condition); 3218 3219 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3220 I.getType()); 3221 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3222 } 3223 3224 // Check if the condition of the select has one use or two users that are both 3225 // selects with the same condition. 3226 static bool hasOnlySelectUsers(const Value *Cond) { 3227 return llvm::all_of(Cond->users(), [](const Value *V) { 3228 return isa<SelectInst>(V); 3229 }); 3230 } 3231 3232 void SelectionDAGBuilder::visitSelect(const User &I) { 3233 SmallVector<EVT, 4> ValueVTs; 3234 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3235 ValueVTs); 3236 unsigned NumValues = ValueVTs.size(); 3237 if (NumValues == 0) return; 3238 3239 SmallVector<SDValue, 4> Values(NumValues); 3240 SDValue Cond = getValue(I.getOperand(0)); 3241 SDValue LHSVal = getValue(I.getOperand(1)); 3242 SDValue RHSVal = getValue(I.getOperand(2)); 3243 auto BaseOps = {Cond}; 3244 ISD::NodeType OpCode = Cond.getValueType().isVector() ? 3245 ISD::VSELECT : ISD::SELECT; 3246 3247 bool IsUnaryAbs = false; 3248 3249 // Min/max matching is only viable if all output VTs are the same. 3250 if (is_splat(ValueVTs)) { 3251 EVT VT = ValueVTs[0]; 3252 LLVMContext &Ctx = *DAG.getContext(); 3253 auto &TLI = DAG.getTargetLoweringInfo(); 3254 3255 // We care about the legality of the operation after it has been type 3256 // legalized. 3257 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal && 3258 VT != TLI.getTypeToTransformTo(Ctx, VT)) 3259 VT = TLI.getTypeToTransformTo(Ctx, VT); 3260 3261 // If the vselect is legal, assume we want to leave this as a vector setcc + 3262 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3263 // min/max is legal on the scalar type. 3264 bool UseScalarMinMax = VT.isVector() && 3265 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3266 3267 Value *LHS, *RHS; 3268 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3269 ISD::NodeType Opc = ISD::DELETED_NODE; 3270 switch (SPR.Flavor) { 3271 case SPF_UMAX: Opc = ISD::UMAX; break; 3272 case SPF_UMIN: Opc = ISD::UMIN; break; 3273 case SPF_SMAX: Opc = ISD::SMAX; break; 3274 case SPF_SMIN: Opc = ISD::SMIN; break; 3275 case SPF_FMINNUM: 3276 switch (SPR.NaNBehavior) { 3277 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3278 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3279 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3280 case SPNB_RETURNS_ANY: { 3281 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3282 Opc = ISD::FMINNUM; 3283 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3284 Opc = ISD::FMINIMUM; 3285 else if (UseScalarMinMax) 3286 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3287 ISD::FMINNUM : ISD::FMINIMUM; 3288 break; 3289 } 3290 } 3291 break; 3292 case SPF_FMAXNUM: 3293 switch (SPR.NaNBehavior) { 3294 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3295 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3296 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3297 case SPNB_RETURNS_ANY: 3298 3299 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3300 Opc = ISD::FMAXNUM; 3301 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3302 Opc = ISD::FMAXIMUM; 3303 else if (UseScalarMinMax) 3304 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3305 ISD::FMAXNUM : ISD::FMAXIMUM; 3306 break; 3307 } 3308 break; 3309 case SPF_ABS: 3310 IsUnaryAbs = true; 3311 Opc = ISD::ABS; 3312 break; 3313 case SPF_NABS: 3314 // TODO: we need to produce sub(0, abs(X)). 3315 default: break; 3316 } 3317 3318 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3319 (TLI.isOperationLegalOrCustom(Opc, VT) || 3320 (UseScalarMinMax && 3321 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3322 // If the underlying comparison instruction is used by any other 3323 // instruction, the consumed instructions won't be destroyed, so it is 3324 // not profitable to convert to a min/max. 3325 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3326 OpCode = Opc; 3327 LHSVal = getValue(LHS); 3328 RHSVal = getValue(RHS); 3329 BaseOps = {}; 3330 } 3331 3332 if (IsUnaryAbs) { 3333 OpCode = Opc; 3334 LHSVal = getValue(LHS); 3335 BaseOps = {}; 3336 } 3337 } 3338 3339 if (IsUnaryAbs) { 3340 for (unsigned i = 0; i != NumValues; ++i) { 3341 Values[i] = 3342 DAG.getNode(OpCode, getCurSDLoc(), 3343 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), 3344 SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3345 } 3346 } else { 3347 for (unsigned i = 0; i != NumValues; ++i) { 3348 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3349 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3350 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3351 Values[i] = DAG.getNode( 3352 OpCode, getCurSDLoc(), 3353 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops); 3354 } 3355 } 3356 3357 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3358 DAG.getVTList(ValueVTs), Values)); 3359 } 3360 3361 void SelectionDAGBuilder::visitTrunc(const User &I) { 3362 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3363 SDValue N = getValue(I.getOperand(0)); 3364 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3365 I.getType()); 3366 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3367 } 3368 3369 void SelectionDAGBuilder::visitZExt(const User &I) { 3370 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3371 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3372 SDValue N = getValue(I.getOperand(0)); 3373 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3374 I.getType()); 3375 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3376 } 3377 3378 void SelectionDAGBuilder::visitSExt(const User &I) { 3379 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3380 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3381 SDValue N = getValue(I.getOperand(0)); 3382 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3383 I.getType()); 3384 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3385 } 3386 3387 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3388 // FPTrunc is never a no-op cast, no need to check 3389 SDValue N = getValue(I.getOperand(0)); 3390 SDLoc dl = getCurSDLoc(); 3391 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3392 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3393 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3394 DAG.getTargetConstant( 3395 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3396 } 3397 3398 void SelectionDAGBuilder::visitFPExt(const User &I) { 3399 // FPExt is never a no-op cast, no need to check 3400 SDValue N = getValue(I.getOperand(0)); 3401 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3402 I.getType()); 3403 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3404 } 3405 3406 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3407 // FPToUI is never a no-op cast, no need to check 3408 SDValue N = getValue(I.getOperand(0)); 3409 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3410 I.getType()); 3411 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3412 } 3413 3414 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3415 // FPToSI is never a no-op cast, no need to check 3416 SDValue N = getValue(I.getOperand(0)); 3417 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3418 I.getType()); 3419 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3420 } 3421 3422 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3423 // UIToFP is never a no-op cast, no need to check 3424 SDValue N = getValue(I.getOperand(0)); 3425 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3426 I.getType()); 3427 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3428 } 3429 3430 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3431 // SIToFP is never a no-op cast, no need to check 3432 SDValue N = getValue(I.getOperand(0)); 3433 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3434 I.getType()); 3435 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3436 } 3437 3438 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3439 // What to do depends on the size of the integer and the size of the pointer. 3440 // We can either truncate, zero extend, or no-op, accordingly. 3441 SDValue N = getValue(I.getOperand(0)); 3442 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3443 I.getType()); 3444 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT)); 3445 } 3446 3447 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3448 // What to do depends on the size of the integer and the size of the pointer. 3449 // We can either truncate, zero extend, or no-op, accordingly. 3450 SDValue N = getValue(I.getOperand(0)); 3451 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3452 I.getType()); 3453 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT)); 3454 } 3455 3456 void SelectionDAGBuilder::visitBitCast(const User &I) { 3457 SDValue N = getValue(I.getOperand(0)); 3458 SDLoc dl = getCurSDLoc(); 3459 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3460 I.getType()); 3461 3462 // BitCast assures us that source and destination are the same size so this is 3463 // either a BITCAST or a no-op. 3464 if (DestVT != N.getValueType()) 3465 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3466 DestVT, N)); // convert types. 3467 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3468 // might fold any kind of constant expression to an integer constant and that 3469 // is not what we are looking for. Only recognize a bitcast of a genuine 3470 // constant integer as an opaque constant. 3471 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3472 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3473 /*isOpaque*/true)); 3474 else 3475 setValue(&I, N); // noop cast. 3476 } 3477 3478 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3479 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3480 const Value *SV = I.getOperand(0); 3481 SDValue N = getValue(SV); 3482 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3483 3484 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3485 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3486 3487 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) 3488 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3489 3490 setValue(&I, N); 3491 } 3492 3493 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3494 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3495 SDValue InVec = getValue(I.getOperand(0)); 3496 SDValue InVal = getValue(I.getOperand(1)); 3497 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3498 TLI.getVectorIdxTy(DAG.getDataLayout())); 3499 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3500 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3501 InVec, InVal, InIdx)); 3502 } 3503 3504 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3505 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3506 SDValue InVec = getValue(I.getOperand(0)); 3507 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3508 TLI.getVectorIdxTy(DAG.getDataLayout())); 3509 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3510 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3511 InVec, InIdx)); 3512 } 3513 3514 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3515 SDValue Src1 = getValue(I.getOperand(0)); 3516 SDValue Src2 = getValue(I.getOperand(1)); 3517 SDLoc DL = getCurSDLoc(); 3518 3519 SmallVector<int, 8> Mask; 3520 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask); 3521 unsigned MaskNumElts = Mask.size(); 3522 3523 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3524 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3525 EVT SrcVT = Src1.getValueType(); 3526 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3527 3528 if (SrcNumElts == MaskNumElts) { 3529 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3530 return; 3531 } 3532 3533 // Normalize the shuffle vector since mask and vector length don't match. 3534 if (SrcNumElts < MaskNumElts) { 3535 // Mask is longer than the source vectors. We can use concatenate vector to 3536 // make the mask and vectors lengths match. 3537 3538 if (MaskNumElts % SrcNumElts == 0) { 3539 // Mask length is a multiple of the source vector length. 3540 // Check if the shuffle is some kind of concatenation of the input 3541 // vectors. 3542 unsigned NumConcat = MaskNumElts / SrcNumElts; 3543 bool IsConcat = true; 3544 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3545 for (unsigned i = 0; i != MaskNumElts; ++i) { 3546 int Idx = Mask[i]; 3547 if (Idx < 0) 3548 continue; 3549 // Ensure the indices in each SrcVT sized piece are sequential and that 3550 // the same source is used for the whole piece. 3551 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3552 (ConcatSrcs[i / SrcNumElts] >= 0 && 3553 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3554 IsConcat = false; 3555 break; 3556 } 3557 // Remember which source this index came from. 3558 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3559 } 3560 3561 // The shuffle is concatenating multiple vectors together. Just emit 3562 // a CONCAT_VECTORS operation. 3563 if (IsConcat) { 3564 SmallVector<SDValue, 8> ConcatOps; 3565 for (auto Src : ConcatSrcs) { 3566 if (Src < 0) 3567 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3568 else if (Src == 0) 3569 ConcatOps.push_back(Src1); 3570 else 3571 ConcatOps.push_back(Src2); 3572 } 3573 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3574 return; 3575 } 3576 } 3577 3578 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3579 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3580 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3581 PaddedMaskNumElts); 3582 3583 // Pad both vectors with undefs to make them the same length as the mask. 3584 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3585 3586 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3587 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3588 MOps1[0] = Src1; 3589 MOps2[0] = Src2; 3590 3591 Src1 = Src1.isUndef() 3592 ? DAG.getUNDEF(PaddedVT) 3593 : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3594 Src2 = Src2.isUndef() 3595 ? DAG.getUNDEF(PaddedVT) 3596 : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3597 3598 // Readjust mask for new input vector length. 3599 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3600 for (unsigned i = 0; i != MaskNumElts; ++i) { 3601 int Idx = Mask[i]; 3602 if (Idx >= (int)SrcNumElts) 3603 Idx -= SrcNumElts - PaddedMaskNumElts; 3604 MappedOps[i] = Idx; 3605 } 3606 3607 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3608 3609 // If the concatenated vector was padded, extract a subvector with the 3610 // correct number of elements. 3611 if (MaskNumElts != PaddedMaskNumElts) 3612 Result = DAG.getNode( 3613 ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3614 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 3615 3616 setValue(&I, Result); 3617 return; 3618 } 3619 3620 if (SrcNumElts > MaskNumElts) { 3621 // Analyze the access pattern of the vector to see if we can extract 3622 // two subvectors and do the shuffle. 3623 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3624 bool CanExtract = true; 3625 for (int Idx : Mask) { 3626 unsigned Input = 0; 3627 if (Idx < 0) 3628 continue; 3629 3630 if (Idx >= (int)SrcNumElts) { 3631 Input = 1; 3632 Idx -= SrcNumElts; 3633 } 3634 3635 // If all the indices come from the same MaskNumElts sized portion of 3636 // the sources we can use extract. Also make sure the extract wouldn't 3637 // extract past the end of the source. 3638 int NewStartIdx = alignDown(Idx, MaskNumElts); 3639 if (NewStartIdx + MaskNumElts > SrcNumElts || 3640 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3641 CanExtract = false; 3642 // Make sure we always update StartIdx as we use it to track if all 3643 // elements are undef. 3644 StartIdx[Input] = NewStartIdx; 3645 } 3646 3647 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3648 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3649 return; 3650 } 3651 if (CanExtract) { 3652 // Extract appropriate subvector and generate a vector shuffle 3653 for (unsigned Input = 0; Input < 2; ++Input) { 3654 SDValue &Src = Input == 0 ? Src1 : Src2; 3655 if (StartIdx[Input] < 0) 3656 Src = DAG.getUNDEF(VT); 3657 else { 3658 Src = DAG.getNode( 3659 ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3660 DAG.getConstant(StartIdx[Input], DL, 3661 TLI.getVectorIdxTy(DAG.getDataLayout()))); 3662 } 3663 } 3664 3665 // Calculate new mask. 3666 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3667 for (int &Idx : MappedOps) { 3668 if (Idx >= (int)SrcNumElts) 3669 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3670 else if (Idx >= 0) 3671 Idx -= StartIdx[0]; 3672 } 3673 3674 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3675 return; 3676 } 3677 } 3678 3679 // We can't use either concat vectors or extract subvectors so fall back to 3680 // replacing the shuffle with extract and build vector. 3681 // to insert and build vector. 3682 EVT EltVT = VT.getVectorElementType(); 3683 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 3684 SmallVector<SDValue,8> Ops; 3685 for (int Idx : Mask) { 3686 SDValue Res; 3687 3688 if (Idx < 0) { 3689 Res = DAG.getUNDEF(EltVT); 3690 } else { 3691 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3692 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3693 3694 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 3695 EltVT, Src, DAG.getConstant(Idx, DL, IdxVT)); 3696 } 3697 3698 Ops.push_back(Res); 3699 } 3700 3701 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3702 } 3703 3704 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3705 ArrayRef<unsigned> Indices; 3706 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3707 Indices = IV->getIndices(); 3708 else 3709 Indices = cast<ConstantExpr>(&I)->getIndices(); 3710 3711 const Value *Op0 = I.getOperand(0); 3712 const Value *Op1 = I.getOperand(1); 3713 Type *AggTy = I.getType(); 3714 Type *ValTy = Op1->getType(); 3715 bool IntoUndef = isa<UndefValue>(Op0); 3716 bool FromUndef = isa<UndefValue>(Op1); 3717 3718 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3719 3720 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3721 SmallVector<EVT, 4> AggValueVTs; 3722 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3723 SmallVector<EVT, 4> ValValueVTs; 3724 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3725 3726 unsigned NumAggValues = AggValueVTs.size(); 3727 unsigned NumValValues = ValValueVTs.size(); 3728 SmallVector<SDValue, 4> Values(NumAggValues); 3729 3730 // Ignore an insertvalue that produces an empty object 3731 if (!NumAggValues) { 3732 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3733 return; 3734 } 3735 3736 SDValue Agg = getValue(Op0); 3737 unsigned i = 0; 3738 // Copy the beginning value(s) from the original aggregate. 3739 for (; i != LinearIndex; ++i) 3740 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3741 SDValue(Agg.getNode(), Agg.getResNo() + i); 3742 // Copy values from the inserted value(s). 3743 if (NumValValues) { 3744 SDValue Val = getValue(Op1); 3745 for (; i != LinearIndex + NumValValues; ++i) 3746 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3747 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3748 } 3749 // Copy remaining value(s) from the original aggregate. 3750 for (; i != NumAggValues; ++i) 3751 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3752 SDValue(Agg.getNode(), Agg.getResNo() + i); 3753 3754 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3755 DAG.getVTList(AggValueVTs), Values)); 3756 } 3757 3758 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3759 ArrayRef<unsigned> Indices; 3760 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3761 Indices = EV->getIndices(); 3762 else 3763 Indices = cast<ConstantExpr>(&I)->getIndices(); 3764 3765 const Value *Op0 = I.getOperand(0); 3766 Type *AggTy = Op0->getType(); 3767 Type *ValTy = I.getType(); 3768 bool OutOfUndef = isa<UndefValue>(Op0); 3769 3770 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3771 3772 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3773 SmallVector<EVT, 4> ValValueVTs; 3774 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3775 3776 unsigned NumValValues = ValValueVTs.size(); 3777 3778 // Ignore a extractvalue that produces an empty object 3779 if (!NumValValues) { 3780 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3781 return; 3782 } 3783 3784 SmallVector<SDValue, 4> Values(NumValValues); 3785 3786 SDValue Agg = getValue(Op0); 3787 // Copy out the selected value(s). 3788 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3789 Values[i - LinearIndex] = 3790 OutOfUndef ? 3791 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3792 SDValue(Agg.getNode(), Agg.getResNo() + i); 3793 3794 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3795 DAG.getVTList(ValValueVTs), Values)); 3796 } 3797 3798 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3799 Value *Op0 = I.getOperand(0); 3800 // Note that the pointer operand may be a vector of pointers. Take the scalar 3801 // element which holds a pointer. 3802 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3803 SDValue N = getValue(Op0); 3804 SDLoc dl = getCurSDLoc(); 3805 3806 // Normalize Vector GEP - all scalar operands should be converted to the 3807 // splat vector. 3808 unsigned VectorWidth = I.getType()->isVectorTy() ? 3809 cast<VectorType>(I.getType())->getVectorNumElements() : 0; 3810 3811 if (VectorWidth && !N.getValueType().isVector()) { 3812 LLVMContext &Context = *DAG.getContext(); 3813 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth); 3814 N = DAG.getSplatBuildVector(VT, dl, N); 3815 } 3816 3817 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3818 GTI != E; ++GTI) { 3819 const Value *Idx = GTI.getOperand(); 3820 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3821 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3822 if (Field) { 3823 // N = N + Offset 3824 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3825 3826 // In an inbounds GEP with an offset that is nonnegative even when 3827 // interpreted as signed, assume there is no unsigned overflow. 3828 SDNodeFlags Flags; 3829 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3830 Flags.setNoUnsignedWrap(true); 3831 3832 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3833 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3834 } 3835 } else { 3836 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3837 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3838 APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType())); 3839 3840 // If this is a scalar constant or a splat vector of constants, 3841 // handle it quickly. 3842 const auto *CI = dyn_cast<ConstantInt>(Idx); 3843 if (!CI && isa<ConstantDataVector>(Idx) && 3844 cast<ConstantDataVector>(Idx)->getSplatValue()) 3845 CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue()); 3846 3847 if (CI) { 3848 if (CI->isZero()) 3849 continue; 3850 APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize); 3851 LLVMContext &Context = *DAG.getContext(); 3852 SDValue OffsVal = VectorWidth ? 3853 DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) : 3854 DAG.getConstant(Offs, dl, IdxTy); 3855 3856 // In an inbouds GEP with an offset that is nonnegative even when 3857 // interpreted as signed, assume there is no unsigned overflow. 3858 SDNodeFlags Flags; 3859 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3860 Flags.setNoUnsignedWrap(true); 3861 3862 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3863 continue; 3864 } 3865 3866 // N = N + Idx * ElementSize; 3867 SDValue IdxN = getValue(Idx); 3868 3869 if (!IdxN.getValueType().isVector() && VectorWidth) { 3870 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth); 3871 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3872 } 3873 3874 // If the index is smaller or larger than intptr_t, truncate or extend 3875 // it. 3876 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3877 3878 // If this is a multiply by a power of two, turn it into a shl 3879 // immediately. This is a very common case. 3880 if (ElementSize != 1) { 3881 if (ElementSize.isPowerOf2()) { 3882 unsigned Amt = ElementSize.logBase2(); 3883 IdxN = DAG.getNode(ISD::SHL, dl, 3884 N.getValueType(), IdxN, 3885 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3886 } else { 3887 SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType()); 3888 IdxN = DAG.getNode(ISD::MUL, dl, 3889 N.getValueType(), IdxN, Scale); 3890 } 3891 } 3892 3893 N = DAG.getNode(ISD::ADD, dl, 3894 N.getValueType(), N, IdxN); 3895 } 3896 } 3897 3898 setValue(&I, N); 3899 } 3900 3901 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3902 // If this is a fixed sized alloca in the entry block of the function, 3903 // allocate it statically on the stack. 3904 if (FuncInfo.StaticAllocaMap.count(&I)) 3905 return; // getValue will auto-populate this. 3906 3907 SDLoc dl = getCurSDLoc(); 3908 Type *Ty = I.getAllocatedType(); 3909 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3910 auto &DL = DAG.getDataLayout(); 3911 uint64_t TySize = DL.getTypeAllocSize(Ty); 3912 unsigned Align = 3913 std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment()); 3914 3915 SDValue AllocSize = getValue(I.getArraySize()); 3916 3917 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3918 if (AllocSize.getValueType() != IntPtr) 3919 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3920 3921 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3922 AllocSize, 3923 DAG.getConstant(TySize, dl, IntPtr)); 3924 3925 // Handle alignment. If the requested alignment is less than or equal to 3926 // the stack alignment, ignore it. If the size is greater than or equal to 3927 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3928 unsigned StackAlign = 3929 DAG.getSubtarget().getFrameLowering()->getStackAlignment(); 3930 if (Align <= StackAlign) 3931 Align = 0; 3932 3933 // Round the size of the allocation up to the stack alignment size 3934 // by add SA-1 to the size. This doesn't overflow because we're computing 3935 // an address inside an alloca. 3936 SDNodeFlags Flags; 3937 Flags.setNoUnsignedWrap(true); 3938 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 3939 DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags); 3940 3941 // Mask out the low bits for alignment purposes. 3942 AllocSize = 3943 DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 3944 DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr)); 3945 3946 SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)}; 3947 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 3948 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 3949 setValue(&I, DSA); 3950 DAG.setRoot(DSA.getValue(1)); 3951 3952 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 3953 } 3954 3955 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 3956 if (I.isAtomic()) 3957 return visitAtomicLoad(I); 3958 3959 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3960 const Value *SV = I.getOperand(0); 3961 if (TLI.supportSwiftError()) { 3962 // Swifterror values can come from either a function parameter with 3963 // swifterror attribute or an alloca with swifterror attribute. 3964 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 3965 if (Arg->hasSwiftErrorAttr()) 3966 return visitLoadFromSwiftError(I); 3967 } 3968 3969 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 3970 if (Alloca->isSwiftError()) 3971 return visitLoadFromSwiftError(I); 3972 } 3973 } 3974 3975 SDValue Ptr = getValue(SV); 3976 3977 Type *Ty = I.getType(); 3978 3979 bool isVolatile = I.isVolatile(); 3980 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr; 3981 bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr; 3982 bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout()); 3983 unsigned Alignment = I.getAlignment(); 3984 3985 AAMDNodes AAInfo; 3986 I.getAAMetadata(AAInfo); 3987 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 3988 3989 SmallVector<EVT, 4> ValueVTs; 3990 SmallVector<uint64_t, 4> Offsets; 3991 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets); 3992 unsigned NumValues = ValueVTs.size(); 3993 if (NumValues == 0) 3994 return; 3995 3996 SDValue Root; 3997 bool ConstantMemory = false; 3998 if (isVolatile || NumValues > MaxParallelChains) 3999 // Serialize volatile loads with other side effects. 4000 Root = getRoot(); 4001 else if (AA && 4002 AA->pointsToConstantMemory(MemoryLocation( 4003 SV, 4004 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4005 AAInfo))) { 4006 // Do not serialize (non-volatile) loads of constant memory with anything. 4007 Root = DAG.getEntryNode(); 4008 ConstantMemory = true; 4009 } else { 4010 // Do not serialize non-volatile loads against each other. 4011 Root = DAG.getRoot(); 4012 } 4013 4014 SDLoc dl = getCurSDLoc(); 4015 4016 if (isVolatile) 4017 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4018 4019 // An aggregate load cannot wrap around the address space, so offsets to its 4020 // parts don't wrap either. 4021 SDNodeFlags Flags; 4022 Flags.setNoUnsignedWrap(true); 4023 4024 SmallVector<SDValue, 4> Values(NumValues); 4025 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4026 EVT PtrVT = Ptr.getValueType(); 4027 unsigned ChainI = 0; 4028 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4029 // Serializing loads here may result in excessive register pressure, and 4030 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4031 // could recover a bit by hoisting nodes upward in the chain by recognizing 4032 // they are side-effect free or do not alias. The optimizer should really 4033 // avoid this case by converting large object/array copies to llvm.memcpy 4034 // (MaxParallelChains should always remain as failsafe). 4035 if (ChainI == MaxParallelChains) { 4036 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4037 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4038 makeArrayRef(Chains.data(), ChainI)); 4039 Root = Chain; 4040 ChainI = 0; 4041 } 4042 SDValue A = DAG.getNode(ISD::ADD, dl, 4043 PtrVT, Ptr, 4044 DAG.getConstant(Offsets[i], dl, PtrVT), 4045 Flags); 4046 auto MMOFlags = MachineMemOperand::MONone; 4047 if (isVolatile) 4048 MMOFlags |= MachineMemOperand::MOVolatile; 4049 if (isNonTemporal) 4050 MMOFlags |= MachineMemOperand::MONonTemporal; 4051 if (isInvariant) 4052 MMOFlags |= MachineMemOperand::MOInvariant; 4053 if (isDereferenceable) 4054 MMOFlags |= MachineMemOperand::MODereferenceable; 4055 MMOFlags |= TLI.getMMOFlags(I); 4056 4057 SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A, 4058 MachinePointerInfo(SV, Offsets[i]), Alignment, 4059 MMOFlags, AAInfo, Ranges); 4060 4061 Values[i] = L; 4062 Chains[ChainI] = L.getValue(1); 4063 } 4064 4065 if (!ConstantMemory) { 4066 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4067 makeArrayRef(Chains.data(), ChainI)); 4068 if (isVolatile) 4069 DAG.setRoot(Chain); 4070 else 4071 PendingLoads.push_back(Chain); 4072 } 4073 4074 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4075 DAG.getVTList(ValueVTs), Values)); 4076 } 4077 4078 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4079 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4080 "call visitStoreToSwiftError when backend supports swifterror"); 4081 4082 SmallVector<EVT, 4> ValueVTs; 4083 SmallVector<uint64_t, 4> Offsets; 4084 const Value *SrcV = I.getOperand(0); 4085 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4086 SrcV->getType(), ValueVTs, &Offsets); 4087 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4088 "expect a single EVT for swifterror"); 4089 4090 SDValue Src = getValue(SrcV); 4091 // Create a virtual register, then update the virtual register. 4092 unsigned VReg; bool CreatedVReg; 4093 std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I); 4094 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4095 // Chain can be getRoot or getControlRoot. 4096 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4097 SDValue(Src.getNode(), Src.getResNo())); 4098 DAG.setRoot(CopyNode); 4099 if (CreatedVReg) 4100 FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg); 4101 } 4102 4103 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4104 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4105 "call visitLoadFromSwiftError when backend supports swifterror"); 4106 4107 assert(!I.isVolatile() && 4108 I.getMetadata(LLVMContext::MD_nontemporal) == nullptr && 4109 I.getMetadata(LLVMContext::MD_invariant_load) == nullptr && 4110 "Support volatile, non temporal, invariant for load_from_swift_error"); 4111 4112 const Value *SV = I.getOperand(0); 4113 Type *Ty = I.getType(); 4114 AAMDNodes AAInfo; 4115 I.getAAMetadata(AAInfo); 4116 assert( 4117 (!AA || 4118 !AA->pointsToConstantMemory(MemoryLocation( 4119 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4120 AAInfo))) && 4121 "load_from_swift_error should not be constant memory"); 4122 4123 SmallVector<EVT, 4> ValueVTs; 4124 SmallVector<uint64_t, 4> Offsets; 4125 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4126 ValueVTs, &Offsets); 4127 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4128 "expect a single EVT for swifterror"); 4129 4130 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4131 SDValue L = DAG.getCopyFromReg( 4132 getRoot(), getCurSDLoc(), 4133 FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first, 4134 ValueVTs[0]); 4135 4136 setValue(&I, L); 4137 } 4138 4139 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4140 if (I.isAtomic()) 4141 return visitAtomicStore(I); 4142 4143 const Value *SrcV = I.getOperand(0); 4144 const Value *PtrV = I.getOperand(1); 4145 4146 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4147 if (TLI.supportSwiftError()) { 4148 // Swifterror values can come from either a function parameter with 4149 // swifterror attribute or an alloca with swifterror attribute. 4150 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4151 if (Arg->hasSwiftErrorAttr()) 4152 return visitStoreToSwiftError(I); 4153 } 4154 4155 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4156 if (Alloca->isSwiftError()) 4157 return visitStoreToSwiftError(I); 4158 } 4159 } 4160 4161 SmallVector<EVT, 4> ValueVTs; 4162 SmallVector<uint64_t, 4> Offsets; 4163 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4164 SrcV->getType(), ValueVTs, &Offsets); 4165 unsigned NumValues = ValueVTs.size(); 4166 if (NumValues == 0) 4167 return; 4168 4169 // Get the lowered operands. Note that we do this after 4170 // checking if NumResults is zero, because with zero results 4171 // the operands won't have values in the map. 4172 SDValue Src = getValue(SrcV); 4173 SDValue Ptr = getValue(PtrV); 4174 4175 SDValue Root = getRoot(); 4176 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4177 SDLoc dl = getCurSDLoc(); 4178 EVT PtrVT = Ptr.getValueType(); 4179 unsigned Alignment = I.getAlignment(); 4180 AAMDNodes AAInfo; 4181 I.getAAMetadata(AAInfo); 4182 4183 auto MMOFlags = MachineMemOperand::MONone; 4184 if (I.isVolatile()) 4185 MMOFlags |= MachineMemOperand::MOVolatile; 4186 if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr) 4187 MMOFlags |= MachineMemOperand::MONonTemporal; 4188 MMOFlags |= TLI.getMMOFlags(I); 4189 4190 // An aggregate load cannot wrap around the address space, so offsets to its 4191 // parts don't wrap either. 4192 SDNodeFlags Flags; 4193 Flags.setNoUnsignedWrap(true); 4194 4195 unsigned ChainI = 0; 4196 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4197 // See visitLoad comments. 4198 if (ChainI == MaxParallelChains) { 4199 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4200 makeArrayRef(Chains.data(), ChainI)); 4201 Root = Chain; 4202 ChainI = 0; 4203 } 4204 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, 4205 DAG.getConstant(Offsets[i], dl, PtrVT), Flags); 4206 SDValue St = DAG.getStore( 4207 Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add, 4208 MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo); 4209 Chains[ChainI] = St; 4210 } 4211 4212 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4213 makeArrayRef(Chains.data(), ChainI)); 4214 DAG.setRoot(StoreNode); 4215 } 4216 4217 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4218 bool IsCompressing) { 4219 SDLoc sdl = getCurSDLoc(); 4220 4221 auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4222 unsigned& Alignment) { 4223 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4224 Src0 = I.getArgOperand(0); 4225 Ptr = I.getArgOperand(1); 4226 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 4227 Mask = I.getArgOperand(3); 4228 }; 4229 auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4230 unsigned& Alignment) { 4231 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4232 Src0 = I.getArgOperand(0); 4233 Ptr = I.getArgOperand(1); 4234 Mask = I.getArgOperand(2); 4235 Alignment = 0; 4236 }; 4237 4238 Value *PtrOperand, *MaskOperand, *Src0Operand; 4239 unsigned Alignment; 4240 if (IsCompressing) 4241 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4242 else 4243 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4244 4245 SDValue Ptr = getValue(PtrOperand); 4246 SDValue Src0 = getValue(Src0Operand); 4247 SDValue Mask = getValue(MaskOperand); 4248 4249 EVT VT = Src0.getValueType(); 4250 if (!Alignment) 4251 Alignment = DAG.getEVTAlignment(VT); 4252 4253 AAMDNodes AAInfo; 4254 I.getAAMetadata(AAInfo); 4255 4256 MachineMemOperand *MMO = 4257 DAG.getMachineFunction(). 4258 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4259 MachineMemOperand::MOStore, VT.getStoreSize(), 4260 Alignment, AAInfo); 4261 SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT, 4262 MMO, false /* Truncating */, 4263 IsCompressing); 4264 DAG.setRoot(StoreNode); 4265 setValue(&I, StoreNode); 4266 } 4267 4268 // Get a uniform base for the Gather/Scatter intrinsic. 4269 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4270 // We try to represent it as a base pointer + vector of indices. 4271 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4272 // The first operand of the GEP may be a single pointer or a vector of pointers 4273 // Example: 4274 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4275 // or 4276 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4277 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4278 // 4279 // When the first GEP operand is a single pointer - it is the uniform base we 4280 // are looking for. If first operand of the GEP is a splat vector - we 4281 // extract the splat value and use it as a uniform base. 4282 // In all other cases the function returns 'false'. 4283 static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index, 4284 SDValue &Scale, SelectionDAGBuilder* SDB) { 4285 SelectionDAG& DAG = SDB->DAG; 4286 LLVMContext &Context = *DAG.getContext(); 4287 4288 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 4289 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4290 if (!GEP) 4291 return false; 4292 4293 const Value *GEPPtr = GEP->getPointerOperand(); 4294 if (!GEPPtr->getType()->isVectorTy()) 4295 Ptr = GEPPtr; 4296 else if (!(Ptr = getSplatValue(GEPPtr))) 4297 return false; 4298 4299 unsigned FinalIndex = GEP->getNumOperands() - 1; 4300 Value *IndexVal = GEP->getOperand(FinalIndex); 4301 4302 // Ensure all the other indices are 0. 4303 for (unsigned i = 1; i < FinalIndex; ++i) { 4304 auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i)); 4305 if (!C || !C->isZero()) 4306 return false; 4307 } 4308 4309 // The operands of the GEP may be defined in another basic block. 4310 // In this case we'll not find nodes for the operands. 4311 if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal)) 4312 return false; 4313 4314 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4315 const DataLayout &DL = DAG.getDataLayout(); 4316 Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()), 4317 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4318 Base = SDB->getValue(Ptr); 4319 Index = SDB->getValue(IndexVal); 4320 4321 if (!Index.getValueType().isVector()) { 4322 unsigned GEPWidth = GEP->getType()->getVectorNumElements(); 4323 EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth); 4324 Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index); 4325 } 4326 return true; 4327 } 4328 4329 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4330 SDLoc sdl = getCurSDLoc(); 4331 4332 // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask) 4333 const Value *Ptr = I.getArgOperand(1); 4334 SDValue Src0 = getValue(I.getArgOperand(0)); 4335 SDValue Mask = getValue(I.getArgOperand(3)); 4336 EVT VT = Src0.getValueType(); 4337 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue(); 4338 if (!Alignment) 4339 Alignment = DAG.getEVTAlignment(VT); 4340 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4341 4342 AAMDNodes AAInfo; 4343 I.getAAMetadata(AAInfo); 4344 4345 SDValue Base; 4346 SDValue Index; 4347 SDValue Scale; 4348 const Value *BasePtr = Ptr; 4349 bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this); 4350 4351 const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr; 4352 MachineMemOperand *MMO = DAG.getMachineFunction(). 4353 getMachineMemOperand(MachinePointerInfo(MemOpBasePtr), 4354 MachineMemOperand::MOStore, VT.getStoreSize(), 4355 Alignment, AAInfo); 4356 if (!UniformBase) { 4357 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4358 Index = getValue(Ptr); 4359 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4360 } 4361 SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale }; 4362 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4363 Ops, MMO); 4364 DAG.setRoot(Scatter); 4365 setValue(&I, Scatter); 4366 } 4367 4368 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4369 SDLoc sdl = getCurSDLoc(); 4370 4371 auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4372 unsigned& Alignment) { 4373 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4374 Ptr = I.getArgOperand(0); 4375 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 4376 Mask = I.getArgOperand(2); 4377 Src0 = I.getArgOperand(3); 4378 }; 4379 auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4380 unsigned& Alignment) { 4381 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4382 Ptr = I.getArgOperand(0); 4383 Alignment = 0; 4384 Mask = I.getArgOperand(1); 4385 Src0 = I.getArgOperand(2); 4386 }; 4387 4388 Value *PtrOperand, *MaskOperand, *Src0Operand; 4389 unsigned Alignment; 4390 if (IsExpanding) 4391 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4392 else 4393 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4394 4395 SDValue Ptr = getValue(PtrOperand); 4396 SDValue Src0 = getValue(Src0Operand); 4397 SDValue Mask = getValue(MaskOperand); 4398 4399 EVT VT = Src0.getValueType(); 4400 if (!Alignment) 4401 Alignment = DAG.getEVTAlignment(VT); 4402 4403 AAMDNodes AAInfo; 4404 I.getAAMetadata(AAInfo); 4405 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4406 4407 // Do not serialize masked loads of constant memory with anything. 4408 bool AddToChain = 4409 !AA || !AA->pointsToConstantMemory(MemoryLocation( 4410 PtrOperand, 4411 LocationSize::precise( 4412 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4413 AAInfo)); 4414 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4415 4416 MachineMemOperand *MMO = 4417 DAG.getMachineFunction(). 4418 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4419 MachineMemOperand::MOLoad, VT.getStoreSize(), 4420 Alignment, AAInfo, Ranges); 4421 4422 SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO, 4423 ISD::NON_EXTLOAD, IsExpanding); 4424 if (AddToChain) 4425 PendingLoads.push_back(Load.getValue(1)); 4426 setValue(&I, Load); 4427 } 4428 4429 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4430 SDLoc sdl = getCurSDLoc(); 4431 4432 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4433 const Value *Ptr = I.getArgOperand(0); 4434 SDValue Src0 = getValue(I.getArgOperand(3)); 4435 SDValue Mask = getValue(I.getArgOperand(2)); 4436 4437 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4438 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4439 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue(); 4440 if (!Alignment) 4441 Alignment = DAG.getEVTAlignment(VT); 4442 4443 AAMDNodes AAInfo; 4444 I.getAAMetadata(AAInfo); 4445 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4446 4447 SDValue Root = DAG.getRoot(); 4448 SDValue Base; 4449 SDValue Index; 4450 SDValue Scale; 4451 const Value *BasePtr = Ptr; 4452 bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this); 4453 bool ConstantMemory = false; 4454 if (UniformBase && AA && 4455 AA->pointsToConstantMemory( 4456 MemoryLocation(BasePtr, 4457 LocationSize::precise( 4458 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4459 AAInfo))) { 4460 // Do not serialize (non-volatile) loads of constant memory with anything. 4461 Root = DAG.getEntryNode(); 4462 ConstantMemory = true; 4463 } 4464 4465 MachineMemOperand *MMO = 4466 DAG.getMachineFunction(). 4467 getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr), 4468 MachineMemOperand::MOLoad, VT.getStoreSize(), 4469 Alignment, AAInfo, Ranges); 4470 4471 if (!UniformBase) { 4472 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4473 Index = getValue(Ptr); 4474 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4475 } 4476 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4477 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4478 Ops, MMO); 4479 4480 SDValue OutChain = Gather.getValue(1); 4481 if (!ConstantMemory) 4482 PendingLoads.push_back(OutChain); 4483 setValue(&I, Gather); 4484 } 4485 4486 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4487 SDLoc dl = getCurSDLoc(); 4488 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4489 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4490 SyncScope::ID SSID = I.getSyncScopeID(); 4491 4492 SDValue InChain = getRoot(); 4493 4494 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4495 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4496 4497 auto Alignment = DAG.getEVTAlignment(MemVT); 4498 4499 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 4500 if (I.isVolatile()) 4501 Flags |= MachineMemOperand::MOVolatile; 4502 Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I); 4503 4504 MachineFunction &MF = DAG.getMachineFunction(); 4505 MachineMemOperand *MMO = 4506 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4507 Flags, MemVT.getStoreSize(), Alignment, 4508 AAMDNodes(), nullptr, SSID, SuccessOrdering, 4509 FailureOrdering); 4510 4511 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4512 dl, MemVT, VTs, InChain, 4513 getValue(I.getPointerOperand()), 4514 getValue(I.getCompareOperand()), 4515 getValue(I.getNewValOperand()), MMO); 4516 4517 SDValue OutChain = L.getValue(2); 4518 4519 setValue(&I, L); 4520 DAG.setRoot(OutChain); 4521 } 4522 4523 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4524 SDLoc dl = getCurSDLoc(); 4525 ISD::NodeType NT; 4526 switch (I.getOperation()) { 4527 default: llvm_unreachable("Unknown atomicrmw operation"); 4528 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4529 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4530 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4531 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4532 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4533 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4534 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4535 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4536 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4537 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4538 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4539 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4540 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4541 } 4542 AtomicOrdering Ordering = I.getOrdering(); 4543 SyncScope::ID SSID = I.getSyncScopeID(); 4544 4545 SDValue InChain = getRoot(); 4546 4547 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4548 auto Alignment = DAG.getEVTAlignment(MemVT); 4549 4550 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 4551 if (I.isVolatile()) 4552 Flags |= MachineMemOperand::MOVolatile; 4553 Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I); 4554 4555 MachineFunction &MF = DAG.getMachineFunction(); 4556 MachineMemOperand *MMO = 4557 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags, 4558 MemVT.getStoreSize(), Alignment, AAMDNodes(), 4559 nullptr, SSID, Ordering); 4560 4561 SDValue L = 4562 DAG.getAtomic(NT, dl, MemVT, InChain, 4563 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4564 MMO); 4565 4566 SDValue OutChain = L.getValue(1); 4567 4568 setValue(&I, L); 4569 DAG.setRoot(OutChain); 4570 } 4571 4572 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4573 SDLoc dl = getCurSDLoc(); 4574 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4575 SDValue Ops[3]; 4576 Ops[0] = getRoot(); 4577 Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl, 4578 TLI.getFenceOperandTy(DAG.getDataLayout())); 4579 Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl, 4580 TLI.getFenceOperandTy(DAG.getDataLayout())); 4581 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4582 } 4583 4584 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4585 SDLoc dl = getCurSDLoc(); 4586 AtomicOrdering Order = I.getOrdering(); 4587 SyncScope::ID SSID = I.getSyncScopeID(); 4588 4589 SDValue InChain = getRoot(); 4590 4591 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4592 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4593 4594 if (!TLI.supportsUnalignedAtomics() && 4595 I.getAlignment() < VT.getStoreSize()) 4596 report_fatal_error("Cannot generate unaligned atomic load"); 4597 4598 auto Flags = MachineMemOperand::MOLoad; 4599 if (I.isVolatile()) 4600 Flags |= MachineMemOperand::MOVolatile; 4601 if (I.getMetadata(LLVMContext::MD_invariant_load) != nullptr) 4602 Flags |= MachineMemOperand::MOInvariant; 4603 if (isDereferenceablePointer(I.getPointerOperand(), DAG.getDataLayout())) 4604 Flags |= MachineMemOperand::MODereferenceable; 4605 4606 Flags |= TLI.getMMOFlags(I); 4607 4608 MachineMemOperand *MMO = 4609 DAG.getMachineFunction(). 4610 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4611 Flags, VT.getStoreSize(), 4612 I.getAlignment() ? I.getAlignment() : 4613 DAG.getEVTAlignment(VT), 4614 AAMDNodes(), nullptr, SSID, Order); 4615 4616 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4617 SDValue L = 4618 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain, 4619 getValue(I.getPointerOperand()), MMO); 4620 4621 SDValue OutChain = L.getValue(1); 4622 4623 setValue(&I, L); 4624 DAG.setRoot(OutChain); 4625 } 4626 4627 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4628 SDLoc dl = getCurSDLoc(); 4629 4630 AtomicOrdering Ordering = I.getOrdering(); 4631 SyncScope::ID SSID = I.getSyncScopeID(); 4632 4633 SDValue InChain = getRoot(); 4634 4635 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4636 EVT VT = 4637 TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4638 4639 if (I.getAlignment() < VT.getStoreSize()) 4640 report_fatal_error("Cannot generate unaligned atomic store"); 4641 4642 auto Flags = MachineMemOperand::MOStore; 4643 if (I.isVolatile()) 4644 Flags |= MachineMemOperand::MOVolatile; 4645 Flags |= TLI.getMMOFlags(I); 4646 4647 MachineFunction &MF = DAG.getMachineFunction(); 4648 MachineMemOperand *MMO = 4649 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags, 4650 VT.getStoreSize(), I.getAlignment(), AAMDNodes(), 4651 nullptr, SSID, Ordering); 4652 SDValue OutChain = 4653 DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT, InChain, 4654 getValue(I.getPointerOperand()), getValue(I.getValueOperand()), 4655 MMO); 4656 4657 4658 DAG.setRoot(OutChain); 4659 } 4660 4661 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4662 /// node. 4663 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4664 unsigned Intrinsic) { 4665 // Ignore the callsite's attributes. A specific call site may be marked with 4666 // readnone, but the lowering code will expect the chain based on the 4667 // definition. 4668 const Function *F = I.getCalledFunction(); 4669 bool HasChain = !F->doesNotAccessMemory(); 4670 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4671 4672 // Build the operand list. 4673 SmallVector<SDValue, 8> Ops; 4674 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4675 if (OnlyLoad) { 4676 // We don't need to serialize loads against other loads. 4677 Ops.push_back(DAG.getRoot()); 4678 } else { 4679 Ops.push_back(getRoot()); 4680 } 4681 } 4682 4683 // Info is set by getTgtMemInstrinsic 4684 TargetLowering::IntrinsicInfo Info; 4685 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4686 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4687 DAG.getMachineFunction(), 4688 Intrinsic); 4689 4690 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4691 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4692 Info.opc == ISD::INTRINSIC_W_CHAIN) 4693 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4694 TLI.getPointerTy(DAG.getDataLayout()))); 4695 4696 // Add all operands of the call to the operand list. 4697 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4698 SDValue Op = getValue(I.getArgOperand(i)); 4699 Ops.push_back(Op); 4700 } 4701 4702 SmallVector<EVT, 4> ValueVTs; 4703 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4704 4705 if (HasChain) 4706 ValueVTs.push_back(MVT::Other); 4707 4708 SDVTList VTs = DAG.getVTList(ValueVTs); 4709 4710 // Create the node. 4711 SDValue Result; 4712 if (IsTgtIntrinsic) { 4713 // This is target intrinsic that touches memory 4714 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, 4715 Ops, Info.memVT, 4716 MachinePointerInfo(Info.ptrVal, Info.offset), Info.align, 4717 Info.flags, Info.size); 4718 } else if (!HasChain) { 4719 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4720 } else if (!I.getType()->isVoidTy()) { 4721 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4722 } else { 4723 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4724 } 4725 4726 if (HasChain) { 4727 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4728 if (OnlyLoad) 4729 PendingLoads.push_back(Chain); 4730 else 4731 DAG.setRoot(Chain); 4732 } 4733 4734 if (!I.getType()->isVoidTy()) { 4735 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4736 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4737 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4738 } else 4739 Result = lowerRangeToAssertZExt(DAG, I, Result); 4740 4741 setValue(&I, Result); 4742 } 4743 } 4744 4745 /// GetSignificand - Get the significand and build it into a floating-point 4746 /// number with exponent of 1: 4747 /// 4748 /// Op = (Op & 0x007fffff) | 0x3f800000; 4749 /// 4750 /// where Op is the hexadecimal representation of floating point value. 4751 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4752 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4753 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4754 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4755 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4756 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4757 } 4758 4759 /// GetExponent - Get the exponent: 4760 /// 4761 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4762 /// 4763 /// where Op is the hexadecimal representation of floating point value. 4764 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4765 const TargetLowering &TLI, const SDLoc &dl) { 4766 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4767 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4768 SDValue t1 = DAG.getNode( 4769 ISD::SRL, dl, MVT::i32, t0, 4770 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4771 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4772 DAG.getConstant(127, dl, MVT::i32)); 4773 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4774 } 4775 4776 /// getF32Constant - Get 32-bit floating point constant. 4777 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4778 const SDLoc &dl) { 4779 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4780 MVT::f32); 4781 } 4782 4783 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4784 SelectionDAG &DAG) { 4785 // TODO: What fast-math-flags should be set on the floating-point nodes? 4786 4787 // IntegerPartOfX = ((int32_t)(t0); 4788 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4789 4790 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4791 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4792 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4793 4794 // IntegerPartOfX <<= 23; 4795 IntegerPartOfX = DAG.getNode( 4796 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4797 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4798 DAG.getDataLayout()))); 4799 4800 SDValue TwoToFractionalPartOfX; 4801 if (LimitFloatPrecision <= 6) { 4802 // For floating-point precision of 6: 4803 // 4804 // TwoToFractionalPartOfX = 4805 // 0.997535578f + 4806 // (0.735607626f + 0.252464424f * x) * x; 4807 // 4808 // error 0.0144103317, which is 6 bits 4809 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4810 getF32Constant(DAG, 0x3e814304, dl)); 4811 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4812 getF32Constant(DAG, 0x3f3c50c8, dl)); 4813 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4814 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4815 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4816 } else if (LimitFloatPrecision <= 12) { 4817 // For floating-point precision of 12: 4818 // 4819 // TwoToFractionalPartOfX = 4820 // 0.999892986f + 4821 // (0.696457318f + 4822 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4823 // 4824 // error 0.000107046256, which is 13 to 14 bits 4825 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4826 getF32Constant(DAG, 0x3da235e3, dl)); 4827 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4828 getF32Constant(DAG, 0x3e65b8f3, dl)); 4829 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4830 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4831 getF32Constant(DAG, 0x3f324b07, dl)); 4832 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4833 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4834 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4835 } else { // LimitFloatPrecision <= 18 4836 // For floating-point precision of 18: 4837 // 4838 // TwoToFractionalPartOfX = 4839 // 0.999999982f + 4840 // (0.693148872f + 4841 // (0.240227044f + 4842 // (0.554906021e-1f + 4843 // (0.961591928e-2f + 4844 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4845 // error 2.47208000*10^(-7), which is better than 18 bits 4846 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4847 getF32Constant(DAG, 0x3924b03e, dl)); 4848 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4849 getF32Constant(DAG, 0x3ab24b87, dl)); 4850 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4851 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4852 getF32Constant(DAG, 0x3c1d8c17, dl)); 4853 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4854 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4855 getF32Constant(DAG, 0x3d634a1d, dl)); 4856 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4857 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4858 getF32Constant(DAG, 0x3e75fe14, dl)); 4859 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4860 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4861 getF32Constant(DAG, 0x3f317234, dl)); 4862 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4863 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4864 getF32Constant(DAG, 0x3f800000, dl)); 4865 } 4866 4867 // Add the exponent into the result in integer domain. 4868 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4869 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4870 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4871 } 4872 4873 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4874 /// limited-precision mode. 4875 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4876 const TargetLowering &TLI) { 4877 if (Op.getValueType() == MVT::f32 && 4878 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4879 4880 // Put the exponent in the right bit position for later addition to the 4881 // final result: 4882 // 4883 // #define LOG2OFe 1.4426950f 4884 // t0 = Op * LOG2OFe 4885 4886 // TODO: What fast-math-flags should be set here? 4887 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 4888 getF32Constant(DAG, 0x3fb8aa3b, dl)); 4889 return getLimitedPrecisionExp2(t0, dl, DAG); 4890 } 4891 4892 // No special expansion. 4893 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op); 4894 } 4895 4896 /// expandLog - Lower a log intrinsic. Handles the special sequences for 4897 /// limited-precision mode. 4898 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4899 const TargetLowering &TLI) { 4900 // TODO: What fast-math-flags should be set on the floating-point nodes? 4901 4902 if (Op.getValueType() == MVT::f32 && 4903 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4904 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4905 4906 // Scale the exponent by log(2) [0.69314718f]. 4907 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4908 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4909 getF32Constant(DAG, 0x3f317218, dl)); 4910 4911 // Get the significand and build it into a floating-point number with 4912 // exponent of 1. 4913 SDValue X = GetSignificand(DAG, Op1, dl); 4914 4915 SDValue LogOfMantissa; 4916 if (LimitFloatPrecision <= 6) { 4917 // For floating-point precision of 6: 4918 // 4919 // LogofMantissa = 4920 // -1.1609546f + 4921 // (1.4034025f - 0.23903021f * x) * x; 4922 // 4923 // error 0.0034276066, which is better than 8 bits 4924 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4925 getF32Constant(DAG, 0xbe74c456, dl)); 4926 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4927 getF32Constant(DAG, 0x3fb3a2b1, dl)); 4928 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4929 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4930 getF32Constant(DAG, 0x3f949a29, dl)); 4931 } else if (LimitFloatPrecision <= 12) { 4932 // For floating-point precision of 12: 4933 // 4934 // LogOfMantissa = 4935 // -1.7417939f + 4936 // (2.8212026f + 4937 // (-1.4699568f + 4938 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 4939 // 4940 // error 0.000061011436, which is 14 bits 4941 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4942 getF32Constant(DAG, 0xbd67b6d6, dl)); 4943 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4944 getF32Constant(DAG, 0x3ee4f4b8, dl)); 4945 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4946 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4947 getF32Constant(DAG, 0x3fbc278b, dl)); 4948 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4949 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4950 getF32Constant(DAG, 0x40348e95, dl)); 4951 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4952 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4953 getF32Constant(DAG, 0x3fdef31a, dl)); 4954 } else { // LimitFloatPrecision <= 18 4955 // For floating-point precision of 18: 4956 // 4957 // LogOfMantissa = 4958 // -2.1072184f + 4959 // (4.2372794f + 4960 // (-3.7029485f + 4961 // (2.2781945f + 4962 // (-0.87823314f + 4963 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 4964 // 4965 // error 0.0000023660568, which is better than 18 bits 4966 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4967 getF32Constant(DAG, 0xbc91e5ac, dl)); 4968 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4969 getF32Constant(DAG, 0x3e4350aa, dl)); 4970 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4971 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4972 getF32Constant(DAG, 0x3f60d3e3, dl)); 4973 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4974 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4975 getF32Constant(DAG, 0x4011cdf0, dl)); 4976 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4977 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4978 getF32Constant(DAG, 0x406cfd1c, dl)); 4979 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4980 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4981 getF32Constant(DAG, 0x408797cb, dl)); 4982 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4983 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4984 getF32Constant(DAG, 0x4006dcab, dl)); 4985 } 4986 4987 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 4988 } 4989 4990 // No special expansion. 4991 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op); 4992 } 4993 4994 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 4995 /// limited-precision mode. 4996 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4997 const TargetLowering &TLI) { 4998 // TODO: What fast-math-flags should be set on the floating-point nodes? 4999 5000 if (Op.getValueType() == MVT::f32 && 5001 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5002 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5003 5004 // Get the exponent. 5005 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5006 5007 // Get the significand and build it into a floating-point number with 5008 // exponent of 1. 5009 SDValue X = GetSignificand(DAG, Op1, dl); 5010 5011 // Different possible minimax approximations of significand in 5012 // floating-point for various degrees of accuracy over [1,2]. 5013 SDValue Log2ofMantissa; 5014 if (LimitFloatPrecision <= 6) { 5015 // For floating-point precision of 6: 5016 // 5017 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5018 // 5019 // error 0.0049451742, which is more than 7 bits 5020 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5021 getF32Constant(DAG, 0xbeb08fe0, dl)); 5022 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5023 getF32Constant(DAG, 0x40019463, dl)); 5024 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5025 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5026 getF32Constant(DAG, 0x3fd6633d, dl)); 5027 } else if (LimitFloatPrecision <= 12) { 5028 // For floating-point precision of 12: 5029 // 5030 // Log2ofMantissa = 5031 // -2.51285454f + 5032 // (4.07009056f + 5033 // (-2.12067489f + 5034 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5035 // 5036 // error 0.0000876136000, which is better than 13 bits 5037 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5038 getF32Constant(DAG, 0xbda7262e, dl)); 5039 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5040 getF32Constant(DAG, 0x3f25280b, dl)); 5041 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5042 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5043 getF32Constant(DAG, 0x4007b923, dl)); 5044 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5045 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5046 getF32Constant(DAG, 0x40823e2f, dl)); 5047 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5048 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5049 getF32Constant(DAG, 0x4020d29c, dl)); 5050 } else { // LimitFloatPrecision <= 18 5051 // For floating-point precision of 18: 5052 // 5053 // Log2ofMantissa = 5054 // -3.0400495f + 5055 // (6.1129976f + 5056 // (-5.3420409f + 5057 // (3.2865683f + 5058 // (-1.2669343f + 5059 // (0.27515199f - 5060 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5061 // 5062 // error 0.0000018516, which is better than 18 bits 5063 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5064 getF32Constant(DAG, 0xbcd2769e, dl)); 5065 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5066 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5067 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5068 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5069 getF32Constant(DAG, 0x3fa22ae7, dl)); 5070 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5071 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5072 getF32Constant(DAG, 0x40525723, dl)); 5073 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5074 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5075 getF32Constant(DAG, 0x40aaf200, dl)); 5076 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5077 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5078 getF32Constant(DAG, 0x40c39dad, dl)); 5079 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5080 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5081 getF32Constant(DAG, 0x4042902c, dl)); 5082 } 5083 5084 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5085 } 5086 5087 // No special expansion. 5088 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op); 5089 } 5090 5091 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5092 /// limited-precision mode. 5093 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5094 const TargetLowering &TLI) { 5095 // TODO: What fast-math-flags should be set on the floating-point nodes? 5096 5097 if (Op.getValueType() == MVT::f32 && 5098 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5099 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5100 5101 // Scale the exponent by log10(2) [0.30102999f]. 5102 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5103 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5104 getF32Constant(DAG, 0x3e9a209a, dl)); 5105 5106 // Get the significand and build it into a floating-point number with 5107 // exponent of 1. 5108 SDValue X = GetSignificand(DAG, Op1, dl); 5109 5110 SDValue Log10ofMantissa; 5111 if (LimitFloatPrecision <= 6) { 5112 // For floating-point precision of 6: 5113 // 5114 // Log10ofMantissa = 5115 // -0.50419619f + 5116 // (0.60948995f - 0.10380950f * x) * x; 5117 // 5118 // error 0.0014886165, which is 6 bits 5119 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5120 getF32Constant(DAG, 0xbdd49a13, dl)); 5121 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5122 getF32Constant(DAG, 0x3f1c0789, dl)); 5123 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5124 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5125 getF32Constant(DAG, 0x3f011300, dl)); 5126 } else if (LimitFloatPrecision <= 12) { 5127 // For floating-point precision of 12: 5128 // 5129 // Log10ofMantissa = 5130 // -0.64831180f + 5131 // (0.91751397f + 5132 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5133 // 5134 // error 0.00019228036, which is better than 12 bits 5135 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5136 getF32Constant(DAG, 0x3d431f31, dl)); 5137 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5138 getF32Constant(DAG, 0x3ea21fb2, dl)); 5139 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5140 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5141 getF32Constant(DAG, 0x3f6ae232, dl)); 5142 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5143 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5144 getF32Constant(DAG, 0x3f25f7c3, dl)); 5145 } else { // LimitFloatPrecision <= 18 5146 // For floating-point precision of 18: 5147 // 5148 // Log10ofMantissa = 5149 // -0.84299375f + 5150 // (1.5327582f + 5151 // (-1.0688956f + 5152 // (0.49102474f + 5153 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5154 // 5155 // error 0.0000037995730, which is better than 18 bits 5156 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5157 getF32Constant(DAG, 0x3c5d51ce, dl)); 5158 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5159 getF32Constant(DAG, 0x3e00685a, dl)); 5160 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5161 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5162 getF32Constant(DAG, 0x3efb6798, dl)); 5163 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5164 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5165 getF32Constant(DAG, 0x3f88d192, dl)); 5166 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5167 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5168 getF32Constant(DAG, 0x3fc4316c, dl)); 5169 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5170 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5171 getF32Constant(DAG, 0x3f57ce70, dl)); 5172 } 5173 5174 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5175 } 5176 5177 // No special expansion. 5178 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op); 5179 } 5180 5181 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5182 /// limited-precision mode. 5183 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5184 const TargetLowering &TLI) { 5185 if (Op.getValueType() == MVT::f32 && 5186 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5187 return getLimitedPrecisionExp2(Op, dl, DAG); 5188 5189 // No special expansion. 5190 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op); 5191 } 5192 5193 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5194 /// limited-precision mode with x == 10.0f. 5195 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5196 SelectionDAG &DAG, const TargetLowering &TLI) { 5197 bool IsExp10 = false; 5198 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5199 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5200 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5201 APFloat Ten(10.0f); 5202 IsExp10 = LHSC->isExactlyValue(Ten); 5203 } 5204 } 5205 5206 // TODO: What fast-math-flags should be set on the FMUL node? 5207 if (IsExp10) { 5208 // Put the exponent in the right bit position for later addition to the 5209 // final result: 5210 // 5211 // #define LOG2OF10 3.3219281f 5212 // t0 = Op * LOG2OF10; 5213 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5214 getF32Constant(DAG, 0x40549a78, dl)); 5215 return getLimitedPrecisionExp2(t0, dl, DAG); 5216 } 5217 5218 // No special expansion. 5219 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS); 5220 } 5221 5222 /// ExpandPowI - Expand a llvm.powi intrinsic. 5223 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5224 SelectionDAG &DAG) { 5225 // If RHS is a constant, we can expand this out to a multiplication tree, 5226 // otherwise we end up lowering to a call to __powidf2 (for example). When 5227 // optimizing for size, we only want to do this if the expansion would produce 5228 // a small number of multiplies, otherwise we do the full expansion. 5229 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5230 // Get the exponent as a positive value. 5231 unsigned Val = RHSC->getSExtValue(); 5232 if ((int)Val < 0) Val = -Val; 5233 5234 // powi(x, 0) -> 1.0 5235 if (Val == 0) 5236 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5237 5238 const Function &F = DAG.getMachineFunction().getFunction(); 5239 if (!F.hasOptSize() || 5240 // If optimizing for size, don't insert too many multiplies. 5241 // This inserts up to 5 multiplies. 5242 countPopulation(Val) + Log2_32(Val) < 7) { 5243 // We use the simple binary decomposition method to generate the multiply 5244 // sequence. There are more optimal ways to do this (for example, 5245 // powi(x,15) generates one more multiply than it should), but this has 5246 // the benefit of being both really simple and much better than a libcall. 5247 SDValue Res; // Logically starts equal to 1.0 5248 SDValue CurSquare = LHS; 5249 // TODO: Intrinsics should have fast-math-flags that propagate to these 5250 // nodes. 5251 while (Val) { 5252 if (Val & 1) { 5253 if (Res.getNode()) 5254 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 5255 else 5256 Res = CurSquare; // 1.0*CurSquare. 5257 } 5258 5259 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5260 CurSquare, CurSquare); 5261 Val >>= 1; 5262 } 5263 5264 // If the original was negative, invert the result, producing 1/(x*x*x). 5265 if (RHSC->getSExtValue() < 0) 5266 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5267 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5268 return Res; 5269 } 5270 } 5271 5272 // Otherwise, expand to a libcall. 5273 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5274 } 5275 5276 // getUnderlyingArgReg - Find underlying register used for a truncated or 5277 // bitcasted argument. 5278 static unsigned getUnderlyingArgReg(const SDValue &N) { 5279 switch (N.getOpcode()) { 5280 case ISD::CopyFromReg: 5281 return cast<RegisterSDNode>(N.getOperand(1))->getReg(); 5282 case ISD::BITCAST: 5283 case ISD::AssertZext: 5284 case ISD::AssertSext: 5285 case ISD::TRUNCATE: 5286 return getUnderlyingArgReg(N.getOperand(0)); 5287 default: 5288 return 0; 5289 } 5290 } 5291 5292 /// If the DbgValueInst is a dbg_value of a function argument, create the 5293 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5294 /// instruction selection, they will be inserted to the entry BB. 5295 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5296 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5297 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 5298 const Argument *Arg = dyn_cast<Argument>(V); 5299 if (!Arg) 5300 return false; 5301 5302 if (!IsDbgDeclare) { 5303 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5304 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5305 // the entry block. 5306 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5307 if (!IsInEntryBlock) 5308 return false; 5309 5310 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5311 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5312 // variable that also is a param. 5313 // 5314 // Although, if we are at the top of the entry block already, we can still 5315 // emit using ArgDbgValue. This might catch some situations when the 5316 // dbg.value refers to an argument that isn't used in the entry block, so 5317 // any CopyToReg node would be optimized out and the only way to express 5318 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5319 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5320 // we should only emit as ArgDbgValue if the Variable is an argument to the 5321 // current function, and the dbg.value intrinsic is found in the entry 5322 // block. 5323 bool VariableIsFunctionInputArg = Variable->isParameter() && 5324 !DL->getInlinedAt(); 5325 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5326 if (!IsInPrologue && !VariableIsFunctionInputArg) 5327 return false; 5328 5329 // Here we assume that a function argument on IR level only can be used to 5330 // describe one input parameter on source level. If we for example have 5331 // source code like this 5332 // 5333 // struct A { long x, y; }; 5334 // void foo(struct A a, long b) { 5335 // ... 5336 // b = a.x; 5337 // ... 5338 // } 5339 // 5340 // and IR like this 5341 // 5342 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5343 // entry: 5344 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5345 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5346 // call void @llvm.dbg.value(metadata i32 %b, "b", 5347 // ... 5348 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5349 // ... 5350 // 5351 // then the last dbg.value is describing a parameter "b" using a value that 5352 // is an argument. But since we already has used %a1 to describe a parameter 5353 // we should not handle that last dbg.value here (that would result in an 5354 // incorrect hoisting of the DBG_VALUE to the function entry). 5355 // Notice that we allow one dbg.value per IR level argument, to accomodate 5356 // for the situation with fragments above. 5357 if (VariableIsFunctionInputArg) { 5358 unsigned ArgNo = Arg->getArgNo(); 5359 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5360 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5361 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5362 return false; 5363 FuncInfo.DescribedArgs.set(ArgNo); 5364 } 5365 } 5366 5367 MachineFunction &MF = DAG.getMachineFunction(); 5368 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5369 5370 bool IsIndirect = false; 5371 Optional<MachineOperand> Op; 5372 // Some arguments' frame index is recorded during argument lowering. 5373 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5374 if (FI != std::numeric_limits<int>::max()) 5375 Op = MachineOperand::CreateFI(FI); 5376 5377 if (!Op && N.getNode()) { 5378 unsigned Reg = getUnderlyingArgReg(N); 5379 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) { 5380 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5381 unsigned PR = RegInfo.getLiveInPhysReg(Reg); 5382 if (PR) 5383 Reg = PR; 5384 } 5385 if (Reg) { 5386 Op = MachineOperand::CreateReg(Reg, false); 5387 IsIndirect = IsDbgDeclare; 5388 } 5389 } 5390 5391 if (!Op && N.getNode()) { 5392 // Check if frame index is available. 5393 SDValue LCandidate = peekThroughBitcasts(N); 5394 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5395 if (FrameIndexSDNode *FINode = 5396 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5397 Op = MachineOperand::CreateFI(FINode->getIndex()); 5398 } 5399 5400 if (!Op) { 5401 // Check if ValueMap has reg number. 5402 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 5403 if (VMI != FuncInfo.ValueMap.end()) { 5404 const auto &TLI = DAG.getTargetLoweringInfo(); 5405 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5406 V->getType(), getABIRegCopyCC(V)); 5407 if (RFV.occupiesMultipleRegs()) { 5408 unsigned Offset = 0; 5409 for (auto RegAndSize : RFV.getRegsAndSizes()) { 5410 Op = MachineOperand::CreateReg(RegAndSize.first, false); 5411 auto FragmentExpr = DIExpression::createFragmentExpression( 5412 Expr, Offset, RegAndSize.second); 5413 if (!FragmentExpr) 5414 continue; 5415 FuncInfo.ArgDbgValues.push_back( 5416 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare, 5417 Op->getReg(), Variable, *FragmentExpr)); 5418 Offset += RegAndSize.second; 5419 } 5420 return true; 5421 } 5422 Op = MachineOperand::CreateReg(VMI->second, false); 5423 IsIndirect = IsDbgDeclare; 5424 } 5425 } 5426 5427 if (!Op) 5428 return false; 5429 5430 assert(Variable->isValidLocationForIntrinsic(DL) && 5431 "Expected inlined-at fields to agree"); 5432 IsIndirect = (Op->isReg()) ? IsIndirect : true; 5433 FuncInfo.ArgDbgValues.push_back( 5434 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 5435 *Op, Variable, Expr)); 5436 5437 return true; 5438 } 5439 5440 /// Return the appropriate SDDbgValue based on N. 5441 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5442 DILocalVariable *Variable, 5443 DIExpression *Expr, 5444 const DebugLoc &dl, 5445 unsigned DbgSDNodeOrder) { 5446 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5447 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5448 // stack slot locations. 5449 // 5450 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5451 // debug values here after optimization: 5452 // 5453 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5454 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5455 // 5456 // Both describe the direct values of their associated variables. 5457 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5458 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5459 } 5460 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5461 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5462 } 5463 5464 // VisualStudio defines setjmp as _setjmp 5465 #if defined(_MSC_VER) && defined(setjmp) && \ 5466 !defined(setjmp_undefined_for_msvc) 5467 # pragma push_macro("setjmp") 5468 # undef setjmp 5469 # define setjmp_undefined_for_msvc 5470 #endif 5471 5472 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5473 switch (Intrinsic) { 5474 case Intrinsic::smul_fix: 5475 return ISD::SMULFIX; 5476 case Intrinsic::umul_fix: 5477 return ISD::UMULFIX; 5478 default: 5479 llvm_unreachable("Unhandled fixed point intrinsic"); 5480 } 5481 } 5482 5483 /// Lower the call to the specified intrinsic function. If we want to emit this 5484 /// as a call to a named external function, return the name. Otherwise, lower it 5485 /// and return null. 5486 const char * 5487 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) { 5488 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5489 SDLoc sdl = getCurSDLoc(); 5490 DebugLoc dl = getCurDebugLoc(); 5491 SDValue Res; 5492 5493 switch (Intrinsic) { 5494 default: 5495 // By default, turn this into a target intrinsic node. 5496 visitTargetIntrinsic(I, Intrinsic); 5497 return nullptr; 5498 case Intrinsic::vastart: visitVAStart(I); return nullptr; 5499 case Intrinsic::vaend: visitVAEnd(I); return nullptr; 5500 case Intrinsic::vacopy: visitVACopy(I); return nullptr; 5501 case Intrinsic::returnaddress: 5502 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5503 TLI.getPointerTy(DAG.getDataLayout()), 5504 getValue(I.getArgOperand(0)))); 5505 return nullptr; 5506 case Intrinsic::addressofreturnaddress: 5507 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5508 TLI.getPointerTy(DAG.getDataLayout()))); 5509 return nullptr; 5510 case Intrinsic::sponentry: 5511 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5512 TLI.getPointerTy(DAG.getDataLayout()))); 5513 return nullptr; 5514 case Intrinsic::frameaddress: 5515 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5516 TLI.getPointerTy(DAG.getDataLayout()), 5517 getValue(I.getArgOperand(0)))); 5518 return nullptr; 5519 case Intrinsic::read_register: { 5520 Value *Reg = I.getArgOperand(0); 5521 SDValue Chain = getRoot(); 5522 SDValue RegName = 5523 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5524 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5525 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5526 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5527 setValue(&I, Res); 5528 DAG.setRoot(Res.getValue(1)); 5529 return nullptr; 5530 } 5531 case Intrinsic::write_register: { 5532 Value *Reg = I.getArgOperand(0); 5533 Value *RegValue = I.getArgOperand(1); 5534 SDValue Chain = getRoot(); 5535 SDValue RegName = 5536 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5537 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5538 RegName, getValue(RegValue))); 5539 return nullptr; 5540 } 5541 case Intrinsic::setjmp: 5542 return &"_setjmp"[!TLI.usesUnderscoreSetJmp()]; 5543 case Intrinsic::longjmp: 5544 return &"_longjmp"[!TLI.usesUnderscoreLongJmp()]; 5545 case Intrinsic::memcpy: { 5546 const auto &MCI = cast<MemCpyInst>(I); 5547 SDValue Op1 = getValue(I.getArgOperand(0)); 5548 SDValue Op2 = getValue(I.getArgOperand(1)); 5549 SDValue Op3 = getValue(I.getArgOperand(2)); 5550 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5551 unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1); 5552 unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1); 5553 unsigned Align = MinAlign(DstAlign, SrcAlign); 5554 bool isVol = MCI.isVolatile(); 5555 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5556 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5557 // node. 5558 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5559 false, isTC, 5560 MachinePointerInfo(I.getArgOperand(0)), 5561 MachinePointerInfo(I.getArgOperand(1))); 5562 updateDAGForMaybeTailCall(MC); 5563 return nullptr; 5564 } 5565 case Intrinsic::memset: { 5566 const auto &MSI = cast<MemSetInst>(I); 5567 SDValue Op1 = getValue(I.getArgOperand(0)); 5568 SDValue Op2 = getValue(I.getArgOperand(1)); 5569 SDValue Op3 = getValue(I.getArgOperand(2)); 5570 // @llvm.memset defines 0 and 1 to both mean no alignment. 5571 unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1); 5572 bool isVol = MSI.isVolatile(); 5573 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5574 SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5575 isTC, MachinePointerInfo(I.getArgOperand(0))); 5576 updateDAGForMaybeTailCall(MS); 5577 return nullptr; 5578 } 5579 case Intrinsic::memmove: { 5580 const auto &MMI = cast<MemMoveInst>(I); 5581 SDValue Op1 = getValue(I.getArgOperand(0)); 5582 SDValue Op2 = getValue(I.getArgOperand(1)); 5583 SDValue Op3 = getValue(I.getArgOperand(2)); 5584 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5585 unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1); 5586 unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1); 5587 unsigned Align = MinAlign(DstAlign, SrcAlign); 5588 bool isVol = MMI.isVolatile(); 5589 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5590 // FIXME: Support passing different dest/src alignments to the memmove DAG 5591 // node. 5592 SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5593 isTC, MachinePointerInfo(I.getArgOperand(0)), 5594 MachinePointerInfo(I.getArgOperand(1))); 5595 updateDAGForMaybeTailCall(MM); 5596 return nullptr; 5597 } 5598 case Intrinsic::memcpy_element_unordered_atomic: { 5599 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5600 SDValue Dst = getValue(MI.getRawDest()); 5601 SDValue Src = getValue(MI.getRawSource()); 5602 SDValue Length = getValue(MI.getLength()); 5603 5604 unsigned DstAlign = MI.getDestAlignment(); 5605 unsigned SrcAlign = MI.getSourceAlignment(); 5606 Type *LengthTy = MI.getLength()->getType(); 5607 unsigned ElemSz = MI.getElementSizeInBytes(); 5608 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5609 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5610 SrcAlign, Length, LengthTy, ElemSz, isTC, 5611 MachinePointerInfo(MI.getRawDest()), 5612 MachinePointerInfo(MI.getRawSource())); 5613 updateDAGForMaybeTailCall(MC); 5614 return nullptr; 5615 } 5616 case Intrinsic::memmove_element_unordered_atomic: { 5617 auto &MI = cast<AtomicMemMoveInst>(I); 5618 SDValue Dst = getValue(MI.getRawDest()); 5619 SDValue Src = getValue(MI.getRawSource()); 5620 SDValue Length = getValue(MI.getLength()); 5621 5622 unsigned DstAlign = MI.getDestAlignment(); 5623 unsigned SrcAlign = MI.getSourceAlignment(); 5624 Type *LengthTy = MI.getLength()->getType(); 5625 unsigned ElemSz = MI.getElementSizeInBytes(); 5626 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5627 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5628 SrcAlign, Length, LengthTy, ElemSz, isTC, 5629 MachinePointerInfo(MI.getRawDest()), 5630 MachinePointerInfo(MI.getRawSource())); 5631 updateDAGForMaybeTailCall(MC); 5632 return nullptr; 5633 } 5634 case Intrinsic::memset_element_unordered_atomic: { 5635 auto &MI = cast<AtomicMemSetInst>(I); 5636 SDValue Dst = getValue(MI.getRawDest()); 5637 SDValue Val = getValue(MI.getValue()); 5638 SDValue Length = getValue(MI.getLength()); 5639 5640 unsigned DstAlign = MI.getDestAlignment(); 5641 Type *LengthTy = MI.getLength()->getType(); 5642 unsigned ElemSz = MI.getElementSizeInBytes(); 5643 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5644 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5645 LengthTy, ElemSz, isTC, 5646 MachinePointerInfo(MI.getRawDest())); 5647 updateDAGForMaybeTailCall(MC); 5648 return nullptr; 5649 } 5650 case Intrinsic::dbg_addr: 5651 case Intrinsic::dbg_declare: { 5652 const auto &DI = cast<DbgVariableIntrinsic>(I); 5653 DILocalVariable *Variable = DI.getVariable(); 5654 DIExpression *Expression = DI.getExpression(); 5655 dropDanglingDebugInfo(Variable, Expression); 5656 assert(Variable && "Missing variable"); 5657 5658 // Check if address has undef value. 5659 const Value *Address = DI.getVariableLocation(); 5660 if (!Address || isa<UndefValue>(Address) || 5661 (Address->use_empty() && !isa<Argument>(Address))) { 5662 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5663 return nullptr; 5664 } 5665 5666 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5667 5668 // Check if this variable can be described by a frame index, typically 5669 // either as a static alloca or a byval parameter. 5670 int FI = std::numeric_limits<int>::max(); 5671 if (const auto *AI = 5672 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5673 if (AI->isStaticAlloca()) { 5674 auto I = FuncInfo.StaticAllocaMap.find(AI); 5675 if (I != FuncInfo.StaticAllocaMap.end()) 5676 FI = I->second; 5677 } 5678 } else if (const auto *Arg = dyn_cast<Argument>( 5679 Address->stripInBoundsConstantOffsets())) { 5680 FI = FuncInfo.getArgumentFrameIndex(Arg); 5681 } 5682 5683 // llvm.dbg.addr is control dependent and always generates indirect 5684 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5685 // the MachineFunction variable table. 5686 if (FI != std::numeric_limits<int>::max()) { 5687 if (Intrinsic == Intrinsic::dbg_addr) { 5688 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 5689 Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder); 5690 DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter); 5691 } 5692 return nullptr; 5693 } 5694 5695 SDValue &N = NodeMap[Address]; 5696 if (!N.getNode() && isa<Argument>(Address)) 5697 // Check unused arguments map. 5698 N = UnusedArgNodeMap[Address]; 5699 SDDbgValue *SDV; 5700 if (N.getNode()) { 5701 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 5702 Address = BCI->getOperand(0); 5703 // Parameters are handled specially. 5704 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 5705 if (isParameter && FINode) { 5706 // Byval parameter. We have a frame index at this point. 5707 SDV = 5708 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 5709 /*IsIndirect*/ true, dl, SDNodeOrder); 5710 } else if (isa<Argument>(Address)) { 5711 // Address is an argument, so try to emit its dbg value using 5712 // virtual register info from the FuncInfo.ValueMap. 5713 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 5714 return nullptr; 5715 } else { 5716 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 5717 true, dl, SDNodeOrder); 5718 } 5719 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 5720 } else { 5721 // If Address is an argument then try to emit its dbg value using 5722 // virtual register info from the FuncInfo.ValueMap. 5723 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 5724 N)) { 5725 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5726 } 5727 } 5728 return nullptr; 5729 } 5730 case Intrinsic::dbg_label: { 5731 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 5732 DILabel *Label = DI.getLabel(); 5733 assert(Label && "Missing label"); 5734 5735 SDDbgLabel *SDV; 5736 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 5737 DAG.AddDbgLabel(SDV); 5738 return nullptr; 5739 } 5740 case Intrinsic::dbg_value: { 5741 const DbgValueInst &DI = cast<DbgValueInst>(I); 5742 assert(DI.getVariable() && "Missing variable"); 5743 5744 DILocalVariable *Variable = DI.getVariable(); 5745 DIExpression *Expression = DI.getExpression(); 5746 dropDanglingDebugInfo(Variable, Expression); 5747 const Value *V = DI.getValue(); 5748 if (!V) 5749 return nullptr; 5750 5751 if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(), 5752 SDNodeOrder)) 5753 return nullptr; 5754 5755 // TODO: Dangling debug info will eventually either be resolved or produce 5756 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 5757 // between the original dbg.value location and its resolved DBG_VALUE, which 5758 // we should ideally fill with an extra Undef DBG_VALUE. 5759 5760 DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder); 5761 return nullptr; 5762 } 5763 5764 case Intrinsic::eh_typeid_for: { 5765 // Find the type id for the given typeinfo. 5766 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 5767 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 5768 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 5769 setValue(&I, Res); 5770 return nullptr; 5771 } 5772 5773 case Intrinsic::eh_return_i32: 5774 case Intrinsic::eh_return_i64: 5775 DAG.getMachineFunction().setCallsEHReturn(true); 5776 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 5777 MVT::Other, 5778 getControlRoot(), 5779 getValue(I.getArgOperand(0)), 5780 getValue(I.getArgOperand(1)))); 5781 return nullptr; 5782 case Intrinsic::eh_unwind_init: 5783 DAG.getMachineFunction().setCallsUnwindInit(true); 5784 return nullptr; 5785 case Intrinsic::eh_dwarf_cfa: 5786 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 5787 TLI.getPointerTy(DAG.getDataLayout()), 5788 getValue(I.getArgOperand(0)))); 5789 return nullptr; 5790 case Intrinsic::eh_sjlj_callsite: { 5791 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5792 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 5793 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 5794 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 5795 5796 MMI.setCurrentCallSite(CI->getZExtValue()); 5797 return nullptr; 5798 } 5799 case Intrinsic::eh_sjlj_functioncontext: { 5800 // Get and store the index of the function context. 5801 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5802 AllocaInst *FnCtx = 5803 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 5804 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 5805 MFI.setFunctionContextIndex(FI); 5806 return nullptr; 5807 } 5808 case Intrinsic::eh_sjlj_setjmp: { 5809 SDValue Ops[2]; 5810 Ops[0] = getRoot(); 5811 Ops[1] = getValue(I.getArgOperand(0)); 5812 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 5813 DAG.getVTList(MVT::i32, MVT::Other), Ops); 5814 setValue(&I, Op.getValue(0)); 5815 DAG.setRoot(Op.getValue(1)); 5816 return nullptr; 5817 } 5818 case Intrinsic::eh_sjlj_longjmp: 5819 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 5820 getRoot(), getValue(I.getArgOperand(0)))); 5821 return nullptr; 5822 case Intrinsic::eh_sjlj_setup_dispatch: 5823 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 5824 getRoot())); 5825 return nullptr; 5826 case Intrinsic::masked_gather: 5827 visitMaskedGather(I); 5828 return nullptr; 5829 case Intrinsic::masked_load: 5830 visitMaskedLoad(I); 5831 return nullptr; 5832 case Intrinsic::masked_scatter: 5833 visitMaskedScatter(I); 5834 return nullptr; 5835 case Intrinsic::masked_store: 5836 visitMaskedStore(I); 5837 return nullptr; 5838 case Intrinsic::masked_expandload: 5839 visitMaskedLoad(I, true /* IsExpanding */); 5840 return nullptr; 5841 case Intrinsic::masked_compressstore: 5842 visitMaskedStore(I, true /* IsCompressing */); 5843 return nullptr; 5844 case Intrinsic::x86_mmx_pslli_w: 5845 case Intrinsic::x86_mmx_pslli_d: 5846 case Intrinsic::x86_mmx_pslli_q: 5847 case Intrinsic::x86_mmx_psrli_w: 5848 case Intrinsic::x86_mmx_psrli_d: 5849 case Intrinsic::x86_mmx_psrli_q: 5850 case Intrinsic::x86_mmx_psrai_w: 5851 case Intrinsic::x86_mmx_psrai_d: { 5852 SDValue ShAmt = getValue(I.getArgOperand(1)); 5853 if (isa<ConstantSDNode>(ShAmt)) { 5854 visitTargetIntrinsic(I, Intrinsic); 5855 return nullptr; 5856 } 5857 unsigned NewIntrinsic = 0; 5858 EVT ShAmtVT = MVT::v2i32; 5859 switch (Intrinsic) { 5860 case Intrinsic::x86_mmx_pslli_w: 5861 NewIntrinsic = Intrinsic::x86_mmx_psll_w; 5862 break; 5863 case Intrinsic::x86_mmx_pslli_d: 5864 NewIntrinsic = Intrinsic::x86_mmx_psll_d; 5865 break; 5866 case Intrinsic::x86_mmx_pslli_q: 5867 NewIntrinsic = Intrinsic::x86_mmx_psll_q; 5868 break; 5869 case Intrinsic::x86_mmx_psrli_w: 5870 NewIntrinsic = Intrinsic::x86_mmx_psrl_w; 5871 break; 5872 case Intrinsic::x86_mmx_psrli_d: 5873 NewIntrinsic = Intrinsic::x86_mmx_psrl_d; 5874 break; 5875 case Intrinsic::x86_mmx_psrli_q: 5876 NewIntrinsic = Intrinsic::x86_mmx_psrl_q; 5877 break; 5878 case Intrinsic::x86_mmx_psrai_w: 5879 NewIntrinsic = Intrinsic::x86_mmx_psra_w; 5880 break; 5881 case Intrinsic::x86_mmx_psrai_d: 5882 NewIntrinsic = Intrinsic::x86_mmx_psra_d; 5883 break; 5884 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5885 } 5886 5887 // The vector shift intrinsics with scalars uses 32b shift amounts but 5888 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits 5889 // to be zero. 5890 // We must do this early because v2i32 is not a legal type. 5891 SDValue ShOps[2]; 5892 ShOps[0] = ShAmt; 5893 ShOps[1] = DAG.getConstant(0, sdl, MVT::i32); 5894 ShAmt = DAG.getBuildVector(ShAmtVT, sdl, ShOps); 5895 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5896 ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt); 5897 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT, 5898 DAG.getConstant(NewIntrinsic, sdl, MVT::i32), 5899 getValue(I.getArgOperand(0)), ShAmt); 5900 setValue(&I, Res); 5901 return nullptr; 5902 } 5903 case Intrinsic::powi: 5904 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 5905 getValue(I.getArgOperand(1)), DAG)); 5906 return nullptr; 5907 case Intrinsic::log: 5908 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5909 return nullptr; 5910 case Intrinsic::log2: 5911 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5912 return nullptr; 5913 case Intrinsic::log10: 5914 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5915 return nullptr; 5916 case Intrinsic::exp: 5917 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5918 return nullptr; 5919 case Intrinsic::exp2: 5920 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5921 return nullptr; 5922 case Intrinsic::pow: 5923 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 5924 getValue(I.getArgOperand(1)), DAG, TLI)); 5925 return nullptr; 5926 case Intrinsic::sqrt: 5927 case Intrinsic::fabs: 5928 case Intrinsic::sin: 5929 case Intrinsic::cos: 5930 case Intrinsic::floor: 5931 case Intrinsic::ceil: 5932 case Intrinsic::trunc: 5933 case Intrinsic::rint: 5934 case Intrinsic::nearbyint: 5935 case Intrinsic::round: 5936 case Intrinsic::canonicalize: { 5937 unsigned Opcode; 5938 switch (Intrinsic) { 5939 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5940 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 5941 case Intrinsic::fabs: Opcode = ISD::FABS; break; 5942 case Intrinsic::sin: Opcode = ISD::FSIN; break; 5943 case Intrinsic::cos: Opcode = ISD::FCOS; break; 5944 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 5945 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 5946 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 5947 case Intrinsic::rint: Opcode = ISD::FRINT; break; 5948 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 5949 case Intrinsic::round: Opcode = ISD::FROUND; break; 5950 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 5951 } 5952 5953 setValue(&I, DAG.getNode(Opcode, sdl, 5954 getValue(I.getArgOperand(0)).getValueType(), 5955 getValue(I.getArgOperand(0)))); 5956 return nullptr; 5957 } 5958 case Intrinsic::minnum: { 5959 auto VT = getValue(I.getArgOperand(0)).getValueType(); 5960 unsigned Opc = 5961 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT) 5962 ? ISD::FMINIMUM 5963 : ISD::FMINNUM; 5964 setValue(&I, DAG.getNode(Opc, sdl, VT, 5965 getValue(I.getArgOperand(0)), 5966 getValue(I.getArgOperand(1)))); 5967 return nullptr; 5968 } 5969 case Intrinsic::maxnum: { 5970 auto VT = getValue(I.getArgOperand(0)).getValueType(); 5971 unsigned Opc = 5972 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT) 5973 ? ISD::FMAXIMUM 5974 : ISD::FMAXNUM; 5975 setValue(&I, DAG.getNode(Opc, sdl, VT, 5976 getValue(I.getArgOperand(0)), 5977 getValue(I.getArgOperand(1)))); 5978 return nullptr; 5979 } 5980 case Intrinsic::minimum: 5981 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 5982 getValue(I.getArgOperand(0)).getValueType(), 5983 getValue(I.getArgOperand(0)), 5984 getValue(I.getArgOperand(1)))); 5985 return nullptr; 5986 case Intrinsic::maximum: 5987 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 5988 getValue(I.getArgOperand(0)).getValueType(), 5989 getValue(I.getArgOperand(0)), 5990 getValue(I.getArgOperand(1)))); 5991 return nullptr; 5992 case Intrinsic::copysign: 5993 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 5994 getValue(I.getArgOperand(0)).getValueType(), 5995 getValue(I.getArgOperand(0)), 5996 getValue(I.getArgOperand(1)))); 5997 return nullptr; 5998 case Intrinsic::fma: 5999 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6000 getValue(I.getArgOperand(0)).getValueType(), 6001 getValue(I.getArgOperand(0)), 6002 getValue(I.getArgOperand(1)), 6003 getValue(I.getArgOperand(2)))); 6004 return nullptr; 6005 case Intrinsic::experimental_constrained_fadd: 6006 case Intrinsic::experimental_constrained_fsub: 6007 case Intrinsic::experimental_constrained_fmul: 6008 case Intrinsic::experimental_constrained_fdiv: 6009 case Intrinsic::experimental_constrained_frem: 6010 case Intrinsic::experimental_constrained_fma: 6011 case Intrinsic::experimental_constrained_sqrt: 6012 case Intrinsic::experimental_constrained_pow: 6013 case Intrinsic::experimental_constrained_powi: 6014 case Intrinsic::experimental_constrained_sin: 6015 case Intrinsic::experimental_constrained_cos: 6016 case Intrinsic::experimental_constrained_exp: 6017 case Intrinsic::experimental_constrained_exp2: 6018 case Intrinsic::experimental_constrained_log: 6019 case Intrinsic::experimental_constrained_log10: 6020 case Intrinsic::experimental_constrained_log2: 6021 case Intrinsic::experimental_constrained_rint: 6022 case Intrinsic::experimental_constrained_nearbyint: 6023 case Intrinsic::experimental_constrained_maxnum: 6024 case Intrinsic::experimental_constrained_minnum: 6025 case Intrinsic::experimental_constrained_ceil: 6026 case Intrinsic::experimental_constrained_floor: 6027 case Intrinsic::experimental_constrained_round: 6028 case Intrinsic::experimental_constrained_trunc: 6029 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6030 return nullptr; 6031 case Intrinsic::fmuladd: { 6032 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6033 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6034 TLI.isFMAFasterThanFMulAndFAdd(VT)) { 6035 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6036 getValue(I.getArgOperand(0)).getValueType(), 6037 getValue(I.getArgOperand(0)), 6038 getValue(I.getArgOperand(1)), 6039 getValue(I.getArgOperand(2)))); 6040 } else { 6041 // TODO: Intrinsic calls should have fast-math-flags. 6042 SDValue Mul = DAG.getNode(ISD::FMUL, sdl, 6043 getValue(I.getArgOperand(0)).getValueType(), 6044 getValue(I.getArgOperand(0)), 6045 getValue(I.getArgOperand(1))); 6046 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6047 getValue(I.getArgOperand(0)).getValueType(), 6048 Mul, 6049 getValue(I.getArgOperand(2))); 6050 setValue(&I, Add); 6051 } 6052 return nullptr; 6053 } 6054 case Intrinsic::convert_to_fp16: 6055 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6056 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6057 getValue(I.getArgOperand(0)), 6058 DAG.getTargetConstant(0, sdl, 6059 MVT::i32)))); 6060 return nullptr; 6061 case Intrinsic::convert_from_fp16: 6062 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6063 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6064 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6065 getValue(I.getArgOperand(0))))); 6066 return nullptr; 6067 case Intrinsic::pcmarker: { 6068 SDValue Tmp = getValue(I.getArgOperand(0)); 6069 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6070 return nullptr; 6071 } 6072 case Intrinsic::readcyclecounter: { 6073 SDValue Op = getRoot(); 6074 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6075 DAG.getVTList(MVT::i64, MVT::Other), Op); 6076 setValue(&I, Res); 6077 DAG.setRoot(Res.getValue(1)); 6078 return nullptr; 6079 } 6080 case Intrinsic::bitreverse: 6081 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6082 getValue(I.getArgOperand(0)).getValueType(), 6083 getValue(I.getArgOperand(0)))); 6084 return nullptr; 6085 case Intrinsic::bswap: 6086 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6087 getValue(I.getArgOperand(0)).getValueType(), 6088 getValue(I.getArgOperand(0)))); 6089 return nullptr; 6090 case Intrinsic::cttz: { 6091 SDValue Arg = getValue(I.getArgOperand(0)); 6092 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6093 EVT Ty = Arg.getValueType(); 6094 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6095 sdl, Ty, Arg)); 6096 return nullptr; 6097 } 6098 case Intrinsic::ctlz: { 6099 SDValue Arg = getValue(I.getArgOperand(0)); 6100 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6101 EVT Ty = Arg.getValueType(); 6102 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6103 sdl, Ty, Arg)); 6104 return nullptr; 6105 } 6106 case Intrinsic::ctpop: { 6107 SDValue Arg = getValue(I.getArgOperand(0)); 6108 EVT Ty = Arg.getValueType(); 6109 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6110 return nullptr; 6111 } 6112 case Intrinsic::fshl: 6113 case Intrinsic::fshr: { 6114 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6115 SDValue X = getValue(I.getArgOperand(0)); 6116 SDValue Y = getValue(I.getArgOperand(1)); 6117 SDValue Z = getValue(I.getArgOperand(2)); 6118 EVT VT = X.getValueType(); 6119 SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT); 6120 SDValue Zero = DAG.getConstant(0, sdl, VT); 6121 SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC); 6122 6123 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6124 if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) { 6125 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6126 return nullptr; 6127 } 6128 6129 // When X == Y, this is rotate. If the data type has a power-of-2 size, we 6130 // avoid the select that is necessary in the general case to filter out 6131 // the 0-shift possibility that leads to UB. 6132 if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) { 6133 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6134 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 6135 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6136 return nullptr; 6137 } 6138 6139 // Some targets only rotate one way. Try the opposite direction. 6140 RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL; 6141 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 6142 // Negate the shift amount because it is safe to ignore the high bits. 6143 SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 6144 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt)); 6145 return nullptr; 6146 } 6147 6148 // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW)) 6149 // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW)) 6150 SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 6151 SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC); 6152 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt); 6153 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt); 6154 setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY)); 6155 return nullptr; 6156 } 6157 6158 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 6159 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 6160 SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt); 6161 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt); 6162 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt); 6163 SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY); 6164 6165 // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth, 6166 // and that is undefined. We must compare and select to avoid UB. 6167 EVT CCVT = MVT::i1; 6168 if (VT.isVector()) 6169 CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements()); 6170 6171 // For fshl, 0-shift returns the 1st arg (X). 6172 // For fshr, 0-shift returns the 2nd arg (Y). 6173 SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ); 6174 setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or)); 6175 return nullptr; 6176 } 6177 case Intrinsic::sadd_sat: { 6178 SDValue Op1 = getValue(I.getArgOperand(0)); 6179 SDValue Op2 = getValue(I.getArgOperand(1)); 6180 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6181 return nullptr; 6182 } 6183 case Intrinsic::uadd_sat: { 6184 SDValue Op1 = getValue(I.getArgOperand(0)); 6185 SDValue Op2 = getValue(I.getArgOperand(1)); 6186 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6187 return nullptr; 6188 } 6189 case Intrinsic::ssub_sat: { 6190 SDValue Op1 = getValue(I.getArgOperand(0)); 6191 SDValue Op2 = getValue(I.getArgOperand(1)); 6192 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6193 return nullptr; 6194 } 6195 case Intrinsic::usub_sat: { 6196 SDValue Op1 = getValue(I.getArgOperand(0)); 6197 SDValue Op2 = getValue(I.getArgOperand(1)); 6198 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6199 return nullptr; 6200 } 6201 case Intrinsic::smul_fix: 6202 case Intrinsic::umul_fix: { 6203 SDValue Op1 = getValue(I.getArgOperand(0)); 6204 SDValue Op2 = getValue(I.getArgOperand(1)); 6205 SDValue Op3 = getValue(I.getArgOperand(2)); 6206 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6207 Op1.getValueType(), Op1, Op2, Op3)); 6208 return nullptr; 6209 } 6210 case Intrinsic::stacksave: { 6211 SDValue Op = getRoot(); 6212 Res = DAG.getNode( 6213 ISD::STACKSAVE, sdl, 6214 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op); 6215 setValue(&I, Res); 6216 DAG.setRoot(Res.getValue(1)); 6217 return nullptr; 6218 } 6219 case Intrinsic::stackrestore: 6220 Res = getValue(I.getArgOperand(0)); 6221 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6222 return nullptr; 6223 case Intrinsic::get_dynamic_area_offset: { 6224 SDValue Op = getRoot(); 6225 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6226 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6227 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6228 // target. 6229 if (PtrTy != ResTy) 6230 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6231 " intrinsic!"); 6232 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6233 Op); 6234 DAG.setRoot(Op); 6235 setValue(&I, Res); 6236 return nullptr; 6237 } 6238 case Intrinsic::stackguard: { 6239 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6240 MachineFunction &MF = DAG.getMachineFunction(); 6241 const Module &M = *MF.getFunction().getParent(); 6242 SDValue Chain = getRoot(); 6243 if (TLI.useLoadStackGuardNode()) { 6244 Res = getLoadStackGuard(DAG, sdl, Chain); 6245 } else { 6246 const Value *Global = TLI.getSDagStackGuard(M); 6247 unsigned Align = DL->getPrefTypeAlignment(Global->getType()); 6248 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6249 MachinePointerInfo(Global, 0), Align, 6250 MachineMemOperand::MOVolatile); 6251 } 6252 if (TLI.useStackGuardXorFP()) 6253 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6254 DAG.setRoot(Chain); 6255 setValue(&I, Res); 6256 return nullptr; 6257 } 6258 case Intrinsic::stackprotector: { 6259 // Emit code into the DAG to store the stack guard onto the stack. 6260 MachineFunction &MF = DAG.getMachineFunction(); 6261 MachineFrameInfo &MFI = MF.getFrameInfo(); 6262 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6263 SDValue Src, Chain = getRoot(); 6264 6265 if (TLI.useLoadStackGuardNode()) 6266 Src = getLoadStackGuard(DAG, sdl, Chain); 6267 else 6268 Src = getValue(I.getArgOperand(0)); // The guard's value. 6269 6270 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6271 6272 int FI = FuncInfo.StaticAllocaMap[Slot]; 6273 MFI.setStackProtectorIndex(FI); 6274 6275 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6276 6277 // Store the stack protector onto the stack. 6278 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack( 6279 DAG.getMachineFunction(), FI), 6280 /* Alignment = */ 0, MachineMemOperand::MOVolatile); 6281 setValue(&I, Res); 6282 DAG.setRoot(Res); 6283 return nullptr; 6284 } 6285 case Intrinsic::objectsize: { 6286 // If we don't know by now, we're never going to know. 6287 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1)); 6288 6289 assert(CI && "Non-constant type in __builtin_object_size?"); 6290 6291 SDValue Arg = getValue(I.getCalledValue()); 6292 EVT Ty = Arg.getValueType(); 6293 6294 if (CI->isZero()) 6295 Res = DAG.getConstant(-1ULL, sdl, Ty); 6296 else 6297 Res = DAG.getConstant(0, sdl, Ty); 6298 6299 setValue(&I, Res); 6300 return nullptr; 6301 } 6302 6303 case Intrinsic::is_constant: 6304 // If this wasn't constant-folded away by now, then it's not a 6305 // constant. 6306 setValue(&I, DAG.getConstant(0, sdl, MVT::i1)); 6307 return nullptr; 6308 6309 case Intrinsic::annotation: 6310 case Intrinsic::ptr_annotation: 6311 case Intrinsic::launder_invariant_group: 6312 case Intrinsic::strip_invariant_group: 6313 // Drop the intrinsic, but forward the value 6314 setValue(&I, getValue(I.getOperand(0))); 6315 return nullptr; 6316 case Intrinsic::assume: 6317 case Intrinsic::var_annotation: 6318 case Intrinsic::sideeffect: 6319 // Discard annotate attributes, assumptions, and artificial side-effects. 6320 return nullptr; 6321 6322 case Intrinsic::codeview_annotation: { 6323 // Emit a label associated with this metadata. 6324 MachineFunction &MF = DAG.getMachineFunction(); 6325 MCSymbol *Label = 6326 MF.getMMI().getContext().createTempSymbol("annotation", true); 6327 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6328 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6329 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6330 DAG.setRoot(Res); 6331 return nullptr; 6332 } 6333 6334 case Intrinsic::init_trampoline: { 6335 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6336 6337 SDValue Ops[6]; 6338 Ops[0] = getRoot(); 6339 Ops[1] = getValue(I.getArgOperand(0)); 6340 Ops[2] = getValue(I.getArgOperand(1)); 6341 Ops[3] = getValue(I.getArgOperand(2)); 6342 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6343 Ops[5] = DAG.getSrcValue(F); 6344 6345 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6346 6347 DAG.setRoot(Res); 6348 return nullptr; 6349 } 6350 case Intrinsic::adjust_trampoline: 6351 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6352 TLI.getPointerTy(DAG.getDataLayout()), 6353 getValue(I.getArgOperand(0)))); 6354 return nullptr; 6355 case Intrinsic::gcroot: { 6356 assert(DAG.getMachineFunction().getFunction().hasGC() && 6357 "only valid in functions with gc specified, enforced by Verifier"); 6358 assert(GFI && "implied by previous"); 6359 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6360 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6361 6362 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6363 GFI->addStackRoot(FI->getIndex(), TypeMap); 6364 return nullptr; 6365 } 6366 case Intrinsic::gcread: 6367 case Intrinsic::gcwrite: 6368 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6369 case Intrinsic::flt_rounds: 6370 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32)); 6371 return nullptr; 6372 6373 case Intrinsic::expect: 6374 // Just replace __builtin_expect(exp, c) with EXP. 6375 setValue(&I, getValue(I.getArgOperand(0))); 6376 return nullptr; 6377 6378 case Intrinsic::debugtrap: 6379 case Intrinsic::trap: { 6380 StringRef TrapFuncName = 6381 I.getAttributes() 6382 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6383 .getValueAsString(); 6384 if (TrapFuncName.empty()) { 6385 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 6386 ISD::TRAP : ISD::DEBUGTRAP; 6387 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 6388 return nullptr; 6389 } 6390 TargetLowering::ArgListTy Args; 6391 6392 TargetLowering::CallLoweringInfo CLI(DAG); 6393 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6394 CallingConv::C, I.getType(), 6395 DAG.getExternalSymbol(TrapFuncName.data(), 6396 TLI.getPointerTy(DAG.getDataLayout())), 6397 std::move(Args)); 6398 6399 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6400 DAG.setRoot(Result.second); 6401 return nullptr; 6402 } 6403 6404 case Intrinsic::uadd_with_overflow: 6405 case Intrinsic::sadd_with_overflow: 6406 case Intrinsic::usub_with_overflow: 6407 case Intrinsic::ssub_with_overflow: 6408 case Intrinsic::umul_with_overflow: 6409 case Intrinsic::smul_with_overflow: { 6410 ISD::NodeType Op; 6411 switch (Intrinsic) { 6412 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6413 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6414 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6415 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6416 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6417 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6418 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6419 } 6420 SDValue Op1 = getValue(I.getArgOperand(0)); 6421 SDValue Op2 = getValue(I.getArgOperand(1)); 6422 6423 EVT ResultVT = Op1.getValueType(); 6424 EVT OverflowVT = MVT::i1; 6425 if (ResultVT.isVector()) 6426 OverflowVT = EVT::getVectorVT( 6427 *Context, OverflowVT, ResultVT.getVectorNumElements()); 6428 6429 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6430 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6431 return nullptr; 6432 } 6433 case Intrinsic::prefetch: { 6434 SDValue Ops[5]; 6435 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6436 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6437 Ops[0] = DAG.getRoot(); 6438 Ops[1] = getValue(I.getArgOperand(0)); 6439 Ops[2] = getValue(I.getArgOperand(1)); 6440 Ops[3] = getValue(I.getArgOperand(2)); 6441 Ops[4] = getValue(I.getArgOperand(3)); 6442 SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl, 6443 DAG.getVTList(MVT::Other), Ops, 6444 EVT::getIntegerVT(*Context, 8), 6445 MachinePointerInfo(I.getArgOperand(0)), 6446 0, /* align */ 6447 Flags); 6448 6449 // Chain the prefetch in parallell with any pending loads, to stay out of 6450 // the way of later optimizations. 6451 PendingLoads.push_back(Result); 6452 Result = getRoot(); 6453 DAG.setRoot(Result); 6454 return nullptr; 6455 } 6456 case Intrinsic::lifetime_start: 6457 case Intrinsic::lifetime_end: { 6458 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6459 // Stack coloring is not enabled in O0, discard region information. 6460 if (TM.getOptLevel() == CodeGenOpt::None) 6461 return nullptr; 6462 6463 const int64_t ObjectSize = 6464 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6465 Value *const ObjectPtr = I.getArgOperand(1); 6466 SmallVector<Value *, 4> Allocas; 6467 GetUnderlyingObjects(ObjectPtr, Allocas, *DL); 6468 6469 for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(), 6470 E = Allocas.end(); Object != E; ++Object) { 6471 AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 6472 6473 // Could not find an Alloca. 6474 if (!LifetimeObject) 6475 continue; 6476 6477 // First check that the Alloca is static, otherwise it won't have a 6478 // valid frame index. 6479 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6480 if (SI == FuncInfo.StaticAllocaMap.end()) 6481 return nullptr; 6482 6483 const int FrameIndex = SI->second; 6484 int64_t Offset; 6485 if (GetPointerBaseWithConstantOffset( 6486 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6487 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6488 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6489 Offset); 6490 DAG.setRoot(Res); 6491 } 6492 return nullptr; 6493 } 6494 case Intrinsic::invariant_start: 6495 // Discard region information. 6496 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6497 return nullptr; 6498 case Intrinsic::invariant_end: 6499 // Discard region information. 6500 return nullptr; 6501 case Intrinsic::clear_cache: 6502 return TLI.getClearCacheBuiltinName(); 6503 case Intrinsic::donothing: 6504 // ignore 6505 return nullptr; 6506 case Intrinsic::experimental_stackmap: 6507 visitStackmap(I); 6508 return nullptr; 6509 case Intrinsic::experimental_patchpoint_void: 6510 case Intrinsic::experimental_patchpoint_i64: 6511 visitPatchpoint(&I); 6512 return nullptr; 6513 case Intrinsic::experimental_gc_statepoint: 6514 LowerStatepoint(ImmutableStatepoint(&I)); 6515 return nullptr; 6516 case Intrinsic::experimental_gc_result: 6517 visitGCResult(cast<GCResultInst>(I)); 6518 return nullptr; 6519 case Intrinsic::experimental_gc_relocate: 6520 visitGCRelocate(cast<GCRelocateInst>(I)); 6521 return nullptr; 6522 case Intrinsic::instrprof_increment: 6523 llvm_unreachable("instrprof failed to lower an increment"); 6524 case Intrinsic::instrprof_value_profile: 6525 llvm_unreachable("instrprof failed to lower a value profiling call"); 6526 case Intrinsic::localescape: { 6527 MachineFunction &MF = DAG.getMachineFunction(); 6528 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6529 6530 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6531 // is the same on all targets. 6532 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6533 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6534 if (isa<ConstantPointerNull>(Arg)) 6535 continue; // Skip null pointers. They represent a hole in index space. 6536 AllocaInst *Slot = cast<AllocaInst>(Arg); 6537 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6538 "can only escape static allocas"); 6539 int FI = FuncInfo.StaticAllocaMap[Slot]; 6540 MCSymbol *FrameAllocSym = 6541 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6542 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6543 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6544 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6545 .addSym(FrameAllocSym) 6546 .addFrameIndex(FI); 6547 } 6548 6549 return nullptr; 6550 } 6551 6552 case Intrinsic::localrecover: { 6553 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6554 MachineFunction &MF = DAG.getMachineFunction(); 6555 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0); 6556 6557 // Get the symbol that defines the frame offset. 6558 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6559 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6560 unsigned IdxVal = 6561 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6562 MCSymbol *FrameAllocSym = 6563 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6564 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6565 6566 // Create a MCSymbol for the label to avoid any target lowering 6567 // that would make this PC relative. 6568 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6569 SDValue OffsetVal = 6570 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6571 6572 // Add the offset to the FP. 6573 Value *FP = I.getArgOperand(1); 6574 SDValue FPVal = getValue(FP); 6575 SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal); 6576 setValue(&I, Add); 6577 6578 return nullptr; 6579 } 6580 6581 case Intrinsic::eh_exceptionpointer: 6582 case Intrinsic::eh_exceptioncode: { 6583 // Get the exception pointer vreg, copy from it, and resize it to fit. 6584 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6585 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6586 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6587 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6588 SDValue N = 6589 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6590 if (Intrinsic == Intrinsic::eh_exceptioncode) 6591 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6592 setValue(&I, N); 6593 return nullptr; 6594 } 6595 case Intrinsic::xray_customevent: { 6596 // Here we want to make sure that the intrinsic behaves as if it has a 6597 // specific calling convention, and only for x86_64. 6598 // FIXME: Support other platforms later. 6599 const auto &Triple = DAG.getTarget().getTargetTriple(); 6600 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6601 return nullptr; 6602 6603 SDLoc DL = getCurSDLoc(); 6604 SmallVector<SDValue, 8> Ops; 6605 6606 // We want to say that we always want the arguments in registers. 6607 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6608 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6609 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6610 SDValue Chain = getRoot(); 6611 Ops.push_back(LogEntryVal); 6612 Ops.push_back(StrSizeVal); 6613 Ops.push_back(Chain); 6614 6615 // We need to enforce the calling convention for the callsite, so that 6616 // argument ordering is enforced correctly, and that register allocation can 6617 // see that some registers may be assumed clobbered and have to preserve 6618 // them across calls to the intrinsic. 6619 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6620 DL, NodeTys, Ops); 6621 SDValue patchableNode = SDValue(MN, 0); 6622 DAG.setRoot(patchableNode); 6623 setValue(&I, patchableNode); 6624 return nullptr; 6625 } 6626 case Intrinsic::xray_typedevent: { 6627 // Here we want to make sure that the intrinsic behaves as if it has a 6628 // specific calling convention, and only for x86_64. 6629 // FIXME: Support other platforms later. 6630 const auto &Triple = DAG.getTarget().getTargetTriple(); 6631 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6632 return nullptr; 6633 6634 SDLoc DL = getCurSDLoc(); 6635 SmallVector<SDValue, 8> Ops; 6636 6637 // We want to say that we always want the arguments in registers. 6638 // It's unclear to me how manipulating the selection DAG here forces callers 6639 // to provide arguments in registers instead of on the stack. 6640 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6641 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6642 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6643 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6644 SDValue Chain = getRoot(); 6645 Ops.push_back(LogTypeId); 6646 Ops.push_back(LogEntryVal); 6647 Ops.push_back(StrSizeVal); 6648 Ops.push_back(Chain); 6649 6650 // We need to enforce the calling convention for the callsite, so that 6651 // argument ordering is enforced correctly, and that register allocation can 6652 // see that some registers may be assumed clobbered and have to preserve 6653 // them across calls to the intrinsic. 6654 MachineSDNode *MN = DAG.getMachineNode( 6655 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6656 SDValue patchableNode = SDValue(MN, 0); 6657 DAG.setRoot(patchableNode); 6658 setValue(&I, patchableNode); 6659 return nullptr; 6660 } 6661 case Intrinsic::experimental_deoptimize: 6662 LowerDeoptimizeCall(&I); 6663 return nullptr; 6664 6665 case Intrinsic::experimental_vector_reduce_fadd: 6666 case Intrinsic::experimental_vector_reduce_fmul: 6667 case Intrinsic::experimental_vector_reduce_add: 6668 case Intrinsic::experimental_vector_reduce_mul: 6669 case Intrinsic::experimental_vector_reduce_and: 6670 case Intrinsic::experimental_vector_reduce_or: 6671 case Intrinsic::experimental_vector_reduce_xor: 6672 case Intrinsic::experimental_vector_reduce_smax: 6673 case Intrinsic::experimental_vector_reduce_smin: 6674 case Intrinsic::experimental_vector_reduce_umax: 6675 case Intrinsic::experimental_vector_reduce_umin: 6676 case Intrinsic::experimental_vector_reduce_fmax: 6677 case Intrinsic::experimental_vector_reduce_fmin: 6678 visitVectorReduce(I, Intrinsic); 6679 return nullptr; 6680 6681 case Intrinsic::icall_branch_funnel: { 6682 SmallVector<SDValue, 16> Ops; 6683 Ops.push_back(DAG.getRoot()); 6684 Ops.push_back(getValue(I.getArgOperand(0))); 6685 6686 int64_t Offset; 6687 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6688 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6689 if (!Base) 6690 report_fatal_error( 6691 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6692 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6693 6694 struct BranchFunnelTarget { 6695 int64_t Offset; 6696 SDValue Target; 6697 }; 6698 SmallVector<BranchFunnelTarget, 8> Targets; 6699 6700 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6701 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6702 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6703 if (ElemBase != Base) 6704 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6705 "to the same GlobalValue"); 6706 6707 SDValue Val = getValue(I.getArgOperand(Op + 1)); 6708 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 6709 if (!GA) 6710 report_fatal_error( 6711 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6712 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 6713 GA->getGlobal(), getCurSDLoc(), 6714 Val.getValueType(), GA->getOffset())}); 6715 } 6716 llvm::sort(Targets, 6717 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 6718 return T1.Offset < T2.Offset; 6719 }); 6720 6721 for (auto &T : Targets) { 6722 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 6723 Ops.push_back(T.Target); 6724 } 6725 6726 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 6727 getCurSDLoc(), MVT::Other, Ops), 6728 0); 6729 DAG.setRoot(N); 6730 setValue(&I, N); 6731 HasTailCall = true; 6732 return nullptr; 6733 } 6734 6735 case Intrinsic::wasm_landingpad_index: 6736 // Information this intrinsic contained has been transferred to 6737 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 6738 // delete it now. 6739 return nullptr; 6740 } 6741 } 6742 6743 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 6744 const ConstrainedFPIntrinsic &FPI) { 6745 SDLoc sdl = getCurSDLoc(); 6746 unsigned Opcode; 6747 switch (FPI.getIntrinsicID()) { 6748 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6749 case Intrinsic::experimental_constrained_fadd: 6750 Opcode = ISD::STRICT_FADD; 6751 break; 6752 case Intrinsic::experimental_constrained_fsub: 6753 Opcode = ISD::STRICT_FSUB; 6754 break; 6755 case Intrinsic::experimental_constrained_fmul: 6756 Opcode = ISD::STRICT_FMUL; 6757 break; 6758 case Intrinsic::experimental_constrained_fdiv: 6759 Opcode = ISD::STRICT_FDIV; 6760 break; 6761 case Intrinsic::experimental_constrained_frem: 6762 Opcode = ISD::STRICT_FREM; 6763 break; 6764 case Intrinsic::experimental_constrained_fma: 6765 Opcode = ISD::STRICT_FMA; 6766 break; 6767 case Intrinsic::experimental_constrained_sqrt: 6768 Opcode = ISD::STRICT_FSQRT; 6769 break; 6770 case Intrinsic::experimental_constrained_pow: 6771 Opcode = ISD::STRICT_FPOW; 6772 break; 6773 case Intrinsic::experimental_constrained_powi: 6774 Opcode = ISD::STRICT_FPOWI; 6775 break; 6776 case Intrinsic::experimental_constrained_sin: 6777 Opcode = ISD::STRICT_FSIN; 6778 break; 6779 case Intrinsic::experimental_constrained_cos: 6780 Opcode = ISD::STRICT_FCOS; 6781 break; 6782 case Intrinsic::experimental_constrained_exp: 6783 Opcode = ISD::STRICT_FEXP; 6784 break; 6785 case Intrinsic::experimental_constrained_exp2: 6786 Opcode = ISD::STRICT_FEXP2; 6787 break; 6788 case Intrinsic::experimental_constrained_log: 6789 Opcode = ISD::STRICT_FLOG; 6790 break; 6791 case Intrinsic::experimental_constrained_log10: 6792 Opcode = ISD::STRICT_FLOG10; 6793 break; 6794 case Intrinsic::experimental_constrained_log2: 6795 Opcode = ISD::STRICT_FLOG2; 6796 break; 6797 case Intrinsic::experimental_constrained_rint: 6798 Opcode = ISD::STRICT_FRINT; 6799 break; 6800 case Intrinsic::experimental_constrained_nearbyint: 6801 Opcode = ISD::STRICT_FNEARBYINT; 6802 break; 6803 case Intrinsic::experimental_constrained_maxnum: 6804 Opcode = ISD::STRICT_FMAXNUM; 6805 break; 6806 case Intrinsic::experimental_constrained_minnum: 6807 Opcode = ISD::STRICT_FMINNUM; 6808 break; 6809 case Intrinsic::experimental_constrained_ceil: 6810 Opcode = ISD::STRICT_FCEIL; 6811 break; 6812 case Intrinsic::experimental_constrained_floor: 6813 Opcode = ISD::STRICT_FFLOOR; 6814 break; 6815 case Intrinsic::experimental_constrained_round: 6816 Opcode = ISD::STRICT_FROUND; 6817 break; 6818 case Intrinsic::experimental_constrained_trunc: 6819 Opcode = ISD::STRICT_FTRUNC; 6820 break; 6821 } 6822 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6823 SDValue Chain = getRoot(); 6824 SmallVector<EVT, 4> ValueVTs; 6825 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 6826 ValueVTs.push_back(MVT::Other); // Out chain 6827 6828 SDVTList VTs = DAG.getVTList(ValueVTs); 6829 SDValue Result; 6830 if (FPI.isUnaryOp()) 6831 Result = DAG.getNode(Opcode, sdl, VTs, 6832 { Chain, getValue(FPI.getArgOperand(0)) }); 6833 else if (FPI.isTernaryOp()) 6834 Result = DAG.getNode(Opcode, sdl, VTs, 6835 { Chain, getValue(FPI.getArgOperand(0)), 6836 getValue(FPI.getArgOperand(1)), 6837 getValue(FPI.getArgOperand(2)) }); 6838 else 6839 Result = DAG.getNode(Opcode, sdl, VTs, 6840 { Chain, getValue(FPI.getArgOperand(0)), 6841 getValue(FPI.getArgOperand(1)) }); 6842 6843 assert(Result.getNode()->getNumValues() == 2); 6844 SDValue OutChain = Result.getValue(1); 6845 DAG.setRoot(OutChain); 6846 SDValue FPResult = Result.getValue(0); 6847 setValue(&FPI, FPResult); 6848 } 6849 6850 std::pair<SDValue, SDValue> 6851 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 6852 const BasicBlock *EHPadBB) { 6853 MachineFunction &MF = DAG.getMachineFunction(); 6854 MachineModuleInfo &MMI = MF.getMMI(); 6855 MCSymbol *BeginLabel = nullptr; 6856 6857 if (EHPadBB) { 6858 // Insert a label before the invoke call to mark the try range. This can be 6859 // used to detect deletion of the invoke via the MachineModuleInfo. 6860 BeginLabel = MMI.getContext().createTempSymbol(); 6861 6862 // For SjLj, keep track of which landing pads go with which invokes 6863 // so as to maintain the ordering of pads in the LSDA. 6864 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 6865 if (CallSiteIndex) { 6866 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 6867 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 6868 6869 // Now that the call site is handled, stop tracking it. 6870 MMI.setCurrentCallSite(0); 6871 } 6872 6873 // Both PendingLoads and PendingExports must be flushed here; 6874 // this call might not return. 6875 (void)getRoot(); 6876 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 6877 6878 CLI.setChain(getRoot()); 6879 } 6880 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6881 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6882 6883 assert((CLI.IsTailCall || Result.second.getNode()) && 6884 "Non-null chain expected with non-tail call!"); 6885 assert((Result.second.getNode() || !Result.first.getNode()) && 6886 "Null value expected with tail call!"); 6887 6888 if (!Result.second.getNode()) { 6889 // As a special case, a null chain means that a tail call has been emitted 6890 // and the DAG root is already updated. 6891 HasTailCall = true; 6892 6893 // Since there's no actual continuation from this block, nothing can be 6894 // relying on us setting vregs for them. 6895 PendingExports.clear(); 6896 } else { 6897 DAG.setRoot(Result.second); 6898 } 6899 6900 if (EHPadBB) { 6901 // Insert a label at the end of the invoke call to mark the try range. This 6902 // can be used to detect deletion of the invoke via the MachineModuleInfo. 6903 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 6904 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 6905 6906 // Inform MachineModuleInfo of range. 6907 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 6908 // There is a platform (e.g. wasm) that uses funclet style IR but does not 6909 // actually use outlined funclets and their LSDA info style. 6910 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 6911 assert(CLI.CS); 6912 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 6913 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()), 6914 BeginLabel, EndLabel); 6915 } else if (!isScopedEHPersonality(Pers)) { 6916 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 6917 } 6918 } 6919 6920 return Result; 6921 } 6922 6923 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee, 6924 bool isTailCall, 6925 const BasicBlock *EHPadBB) { 6926 auto &DL = DAG.getDataLayout(); 6927 FunctionType *FTy = CS.getFunctionType(); 6928 Type *RetTy = CS.getType(); 6929 6930 TargetLowering::ArgListTy Args; 6931 Args.reserve(CS.arg_size()); 6932 6933 const Value *SwiftErrorVal = nullptr; 6934 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6935 6936 // We can't tail call inside a function with a swifterror argument. Lowering 6937 // does not support this yet. It would have to move into the swifterror 6938 // register before the call. 6939 auto *Caller = CS.getInstruction()->getParent()->getParent(); 6940 if (TLI.supportSwiftError() && 6941 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 6942 isTailCall = false; 6943 6944 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 6945 i != e; ++i) { 6946 TargetLowering::ArgListEntry Entry; 6947 const Value *V = *i; 6948 6949 // Skip empty types 6950 if (V->getType()->isEmptyTy()) 6951 continue; 6952 6953 SDValue ArgNode = getValue(V); 6954 Entry.Node = ArgNode; Entry.Ty = V->getType(); 6955 6956 Entry.setAttributes(&CS, i - CS.arg_begin()); 6957 6958 // Use swifterror virtual register as input to the call. 6959 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 6960 SwiftErrorVal = V; 6961 // We find the virtual register for the actual swifterror argument. 6962 // Instead of using the Value, we use the virtual register instead. 6963 Entry.Node = DAG.getRegister(FuncInfo 6964 .getOrCreateSwiftErrorVRegUseAt( 6965 CS.getInstruction(), FuncInfo.MBB, V) 6966 .first, 6967 EVT(TLI.getPointerTy(DL))); 6968 } 6969 6970 Args.push_back(Entry); 6971 6972 // If we have an explicit sret argument that is an Instruction, (i.e., it 6973 // might point to function-local memory), we can't meaningfully tail-call. 6974 if (Entry.IsSRet && isa<Instruction>(V)) 6975 isTailCall = false; 6976 } 6977 6978 // Check if target-independent constraints permit a tail call here. 6979 // Target-dependent constraints are checked within TLI->LowerCallTo. 6980 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget())) 6981 isTailCall = false; 6982 6983 // Disable tail calls if there is an swifterror argument. Targets have not 6984 // been updated to support tail calls. 6985 if (TLI.supportSwiftError() && SwiftErrorVal) 6986 isTailCall = false; 6987 6988 TargetLowering::CallLoweringInfo CLI(DAG); 6989 CLI.setDebugLoc(getCurSDLoc()) 6990 .setChain(getRoot()) 6991 .setCallee(RetTy, FTy, Callee, std::move(Args), CS) 6992 .setTailCall(isTailCall) 6993 .setConvergent(CS.isConvergent()); 6994 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 6995 6996 if (Result.first.getNode()) { 6997 const Instruction *Inst = CS.getInstruction(); 6998 Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first); 6999 setValue(Inst, Result.first); 7000 } 7001 7002 // The last element of CLI.InVals has the SDValue for swifterror return. 7003 // Here we copy it to a virtual register and update SwiftErrorMap for 7004 // book-keeping. 7005 if (SwiftErrorVal && TLI.supportSwiftError()) { 7006 // Get the last element of InVals. 7007 SDValue Src = CLI.InVals.back(); 7008 unsigned VReg; bool CreatedVReg; 7009 std::tie(VReg, CreatedVReg) = 7010 FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction()); 7011 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7012 // We update the virtual register for the actual swifterror argument. 7013 if (CreatedVReg) 7014 FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg); 7015 DAG.setRoot(CopyNode); 7016 } 7017 } 7018 7019 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7020 SelectionDAGBuilder &Builder) { 7021 // Check to see if this load can be trivially constant folded, e.g. if the 7022 // input is from a string literal. 7023 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7024 // Cast pointer to the type we really want to load. 7025 Type *LoadTy = 7026 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7027 if (LoadVT.isVector()) 7028 LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7029 7030 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7031 PointerType::getUnqual(LoadTy)); 7032 7033 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 7034 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 7035 return Builder.getValue(LoadCst); 7036 } 7037 7038 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7039 // still constant memory, the input chain can be the entry node. 7040 SDValue Root; 7041 bool ConstantMemory = false; 7042 7043 // Do not serialize (non-volatile) loads of constant memory with anything. 7044 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7045 Root = Builder.DAG.getEntryNode(); 7046 ConstantMemory = true; 7047 } else { 7048 // Do not serialize non-volatile loads against each other. 7049 Root = Builder.DAG.getRoot(); 7050 } 7051 7052 SDValue Ptr = Builder.getValue(PtrVal); 7053 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, 7054 Ptr, MachinePointerInfo(PtrVal), 7055 /* Alignment = */ 1); 7056 7057 if (!ConstantMemory) 7058 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7059 return LoadVal; 7060 } 7061 7062 /// Record the value for an instruction that produces an integer result, 7063 /// converting the type where necessary. 7064 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7065 SDValue Value, 7066 bool IsSigned) { 7067 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7068 I.getType(), true); 7069 if (IsSigned) 7070 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7071 else 7072 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7073 setValue(&I, Value); 7074 } 7075 7076 /// See if we can lower a memcmp call into an optimized form. If so, return 7077 /// true and lower it. Otherwise return false, and it will be lowered like a 7078 /// normal call. 7079 /// The caller already checked that \p I calls the appropriate LibFunc with a 7080 /// correct prototype. 7081 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 7082 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 7083 const Value *Size = I.getArgOperand(2); 7084 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 7085 if (CSize && CSize->getZExtValue() == 0) { 7086 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7087 I.getType(), true); 7088 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 7089 return true; 7090 } 7091 7092 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7093 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 7094 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 7095 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 7096 if (Res.first.getNode()) { 7097 processIntegerCallValue(I, Res.first, true); 7098 PendingLoads.push_back(Res.second); 7099 return true; 7100 } 7101 7102 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 7103 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 7104 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 7105 return false; 7106 7107 // If the target has a fast compare for the given size, it will return a 7108 // preferred load type for that size. Require that the load VT is legal and 7109 // that the target supports unaligned loads of that type. Otherwise, return 7110 // INVALID. 7111 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 7112 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7113 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 7114 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 7115 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 7116 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 7117 // TODO: Check alignment of src and dest ptrs. 7118 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 7119 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 7120 if (!TLI.isTypeLegal(LVT) || 7121 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 7122 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 7123 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 7124 } 7125 7126 return LVT; 7127 }; 7128 7129 // This turns into unaligned loads. We only do this if the target natively 7130 // supports the MVT we'll be loading or if it is small enough (<= 4) that 7131 // we'll only produce a small number of byte loads. 7132 MVT LoadVT; 7133 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 7134 switch (NumBitsToCompare) { 7135 default: 7136 return false; 7137 case 16: 7138 LoadVT = MVT::i16; 7139 break; 7140 case 32: 7141 LoadVT = MVT::i32; 7142 break; 7143 case 64: 7144 case 128: 7145 case 256: 7146 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 7147 break; 7148 } 7149 7150 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 7151 return false; 7152 7153 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 7154 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 7155 7156 // Bitcast to a wide integer type if the loads are vectors. 7157 if (LoadVT.isVector()) { 7158 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 7159 LoadL = DAG.getBitcast(CmpVT, LoadL); 7160 LoadR = DAG.getBitcast(CmpVT, LoadR); 7161 } 7162 7163 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 7164 processIntegerCallValue(I, Cmp, false); 7165 return true; 7166 } 7167 7168 /// See if we can lower a memchr call into an optimized form. If so, return 7169 /// true and lower it. Otherwise return false, and it will be lowered like a 7170 /// normal call. 7171 /// The caller already checked that \p I calls the appropriate LibFunc with a 7172 /// correct prototype. 7173 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 7174 const Value *Src = I.getArgOperand(0); 7175 const Value *Char = I.getArgOperand(1); 7176 const Value *Length = I.getArgOperand(2); 7177 7178 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7179 std::pair<SDValue, SDValue> Res = 7180 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 7181 getValue(Src), getValue(Char), getValue(Length), 7182 MachinePointerInfo(Src)); 7183 if (Res.first.getNode()) { 7184 setValue(&I, Res.first); 7185 PendingLoads.push_back(Res.second); 7186 return true; 7187 } 7188 7189 return false; 7190 } 7191 7192 /// See if we can lower a mempcpy call into an optimized form. If so, return 7193 /// true and lower it. Otherwise return false, and it will be lowered like a 7194 /// normal call. 7195 /// The caller already checked that \p I calls the appropriate LibFunc with a 7196 /// correct prototype. 7197 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 7198 SDValue Dst = getValue(I.getArgOperand(0)); 7199 SDValue Src = getValue(I.getArgOperand(1)); 7200 SDValue Size = getValue(I.getArgOperand(2)); 7201 7202 unsigned DstAlign = DAG.InferPtrAlignment(Dst); 7203 unsigned SrcAlign = DAG.InferPtrAlignment(Src); 7204 unsigned Align = std::min(DstAlign, SrcAlign); 7205 if (Align == 0) // Alignment of one or both could not be inferred. 7206 Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved. 7207 7208 bool isVol = false; 7209 SDLoc sdl = getCurSDLoc(); 7210 7211 // In the mempcpy context we need to pass in a false value for isTailCall 7212 // because the return pointer needs to be adjusted by the size of 7213 // the copied memory. 7214 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol, 7215 false, /*isTailCall=*/false, 7216 MachinePointerInfo(I.getArgOperand(0)), 7217 MachinePointerInfo(I.getArgOperand(1))); 7218 assert(MC.getNode() != nullptr && 7219 "** memcpy should not be lowered as TailCall in mempcpy context **"); 7220 DAG.setRoot(MC); 7221 7222 // Check if Size needs to be truncated or extended. 7223 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 7224 7225 // Adjust return pointer to point just past the last dst byte. 7226 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 7227 Dst, Size); 7228 setValue(&I, DstPlusSize); 7229 return true; 7230 } 7231 7232 /// See if we can lower a strcpy call into an optimized form. If so, return 7233 /// true and lower it, otherwise return false and it will be lowered like a 7234 /// normal call. 7235 /// The caller already checked that \p I calls the appropriate LibFunc with a 7236 /// correct prototype. 7237 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 7238 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7239 7240 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7241 std::pair<SDValue, SDValue> Res = 7242 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 7243 getValue(Arg0), getValue(Arg1), 7244 MachinePointerInfo(Arg0), 7245 MachinePointerInfo(Arg1), isStpcpy); 7246 if (Res.first.getNode()) { 7247 setValue(&I, Res.first); 7248 DAG.setRoot(Res.second); 7249 return true; 7250 } 7251 7252 return false; 7253 } 7254 7255 /// See if we can lower a strcmp call into an optimized form. If so, return 7256 /// true and lower it, otherwise return false and it will be lowered like a 7257 /// normal call. 7258 /// The caller already checked that \p I calls the appropriate LibFunc with a 7259 /// correct prototype. 7260 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 7261 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7262 7263 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7264 std::pair<SDValue, SDValue> Res = 7265 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 7266 getValue(Arg0), getValue(Arg1), 7267 MachinePointerInfo(Arg0), 7268 MachinePointerInfo(Arg1)); 7269 if (Res.first.getNode()) { 7270 processIntegerCallValue(I, Res.first, true); 7271 PendingLoads.push_back(Res.second); 7272 return true; 7273 } 7274 7275 return false; 7276 } 7277 7278 /// See if we can lower a strlen call into an optimized form. If so, return 7279 /// true and lower it, otherwise return false and it will be lowered like a 7280 /// normal call. 7281 /// The caller already checked that \p I calls the appropriate LibFunc with a 7282 /// correct prototype. 7283 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 7284 const Value *Arg0 = I.getArgOperand(0); 7285 7286 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7287 std::pair<SDValue, SDValue> Res = 7288 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 7289 getValue(Arg0), MachinePointerInfo(Arg0)); 7290 if (Res.first.getNode()) { 7291 processIntegerCallValue(I, Res.first, false); 7292 PendingLoads.push_back(Res.second); 7293 return true; 7294 } 7295 7296 return false; 7297 } 7298 7299 /// See if we can lower a strnlen call into an optimized form. If so, return 7300 /// true and lower it, otherwise return false and it will be lowered like a 7301 /// normal call. 7302 /// The caller already checked that \p I calls the appropriate LibFunc with a 7303 /// correct prototype. 7304 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 7305 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7306 7307 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7308 std::pair<SDValue, SDValue> Res = 7309 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 7310 getValue(Arg0), getValue(Arg1), 7311 MachinePointerInfo(Arg0)); 7312 if (Res.first.getNode()) { 7313 processIntegerCallValue(I, Res.first, false); 7314 PendingLoads.push_back(Res.second); 7315 return true; 7316 } 7317 7318 return false; 7319 } 7320 7321 /// See if we can lower a unary floating-point operation into an SDNode with 7322 /// the specified Opcode. If so, return true and lower it, otherwise return 7323 /// false and it will be lowered like a normal call. 7324 /// The caller already checked that \p I calls the appropriate LibFunc with a 7325 /// correct prototype. 7326 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 7327 unsigned Opcode) { 7328 // We already checked this call's prototype; verify it doesn't modify errno. 7329 if (!I.onlyReadsMemory()) 7330 return false; 7331 7332 SDValue Tmp = getValue(I.getArgOperand(0)); 7333 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); 7334 return true; 7335 } 7336 7337 /// See if we can lower a binary floating-point operation into an SDNode with 7338 /// the specified Opcode. If so, return true and lower it. Otherwise return 7339 /// false, and it will be lowered like a normal call. 7340 /// The caller already checked that \p I calls the appropriate LibFunc with a 7341 /// correct prototype. 7342 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 7343 unsigned Opcode) { 7344 // We already checked this call's prototype; verify it doesn't modify errno. 7345 if (!I.onlyReadsMemory()) 7346 return false; 7347 7348 SDValue Tmp0 = getValue(I.getArgOperand(0)); 7349 SDValue Tmp1 = getValue(I.getArgOperand(1)); 7350 EVT VT = Tmp0.getValueType(); 7351 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1)); 7352 return true; 7353 } 7354 7355 void SelectionDAGBuilder::visitCall(const CallInst &I) { 7356 // Handle inline assembly differently. 7357 if (isa<InlineAsm>(I.getCalledValue())) { 7358 visitInlineAsm(&I); 7359 return; 7360 } 7361 7362 const char *RenameFn = nullptr; 7363 if (Function *F = I.getCalledFunction()) { 7364 if (F->isDeclaration()) { 7365 // Is this an LLVM intrinsic or a target-specific intrinsic? 7366 unsigned IID = F->getIntrinsicID(); 7367 if (!IID) 7368 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7369 IID = II->getIntrinsicID(F); 7370 7371 if (IID) { 7372 RenameFn = visitIntrinsicCall(I, IID); 7373 if (!RenameFn) 7374 return; 7375 } 7376 } 7377 7378 // Check for well-known libc/libm calls. If the function is internal, it 7379 // can't be a library call. Don't do the check if marked as nobuiltin for 7380 // some reason or the call site requires strict floating point semantics. 7381 LibFunc Func; 7382 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7383 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7384 LibInfo->hasOptimizedCodeGen(Func)) { 7385 switch (Func) { 7386 default: break; 7387 case LibFunc_copysign: 7388 case LibFunc_copysignf: 7389 case LibFunc_copysignl: 7390 // We already checked this call's prototype; verify it doesn't modify 7391 // errno. 7392 if (I.onlyReadsMemory()) { 7393 SDValue LHS = getValue(I.getArgOperand(0)); 7394 SDValue RHS = getValue(I.getArgOperand(1)); 7395 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7396 LHS.getValueType(), LHS, RHS)); 7397 return; 7398 } 7399 break; 7400 case LibFunc_fabs: 7401 case LibFunc_fabsf: 7402 case LibFunc_fabsl: 7403 if (visitUnaryFloatCall(I, ISD::FABS)) 7404 return; 7405 break; 7406 case LibFunc_fmin: 7407 case LibFunc_fminf: 7408 case LibFunc_fminl: 7409 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7410 return; 7411 break; 7412 case LibFunc_fmax: 7413 case LibFunc_fmaxf: 7414 case LibFunc_fmaxl: 7415 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7416 return; 7417 break; 7418 case LibFunc_sin: 7419 case LibFunc_sinf: 7420 case LibFunc_sinl: 7421 if (visitUnaryFloatCall(I, ISD::FSIN)) 7422 return; 7423 break; 7424 case LibFunc_cos: 7425 case LibFunc_cosf: 7426 case LibFunc_cosl: 7427 if (visitUnaryFloatCall(I, ISD::FCOS)) 7428 return; 7429 break; 7430 case LibFunc_sqrt: 7431 case LibFunc_sqrtf: 7432 case LibFunc_sqrtl: 7433 case LibFunc_sqrt_finite: 7434 case LibFunc_sqrtf_finite: 7435 case LibFunc_sqrtl_finite: 7436 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7437 return; 7438 break; 7439 case LibFunc_floor: 7440 case LibFunc_floorf: 7441 case LibFunc_floorl: 7442 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7443 return; 7444 break; 7445 case LibFunc_nearbyint: 7446 case LibFunc_nearbyintf: 7447 case LibFunc_nearbyintl: 7448 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7449 return; 7450 break; 7451 case LibFunc_ceil: 7452 case LibFunc_ceilf: 7453 case LibFunc_ceill: 7454 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7455 return; 7456 break; 7457 case LibFunc_rint: 7458 case LibFunc_rintf: 7459 case LibFunc_rintl: 7460 if (visitUnaryFloatCall(I, ISD::FRINT)) 7461 return; 7462 break; 7463 case LibFunc_round: 7464 case LibFunc_roundf: 7465 case LibFunc_roundl: 7466 if (visitUnaryFloatCall(I, ISD::FROUND)) 7467 return; 7468 break; 7469 case LibFunc_trunc: 7470 case LibFunc_truncf: 7471 case LibFunc_truncl: 7472 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7473 return; 7474 break; 7475 case LibFunc_log2: 7476 case LibFunc_log2f: 7477 case LibFunc_log2l: 7478 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7479 return; 7480 break; 7481 case LibFunc_exp2: 7482 case LibFunc_exp2f: 7483 case LibFunc_exp2l: 7484 if (visitUnaryFloatCall(I, ISD::FEXP2)) 7485 return; 7486 break; 7487 case LibFunc_memcmp: 7488 if (visitMemCmpCall(I)) 7489 return; 7490 break; 7491 case LibFunc_mempcpy: 7492 if (visitMemPCpyCall(I)) 7493 return; 7494 break; 7495 case LibFunc_memchr: 7496 if (visitMemChrCall(I)) 7497 return; 7498 break; 7499 case LibFunc_strcpy: 7500 if (visitStrCpyCall(I, false)) 7501 return; 7502 break; 7503 case LibFunc_stpcpy: 7504 if (visitStrCpyCall(I, true)) 7505 return; 7506 break; 7507 case LibFunc_strcmp: 7508 if (visitStrCmpCall(I)) 7509 return; 7510 break; 7511 case LibFunc_strlen: 7512 if (visitStrLenCall(I)) 7513 return; 7514 break; 7515 case LibFunc_strnlen: 7516 if (visitStrNLenCall(I)) 7517 return; 7518 break; 7519 } 7520 } 7521 } 7522 7523 SDValue Callee; 7524 if (!RenameFn) 7525 Callee = getValue(I.getCalledValue()); 7526 else 7527 Callee = DAG.getExternalSymbol( 7528 RenameFn, 7529 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 7530 7531 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 7532 // have to do anything here to lower funclet bundles. 7533 assert(!I.hasOperandBundlesOtherThan( 7534 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 7535 "Cannot lower calls with arbitrary operand bundles!"); 7536 7537 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 7538 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 7539 else 7540 // Check if we can potentially perform a tail call. More detailed checking 7541 // is be done within LowerCallTo, after more information about the call is 7542 // known. 7543 LowerCallTo(&I, Callee, I.isTailCall()); 7544 } 7545 7546 namespace { 7547 7548 /// AsmOperandInfo - This contains information for each constraint that we are 7549 /// lowering. 7550 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 7551 public: 7552 /// CallOperand - If this is the result output operand or a clobber 7553 /// this is null, otherwise it is the incoming operand to the CallInst. 7554 /// This gets modified as the asm is processed. 7555 SDValue CallOperand; 7556 7557 /// AssignedRegs - If this is a register or register class operand, this 7558 /// contains the set of register corresponding to the operand. 7559 RegsForValue AssignedRegs; 7560 7561 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 7562 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 7563 } 7564 7565 /// Whether or not this operand accesses memory 7566 bool hasMemory(const TargetLowering &TLI) const { 7567 // Indirect operand accesses access memory. 7568 if (isIndirect) 7569 return true; 7570 7571 for (const auto &Code : Codes) 7572 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 7573 return true; 7574 7575 return false; 7576 } 7577 7578 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 7579 /// corresponds to. If there is no Value* for this operand, it returns 7580 /// MVT::Other. 7581 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 7582 const DataLayout &DL) const { 7583 if (!CallOperandVal) return MVT::Other; 7584 7585 if (isa<BasicBlock>(CallOperandVal)) 7586 return TLI.getPointerTy(DL); 7587 7588 llvm::Type *OpTy = CallOperandVal->getType(); 7589 7590 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 7591 // If this is an indirect operand, the operand is a pointer to the 7592 // accessed type. 7593 if (isIndirect) { 7594 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 7595 if (!PtrTy) 7596 report_fatal_error("Indirect operand for inline asm not a pointer!"); 7597 OpTy = PtrTy->getElementType(); 7598 } 7599 7600 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 7601 if (StructType *STy = dyn_cast<StructType>(OpTy)) 7602 if (STy->getNumElements() == 1) 7603 OpTy = STy->getElementType(0); 7604 7605 // If OpTy is not a single value, it may be a struct/union that we 7606 // can tile with integers. 7607 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 7608 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 7609 switch (BitSize) { 7610 default: break; 7611 case 1: 7612 case 8: 7613 case 16: 7614 case 32: 7615 case 64: 7616 case 128: 7617 OpTy = IntegerType::get(Context, BitSize); 7618 break; 7619 } 7620 } 7621 7622 return TLI.getValueType(DL, OpTy, true); 7623 } 7624 }; 7625 7626 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>; 7627 7628 } // end anonymous namespace 7629 7630 /// Make sure that the output operand \p OpInfo and its corresponding input 7631 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 7632 /// out). 7633 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 7634 SDISelAsmOperandInfo &MatchingOpInfo, 7635 SelectionDAG &DAG) { 7636 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 7637 return; 7638 7639 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 7640 const auto &TLI = DAG.getTargetLoweringInfo(); 7641 7642 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 7643 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 7644 OpInfo.ConstraintVT); 7645 std::pair<unsigned, const TargetRegisterClass *> InputRC = 7646 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 7647 MatchingOpInfo.ConstraintVT); 7648 if ((OpInfo.ConstraintVT.isInteger() != 7649 MatchingOpInfo.ConstraintVT.isInteger()) || 7650 (MatchRC.second != InputRC.second)) { 7651 // FIXME: error out in a more elegant fashion 7652 report_fatal_error("Unsupported asm: input constraint" 7653 " with a matching output constraint of" 7654 " incompatible type!"); 7655 } 7656 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 7657 } 7658 7659 /// Get a direct memory input to behave well as an indirect operand. 7660 /// This may introduce stores, hence the need for a \p Chain. 7661 /// \return The (possibly updated) chain. 7662 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 7663 SDISelAsmOperandInfo &OpInfo, 7664 SelectionDAG &DAG) { 7665 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7666 7667 // If we don't have an indirect input, put it in the constpool if we can, 7668 // otherwise spill it to a stack slot. 7669 // TODO: This isn't quite right. We need to handle these according to 7670 // the addressing mode that the constraint wants. Also, this may take 7671 // an additional register for the computation and we don't want that 7672 // either. 7673 7674 // If the operand is a float, integer, or vector constant, spill to a 7675 // constant pool entry to get its address. 7676 const Value *OpVal = OpInfo.CallOperandVal; 7677 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 7678 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 7679 OpInfo.CallOperand = DAG.getConstantPool( 7680 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 7681 return Chain; 7682 } 7683 7684 // Otherwise, create a stack slot and emit a store to it before the asm. 7685 Type *Ty = OpVal->getType(); 7686 auto &DL = DAG.getDataLayout(); 7687 uint64_t TySize = DL.getTypeAllocSize(Ty); 7688 unsigned Align = DL.getPrefTypeAlignment(Ty); 7689 MachineFunction &MF = DAG.getMachineFunction(); 7690 int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 7691 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 7692 Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot, 7693 MachinePointerInfo::getFixedStack(MF, SSFI)); 7694 OpInfo.CallOperand = StackSlot; 7695 7696 return Chain; 7697 } 7698 7699 /// GetRegistersForValue - Assign registers (virtual or physical) for the 7700 /// specified operand. We prefer to assign virtual registers, to allow the 7701 /// register allocator to handle the assignment process. However, if the asm 7702 /// uses features that we can't model on machineinstrs, we have SDISel do the 7703 /// allocation. This produces generally horrible, but correct, code. 7704 /// 7705 /// OpInfo describes the operand 7706 /// RefOpInfo describes the matching operand if any, the operand otherwise 7707 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 7708 SDISelAsmOperandInfo &OpInfo, 7709 SDISelAsmOperandInfo &RefOpInfo) { 7710 LLVMContext &Context = *DAG.getContext(); 7711 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7712 7713 MachineFunction &MF = DAG.getMachineFunction(); 7714 SmallVector<unsigned, 4> Regs; 7715 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 7716 7717 // No work to do for memory operations. 7718 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 7719 return; 7720 7721 // If this is a constraint for a single physreg, or a constraint for a 7722 // register class, find it. 7723 unsigned AssignedReg; 7724 const TargetRegisterClass *RC; 7725 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 7726 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 7727 // RC is unset only on failure. Return immediately. 7728 if (!RC) 7729 return; 7730 7731 // Get the actual register value type. This is important, because the user 7732 // may have asked for (e.g.) the AX register in i32 type. We need to 7733 // remember that AX is actually i16 to get the right extension. 7734 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 7735 7736 if (OpInfo.ConstraintVT != MVT::Other) { 7737 // If this is an FP operand in an integer register (or visa versa), or more 7738 // generally if the operand value disagrees with the register class we plan 7739 // to stick it in, fix the operand type. 7740 // 7741 // If this is an input value, the bitcast to the new type is done now. 7742 // Bitcast for output value is done at the end of visitInlineAsm(). 7743 if ((OpInfo.Type == InlineAsm::isOutput || 7744 OpInfo.Type == InlineAsm::isInput) && 7745 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 7746 // Try to convert to the first EVT that the reg class contains. If the 7747 // types are identical size, use a bitcast to convert (e.g. two differing 7748 // vector types). Note: output bitcast is done at the end of 7749 // visitInlineAsm(). 7750 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 7751 // Exclude indirect inputs while they are unsupported because the code 7752 // to perform the load is missing and thus OpInfo.CallOperand still 7753 // refers to the input address rather than the pointed-to value. 7754 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 7755 OpInfo.CallOperand = 7756 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 7757 OpInfo.ConstraintVT = RegVT; 7758 // If the operand is an FP value and we want it in integer registers, 7759 // use the corresponding integer type. This turns an f64 value into 7760 // i64, which can be passed with two i32 values on a 32-bit machine. 7761 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 7762 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 7763 if (OpInfo.Type == InlineAsm::isInput) 7764 OpInfo.CallOperand = 7765 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 7766 OpInfo.ConstraintVT = VT; 7767 } 7768 } 7769 } 7770 7771 // No need to allocate a matching input constraint since the constraint it's 7772 // matching to has already been allocated. 7773 if (OpInfo.isMatchingInputConstraint()) 7774 return; 7775 7776 EVT ValueVT = OpInfo.ConstraintVT; 7777 if (OpInfo.ConstraintVT == MVT::Other) 7778 ValueVT = RegVT; 7779 7780 // Initialize NumRegs. 7781 unsigned NumRegs = 1; 7782 if (OpInfo.ConstraintVT != MVT::Other) 7783 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 7784 7785 // If this is a constraint for a specific physical register, like {r17}, 7786 // assign it now. 7787 7788 // If this associated to a specific register, initialize iterator to correct 7789 // place. If virtual, make sure we have enough registers 7790 7791 // Initialize iterator if necessary 7792 TargetRegisterClass::iterator I = RC->begin(); 7793 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7794 7795 // Do not check for single registers. 7796 if (AssignedReg) { 7797 for (; *I != AssignedReg; ++I) 7798 assert(I != RC->end() && "AssignedReg should be member of RC"); 7799 } 7800 7801 for (; NumRegs; --NumRegs, ++I) { 7802 assert(I != RC->end() && "Ran out of registers to allocate!"); 7803 auto R = (AssignedReg) ? *I : RegInfo.createVirtualRegister(RC); 7804 Regs.push_back(R); 7805 } 7806 7807 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 7808 } 7809 7810 static unsigned 7811 findMatchingInlineAsmOperand(unsigned OperandNo, 7812 const std::vector<SDValue> &AsmNodeOperands) { 7813 // Scan until we find the definition we already emitted of this operand. 7814 unsigned CurOp = InlineAsm::Op_FirstOperand; 7815 for (; OperandNo; --OperandNo) { 7816 // Advance to the next operand. 7817 unsigned OpFlag = 7818 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7819 assert((InlineAsm::isRegDefKind(OpFlag) || 7820 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 7821 InlineAsm::isMemKind(OpFlag)) && 7822 "Skipped past definitions?"); 7823 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 7824 } 7825 return CurOp; 7826 } 7827 7828 namespace { 7829 7830 class ExtraFlags { 7831 unsigned Flags = 0; 7832 7833 public: 7834 explicit ExtraFlags(ImmutableCallSite CS) { 7835 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7836 if (IA->hasSideEffects()) 7837 Flags |= InlineAsm::Extra_HasSideEffects; 7838 if (IA->isAlignStack()) 7839 Flags |= InlineAsm::Extra_IsAlignStack; 7840 if (CS.isConvergent()) 7841 Flags |= InlineAsm::Extra_IsConvergent; 7842 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 7843 } 7844 7845 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 7846 // Ideally, we would only check against memory constraints. However, the 7847 // meaning of an Other constraint can be target-specific and we can't easily 7848 // reason about it. Therefore, be conservative and set MayLoad/MayStore 7849 // for Other constraints as well. 7850 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 7851 OpInfo.ConstraintType == TargetLowering::C_Other) { 7852 if (OpInfo.Type == InlineAsm::isInput) 7853 Flags |= InlineAsm::Extra_MayLoad; 7854 else if (OpInfo.Type == InlineAsm::isOutput) 7855 Flags |= InlineAsm::Extra_MayStore; 7856 else if (OpInfo.Type == InlineAsm::isClobber) 7857 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 7858 } 7859 } 7860 7861 unsigned get() const { return Flags; } 7862 }; 7863 7864 } // end anonymous namespace 7865 7866 /// visitInlineAsm - Handle a call to an InlineAsm object. 7867 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) { 7868 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7869 7870 /// ConstraintOperands - Information about all of the constraints. 7871 SDISelAsmOperandInfoVector ConstraintOperands; 7872 7873 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7874 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 7875 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS); 7876 7877 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 7878 // AsmDialect, MayLoad, MayStore). 7879 bool HasSideEffect = IA->hasSideEffects(); 7880 ExtraFlags ExtraInfo(CS); 7881 7882 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 7883 unsigned ResNo = 0; // ResNo - The result number of the next output. 7884 for (auto &T : TargetConstraints) { 7885 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 7886 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 7887 7888 // Compute the value type for each operand. 7889 if (OpInfo.Type == InlineAsm::isInput || 7890 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 7891 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 7892 7893 // Process the call argument. BasicBlocks are labels, currently appearing 7894 // only in asm's. 7895 const Instruction *I = CS.getInstruction(); 7896 if (isa<CallBrInst>(I) && 7897 (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() - 7898 cast<CallBrInst>(I)->getNumIndirectDests())) { 7899 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal); 7900 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true); 7901 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT); 7902 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 7903 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 7904 } else { 7905 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 7906 } 7907 7908 OpInfo.ConstraintVT = 7909 OpInfo 7910 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout()) 7911 .getSimpleVT(); 7912 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 7913 // The return value of the call is this value. As such, there is no 7914 // corresponding argument. 7915 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 7916 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 7917 OpInfo.ConstraintVT = TLI.getSimpleValueType( 7918 DAG.getDataLayout(), STy->getElementType(ResNo)); 7919 } else { 7920 assert(ResNo == 0 && "Asm only has one result!"); 7921 OpInfo.ConstraintVT = 7922 TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType()); 7923 } 7924 ++ResNo; 7925 } else { 7926 OpInfo.ConstraintVT = MVT::Other; 7927 } 7928 7929 if (!HasSideEffect) 7930 HasSideEffect = OpInfo.hasMemory(TLI); 7931 7932 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 7933 // FIXME: Could we compute this on OpInfo rather than T? 7934 7935 // Compute the constraint code and ConstraintType to use. 7936 TLI.ComputeConstraintToUse(T, SDValue()); 7937 7938 ExtraInfo.update(T); 7939 } 7940 7941 // We won't need to flush pending loads if this asm doesn't touch 7942 // memory and is nonvolatile. 7943 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 7944 7945 // Second pass over the constraints: compute which constraint option to use. 7946 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 7947 // If this is an output operand with a matching input operand, look up the 7948 // matching input. If their types mismatch, e.g. one is an integer, the 7949 // other is floating point, or their sizes are different, flag it as an 7950 // error. 7951 if (OpInfo.hasMatchingInput()) { 7952 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 7953 patchMatchingInput(OpInfo, Input, DAG); 7954 } 7955 7956 // Compute the constraint code and ConstraintType to use. 7957 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 7958 7959 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 7960 OpInfo.Type == InlineAsm::isClobber) 7961 continue; 7962 7963 // If this is a memory input, and if the operand is not indirect, do what we 7964 // need to provide an address for the memory input. 7965 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 7966 !OpInfo.isIndirect) { 7967 assert((OpInfo.isMultipleAlternative || 7968 (OpInfo.Type == InlineAsm::isInput)) && 7969 "Can only indirectify direct input operands!"); 7970 7971 // Memory operands really want the address of the value. 7972 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 7973 7974 // There is no longer a Value* corresponding to this operand. 7975 OpInfo.CallOperandVal = nullptr; 7976 7977 // It is now an indirect operand. 7978 OpInfo.isIndirect = true; 7979 } 7980 7981 } 7982 7983 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 7984 std::vector<SDValue> AsmNodeOperands; 7985 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 7986 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 7987 IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout()))); 7988 7989 // If we have a !srcloc metadata node associated with it, we want to attach 7990 // this to the ultimately generated inline asm machineinstr. To do this, we 7991 // pass in the third operand as this (potentially null) inline asm MDNode. 7992 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc"); 7993 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 7994 7995 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 7996 // bits as operand 3. 7997 AsmNodeOperands.push_back(DAG.getTargetConstant( 7998 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7999 8000 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8001 // this, assign virtual and physical registers for inputs and otput. 8002 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8003 // Assign Registers. 8004 SDISelAsmOperandInfo &RefOpInfo = 8005 OpInfo.isMatchingInputConstraint() 8006 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8007 : OpInfo; 8008 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8009 8010 switch (OpInfo.Type) { 8011 case InlineAsm::isOutput: 8012 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8013 (OpInfo.ConstraintType == TargetLowering::C_Other && 8014 OpInfo.isIndirect)) { 8015 unsigned ConstraintID = 8016 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8017 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8018 "Failed to convert memory constraint code to constraint id."); 8019 8020 // Add information to the INLINEASM node to know about this output. 8021 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8022 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8023 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8024 MVT::i32)); 8025 AsmNodeOperands.push_back(OpInfo.CallOperand); 8026 break; 8027 } else if ((OpInfo.ConstraintType == TargetLowering::C_Other && 8028 !OpInfo.isIndirect) || 8029 OpInfo.ConstraintType == TargetLowering::C_Register || 8030 OpInfo.ConstraintType == TargetLowering::C_RegisterClass) { 8031 // Otherwise, this outputs to a register (directly for C_Register / 8032 // C_RegisterClass, and a target-defined fashion for C_Other). Find a 8033 // register that we can use. 8034 if (OpInfo.AssignedRegs.Regs.empty()) { 8035 emitInlineAsmError( 8036 CS, "couldn't allocate output register for constraint '" + 8037 Twine(OpInfo.ConstraintCode) + "'"); 8038 return; 8039 } 8040 8041 // Add information to the INLINEASM node to know that this register is 8042 // set. 8043 OpInfo.AssignedRegs.AddInlineAsmOperands( 8044 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8045 : InlineAsm::Kind_RegDef, 8046 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8047 } 8048 break; 8049 8050 case InlineAsm::isInput: { 8051 SDValue InOperandVal = OpInfo.CallOperand; 8052 8053 if (OpInfo.isMatchingInputConstraint()) { 8054 // If this is required to match an output register we have already set, 8055 // just use its register. 8056 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8057 AsmNodeOperands); 8058 unsigned OpFlag = 8059 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8060 if (InlineAsm::isRegDefKind(OpFlag) || 8061 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8062 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8063 if (OpInfo.isIndirect) { 8064 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8065 emitInlineAsmError(CS, "inline asm not supported yet:" 8066 " don't know how to handle tied " 8067 "indirect register inputs"); 8068 return; 8069 } 8070 8071 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 8072 SmallVector<unsigned, 4> Regs; 8073 8074 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { 8075 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8076 MachineRegisterInfo &RegInfo = 8077 DAG.getMachineFunction().getRegInfo(); 8078 for (unsigned i = 0; i != NumRegs; ++i) 8079 Regs.push_back(RegInfo.createVirtualRegister(RC)); 8080 } else { 8081 emitInlineAsmError(CS, "inline asm error: This value type register " 8082 "class is not natively supported!"); 8083 return; 8084 } 8085 8086 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8087 8088 SDLoc dl = getCurSDLoc(); 8089 // Use the produced MatchedRegs object to 8090 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 8091 CS.getInstruction()); 8092 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8093 true, OpInfo.getMatchedOperand(), dl, 8094 DAG, AsmNodeOperands); 8095 break; 8096 } 8097 8098 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8099 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8100 "Unexpected number of operands"); 8101 // Add information to the INLINEASM node to know about this input. 8102 // See InlineAsm.h isUseOperandTiedToDef. 8103 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8104 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8105 OpInfo.getMatchedOperand()); 8106 AsmNodeOperands.push_back(DAG.getTargetConstant( 8107 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8108 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8109 break; 8110 } 8111 8112 // Treat indirect 'X' constraint as memory. 8113 if (OpInfo.ConstraintType == TargetLowering::C_Other && 8114 OpInfo.isIndirect) 8115 OpInfo.ConstraintType = TargetLowering::C_Memory; 8116 8117 if (OpInfo.ConstraintType == TargetLowering::C_Other) { 8118 std::vector<SDValue> Ops; 8119 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 8120 Ops, DAG); 8121 if (Ops.empty()) { 8122 emitInlineAsmError(CS, "invalid operand for inline asm constraint '" + 8123 Twine(OpInfo.ConstraintCode) + "'"); 8124 return; 8125 } 8126 8127 // Add information to the INLINEASM node to know about this input. 8128 unsigned ResOpType = 8129 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 8130 AsmNodeOperands.push_back(DAG.getTargetConstant( 8131 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8132 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 8133 break; 8134 } 8135 8136 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8137 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 8138 assert(InOperandVal.getValueType() == 8139 TLI.getPointerTy(DAG.getDataLayout()) && 8140 "Memory operands expect pointer values"); 8141 8142 unsigned ConstraintID = 8143 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8144 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8145 "Failed to convert memory constraint code to constraint id."); 8146 8147 // Add information to the INLINEASM node to know about this input. 8148 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8149 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 8150 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 8151 getCurSDLoc(), 8152 MVT::i32)); 8153 AsmNodeOperands.push_back(InOperandVal); 8154 break; 8155 } 8156 8157 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 8158 OpInfo.ConstraintType == TargetLowering::C_Register) && 8159 "Unknown constraint type!"); 8160 8161 // TODO: Support this. 8162 if (OpInfo.isIndirect) { 8163 emitInlineAsmError( 8164 CS, "Don't know how to handle indirect register inputs yet " 8165 "for constraint '" + 8166 Twine(OpInfo.ConstraintCode) + "'"); 8167 return; 8168 } 8169 8170 // Copy the input into the appropriate registers. 8171 if (OpInfo.AssignedRegs.Regs.empty()) { 8172 emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" + 8173 Twine(OpInfo.ConstraintCode) + "'"); 8174 return; 8175 } 8176 8177 SDLoc dl = getCurSDLoc(); 8178 8179 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, 8180 Chain, &Flag, CS.getInstruction()); 8181 8182 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 8183 dl, DAG, AsmNodeOperands); 8184 break; 8185 } 8186 case InlineAsm::isClobber: 8187 // Add the clobbered value to the operand list, so that the register 8188 // allocator is aware that the physreg got clobbered. 8189 if (!OpInfo.AssignedRegs.Regs.empty()) 8190 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 8191 false, 0, getCurSDLoc(), DAG, 8192 AsmNodeOperands); 8193 break; 8194 } 8195 } 8196 8197 // Finish up input operands. Set the input chain and add the flag last. 8198 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 8199 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 8200 8201 unsigned ISDOpc = isa<CallBrInst>(CS.getInstruction()) ? ISD::INLINEASM_BR 8202 : ISD::INLINEASM; 8203 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 8204 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 8205 Flag = Chain.getValue(1); 8206 8207 // Do additional work to generate outputs. 8208 8209 SmallVector<EVT, 1> ResultVTs; 8210 SmallVector<SDValue, 1> ResultValues; 8211 SmallVector<SDValue, 8> OutChains; 8212 8213 llvm::Type *CSResultType = CS.getType(); 8214 ArrayRef<Type *> ResultTypes; 8215 if (StructType *StructResult = dyn_cast<StructType>(CSResultType)) 8216 ResultTypes = StructResult->elements(); 8217 else if (!CSResultType->isVoidTy()) 8218 ResultTypes = makeArrayRef(CSResultType); 8219 8220 auto CurResultType = ResultTypes.begin(); 8221 auto handleRegAssign = [&](SDValue V) { 8222 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 8223 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 8224 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 8225 ++CurResultType; 8226 // If the type of the inline asm call site return value is different but has 8227 // same size as the type of the asm output bitcast it. One example of this 8228 // is for vectors with different width / number of elements. This can 8229 // happen for register classes that can contain multiple different value 8230 // types. The preg or vreg allocated may not have the same VT as was 8231 // expected. 8232 // 8233 // This can also happen for a return value that disagrees with the register 8234 // class it is put in, eg. a double in a general-purpose register on a 8235 // 32-bit machine. 8236 if (ResultVT != V.getValueType() && 8237 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 8238 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 8239 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 8240 V.getValueType().isInteger()) { 8241 // If a result value was tied to an input value, the computed result 8242 // may have a wider width than the expected result. Extract the 8243 // relevant portion. 8244 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 8245 } 8246 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 8247 ResultVTs.push_back(ResultVT); 8248 ResultValues.push_back(V); 8249 }; 8250 8251 // Deal with output operands. 8252 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8253 if (OpInfo.Type == InlineAsm::isOutput) { 8254 SDValue Val; 8255 // Skip trivial output operands. 8256 if (OpInfo.AssignedRegs.Regs.empty()) 8257 continue; 8258 8259 switch (OpInfo.ConstraintType) { 8260 case TargetLowering::C_Register: 8261 case TargetLowering::C_RegisterClass: 8262 Val = OpInfo.AssignedRegs.getCopyFromRegs( 8263 DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction()); 8264 break; 8265 case TargetLowering::C_Other: 8266 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 8267 OpInfo, DAG); 8268 break; 8269 case TargetLowering::C_Memory: 8270 break; // Already handled. 8271 case TargetLowering::C_Unknown: 8272 assert(false && "Unexpected unknown constraint"); 8273 } 8274 8275 // Indirect output manifest as stores. Record output chains. 8276 if (OpInfo.isIndirect) { 8277 const Value *Ptr = OpInfo.CallOperandVal; 8278 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 8279 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 8280 MachinePointerInfo(Ptr)); 8281 OutChains.push_back(Store); 8282 } else { 8283 // generate CopyFromRegs to associated registers. 8284 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 8285 if (Val.getOpcode() == ISD::MERGE_VALUES) { 8286 for (const SDValue &V : Val->op_values()) 8287 handleRegAssign(V); 8288 } else 8289 handleRegAssign(Val); 8290 } 8291 } 8292 } 8293 8294 // Set results. 8295 if (!ResultValues.empty()) { 8296 assert(CurResultType == ResultTypes.end() && 8297 "Mismatch in number of ResultTypes"); 8298 assert(ResultValues.size() == ResultTypes.size() && 8299 "Mismatch in number of output operands in asm result"); 8300 8301 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 8302 DAG.getVTList(ResultVTs), ResultValues); 8303 setValue(CS.getInstruction(), V); 8304 } 8305 8306 // Collect store chains. 8307 if (!OutChains.empty()) 8308 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 8309 8310 // Only Update Root if inline assembly has a memory effect. 8311 if (ResultValues.empty() || HasSideEffect || !OutChains.empty()) 8312 DAG.setRoot(Chain); 8313 } 8314 8315 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS, 8316 const Twine &Message) { 8317 LLVMContext &Ctx = *DAG.getContext(); 8318 Ctx.emitError(CS.getInstruction(), Message); 8319 8320 // Make sure we leave the DAG in a valid state 8321 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8322 SmallVector<EVT, 1> ValueVTs; 8323 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8324 8325 if (ValueVTs.empty()) 8326 return; 8327 8328 SmallVector<SDValue, 1> Ops; 8329 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 8330 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 8331 8332 setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc())); 8333 } 8334 8335 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 8336 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 8337 MVT::Other, getRoot(), 8338 getValue(I.getArgOperand(0)), 8339 DAG.getSrcValue(I.getArgOperand(0)))); 8340 } 8341 8342 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 8343 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8344 const DataLayout &DL = DAG.getDataLayout(); 8345 SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()), 8346 getCurSDLoc(), getRoot(), getValue(I.getOperand(0)), 8347 DAG.getSrcValue(I.getOperand(0)), 8348 DL.getABITypeAlignment(I.getType())); 8349 setValue(&I, V); 8350 DAG.setRoot(V.getValue(1)); 8351 } 8352 8353 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 8354 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 8355 MVT::Other, getRoot(), 8356 getValue(I.getArgOperand(0)), 8357 DAG.getSrcValue(I.getArgOperand(0)))); 8358 } 8359 8360 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 8361 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 8362 MVT::Other, getRoot(), 8363 getValue(I.getArgOperand(0)), 8364 getValue(I.getArgOperand(1)), 8365 DAG.getSrcValue(I.getArgOperand(0)), 8366 DAG.getSrcValue(I.getArgOperand(1)))); 8367 } 8368 8369 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 8370 const Instruction &I, 8371 SDValue Op) { 8372 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 8373 if (!Range) 8374 return Op; 8375 8376 ConstantRange CR = getConstantRangeFromMetadata(*Range); 8377 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 8378 return Op; 8379 8380 APInt Lo = CR.getUnsignedMin(); 8381 if (!Lo.isMinValue()) 8382 return Op; 8383 8384 APInt Hi = CR.getUnsignedMax(); 8385 unsigned Bits = std::max(Hi.getActiveBits(), 8386 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 8387 8388 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8389 8390 SDLoc SL = getCurSDLoc(); 8391 8392 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8393 DAG.getValueType(SmallVT)); 8394 unsigned NumVals = Op.getNode()->getNumValues(); 8395 if (NumVals == 1) 8396 return ZExt; 8397 8398 SmallVector<SDValue, 4> Ops; 8399 8400 Ops.push_back(ZExt); 8401 for (unsigned I = 1; I != NumVals; ++I) 8402 Ops.push_back(Op.getValue(I)); 8403 8404 return DAG.getMergeValues(Ops, SL); 8405 } 8406 8407 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8408 /// the call being lowered. 8409 /// 8410 /// This is a helper for lowering intrinsics that follow a target calling 8411 /// convention or require stack pointer adjustment. Only a subset of the 8412 /// intrinsic's operands need to participate in the calling convention. 8413 void SelectionDAGBuilder::populateCallLoweringInfo( 8414 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 8415 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8416 bool IsPatchPoint) { 8417 TargetLowering::ArgListTy Args; 8418 Args.reserve(NumArgs); 8419 8420 // Populate the argument list. 8421 // Attributes for args start at offset 1, after the return attribute. 8422 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8423 ArgI != ArgE; ++ArgI) { 8424 const Value *V = Call->getOperand(ArgI); 8425 8426 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 8427 8428 TargetLowering::ArgListEntry Entry; 8429 Entry.Node = getValue(V); 8430 Entry.Ty = V->getType(); 8431 Entry.setAttributes(Call, ArgI); 8432 Args.push_back(Entry); 8433 } 8434 8435 CLI.setDebugLoc(getCurSDLoc()) 8436 .setChain(getRoot()) 8437 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 8438 .setDiscardResult(Call->use_empty()) 8439 .setIsPatchPoint(IsPatchPoint); 8440 } 8441 8442 /// Add a stack map intrinsic call's live variable operands to a stackmap 8443 /// or patchpoint target node's operand list. 8444 /// 8445 /// Constants are converted to TargetConstants purely as an optimization to 8446 /// avoid constant materialization and register allocation. 8447 /// 8448 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 8449 /// generate addess computation nodes, and so ExpandISelPseudo can convert the 8450 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 8451 /// address materialization and register allocation, but may also be required 8452 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 8453 /// alloca in the entry block, then the runtime may assume that the alloca's 8454 /// StackMap location can be read immediately after compilation and that the 8455 /// location is valid at any point during execution (this is similar to the 8456 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 8457 /// only available in a register, then the runtime would need to trap when 8458 /// execution reaches the StackMap in order to read the alloca's location. 8459 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx, 8460 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 8461 SelectionDAGBuilder &Builder) { 8462 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) { 8463 SDValue OpVal = Builder.getValue(CS.getArgument(i)); 8464 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 8465 Ops.push_back( 8466 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 8467 Ops.push_back( 8468 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 8469 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 8470 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 8471 Ops.push_back(Builder.DAG.getTargetFrameIndex( 8472 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 8473 } else 8474 Ops.push_back(OpVal); 8475 } 8476 } 8477 8478 /// Lower llvm.experimental.stackmap directly to its target opcode. 8479 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 8480 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 8481 // [live variables...]) 8482 8483 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 8484 8485 SDValue Chain, InFlag, Callee, NullPtr; 8486 SmallVector<SDValue, 32> Ops; 8487 8488 SDLoc DL = getCurSDLoc(); 8489 Callee = getValue(CI.getCalledValue()); 8490 NullPtr = DAG.getIntPtrConstant(0, DL, true); 8491 8492 // The stackmap intrinsic only records the live variables (the arguemnts 8493 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 8494 // intrinsic, this won't be lowered to a function call. This means we don't 8495 // have to worry about calling conventions and target specific lowering code. 8496 // Instead we perform the call lowering right here. 8497 // 8498 // chain, flag = CALLSEQ_START(chain, 0, 0) 8499 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 8500 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 8501 // 8502 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 8503 InFlag = Chain.getValue(1); 8504 8505 // Add the <id> and <numBytes> constants. 8506 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 8507 Ops.push_back(DAG.getTargetConstant( 8508 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 8509 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 8510 Ops.push_back(DAG.getTargetConstant( 8511 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 8512 MVT::i32)); 8513 8514 // Push live variables for the stack map. 8515 addStackMapLiveVars(&CI, 2, DL, Ops, *this); 8516 8517 // We are not pushing any register mask info here on the operands list, 8518 // because the stackmap doesn't clobber anything. 8519 8520 // Push the chain and the glue flag. 8521 Ops.push_back(Chain); 8522 Ops.push_back(InFlag); 8523 8524 // Create the STACKMAP node. 8525 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8526 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 8527 Chain = SDValue(SM, 0); 8528 InFlag = Chain.getValue(1); 8529 8530 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 8531 8532 // Stackmaps don't generate values, so nothing goes into the NodeMap. 8533 8534 // Set the root to the target-lowered call chain. 8535 DAG.setRoot(Chain); 8536 8537 // Inform the Frame Information that we have a stackmap in this function. 8538 FuncInfo.MF->getFrameInfo().setHasStackMap(); 8539 } 8540 8541 /// Lower llvm.experimental.patchpoint directly to its target opcode. 8542 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS, 8543 const BasicBlock *EHPadBB) { 8544 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 8545 // i32 <numBytes>, 8546 // i8* <target>, 8547 // i32 <numArgs>, 8548 // [Args...], 8549 // [live variables...]) 8550 8551 CallingConv::ID CC = CS.getCallingConv(); 8552 bool IsAnyRegCC = CC == CallingConv::AnyReg; 8553 bool HasDef = !CS->getType()->isVoidTy(); 8554 SDLoc dl = getCurSDLoc(); 8555 SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos)); 8556 8557 // Handle immediate and symbolic callees. 8558 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 8559 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 8560 /*isTarget=*/true); 8561 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 8562 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 8563 SDLoc(SymbolicCallee), 8564 SymbolicCallee->getValueType(0)); 8565 8566 // Get the real number of arguments participating in the call <numArgs> 8567 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos)); 8568 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 8569 8570 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 8571 // Intrinsics include all meta-operands up to but not including CC. 8572 unsigned NumMetaOpers = PatchPointOpers::CCPos; 8573 assert(CS.arg_size() >= NumMetaOpers + NumArgs && 8574 "Not enough arguments provided to the patchpoint intrinsic"); 8575 8576 // For AnyRegCC the arguments are lowered later on manually. 8577 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 8578 Type *ReturnTy = 8579 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType(); 8580 8581 TargetLowering::CallLoweringInfo CLI(DAG); 8582 populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()), 8583 NumMetaOpers, NumCallArgs, Callee, ReturnTy, true); 8584 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8585 8586 SDNode *CallEnd = Result.second.getNode(); 8587 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 8588 CallEnd = CallEnd->getOperand(0).getNode(); 8589 8590 /// Get a call instruction from the call sequence chain. 8591 /// Tail calls are not allowed. 8592 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 8593 "Expected a callseq node."); 8594 SDNode *Call = CallEnd->getOperand(0).getNode(); 8595 bool HasGlue = Call->getGluedNode(); 8596 8597 // Replace the target specific call node with the patchable intrinsic. 8598 SmallVector<SDValue, 8> Ops; 8599 8600 // Add the <id> and <numBytes> constants. 8601 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos)); 8602 Ops.push_back(DAG.getTargetConstant( 8603 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 8604 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos)); 8605 Ops.push_back(DAG.getTargetConstant( 8606 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 8607 MVT::i32)); 8608 8609 // Add the callee. 8610 Ops.push_back(Callee); 8611 8612 // Adjust <numArgs> to account for any arguments that have been passed on the 8613 // stack instead. 8614 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 8615 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 8616 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 8617 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 8618 8619 // Add the calling convention 8620 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 8621 8622 // Add the arguments we omitted previously. The register allocator should 8623 // place these in any free register. 8624 if (IsAnyRegCC) 8625 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 8626 Ops.push_back(getValue(CS.getArgument(i))); 8627 8628 // Push the arguments from the call instruction up to the register mask. 8629 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 8630 Ops.append(Call->op_begin() + 2, e); 8631 8632 // Push live variables for the stack map. 8633 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this); 8634 8635 // Push the register mask info. 8636 if (HasGlue) 8637 Ops.push_back(*(Call->op_end()-2)); 8638 else 8639 Ops.push_back(*(Call->op_end()-1)); 8640 8641 // Push the chain (this is originally the first operand of the call, but 8642 // becomes now the last or second to last operand). 8643 Ops.push_back(*(Call->op_begin())); 8644 8645 // Push the glue flag (last operand). 8646 if (HasGlue) 8647 Ops.push_back(*(Call->op_end()-1)); 8648 8649 SDVTList NodeTys; 8650 if (IsAnyRegCC && HasDef) { 8651 // Create the return types based on the intrinsic definition 8652 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8653 SmallVector<EVT, 3> ValueVTs; 8654 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8655 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 8656 8657 // There is always a chain and a glue type at the end 8658 ValueVTs.push_back(MVT::Other); 8659 ValueVTs.push_back(MVT::Glue); 8660 NodeTys = DAG.getVTList(ValueVTs); 8661 } else 8662 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8663 8664 // Replace the target specific call node with a PATCHPOINT node. 8665 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 8666 dl, NodeTys, Ops); 8667 8668 // Update the NodeMap. 8669 if (HasDef) { 8670 if (IsAnyRegCC) 8671 setValue(CS.getInstruction(), SDValue(MN, 0)); 8672 else 8673 setValue(CS.getInstruction(), Result.first); 8674 } 8675 8676 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 8677 // call sequence. Furthermore the location of the chain and glue can change 8678 // when the AnyReg calling convention is used and the intrinsic returns a 8679 // value. 8680 if (IsAnyRegCC && HasDef) { 8681 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 8682 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 8683 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 8684 } else 8685 DAG.ReplaceAllUsesWith(Call, MN); 8686 DAG.DeleteNode(Call); 8687 8688 // Inform the Frame Information that we have a patchpoint in this function. 8689 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 8690 } 8691 8692 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 8693 unsigned Intrinsic) { 8694 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8695 SDValue Op1 = getValue(I.getArgOperand(0)); 8696 SDValue Op2; 8697 if (I.getNumArgOperands() > 1) 8698 Op2 = getValue(I.getArgOperand(1)); 8699 SDLoc dl = getCurSDLoc(); 8700 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8701 SDValue Res; 8702 FastMathFlags FMF; 8703 if (isa<FPMathOperator>(I)) 8704 FMF = I.getFastMathFlags(); 8705 8706 switch (Intrinsic) { 8707 case Intrinsic::experimental_vector_reduce_fadd: 8708 if (FMF.isFast()) 8709 Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2); 8710 else 8711 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2); 8712 break; 8713 case Intrinsic::experimental_vector_reduce_fmul: 8714 if (FMF.isFast()) 8715 Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2); 8716 else 8717 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2); 8718 break; 8719 case Intrinsic::experimental_vector_reduce_add: 8720 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 8721 break; 8722 case Intrinsic::experimental_vector_reduce_mul: 8723 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 8724 break; 8725 case Intrinsic::experimental_vector_reduce_and: 8726 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 8727 break; 8728 case Intrinsic::experimental_vector_reduce_or: 8729 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 8730 break; 8731 case Intrinsic::experimental_vector_reduce_xor: 8732 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 8733 break; 8734 case Intrinsic::experimental_vector_reduce_smax: 8735 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 8736 break; 8737 case Intrinsic::experimental_vector_reduce_smin: 8738 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 8739 break; 8740 case Intrinsic::experimental_vector_reduce_umax: 8741 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 8742 break; 8743 case Intrinsic::experimental_vector_reduce_umin: 8744 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 8745 break; 8746 case Intrinsic::experimental_vector_reduce_fmax: 8747 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1); 8748 break; 8749 case Intrinsic::experimental_vector_reduce_fmin: 8750 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1); 8751 break; 8752 default: 8753 llvm_unreachable("Unhandled vector reduce intrinsic"); 8754 } 8755 setValue(&I, Res); 8756 } 8757 8758 /// Returns an AttributeList representing the attributes applied to the return 8759 /// value of the given call. 8760 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 8761 SmallVector<Attribute::AttrKind, 2> Attrs; 8762 if (CLI.RetSExt) 8763 Attrs.push_back(Attribute::SExt); 8764 if (CLI.RetZExt) 8765 Attrs.push_back(Attribute::ZExt); 8766 if (CLI.IsInReg) 8767 Attrs.push_back(Attribute::InReg); 8768 8769 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 8770 Attrs); 8771 } 8772 8773 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 8774 /// implementation, which just calls LowerCall. 8775 /// FIXME: When all targets are 8776 /// migrated to using LowerCall, this hook should be integrated into SDISel. 8777 std::pair<SDValue, SDValue> 8778 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 8779 // Handle the incoming return values from the call. 8780 CLI.Ins.clear(); 8781 Type *OrigRetTy = CLI.RetTy; 8782 SmallVector<EVT, 4> RetTys; 8783 SmallVector<uint64_t, 4> Offsets; 8784 auto &DL = CLI.DAG.getDataLayout(); 8785 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 8786 8787 if (CLI.IsPostTypeLegalization) { 8788 // If we are lowering a libcall after legalization, split the return type. 8789 SmallVector<EVT, 4> OldRetTys = std::move(RetTys); 8790 SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets); 8791 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 8792 EVT RetVT = OldRetTys[i]; 8793 uint64_t Offset = OldOffsets[i]; 8794 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 8795 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 8796 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 8797 RetTys.append(NumRegs, RegisterVT); 8798 for (unsigned j = 0; j != NumRegs; ++j) 8799 Offsets.push_back(Offset + j * RegisterVTByteSZ); 8800 } 8801 } 8802 8803 SmallVector<ISD::OutputArg, 4> Outs; 8804 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 8805 8806 bool CanLowerReturn = 8807 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 8808 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 8809 8810 SDValue DemoteStackSlot; 8811 int DemoteStackIdx = -100; 8812 if (!CanLowerReturn) { 8813 // FIXME: equivalent assert? 8814 // assert(!CS.hasInAllocaArgument() && 8815 // "sret demotion is incompatible with inalloca"); 8816 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 8817 unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy); 8818 MachineFunction &MF = CLI.DAG.getMachineFunction(); 8819 DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 8820 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 8821 DL.getAllocaAddrSpace()); 8822 8823 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 8824 ArgListEntry Entry; 8825 Entry.Node = DemoteStackSlot; 8826 Entry.Ty = StackSlotPtrType; 8827 Entry.IsSExt = false; 8828 Entry.IsZExt = false; 8829 Entry.IsInReg = false; 8830 Entry.IsSRet = true; 8831 Entry.IsNest = false; 8832 Entry.IsByVal = false; 8833 Entry.IsReturned = false; 8834 Entry.IsSwiftSelf = false; 8835 Entry.IsSwiftError = false; 8836 Entry.Alignment = Align; 8837 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 8838 CLI.NumFixedArgs += 1; 8839 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 8840 8841 // sret demotion isn't compatible with tail-calls, since the sret argument 8842 // points into the callers stack frame. 8843 CLI.IsTailCall = false; 8844 } else { 8845 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 8846 CLI.RetTy, CLI.CallConv, CLI.IsVarArg); 8847 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 8848 ISD::ArgFlagsTy Flags; 8849 if (NeedsRegBlock) { 8850 Flags.setInConsecutiveRegs(); 8851 if (I == RetTys.size() - 1) 8852 Flags.setInConsecutiveRegsLast(); 8853 } 8854 EVT VT = RetTys[I]; 8855 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 8856 CLI.CallConv, VT); 8857 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 8858 CLI.CallConv, VT); 8859 for (unsigned i = 0; i != NumRegs; ++i) { 8860 ISD::InputArg MyFlags; 8861 MyFlags.Flags = Flags; 8862 MyFlags.VT = RegisterVT; 8863 MyFlags.ArgVT = VT; 8864 MyFlags.Used = CLI.IsReturnValueUsed; 8865 if (CLI.RetTy->isPointerTy()) { 8866 MyFlags.Flags.setPointer(); 8867 MyFlags.Flags.setPointerAddrSpace( 8868 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 8869 } 8870 if (CLI.RetSExt) 8871 MyFlags.Flags.setSExt(); 8872 if (CLI.RetZExt) 8873 MyFlags.Flags.setZExt(); 8874 if (CLI.IsInReg) 8875 MyFlags.Flags.setInReg(); 8876 CLI.Ins.push_back(MyFlags); 8877 } 8878 } 8879 } 8880 8881 // We push in swifterror return as the last element of CLI.Ins. 8882 ArgListTy &Args = CLI.getArgs(); 8883 if (supportSwiftError()) { 8884 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 8885 if (Args[i].IsSwiftError) { 8886 ISD::InputArg MyFlags; 8887 MyFlags.VT = getPointerTy(DL); 8888 MyFlags.ArgVT = EVT(getPointerTy(DL)); 8889 MyFlags.Flags.setSwiftError(); 8890 CLI.Ins.push_back(MyFlags); 8891 } 8892 } 8893 } 8894 8895 // Handle all of the outgoing arguments. 8896 CLI.Outs.clear(); 8897 CLI.OutVals.clear(); 8898 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 8899 SmallVector<EVT, 4> ValueVTs; 8900 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 8901 // FIXME: Split arguments if CLI.IsPostTypeLegalization 8902 Type *FinalType = Args[i].Ty; 8903 if (Args[i].IsByVal) 8904 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 8905 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 8906 FinalType, CLI.CallConv, CLI.IsVarArg); 8907 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 8908 ++Value) { 8909 EVT VT = ValueVTs[Value]; 8910 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 8911 SDValue Op = SDValue(Args[i].Node.getNode(), 8912 Args[i].Node.getResNo() + Value); 8913 ISD::ArgFlagsTy Flags; 8914 8915 // Certain targets (such as MIPS), may have a different ABI alignment 8916 // for a type depending on the context. Give the target a chance to 8917 // specify the alignment it wants. 8918 unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL); 8919 8920 if (Args[i].Ty->isPointerTy()) { 8921 Flags.setPointer(); 8922 Flags.setPointerAddrSpace( 8923 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 8924 } 8925 if (Args[i].IsZExt) 8926 Flags.setZExt(); 8927 if (Args[i].IsSExt) 8928 Flags.setSExt(); 8929 if (Args[i].IsInReg) { 8930 // If we are using vectorcall calling convention, a structure that is 8931 // passed InReg - is surely an HVA 8932 if (CLI.CallConv == CallingConv::X86_VectorCall && 8933 isa<StructType>(FinalType)) { 8934 // The first value of a structure is marked 8935 if (0 == Value) 8936 Flags.setHvaStart(); 8937 Flags.setHva(); 8938 } 8939 // Set InReg Flag 8940 Flags.setInReg(); 8941 } 8942 if (Args[i].IsSRet) 8943 Flags.setSRet(); 8944 if (Args[i].IsSwiftSelf) 8945 Flags.setSwiftSelf(); 8946 if (Args[i].IsSwiftError) 8947 Flags.setSwiftError(); 8948 if (Args[i].IsByVal) 8949 Flags.setByVal(); 8950 if (Args[i].IsInAlloca) { 8951 Flags.setInAlloca(); 8952 // Set the byval flag for CCAssignFn callbacks that don't know about 8953 // inalloca. This way we can know how many bytes we should've allocated 8954 // and how many bytes a callee cleanup function will pop. If we port 8955 // inalloca to more targets, we'll have to add custom inalloca handling 8956 // in the various CC lowering callbacks. 8957 Flags.setByVal(); 8958 } 8959 if (Args[i].IsByVal || Args[i].IsInAlloca) { 8960 PointerType *Ty = cast<PointerType>(Args[i].Ty); 8961 Type *ElementTy = Ty->getElementType(); 8962 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 8963 // For ByVal, alignment should come from FE. BE will guess if this 8964 // info is not there but there are cases it cannot get right. 8965 unsigned FrameAlign; 8966 if (Args[i].Alignment) 8967 FrameAlign = Args[i].Alignment; 8968 else 8969 FrameAlign = getByValTypeAlignment(ElementTy, DL); 8970 Flags.setByValAlign(FrameAlign); 8971 } 8972 if (Args[i].IsNest) 8973 Flags.setNest(); 8974 if (NeedsRegBlock) 8975 Flags.setInConsecutiveRegs(); 8976 Flags.setOrigAlign(OriginalAlignment); 8977 8978 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 8979 CLI.CallConv, VT); 8980 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 8981 CLI.CallConv, VT); 8982 SmallVector<SDValue, 4> Parts(NumParts); 8983 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 8984 8985 if (Args[i].IsSExt) 8986 ExtendKind = ISD::SIGN_EXTEND; 8987 else if (Args[i].IsZExt) 8988 ExtendKind = ISD::ZERO_EXTEND; 8989 8990 // Conservatively only handle 'returned' on non-vectors that can be lowered, 8991 // for now. 8992 if (Args[i].IsReturned && !Op.getValueType().isVector() && 8993 CanLowerReturn) { 8994 assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues && 8995 "unexpected use of 'returned'"); 8996 // Before passing 'returned' to the target lowering code, ensure that 8997 // either the register MVT and the actual EVT are the same size or that 8998 // the return value and argument are extended in the same way; in these 8999 // cases it's safe to pass the argument register value unchanged as the 9000 // return register value (although it's at the target's option whether 9001 // to do so) 9002 // TODO: allow code generation to take advantage of partially preserved 9003 // registers rather than clobbering the entire register when the 9004 // parameter extension method is not compatible with the return 9005 // extension method 9006 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9007 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9008 CLI.RetZExt == Args[i].IsZExt)) 9009 Flags.setReturned(); 9010 } 9011 9012 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, 9013 CLI.CS.getInstruction(), CLI.CallConv, ExtendKind); 9014 9015 for (unsigned j = 0; j != NumParts; ++j) { 9016 // if it isn't first piece, alignment must be 1 9017 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 9018 i < CLI.NumFixedArgs, 9019 i, j*Parts[j].getValueType().getStoreSize()); 9020 if (NumParts > 1 && j == 0) 9021 MyFlags.Flags.setSplit(); 9022 else if (j != 0) { 9023 MyFlags.Flags.setOrigAlign(1); 9024 if (j == NumParts - 1) 9025 MyFlags.Flags.setSplitEnd(); 9026 } 9027 9028 CLI.Outs.push_back(MyFlags); 9029 CLI.OutVals.push_back(Parts[j]); 9030 } 9031 9032 if (NeedsRegBlock && Value == NumValues - 1) 9033 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 9034 } 9035 } 9036 9037 SmallVector<SDValue, 4> InVals; 9038 CLI.Chain = LowerCall(CLI, InVals); 9039 9040 // Update CLI.InVals to use outside of this function. 9041 CLI.InVals = InVals; 9042 9043 // Verify that the target's LowerCall behaved as expected. 9044 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 9045 "LowerCall didn't return a valid chain!"); 9046 assert((!CLI.IsTailCall || InVals.empty()) && 9047 "LowerCall emitted a return value for a tail call!"); 9048 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9049 "LowerCall didn't emit the correct number of values!"); 9050 9051 // For a tail call, the return value is merely live-out and there aren't 9052 // any nodes in the DAG representing it. Return a special value to 9053 // indicate that a tail call has been emitted and no more Instructions 9054 // should be processed in the current block. 9055 if (CLI.IsTailCall) { 9056 CLI.DAG.setRoot(CLI.Chain); 9057 return std::make_pair(SDValue(), SDValue()); 9058 } 9059 9060 #ifndef NDEBUG 9061 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 9062 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 9063 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 9064 "LowerCall emitted a value with the wrong type!"); 9065 } 9066 #endif 9067 9068 SmallVector<SDValue, 4> ReturnValues; 9069 if (!CanLowerReturn) { 9070 // The instruction result is the result of loading from the 9071 // hidden sret parameter. 9072 SmallVector<EVT, 1> PVTs; 9073 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 9074 9075 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 9076 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 9077 EVT PtrVT = PVTs[0]; 9078 9079 unsigned NumValues = RetTys.size(); 9080 ReturnValues.resize(NumValues); 9081 SmallVector<SDValue, 4> Chains(NumValues); 9082 9083 // An aggregate return value cannot wrap around the address space, so 9084 // offsets to its parts don't wrap either. 9085 SDNodeFlags Flags; 9086 Flags.setNoUnsignedWrap(true); 9087 9088 for (unsigned i = 0; i < NumValues; ++i) { 9089 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 9090 CLI.DAG.getConstant(Offsets[i], CLI.DL, 9091 PtrVT), Flags); 9092 SDValue L = CLI.DAG.getLoad( 9093 RetTys[i], CLI.DL, CLI.Chain, Add, 9094 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 9095 DemoteStackIdx, Offsets[i]), 9096 /* Alignment = */ 1); 9097 ReturnValues[i] = L; 9098 Chains[i] = L.getValue(1); 9099 } 9100 9101 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 9102 } else { 9103 // Collect the legal value parts into potentially illegal values 9104 // that correspond to the original function's return values. 9105 Optional<ISD::NodeType> AssertOp; 9106 if (CLI.RetSExt) 9107 AssertOp = ISD::AssertSext; 9108 else if (CLI.RetZExt) 9109 AssertOp = ISD::AssertZext; 9110 unsigned CurReg = 0; 9111 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9112 EVT VT = RetTys[I]; 9113 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9114 CLI.CallConv, VT); 9115 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9116 CLI.CallConv, VT); 9117 9118 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 9119 NumRegs, RegisterVT, VT, nullptr, 9120 CLI.CallConv, AssertOp)); 9121 CurReg += NumRegs; 9122 } 9123 9124 // For a function returning void, there is no return value. We can't create 9125 // such a node, so we just return a null return value in that case. In 9126 // that case, nothing will actually look at the value. 9127 if (ReturnValues.empty()) 9128 return std::make_pair(SDValue(), CLI.Chain); 9129 } 9130 9131 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 9132 CLI.DAG.getVTList(RetTys), ReturnValues); 9133 return std::make_pair(Res, CLI.Chain); 9134 } 9135 9136 void TargetLowering::LowerOperationWrapper(SDNode *N, 9137 SmallVectorImpl<SDValue> &Results, 9138 SelectionDAG &DAG) const { 9139 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG)) 9140 Results.push_back(Res); 9141 } 9142 9143 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9144 llvm_unreachable("LowerOperation not implemented for this target!"); 9145 } 9146 9147 void 9148 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 9149 SDValue Op = getNonRegisterValue(V); 9150 assert((Op.getOpcode() != ISD::CopyFromReg || 9151 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 9152 "Copy from a reg to the same reg!"); 9153 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg"); 9154 9155 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9156 // If this is an InlineAsm we have to match the registers required, not the 9157 // notional registers required by the type. 9158 9159 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 9160 None); // This is not an ABI copy. 9161 SDValue Chain = DAG.getEntryNode(); 9162 9163 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 9164 FuncInfo.PreferredExtendType.end()) 9165 ? ISD::ANY_EXTEND 9166 : FuncInfo.PreferredExtendType[V]; 9167 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 9168 PendingExports.push_back(Chain); 9169 } 9170 9171 #include "llvm/CodeGen/SelectionDAGISel.h" 9172 9173 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 9174 /// entry block, return true. This includes arguments used by switches, since 9175 /// the switch may expand into multiple basic blocks. 9176 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 9177 // With FastISel active, we may be splitting blocks, so force creation 9178 // of virtual registers for all non-dead arguments. 9179 if (FastISel) 9180 return A->use_empty(); 9181 9182 const BasicBlock &Entry = A->getParent()->front(); 9183 for (const User *U : A->users()) 9184 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 9185 return false; // Use not in entry block. 9186 9187 return true; 9188 } 9189 9190 using ArgCopyElisionMapTy = 9191 DenseMap<const Argument *, 9192 std::pair<const AllocaInst *, const StoreInst *>>; 9193 9194 /// Scan the entry block of the function in FuncInfo for arguments that look 9195 /// like copies into a local alloca. Record any copied arguments in 9196 /// ArgCopyElisionCandidates. 9197 static void 9198 findArgumentCopyElisionCandidates(const DataLayout &DL, 9199 FunctionLoweringInfo *FuncInfo, 9200 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 9201 // Record the state of every static alloca used in the entry block. Argument 9202 // allocas are all used in the entry block, so we need approximately as many 9203 // entries as we have arguments. 9204 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 9205 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 9206 unsigned NumArgs = FuncInfo->Fn->arg_size(); 9207 StaticAllocas.reserve(NumArgs * 2); 9208 9209 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 9210 if (!V) 9211 return nullptr; 9212 V = V->stripPointerCasts(); 9213 const auto *AI = dyn_cast<AllocaInst>(V); 9214 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 9215 return nullptr; 9216 auto Iter = StaticAllocas.insert({AI, Unknown}); 9217 return &Iter.first->second; 9218 }; 9219 9220 // Look for stores of arguments to static allocas. Look through bitcasts and 9221 // GEPs to handle type coercions, as long as the alloca is fully initialized 9222 // by the store. Any non-store use of an alloca escapes it and any subsequent 9223 // unanalyzed store might write it. 9224 // FIXME: Handle structs initialized with multiple stores. 9225 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 9226 // Look for stores, and handle non-store uses conservatively. 9227 const auto *SI = dyn_cast<StoreInst>(&I); 9228 if (!SI) { 9229 // We will look through cast uses, so ignore them completely. 9230 if (I.isCast()) 9231 continue; 9232 // Ignore debug info intrinsics, they don't escape or store to allocas. 9233 if (isa<DbgInfoIntrinsic>(I)) 9234 continue; 9235 // This is an unknown instruction. Assume it escapes or writes to all 9236 // static alloca operands. 9237 for (const Use &U : I.operands()) { 9238 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 9239 *Info = StaticAllocaInfo::Clobbered; 9240 } 9241 continue; 9242 } 9243 9244 // If the stored value is a static alloca, mark it as escaped. 9245 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 9246 *Info = StaticAllocaInfo::Clobbered; 9247 9248 // Check if the destination is a static alloca. 9249 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 9250 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 9251 if (!Info) 9252 continue; 9253 const AllocaInst *AI = cast<AllocaInst>(Dst); 9254 9255 // Skip allocas that have been initialized or clobbered. 9256 if (*Info != StaticAllocaInfo::Unknown) 9257 continue; 9258 9259 // Check if the stored value is an argument, and that this store fully 9260 // initializes the alloca. Don't elide copies from the same argument twice. 9261 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 9262 const auto *Arg = dyn_cast<Argument>(Val); 9263 if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() || 9264 Arg->getType()->isEmptyTy() || 9265 DL.getTypeStoreSize(Arg->getType()) != 9266 DL.getTypeAllocSize(AI->getAllocatedType()) || 9267 ArgCopyElisionCandidates.count(Arg)) { 9268 *Info = StaticAllocaInfo::Clobbered; 9269 continue; 9270 } 9271 9272 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 9273 << '\n'); 9274 9275 // Mark this alloca and store for argument copy elision. 9276 *Info = StaticAllocaInfo::Elidable; 9277 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 9278 9279 // Stop scanning if we've seen all arguments. This will happen early in -O0 9280 // builds, which is useful, because -O0 builds have large entry blocks and 9281 // many allocas. 9282 if (ArgCopyElisionCandidates.size() == NumArgs) 9283 break; 9284 } 9285 } 9286 9287 /// Try to elide argument copies from memory into a local alloca. Succeeds if 9288 /// ArgVal is a load from a suitable fixed stack object. 9289 static void tryToElideArgumentCopy( 9290 FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains, 9291 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 9292 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 9293 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 9294 SDValue ArgVal, bool &ArgHasUses) { 9295 // Check if this is a load from a fixed stack object. 9296 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 9297 if (!LNode) 9298 return; 9299 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 9300 if (!FINode) 9301 return; 9302 9303 // Check that the fixed stack object is the right size and alignment. 9304 // Look at the alignment that the user wrote on the alloca instead of looking 9305 // at the stack object. 9306 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 9307 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 9308 const AllocaInst *AI = ArgCopyIter->second.first; 9309 int FixedIndex = FINode->getIndex(); 9310 int &AllocaIndex = FuncInfo->StaticAllocaMap[AI]; 9311 int OldIndex = AllocaIndex; 9312 MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo(); 9313 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 9314 LLVM_DEBUG( 9315 dbgs() << " argument copy elision failed due to bad fixed stack " 9316 "object size\n"); 9317 return; 9318 } 9319 unsigned RequiredAlignment = AI->getAlignment(); 9320 if (!RequiredAlignment) { 9321 RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment( 9322 AI->getAllocatedType()); 9323 } 9324 if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) { 9325 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 9326 "greater than stack argument alignment (" 9327 << RequiredAlignment << " vs " 9328 << MFI.getObjectAlignment(FixedIndex) << ")\n"); 9329 return; 9330 } 9331 9332 // Perform the elision. Delete the old stack object and replace its only use 9333 // in the variable info map. Mark the stack object as mutable. 9334 LLVM_DEBUG({ 9335 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 9336 << " Replacing frame index " << OldIndex << " with " << FixedIndex 9337 << '\n'; 9338 }); 9339 MFI.RemoveStackObject(OldIndex); 9340 MFI.setIsImmutableObjectIndex(FixedIndex, false); 9341 AllocaIndex = FixedIndex; 9342 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 9343 Chains.push_back(ArgVal.getValue(1)); 9344 9345 // Avoid emitting code for the store implementing the copy. 9346 const StoreInst *SI = ArgCopyIter->second.second; 9347 ElidedArgCopyInstrs.insert(SI); 9348 9349 // Check for uses of the argument again so that we can avoid exporting ArgVal 9350 // if it is't used by anything other than the store. 9351 for (const Value *U : Arg.users()) { 9352 if (U != SI) { 9353 ArgHasUses = true; 9354 break; 9355 } 9356 } 9357 } 9358 9359 void SelectionDAGISel::LowerArguments(const Function &F) { 9360 SelectionDAG &DAG = SDB->DAG; 9361 SDLoc dl = SDB->getCurSDLoc(); 9362 const DataLayout &DL = DAG.getDataLayout(); 9363 SmallVector<ISD::InputArg, 16> Ins; 9364 9365 if (!FuncInfo->CanLowerReturn) { 9366 // Put in an sret pointer parameter before all the other parameters. 9367 SmallVector<EVT, 1> ValueVTs; 9368 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9369 F.getReturnType()->getPointerTo( 9370 DAG.getDataLayout().getAllocaAddrSpace()), 9371 ValueVTs); 9372 9373 // NOTE: Assuming that a pointer will never break down to more than one VT 9374 // or one register. 9375 ISD::ArgFlagsTy Flags; 9376 Flags.setSRet(); 9377 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 9378 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 9379 ISD::InputArg::NoArgIndex, 0); 9380 Ins.push_back(RetArg); 9381 } 9382 9383 // Look for stores of arguments to static allocas. Mark such arguments with a 9384 // flag to ask the target to give us the memory location of that argument if 9385 // available. 9386 ArgCopyElisionMapTy ArgCopyElisionCandidates; 9387 findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates); 9388 9389 // Set up the incoming argument description vector. 9390 for (const Argument &Arg : F.args()) { 9391 unsigned ArgNo = Arg.getArgNo(); 9392 SmallVector<EVT, 4> ValueVTs; 9393 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9394 bool isArgValueUsed = !Arg.use_empty(); 9395 unsigned PartBase = 0; 9396 Type *FinalType = Arg.getType(); 9397 if (Arg.hasAttribute(Attribute::ByVal)) 9398 FinalType = cast<PointerType>(FinalType)->getElementType(); 9399 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 9400 FinalType, F.getCallingConv(), F.isVarArg()); 9401 for (unsigned Value = 0, NumValues = ValueVTs.size(); 9402 Value != NumValues; ++Value) { 9403 EVT VT = ValueVTs[Value]; 9404 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 9405 ISD::ArgFlagsTy Flags; 9406 9407 // Certain targets (such as MIPS), may have a different ABI alignment 9408 // for a type depending on the context. Give the target a chance to 9409 // specify the alignment it wants. 9410 unsigned OriginalAlignment = 9411 TLI->getABIAlignmentForCallingConv(ArgTy, DL); 9412 9413 if (Arg.getType()->isPointerTy()) { 9414 Flags.setPointer(); 9415 Flags.setPointerAddrSpace( 9416 cast<PointerType>(Arg.getType())->getAddressSpace()); 9417 } 9418 if (Arg.hasAttribute(Attribute::ZExt)) 9419 Flags.setZExt(); 9420 if (Arg.hasAttribute(Attribute::SExt)) 9421 Flags.setSExt(); 9422 if (Arg.hasAttribute(Attribute::InReg)) { 9423 // If we are using vectorcall calling convention, a structure that is 9424 // passed InReg - is surely an HVA 9425 if (F.getCallingConv() == CallingConv::X86_VectorCall && 9426 isa<StructType>(Arg.getType())) { 9427 // The first value of a structure is marked 9428 if (0 == Value) 9429 Flags.setHvaStart(); 9430 Flags.setHva(); 9431 } 9432 // Set InReg Flag 9433 Flags.setInReg(); 9434 } 9435 if (Arg.hasAttribute(Attribute::StructRet)) 9436 Flags.setSRet(); 9437 if (Arg.hasAttribute(Attribute::SwiftSelf)) 9438 Flags.setSwiftSelf(); 9439 if (Arg.hasAttribute(Attribute::SwiftError)) 9440 Flags.setSwiftError(); 9441 if (Arg.hasAttribute(Attribute::ByVal)) 9442 Flags.setByVal(); 9443 if (Arg.hasAttribute(Attribute::InAlloca)) { 9444 Flags.setInAlloca(); 9445 // Set the byval flag for CCAssignFn callbacks that don't know about 9446 // inalloca. This way we can know how many bytes we should've allocated 9447 // and how many bytes a callee cleanup function will pop. If we port 9448 // inalloca to more targets, we'll have to add custom inalloca handling 9449 // in the various CC lowering callbacks. 9450 Flags.setByVal(); 9451 } 9452 if (F.getCallingConv() == CallingConv::X86_INTR) { 9453 // IA Interrupt passes frame (1st parameter) by value in the stack. 9454 if (ArgNo == 0) 9455 Flags.setByVal(); 9456 } 9457 if (Flags.isByVal() || Flags.isInAlloca()) { 9458 PointerType *Ty = cast<PointerType>(Arg.getType()); 9459 Type *ElementTy = Ty->getElementType(); 9460 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 9461 // For ByVal, alignment should be passed from FE. BE will guess if 9462 // this info is not there but there are cases it cannot get right. 9463 unsigned FrameAlign; 9464 if (Arg.getParamAlignment()) 9465 FrameAlign = Arg.getParamAlignment(); 9466 else 9467 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL); 9468 Flags.setByValAlign(FrameAlign); 9469 } 9470 if (Arg.hasAttribute(Attribute::Nest)) 9471 Flags.setNest(); 9472 if (NeedsRegBlock) 9473 Flags.setInConsecutiveRegs(); 9474 Flags.setOrigAlign(OriginalAlignment); 9475 if (ArgCopyElisionCandidates.count(&Arg)) 9476 Flags.setCopyElisionCandidate(); 9477 9478 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 9479 *CurDAG->getContext(), F.getCallingConv(), VT); 9480 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 9481 *CurDAG->getContext(), F.getCallingConv(), VT); 9482 for (unsigned i = 0; i != NumRegs; ++i) { 9483 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 9484 ArgNo, PartBase+i*RegisterVT.getStoreSize()); 9485 if (NumRegs > 1 && i == 0) 9486 MyFlags.Flags.setSplit(); 9487 // if it isn't first piece, alignment must be 1 9488 else if (i > 0) { 9489 MyFlags.Flags.setOrigAlign(1); 9490 if (i == NumRegs - 1) 9491 MyFlags.Flags.setSplitEnd(); 9492 } 9493 Ins.push_back(MyFlags); 9494 } 9495 if (NeedsRegBlock && Value == NumValues - 1) 9496 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 9497 PartBase += VT.getStoreSize(); 9498 } 9499 } 9500 9501 // Call the target to set up the argument values. 9502 SmallVector<SDValue, 8> InVals; 9503 SDValue NewRoot = TLI->LowerFormalArguments( 9504 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 9505 9506 // Verify that the target's LowerFormalArguments behaved as expected. 9507 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 9508 "LowerFormalArguments didn't return a valid chain!"); 9509 assert(InVals.size() == Ins.size() && 9510 "LowerFormalArguments didn't emit the correct number of values!"); 9511 LLVM_DEBUG({ 9512 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 9513 assert(InVals[i].getNode() && 9514 "LowerFormalArguments emitted a null value!"); 9515 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 9516 "LowerFormalArguments emitted a value with the wrong type!"); 9517 } 9518 }); 9519 9520 // Update the DAG with the new chain value resulting from argument lowering. 9521 DAG.setRoot(NewRoot); 9522 9523 // Set up the argument values. 9524 unsigned i = 0; 9525 if (!FuncInfo->CanLowerReturn) { 9526 // Create a virtual register for the sret pointer, and put in a copy 9527 // from the sret argument into it. 9528 SmallVector<EVT, 1> ValueVTs; 9529 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9530 F.getReturnType()->getPointerTo( 9531 DAG.getDataLayout().getAllocaAddrSpace()), 9532 ValueVTs); 9533 MVT VT = ValueVTs[0].getSimpleVT(); 9534 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 9535 Optional<ISD::NodeType> AssertOp = None; 9536 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 9537 nullptr, F.getCallingConv(), AssertOp); 9538 9539 MachineFunction& MF = SDB->DAG.getMachineFunction(); 9540 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 9541 unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 9542 FuncInfo->DemoteRegister = SRetReg; 9543 NewRoot = 9544 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 9545 DAG.setRoot(NewRoot); 9546 9547 // i indexes lowered arguments. Bump it past the hidden sret argument. 9548 ++i; 9549 } 9550 9551 SmallVector<SDValue, 4> Chains; 9552 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 9553 for (const Argument &Arg : F.args()) { 9554 SmallVector<SDValue, 4> ArgValues; 9555 SmallVector<EVT, 4> ValueVTs; 9556 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9557 unsigned NumValues = ValueVTs.size(); 9558 if (NumValues == 0) 9559 continue; 9560 9561 bool ArgHasUses = !Arg.use_empty(); 9562 9563 // Elide the copying store if the target loaded this argument from a 9564 // suitable fixed stack object. 9565 if (Ins[i].Flags.isCopyElisionCandidate()) { 9566 tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 9567 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 9568 InVals[i], ArgHasUses); 9569 } 9570 9571 // If this argument is unused then remember its value. It is used to generate 9572 // debugging information. 9573 bool isSwiftErrorArg = 9574 TLI->supportSwiftError() && 9575 Arg.hasAttribute(Attribute::SwiftError); 9576 if (!ArgHasUses && !isSwiftErrorArg) { 9577 SDB->setUnusedArgValue(&Arg, InVals[i]); 9578 9579 // Also remember any frame index for use in FastISel. 9580 if (FrameIndexSDNode *FI = 9581 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 9582 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9583 } 9584 9585 for (unsigned Val = 0; Val != NumValues; ++Val) { 9586 EVT VT = ValueVTs[Val]; 9587 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 9588 F.getCallingConv(), VT); 9589 unsigned NumParts = TLI->getNumRegistersForCallingConv( 9590 *CurDAG->getContext(), F.getCallingConv(), VT); 9591 9592 // Even an apparant 'unused' swifterror argument needs to be returned. So 9593 // we do generate a copy for it that can be used on return from the 9594 // function. 9595 if (ArgHasUses || isSwiftErrorArg) { 9596 Optional<ISD::NodeType> AssertOp; 9597 if (Arg.hasAttribute(Attribute::SExt)) 9598 AssertOp = ISD::AssertSext; 9599 else if (Arg.hasAttribute(Attribute::ZExt)) 9600 AssertOp = ISD::AssertZext; 9601 9602 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 9603 PartVT, VT, nullptr, 9604 F.getCallingConv(), AssertOp)); 9605 } 9606 9607 i += NumParts; 9608 } 9609 9610 // We don't need to do anything else for unused arguments. 9611 if (ArgValues.empty()) 9612 continue; 9613 9614 // Note down frame index. 9615 if (FrameIndexSDNode *FI = 9616 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 9617 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9618 9619 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 9620 SDB->getCurSDLoc()); 9621 9622 SDB->setValue(&Arg, Res); 9623 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 9624 // We want to associate the argument with the frame index, among 9625 // involved operands, that correspond to the lowest address. The 9626 // getCopyFromParts function, called earlier, is swapping the order of 9627 // the operands to BUILD_PAIR depending on endianness. The result of 9628 // that swapping is that the least significant bits of the argument will 9629 // be in the first operand of the BUILD_PAIR node, and the most 9630 // significant bits will be in the second operand. 9631 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 9632 if (LoadSDNode *LNode = 9633 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 9634 if (FrameIndexSDNode *FI = 9635 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 9636 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9637 } 9638 9639 // Update the SwiftErrorVRegDefMap. 9640 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 9641 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9642 if (TargetRegisterInfo::isVirtualRegister(Reg)) 9643 FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB, 9644 FuncInfo->SwiftErrorArg, Reg); 9645 } 9646 9647 // If this argument is live outside of the entry block, insert a copy from 9648 // wherever we got it to the vreg that other BB's will reference it as. 9649 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) { 9650 // If we can, though, try to skip creating an unnecessary vreg. 9651 // FIXME: This isn't very clean... it would be nice to make this more 9652 // general. It's also subtly incompatible with the hacks FastISel 9653 // uses with vregs. 9654 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9655 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 9656 FuncInfo->ValueMap[&Arg] = Reg; 9657 continue; 9658 } 9659 } 9660 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 9661 FuncInfo->InitializeRegForValue(&Arg); 9662 SDB->CopyToExportRegsIfNeeded(&Arg); 9663 } 9664 } 9665 9666 if (!Chains.empty()) { 9667 Chains.push_back(NewRoot); 9668 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 9669 } 9670 9671 DAG.setRoot(NewRoot); 9672 9673 assert(i == InVals.size() && "Argument register count mismatch!"); 9674 9675 // If any argument copy elisions occurred and we have debug info, update the 9676 // stale frame indices used in the dbg.declare variable info table. 9677 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 9678 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 9679 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 9680 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 9681 if (I != ArgCopyElisionFrameIndexMap.end()) 9682 VI.Slot = I->second; 9683 } 9684 } 9685 9686 // Finally, if the target has anything special to do, allow it to do so. 9687 EmitFunctionEntryCode(); 9688 } 9689 9690 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 9691 /// ensure constants are generated when needed. Remember the virtual registers 9692 /// that need to be added to the Machine PHI nodes as input. We cannot just 9693 /// directly add them, because expansion might result in multiple MBB's for one 9694 /// BB. As such, the start of the BB might correspond to a different MBB than 9695 /// the end. 9696 void 9697 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 9698 const Instruction *TI = LLVMBB->getTerminator(); 9699 9700 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 9701 9702 // Check PHI nodes in successors that expect a value to be available from this 9703 // block. 9704 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 9705 const BasicBlock *SuccBB = TI->getSuccessor(succ); 9706 if (!isa<PHINode>(SuccBB->begin())) continue; 9707 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 9708 9709 // If this terminator has multiple identical successors (common for 9710 // switches), only handle each succ once. 9711 if (!SuccsHandled.insert(SuccMBB).second) 9712 continue; 9713 9714 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 9715 9716 // At this point we know that there is a 1-1 correspondence between LLVM PHI 9717 // nodes and Machine PHI nodes, but the incoming operands have not been 9718 // emitted yet. 9719 for (const PHINode &PN : SuccBB->phis()) { 9720 // Ignore dead phi's. 9721 if (PN.use_empty()) 9722 continue; 9723 9724 // Skip empty types 9725 if (PN.getType()->isEmptyTy()) 9726 continue; 9727 9728 unsigned Reg; 9729 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 9730 9731 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 9732 unsigned &RegOut = ConstantsOut[C]; 9733 if (RegOut == 0) { 9734 RegOut = FuncInfo.CreateRegs(C->getType()); 9735 CopyValueToVirtualRegister(C, RegOut); 9736 } 9737 Reg = RegOut; 9738 } else { 9739 DenseMap<const Value *, unsigned>::iterator I = 9740 FuncInfo.ValueMap.find(PHIOp); 9741 if (I != FuncInfo.ValueMap.end()) 9742 Reg = I->second; 9743 else { 9744 assert(isa<AllocaInst>(PHIOp) && 9745 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 9746 "Didn't codegen value into a register!??"); 9747 Reg = FuncInfo.CreateRegs(PHIOp->getType()); 9748 CopyValueToVirtualRegister(PHIOp, Reg); 9749 } 9750 } 9751 9752 // Remember that this register needs to added to the machine PHI node as 9753 // the input for this MBB. 9754 SmallVector<EVT, 4> ValueVTs; 9755 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9756 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 9757 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 9758 EVT VT = ValueVTs[vti]; 9759 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 9760 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 9761 FuncInfo.PHINodesToUpdate.push_back( 9762 std::make_pair(&*MBBI++, Reg + i)); 9763 Reg += NumRegisters; 9764 } 9765 } 9766 } 9767 9768 ConstantsOut.clear(); 9769 } 9770 9771 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 9772 /// is 0. 9773 MachineBasicBlock * 9774 SelectionDAGBuilder::StackProtectorDescriptor:: 9775 AddSuccessorMBB(const BasicBlock *BB, 9776 MachineBasicBlock *ParentMBB, 9777 bool IsLikely, 9778 MachineBasicBlock *SuccMBB) { 9779 // If SuccBB has not been created yet, create it. 9780 if (!SuccMBB) { 9781 MachineFunction *MF = ParentMBB->getParent(); 9782 MachineFunction::iterator BBI(ParentMBB); 9783 SuccMBB = MF->CreateMachineBasicBlock(BB); 9784 MF->insert(++BBI, SuccMBB); 9785 } 9786 // Add it as a successor of ParentMBB. 9787 ParentMBB->addSuccessor( 9788 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 9789 return SuccMBB; 9790 } 9791 9792 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 9793 MachineFunction::iterator I(MBB); 9794 if (++I == FuncInfo.MF->end()) 9795 return nullptr; 9796 return &*I; 9797 } 9798 9799 /// During lowering new call nodes can be created (such as memset, etc.). 9800 /// Those will become new roots of the current DAG, but complications arise 9801 /// when they are tail calls. In such cases, the call lowering will update 9802 /// the root, but the builder still needs to know that a tail call has been 9803 /// lowered in order to avoid generating an additional return. 9804 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 9805 // If the node is null, we do have a tail call. 9806 if (MaybeTC.getNode() != nullptr) 9807 DAG.setRoot(MaybeTC); 9808 else 9809 HasTailCall = true; 9810 } 9811 9812 uint64_t 9813 SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters, 9814 unsigned First, unsigned Last) const { 9815 assert(Last >= First); 9816 const APInt &LowCase = Clusters[First].Low->getValue(); 9817 const APInt &HighCase = Clusters[Last].High->getValue(); 9818 assert(LowCase.getBitWidth() == HighCase.getBitWidth()); 9819 9820 // FIXME: A range of consecutive cases has 100% density, but only requires one 9821 // comparison to lower. We should discriminate against such consecutive ranges 9822 // in jump tables. 9823 9824 return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1; 9825 } 9826 9827 uint64_t SelectionDAGBuilder::getJumpTableNumCases( 9828 const SmallVectorImpl<unsigned> &TotalCases, unsigned First, 9829 unsigned Last) const { 9830 assert(Last >= First); 9831 assert(TotalCases[Last] >= TotalCases[First]); 9832 uint64_t NumCases = 9833 TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]); 9834 return NumCases; 9835 } 9836 9837 bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters, 9838 unsigned First, unsigned Last, 9839 const SwitchInst *SI, 9840 MachineBasicBlock *DefaultMBB, 9841 CaseCluster &JTCluster) { 9842 assert(First <= Last); 9843 9844 auto Prob = BranchProbability::getZero(); 9845 unsigned NumCmps = 0; 9846 std::vector<MachineBasicBlock*> Table; 9847 DenseMap<MachineBasicBlock*, BranchProbability> JTProbs; 9848 9849 // Initialize probabilities in JTProbs. 9850 for (unsigned I = First; I <= Last; ++I) 9851 JTProbs[Clusters[I].MBB] = BranchProbability::getZero(); 9852 9853 for (unsigned I = First; I <= Last; ++I) { 9854 assert(Clusters[I].Kind == CC_Range); 9855 Prob += Clusters[I].Prob; 9856 const APInt &Low = Clusters[I].Low->getValue(); 9857 const APInt &High = Clusters[I].High->getValue(); 9858 NumCmps += (Low == High) ? 1 : 2; 9859 if (I != First) { 9860 // Fill the gap between this and the previous cluster. 9861 const APInt &PreviousHigh = Clusters[I - 1].High->getValue(); 9862 assert(PreviousHigh.slt(Low)); 9863 uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1; 9864 for (uint64_t J = 0; J < Gap; J++) 9865 Table.push_back(DefaultMBB); 9866 } 9867 uint64_t ClusterSize = (High - Low).getLimitedValue() + 1; 9868 for (uint64_t J = 0; J < ClusterSize; ++J) 9869 Table.push_back(Clusters[I].MBB); 9870 JTProbs[Clusters[I].MBB] += Clusters[I].Prob; 9871 } 9872 9873 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9874 unsigned NumDests = JTProbs.size(); 9875 if (TLI.isSuitableForBitTests( 9876 NumDests, NumCmps, Clusters[First].Low->getValue(), 9877 Clusters[Last].High->getValue(), DAG.getDataLayout())) { 9878 // Clusters[First..Last] should be lowered as bit tests instead. 9879 return false; 9880 } 9881 9882 // Create the MBB that will load from and jump through the table. 9883 // Note: We create it here, but it's not inserted into the function yet. 9884 MachineFunction *CurMF = FuncInfo.MF; 9885 MachineBasicBlock *JumpTableMBB = 9886 CurMF->CreateMachineBasicBlock(SI->getParent()); 9887 9888 // Add successors. Note: use table order for determinism. 9889 SmallPtrSet<MachineBasicBlock *, 8> Done; 9890 for (MachineBasicBlock *Succ : Table) { 9891 if (Done.count(Succ)) 9892 continue; 9893 addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]); 9894 Done.insert(Succ); 9895 } 9896 JumpTableMBB->normalizeSuccProbs(); 9897 9898 unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding()) 9899 ->createJumpTableIndex(Table); 9900 9901 // Set up the jump table info. 9902 JumpTable JT(-1U, JTI, JumpTableMBB, nullptr); 9903 JumpTableHeader JTH(Clusters[First].Low->getValue(), 9904 Clusters[Last].High->getValue(), SI->getCondition(), 9905 nullptr, false); 9906 JTCases.emplace_back(std::move(JTH), std::move(JT)); 9907 9908 JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High, 9909 JTCases.size() - 1, Prob); 9910 return true; 9911 } 9912 9913 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters, 9914 const SwitchInst *SI, 9915 MachineBasicBlock *DefaultMBB) { 9916 #ifndef NDEBUG 9917 // Clusters must be non-empty, sorted, and only contain Range clusters. 9918 assert(!Clusters.empty()); 9919 for (CaseCluster &C : Clusters) 9920 assert(C.Kind == CC_Range); 9921 for (unsigned i = 1, e = Clusters.size(); i < e; ++i) 9922 assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue())); 9923 #endif 9924 9925 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9926 if (!TLI.areJTsAllowed(SI->getParent()->getParent())) 9927 return; 9928 9929 const int64_t N = Clusters.size(); 9930 const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries(); 9931 const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2; 9932 9933 if (N < 2 || N < MinJumpTableEntries) 9934 return; 9935 9936 // TotalCases[i]: Total nbr of cases in Clusters[0..i]. 9937 SmallVector<unsigned, 8> TotalCases(N); 9938 for (unsigned i = 0; i < N; ++i) { 9939 const APInt &Hi = Clusters[i].High->getValue(); 9940 const APInt &Lo = Clusters[i].Low->getValue(); 9941 TotalCases[i] = (Hi - Lo).getLimitedValue() + 1; 9942 if (i != 0) 9943 TotalCases[i] += TotalCases[i - 1]; 9944 } 9945 9946 // Cheap case: the whole range may be suitable for jump table. 9947 uint64_t Range = getJumpTableRange(Clusters,0, N - 1); 9948 uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1); 9949 assert(NumCases < UINT64_MAX / 100); 9950 assert(Range >= NumCases); 9951 if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) { 9952 CaseCluster JTCluster; 9953 if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) { 9954 Clusters[0] = JTCluster; 9955 Clusters.resize(1); 9956 return; 9957 } 9958 } 9959 9960 // The algorithm below is not suitable for -O0. 9961 if (TM.getOptLevel() == CodeGenOpt::None) 9962 return; 9963 9964 // Split Clusters into minimum number of dense partitions. The algorithm uses 9965 // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code 9966 // for the Case Statement'" (1994), but builds the MinPartitions array in 9967 // reverse order to make it easier to reconstruct the partitions in ascending 9968 // order. In the choice between two optimal partitionings, it picks the one 9969 // which yields more jump tables. 9970 9971 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 9972 SmallVector<unsigned, 8> MinPartitions(N); 9973 // LastElement[i] is the last element of the partition starting at i. 9974 SmallVector<unsigned, 8> LastElement(N); 9975 // PartitionsScore[i] is used to break ties when choosing between two 9976 // partitionings resulting in the same number of partitions. 9977 SmallVector<unsigned, 8> PartitionsScore(N); 9978 // For PartitionsScore, a small number of comparisons is considered as good as 9979 // a jump table and a single comparison is considered better than a jump 9980 // table. 9981 enum PartitionScores : unsigned { 9982 NoTable = 0, 9983 Table = 1, 9984 FewCases = 1, 9985 SingleCase = 2 9986 }; 9987 9988 // Base case: There is only one way to partition Clusters[N-1]. 9989 MinPartitions[N - 1] = 1; 9990 LastElement[N - 1] = N - 1; 9991 PartitionsScore[N - 1] = PartitionScores::SingleCase; 9992 9993 // Note: loop indexes are signed to avoid underflow. 9994 for (int64_t i = N - 2; i >= 0; i--) { 9995 // Find optimal partitioning of Clusters[i..N-1]. 9996 // Baseline: Put Clusters[i] into a partition on its own. 9997 MinPartitions[i] = MinPartitions[i + 1] + 1; 9998 LastElement[i] = i; 9999 PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase; 10000 10001 // Search for a solution that results in fewer partitions. 10002 for (int64_t j = N - 1; j > i; j--) { 10003 // Try building a partition from Clusters[i..j]. 10004 uint64_t Range = getJumpTableRange(Clusters, i, j); 10005 uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j); 10006 assert(NumCases < UINT64_MAX / 100); 10007 assert(Range >= NumCases); 10008 if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) { 10009 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 10010 unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1]; 10011 int64_t NumEntries = j - i + 1; 10012 10013 if (NumEntries == 1) 10014 Score += PartitionScores::SingleCase; 10015 else if (NumEntries <= SmallNumberOfEntries) 10016 Score += PartitionScores::FewCases; 10017 else if (NumEntries >= MinJumpTableEntries) 10018 Score += PartitionScores::Table; 10019 10020 // If this leads to fewer partitions, or to the same number of 10021 // partitions with better score, it is a better partitioning. 10022 if (NumPartitions < MinPartitions[i] || 10023 (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) { 10024 MinPartitions[i] = NumPartitions; 10025 LastElement[i] = j; 10026 PartitionsScore[i] = Score; 10027 } 10028 } 10029 } 10030 } 10031 10032 // Iterate over the partitions, replacing some with jump tables in-place. 10033 unsigned DstIndex = 0; 10034 for (unsigned First = 0, Last; First < N; First = Last + 1) { 10035 Last = LastElement[First]; 10036 assert(Last >= First); 10037 assert(DstIndex <= First); 10038 unsigned NumClusters = Last - First + 1; 10039 10040 CaseCluster JTCluster; 10041 if (NumClusters >= MinJumpTableEntries && 10042 buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) { 10043 Clusters[DstIndex++] = JTCluster; 10044 } else { 10045 for (unsigned I = First; I <= Last; ++I) 10046 std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I])); 10047 } 10048 } 10049 Clusters.resize(DstIndex); 10050 } 10051 10052 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters, 10053 unsigned First, unsigned Last, 10054 const SwitchInst *SI, 10055 CaseCluster &BTCluster) { 10056 assert(First <= Last); 10057 if (First == Last) 10058 return false; 10059 10060 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 10061 unsigned NumCmps = 0; 10062 for (int64_t I = First; I <= Last; ++I) { 10063 assert(Clusters[I].Kind == CC_Range); 10064 Dests.set(Clusters[I].MBB->getNumber()); 10065 NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2; 10066 } 10067 unsigned NumDests = Dests.count(); 10068 10069 APInt Low = Clusters[First].Low->getValue(); 10070 APInt High = Clusters[Last].High->getValue(); 10071 assert(Low.slt(High)); 10072 10073 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10074 const DataLayout &DL = DAG.getDataLayout(); 10075 if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL)) 10076 return false; 10077 10078 APInt LowBound; 10079 APInt CmpRange; 10080 10081 const int BitWidth = TLI.getPointerTy(DL).getSizeInBits(); 10082 assert(TLI.rangeFitsInWord(Low, High, DL) && 10083 "Case range must fit in bit mask!"); 10084 10085 // Check if the clusters cover a contiguous range such that no value in the 10086 // range will jump to the default statement. 10087 bool ContiguousRange = true; 10088 for (int64_t I = First + 1; I <= Last; ++I) { 10089 if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) { 10090 ContiguousRange = false; 10091 break; 10092 } 10093 } 10094 10095 if (Low.isStrictlyPositive() && High.slt(BitWidth)) { 10096 // Optimize the case where all the case values fit in a word without having 10097 // to subtract minValue. In this case, we can optimize away the subtraction. 10098 LowBound = APInt::getNullValue(Low.getBitWidth()); 10099 CmpRange = High; 10100 ContiguousRange = false; 10101 } else { 10102 LowBound = Low; 10103 CmpRange = High - Low; 10104 } 10105 10106 CaseBitsVector CBV; 10107 auto TotalProb = BranchProbability::getZero(); 10108 for (unsigned i = First; i <= Last; ++i) { 10109 // Find the CaseBits for this destination. 10110 unsigned j; 10111 for (j = 0; j < CBV.size(); ++j) 10112 if (CBV[j].BB == Clusters[i].MBB) 10113 break; 10114 if (j == CBV.size()) 10115 CBV.push_back( 10116 CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero())); 10117 CaseBits *CB = &CBV[j]; 10118 10119 // Update Mask, Bits and ExtraProb. 10120 uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue(); 10121 uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue(); 10122 assert(Hi >= Lo && Hi < 64 && "Invalid bit case!"); 10123 CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo; 10124 CB->Bits += Hi - Lo + 1; 10125 CB->ExtraProb += Clusters[i].Prob; 10126 TotalProb += Clusters[i].Prob; 10127 } 10128 10129 BitTestInfo BTI; 10130 llvm::sort(CBV, [](const CaseBits &a, const CaseBits &b) { 10131 // Sort by probability first, number of bits second, bit mask third. 10132 if (a.ExtraProb != b.ExtraProb) 10133 return a.ExtraProb > b.ExtraProb; 10134 if (a.Bits != b.Bits) 10135 return a.Bits > b.Bits; 10136 return a.Mask < b.Mask; 10137 }); 10138 10139 for (auto &CB : CBV) { 10140 MachineBasicBlock *BitTestBB = 10141 FuncInfo.MF->CreateMachineBasicBlock(SI->getParent()); 10142 BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb)); 10143 } 10144 BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange), 10145 SI->getCondition(), -1U, MVT::Other, false, 10146 ContiguousRange, nullptr, nullptr, std::move(BTI), 10147 TotalProb); 10148 10149 BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High, 10150 BitTestCases.size() - 1, TotalProb); 10151 return true; 10152 } 10153 10154 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters, 10155 const SwitchInst *SI) { 10156 // Partition Clusters into as few subsets as possible, where each subset has a 10157 // range that fits in a machine word and has <= 3 unique destinations. 10158 10159 #ifndef NDEBUG 10160 // Clusters must be sorted and contain Range or JumpTable clusters. 10161 assert(!Clusters.empty()); 10162 assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable); 10163 for (const CaseCluster &C : Clusters) 10164 assert(C.Kind == CC_Range || C.Kind == CC_JumpTable); 10165 for (unsigned i = 1; i < Clusters.size(); ++i) 10166 assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue())); 10167 #endif 10168 10169 // The algorithm below is not suitable for -O0. 10170 if (TM.getOptLevel() == CodeGenOpt::None) 10171 return; 10172 10173 // If target does not have legal shift left, do not emit bit tests at all. 10174 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10175 const DataLayout &DL = DAG.getDataLayout(); 10176 10177 EVT PTy = TLI.getPointerTy(DL); 10178 if (!TLI.isOperationLegal(ISD::SHL, PTy)) 10179 return; 10180 10181 int BitWidth = PTy.getSizeInBits(); 10182 const int64_t N = Clusters.size(); 10183 10184 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 10185 SmallVector<unsigned, 8> MinPartitions(N); 10186 // LastElement[i] is the last element of the partition starting at i. 10187 SmallVector<unsigned, 8> LastElement(N); 10188 10189 // FIXME: This might not be the best algorithm for finding bit test clusters. 10190 10191 // Base case: There is only one way to partition Clusters[N-1]. 10192 MinPartitions[N - 1] = 1; 10193 LastElement[N - 1] = N - 1; 10194 10195 // Note: loop indexes are signed to avoid underflow. 10196 for (int64_t i = N - 2; i >= 0; --i) { 10197 // Find optimal partitioning of Clusters[i..N-1]. 10198 // Baseline: Put Clusters[i] into a partition on its own. 10199 MinPartitions[i] = MinPartitions[i + 1] + 1; 10200 LastElement[i] = i; 10201 10202 // Search for a solution that results in fewer partitions. 10203 // Note: the search is limited by BitWidth, reducing time complexity. 10204 for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) { 10205 // Try building a partition from Clusters[i..j]. 10206 10207 // Check the range. 10208 if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(), 10209 Clusters[j].High->getValue(), DL)) 10210 continue; 10211 10212 // Check nbr of destinations and cluster types. 10213 // FIXME: This works, but doesn't seem very efficient. 10214 bool RangesOnly = true; 10215 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 10216 for (int64_t k = i; k <= j; k++) { 10217 if (Clusters[k].Kind != CC_Range) { 10218 RangesOnly = false; 10219 break; 10220 } 10221 Dests.set(Clusters[k].MBB->getNumber()); 10222 } 10223 if (!RangesOnly || Dests.count() > 3) 10224 break; 10225 10226 // Check if it's a better partition. 10227 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 10228 if (NumPartitions < MinPartitions[i]) { 10229 // Found a better partition. 10230 MinPartitions[i] = NumPartitions; 10231 LastElement[i] = j; 10232 } 10233 } 10234 } 10235 10236 // Iterate over the partitions, replacing with bit-test clusters in-place. 10237 unsigned DstIndex = 0; 10238 for (unsigned First = 0, Last; First < N; First = Last + 1) { 10239 Last = LastElement[First]; 10240 assert(First <= Last); 10241 assert(DstIndex <= First); 10242 10243 CaseCluster BitTestCluster; 10244 if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) { 10245 Clusters[DstIndex++] = BitTestCluster; 10246 } else { 10247 size_t NumClusters = Last - First + 1; 10248 std::memmove(&Clusters[DstIndex], &Clusters[First], 10249 sizeof(Clusters[0]) * NumClusters); 10250 DstIndex += NumClusters; 10251 } 10252 } 10253 Clusters.resize(DstIndex); 10254 } 10255 10256 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10257 MachineBasicBlock *SwitchMBB, 10258 MachineBasicBlock *DefaultMBB) { 10259 MachineFunction *CurMF = FuncInfo.MF; 10260 MachineBasicBlock *NextMBB = nullptr; 10261 MachineFunction::iterator BBI(W.MBB); 10262 if (++BBI != FuncInfo.MF->end()) 10263 NextMBB = &*BBI; 10264 10265 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10266 10267 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10268 10269 if (Size == 2 && W.MBB == SwitchMBB) { 10270 // If any two of the cases has the same destination, and if one value 10271 // is the same as the other, but has one bit unset that the other has set, 10272 // use bit manipulation to do two compares at once. For example: 10273 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10274 // TODO: This could be extended to merge any 2 cases in switches with 3 10275 // cases. 10276 // TODO: Handle cases where W.CaseBB != SwitchBB. 10277 CaseCluster &Small = *W.FirstCluster; 10278 CaseCluster &Big = *W.LastCluster; 10279 10280 if (Small.Low == Small.High && Big.Low == Big.High && 10281 Small.MBB == Big.MBB) { 10282 const APInt &SmallValue = Small.Low->getValue(); 10283 const APInt &BigValue = Big.Low->getValue(); 10284 10285 // Check that there is only one bit different. 10286 APInt CommonBit = BigValue ^ SmallValue; 10287 if (CommonBit.isPowerOf2()) { 10288 SDValue CondLHS = getValue(Cond); 10289 EVT VT = CondLHS.getValueType(); 10290 SDLoc DL = getCurSDLoc(); 10291 10292 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10293 DAG.getConstant(CommonBit, DL, VT)); 10294 SDValue Cond = DAG.getSetCC( 10295 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10296 ISD::SETEQ); 10297 10298 // Update successor info. 10299 // Both Small and Big will jump to Small.BB, so we sum up the 10300 // probabilities. 10301 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10302 if (BPI) 10303 addSuccessorWithProb( 10304 SwitchMBB, DefaultMBB, 10305 // The default destination is the first successor in IR. 10306 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10307 else 10308 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10309 10310 // Insert the true branch. 10311 SDValue BrCond = 10312 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10313 DAG.getBasicBlock(Small.MBB)); 10314 // Insert the false branch. 10315 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10316 DAG.getBasicBlock(DefaultMBB)); 10317 10318 DAG.setRoot(BrCond); 10319 return; 10320 } 10321 } 10322 } 10323 10324 if (TM.getOptLevel() != CodeGenOpt::None) { 10325 // Here, we order cases by probability so the most likely case will be 10326 // checked first. However, two clusters can have the same probability in 10327 // which case their relative ordering is non-deterministic. So we use Low 10328 // as a tie-breaker as clusters are guaranteed to never overlap. 10329 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10330 [](const CaseCluster &a, const CaseCluster &b) { 10331 return a.Prob != b.Prob ? 10332 a.Prob > b.Prob : 10333 a.Low->getValue().slt(b.Low->getValue()); 10334 }); 10335 10336 // Rearrange the case blocks so that the last one falls through if possible 10337 // without changing the order of probabilities. 10338 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10339 --I; 10340 if (I->Prob > W.LastCluster->Prob) 10341 break; 10342 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10343 std::swap(*I, *W.LastCluster); 10344 break; 10345 } 10346 } 10347 } 10348 10349 // Compute total probability. 10350 BranchProbability DefaultProb = W.DefaultProb; 10351 BranchProbability UnhandledProbs = DefaultProb; 10352 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10353 UnhandledProbs += I->Prob; 10354 10355 MachineBasicBlock *CurMBB = W.MBB; 10356 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10357 bool FallthroughUnreachable = false; 10358 MachineBasicBlock *Fallthrough; 10359 if (I == W.LastCluster) { 10360 // For the last cluster, fall through to the default destination. 10361 Fallthrough = DefaultMBB; 10362 FallthroughUnreachable = isa<UnreachableInst>( 10363 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10364 } else { 10365 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10366 CurMF->insert(BBI, Fallthrough); 10367 // Put Cond in a virtual register to make it available from the new blocks. 10368 ExportFromCurrentBlock(Cond); 10369 } 10370 UnhandledProbs -= I->Prob; 10371 10372 switch (I->Kind) { 10373 case CC_JumpTable: { 10374 // FIXME: Optimize away range check based on pivot comparisons. 10375 JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first; 10376 JumpTable *JT = &JTCases[I->JTCasesIndex].second; 10377 10378 // The jump block hasn't been inserted yet; insert it here. 10379 MachineBasicBlock *JumpMBB = JT->MBB; 10380 CurMF->insert(BBI, JumpMBB); 10381 10382 auto JumpProb = I->Prob; 10383 auto FallthroughProb = UnhandledProbs; 10384 10385 // If the default statement is a target of the jump table, we evenly 10386 // distribute the default probability to successors of CurMBB. Also 10387 // update the probability on the edge from JumpMBB to Fallthrough. 10388 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10389 SE = JumpMBB->succ_end(); 10390 SI != SE; ++SI) { 10391 if (*SI == DefaultMBB) { 10392 JumpProb += DefaultProb / 2; 10393 FallthroughProb -= DefaultProb / 2; 10394 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10395 JumpMBB->normalizeSuccProbs(); 10396 break; 10397 } 10398 } 10399 10400 if (FallthroughUnreachable) { 10401 // Skip the range check if the fallthrough block is unreachable. 10402 JTH->OmitRangeCheck = true; 10403 } 10404 10405 if (!JTH->OmitRangeCheck) 10406 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10407 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10408 CurMBB->normalizeSuccProbs(); 10409 10410 // The jump table header will be inserted in our current block, do the 10411 // range check, and fall through to our fallthrough block. 10412 JTH->HeaderBB = CurMBB; 10413 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10414 10415 // If we're in the right place, emit the jump table header right now. 10416 if (CurMBB == SwitchMBB) { 10417 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10418 JTH->Emitted = true; 10419 } 10420 break; 10421 } 10422 case CC_BitTests: { 10423 // FIXME: If Fallthrough is unreachable, skip the range check. 10424 10425 // FIXME: Optimize away range check based on pivot comparisons. 10426 BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex]; 10427 10428 // The bit test blocks haven't been inserted yet; insert them here. 10429 for (BitTestCase &BTC : BTB->Cases) 10430 CurMF->insert(BBI, BTC.ThisBB); 10431 10432 // Fill in fields of the BitTestBlock. 10433 BTB->Parent = CurMBB; 10434 BTB->Default = Fallthrough; 10435 10436 BTB->DefaultProb = UnhandledProbs; 10437 // If the cases in bit test don't form a contiguous range, we evenly 10438 // distribute the probability on the edge to Fallthrough to two 10439 // successors of CurMBB. 10440 if (!BTB->ContiguousRange) { 10441 BTB->Prob += DefaultProb / 2; 10442 BTB->DefaultProb -= DefaultProb / 2; 10443 } 10444 10445 // If we're in the right place, emit the bit test header right now. 10446 if (CurMBB == SwitchMBB) { 10447 visitBitTestHeader(*BTB, SwitchMBB); 10448 BTB->Emitted = true; 10449 } 10450 break; 10451 } 10452 case CC_Range: { 10453 const Value *RHS, *LHS, *MHS; 10454 ISD::CondCode CC; 10455 if (I->Low == I->High) { 10456 // Check Cond == I->Low. 10457 CC = ISD::SETEQ; 10458 LHS = Cond; 10459 RHS=I->Low; 10460 MHS = nullptr; 10461 } else { 10462 // Check I->Low <= Cond <= I->High. 10463 CC = ISD::SETLE; 10464 LHS = I->Low; 10465 MHS = Cond; 10466 RHS = I->High; 10467 } 10468 10469 // If Fallthrough is unreachable, fold away the comparison. 10470 if (FallthroughUnreachable) 10471 CC = ISD::SETTRUE; 10472 10473 // The false probability is the sum of all unhandled cases. 10474 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10475 getCurSDLoc(), I->Prob, UnhandledProbs); 10476 10477 if (CurMBB == SwitchMBB) 10478 visitSwitchCase(CB, SwitchMBB); 10479 else 10480 SwitchCases.push_back(CB); 10481 10482 break; 10483 } 10484 } 10485 CurMBB = Fallthrough; 10486 } 10487 } 10488 10489 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10490 CaseClusterIt First, 10491 CaseClusterIt Last) { 10492 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10493 if (X.Prob != CC.Prob) 10494 return X.Prob > CC.Prob; 10495 10496 // Ties are broken by comparing the case value. 10497 return X.Low->getValue().slt(CC.Low->getValue()); 10498 }); 10499 } 10500 10501 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10502 const SwitchWorkListItem &W, 10503 Value *Cond, 10504 MachineBasicBlock *SwitchMBB) { 10505 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10506 "Clusters not sorted?"); 10507 10508 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10509 10510 // Balance the tree based on branch probabilities to create a near-optimal (in 10511 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10512 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10513 CaseClusterIt LastLeft = W.FirstCluster; 10514 CaseClusterIt FirstRight = W.LastCluster; 10515 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10516 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10517 10518 // Move LastLeft and FirstRight towards each other from opposite directions to 10519 // find a partitioning of the clusters which balances the probability on both 10520 // sides. If LeftProb and RightProb are equal, alternate which side is 10521 // taken to ensure 0-probability nodes are distributed evenly. 10522 unsigned I = 0; 10523 while (LastLeft + 1 < FirstRight) { 10524 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10525 LeftProb += (++LastLeft)->Prob; 10526 else 10527 RightProb += (--FirstRight)->Prob; 10528 I++; 10529 } 10530 10531 while (true) { 10532 // Our binary search tree differs from a typical BST in that ours can have up 10533 // to three values in each leaf. The pivot selection above doesn't take that 10534 // into account, which means the tree might require more nodes and be less 10535 // efficient. We compensate for this here. 10536 10537 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10538 unsigned NumRight = W.LastCluster - FirstRight + 1; 10539 10540 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10541 // If one side has less than 3 clusters, and the other has more than 3, 10542 // consider taking a cluster from the other side. 10543 10544 if (NumLeft < NumRight) { 10545 // Consider moving the first cluster on the right to the left side. 10546 CaseCluster &CC = *FirstRight; 10547 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10548 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10549 if (LeftSideRank <= RightSideRank) { 10550 // Moving the cluster to the left does not demote it. 10551 ++LastLeft; 10552 ++FirstRight; 10553 continue; 10554 } 10555 } else { 10556 assert(NumRight < NumLeft); 10557 // Consider moving the last element on the left to the right side. 10558 CaseCluster &CC = *LastLeft; 10559 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10560 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10561 if (RightSideRank <= LeftSideRank) { 10562 // Moving the cluster to the right does not demot it. 10563 --LastLeft; 10564 --FirstRight; 10565 continue; 10566 } 10567 } 10568 } 10569 break; 10570 } 10571 10572 assert(LastLeft + 1 == FirstRight); 10573 assert(LastLeft >= W.FirstCluster); 10574 assert(FirstRight <= W.LastCluster); 10575 10576 // Use the first element on the right as pivot since we will make less-than 10577 // comparisons against it. 10578 CaseClusterIt PivotCluster = FirstRight; 10579 assert(PivotCluster > W.FirstCluster); 10580 assert(PivotCluster <= W.LastCluster); 10581 10582 CaseClusterIt FirstLeft = W.FirstCluster; 10583 CaseClusterIt LastRight = W.LastCluster; 10584 10585 const ConstantInt *Pivot = PivotCluster->Low; 10586 10587 // New blocks will be inserted immediately after the current one. 10588 MachineFunction::iterator BBI(W.MBB); 10589 ++BBI; 10590 10591 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10592 // we can branch to its destination directly if it's squeezed exactly in 10593 // between the known lower bound and Pivot - 1. 10594 MachineBasicBlock *LeftMBB; 10595 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10596 FirstLeft->Low == W.GE && 10597 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10598 LeftMBB = FirstLeft->MBB; 10599 } else { 10600 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10601 FuncInfo.MF->insert(BBI, LeftMBB); 10602 WorkList.push_back( 10603 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10604 // Put Cond in a virtual register to make it available from the new blocks. 10605 ExportFromCurrentBlock(Cond); 10606 } 10607 10608 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10609 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10610 // directly if RHS.High equals the current upper bound. 10611 MachineBasicBlock *RightMBB; 10612 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10613 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10614 RightMBB = FirstRight->MBB; 10615 } else { 10616 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10617 FuncInfo.MF->insert(BBI, RightMBB); 10618 WorkList.push_back( 10619 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10620 // Put Cond in a virtual register to make it available from the new blocks. 10621 ExportFromCurrentBlock(Cond); 10622 } 10623 10624 // Create the CaseBlock record that will be used to lower the branch. 10625 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10626 getCurSDLoc(), LeftProb, RightProb); 10627 10628 if (W.MBB == SwitchMBB) 10629 visitSwitchCase(CB, SwitchMBB); 10630 else 10631 SwitchCases.push_back(CB); 10632 } 10633 10634 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10635 // from the swith statement. 10636 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10637 BranchProbability PeeledCaseProb) { 10638 if (PeeledCaseProb == BranchProbability::getOne()) 10639 return BranchProbability::getZero(); 10640 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10641 10642 uint32_t Numerator = CaseProb.getNumerator(); 10643 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10644 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10645 } 10646 10647 // Try to peel the top probability case if it exceeds the threshold. 10648 // Return current MachineBasicBlock for the switch statement if the peeling 10649 // does not occur. 10650 // If the peeling is performed, return the newly created MachineBasicBlock 10651 // for the peeled switch statement. Also update Clusters to remove the peeled 10652 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10653 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10654 const SwitchInst &SI, CaseClusterVector &Clusters, 10655 BranchProbability &PeeledCaseProb) { 10656 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10657 // Don't perform if there is only one cluster or optimizing for size. 10658 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10659 TM.getOptLevel() == CodeGenOpt::None || 10660 SwitchMBB->getParent()->getFunction().hasMinSize()) 10661 return SwitchMBB; 10662 10663 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10664 unsigned PeeledCaseIndex = 0; 10665 bool SwitchPeeled = false; 10666 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10667 CaseCluster &CC = Clusters[Index]; 10668 if (CC.Prob < TopCaseProb) 10669 continue; 10670 TopCaseProb = CC.Prob; 10671 PeeledCaseIndex = Index; 10672 SwitchPeeled = true; 10673 } 10674 if (!SwitchPeeled) 10675 return SwitchMBB; 10676 10677 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10678 << TopCaseProb << "\n"); 10679 10680 // Record the MBB for the peeled switch statement. 10681 MachineFunction::iterator BBI(SwitchMBB); 10682 ++BBI; 10683 MachineBasicBlock *PeeledSwitchMBB = 10684 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10685 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10686 10687 ExportFromCurrentBlock(SI.getCondition()); 10688 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10689 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10690 nullptr, nullptr, TopCaseProb.getCompl()}; 10691 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10692 10693 Clusters.erase(PeeledCaseIt); 10694 for (CaseCluster &CC : Clusters) { 10695 LLVM_DEBUG( 10696 dbgs() << "Scale the probablity for one cluster, before scaling: " 10697 << CC.Prob << "\n"); 10698 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10699 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10700 } 10701 PeeledCaseProb = TopCaseProb; 10702 return PeeledSwitchMBB; 10703 } 10704 10705 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10706 // Extract cases from the switch. 10707 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10708 CaseClusterVector Clusters; 10709 Clusters.reserve(SI.getNumCases()); 10710 for (auto I : SI.cases()) { 10711 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10712 const ConstantInt *CaseVal = I.getCaseValue(); 10713 BranchProbability Prob = 10714 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10715 : BranchProbability(1, SI.getNumCases() + 1); 10716 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10717 } 10718 10719 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10720 10721 // Cluster adjacent cases with the same destination. We do this at all 10722 // optimization levels because it's cheap to do and will make codegen faster 10723 // if there are many clusters. 10724 sortAndRangeify(Clusters); 10725 10726 // The branch probablity of the peeled case. 10727 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10728 MachineBasicBlock *PeeledSwitchMBB = 10729 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10730 10731 // If there is only the default destination, jump there directly. 10732 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10733 if (Clusters.empty()) { 10734 assert(PeeledSwitchMBB == SwitchMBB); 10735 SwitchMBB->addSuccessor(DefaultMBB); 10736 if (DefaultMBB != NextBlock(SwitchMBB)) { 10737 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10738 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10739 } 10740 return; 10741 } 10742 10743 findJumpTables(Clusters, &SI, DefaultMBB); 10744 findBitTestClusters(Clusters, &SI); 10745 10746 LLVM_DEBUG({ 10747 dbgs() << "Case clusters: "; 10748 for (const CaseCluster &C : Clusters) { 10749 if (C.Kind == CC_JumpTable) 10750 dbgs() << "JT:"; 10751 if (C.Kind == CC_BitTests) 10752 dbgs() << "BT:"; 10753 10754 C.Low->getValue().print(dbgs(), true); 10755 if (C.Low != C.High) { 10756 dbgs() << '-'; 10757 C.High->getValue().print(dbgs(), true); 10758 } 10759 dbgs() << ' '; 10760 } 10761 dbgs() << '\n'; 10762 }); 10763 10764 assert(!Clusters.empty()); 10765 SwitchWorkList WorkList; 10766 CaseClusterIt First = Clusters.begin(); 10767 CaseClusterIt Last = Clusters.end() - 1; 10768 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10769 // Scale the branchprobability for DefaultMBB if the peel occurs and 10770 // DefaultMBB is not replaced. 10771 if (PeeledCaseProb != BranchProbability::getZero() && 10772 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10773 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10774 WorkList.push_back( 10775 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10776 10777 while (!WorkList.empty()) { 10778 SwitchWorkListItem W = WorkList.back(); 10779 WorkList.pop_back(); 10780 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10781 10782 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10783 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 10784 // For optimized builds, lower large range as a balanced binary tree. 10785 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10786 continue; 10787 } 10788 10789 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10790 } 10791 } 10792